Python Guess Game

Question: Estava fazendo um trabalho e me deparei com alguns problemas.
Esse código possui uma limitação: Sempre que o jogador seleciona algum número que já foi selecionado antes o código não invalida e é considerado como uma tentativa. Queria um help pra refinar o código e sempre que o jogador der um chute que ele já tenha dado anteriormente, o programa deverá recusá-lo e emitir uma mensagem informando ao jogador sobre essa situação e pedindo para ele tentar outro chute. Obviamente, esse chute duplicata não deverá ser contabilizado com uma das 10 tentativas que o jogador tem direito. Pensei em criar um array de 10 elementos mas me enrolei em como executar
# apresente jogo ao usuário
print('Você tem 10 chances de acertar o número que eu estou pensando.')
print('Trata-se de um valor entre 1 e 100. Então, vamos lá!')
print()

# gere número-alvo entre 1 e 100
from random import randint
alvo = randint(1, 100)

# inicialize indicador de acerto
acertou = False

# repita 10 vezes:
contador = 0
while contador <= 10:

# obtenha palpite do usuário
while True:
try:
palpite = int(input('Entre o seu palpite: ')
if palpite < 1 or palpite > 100:
raise ValueError
break
except ValueError:
print('Palpite inválido. Tente outra vez!')
contador = contador + 1

# se palpite atingiu o alvo:
if palpite == alvo:

# atualize indicador de acerto
acertou = True

# encerre o jogo
break

# senão:
else:

# comunique erro ao usuário
print('Errou! Tente novamente.\n' \
'Você ainda tem ', 10-contador, ' tentativa(s).')
print(40*'-'+'\n')

# encerre o jogo
if acertou: # comunique sucesso ao usuário
print('Parabéns!\n' \
'Você acertou o número após ', contador, ' tentativa(s).')
else:

# comunique fracasso ao usuário
print('Infelizmente, você fracassou.\n', \
'O número pensado era: ', alvo, ' \n', \
'Quem sabe a próxima vez!')
print('Até breve') # emita saudação final

Answer: Difícil dizer o que está errado no seu código, ou até o que poderia ser melhorado, pois a indentação do seu código na pergunta prejudicou o entendimento. Se puder editar a pergunta corrigindo a indentação, poderei completar a resposta com comentários acerca da sua solução.
Como adendo, coloco uma maneira que eu resolveria o problema. Como você deseja que as tentativas sejam únicas, isto é, que o usuário não entre com o mesmo palpite mais de uma vez, de fato, você terá que armazená-los de alguma maneira. Para tal, utilizarei o set que, por padrão, já não permite valores duplicados.

Retirarei as chamadas à função print() para simplificar o código, atentando-me somente à lógica implementada.

hunches = set()

Como descrito, existirão duas condições de paradas, exclusivas entre si: quando o usuário acertar o número sorteado; ou quando atingir o limite de 10 palpites. Assim, temos:
hit = False

while not hit and len(hunches) < 10:
    try:
        hunch = int(input('Seu palpite:'))
        ...
    except ValueError as e:
        print(e)

Primeiro, validamos se o palpite está no intervalo aceitável:
hit = False

while not hit and len(hunches) < 10:
    try:
        hunch = int(input('Seu palpite:'))

        if not 1 <= hunch <= 100:
            raise ValueError('Palpite deve estar no intervalo [1, 100]')
    except ValueError as e:
        print(e)

Depois, se o palpite já não foi dado anteriormente:
hit = False

while not hit and len(hunches) < 10:
    try:
        hunch = int(input('Seu palpite:'))

        if not 1 <= hunch <= 100:
            raise ValueError('Palpite deve estar no intervalo [1, 100]')

        if hunch in hunches:
            raise ValueError('Você já deu este palpite antes')
    except ValueError as e:
        print(e)

Por fim, verificamos se o usuário acertou o número; se sim, definimos que acertou, mas se não, adicionamos o palpite ao conjunto de palpites:
hit = False

while not hit and len(hunches) < 10:
    try:
        hunch = int(input('Seu palpite:'))

        if not 1 <= hunch <= 100:
            raise ValueError('Palpite deve estar no intervalo [1, 100]')

        if hunch in hunches:
            raise ValueError('Você já deu este palpite antes')

        if hunch == target:
            hit = True
        else:
            hunches.add(hunch)
    except ValueError as e:
        print(e)

Ao final, podemos verificar se o usuário ganhou ou não:
print('Venceu' if hit else 'Perdeu')

O código completo ficaria:
from random import randint

target = randint(1, 100)

hit = False
hunches = set()

while not hit and len(hunches) < 10:
    try:
        hunch = int(input('Seu palpite:'))

        if not 1 <= hunch <= 100:
            raise ValueError('Palpite deve estar no intervalo [1, 100]')

        if hunch in hunches:
            raise ValueError('Você já deu este palpite antes')

        if hunch == target:
            hit = True
        else:
            hunches.add(hunch)
    except ValueError as e:
        print(e)

print('Venceu' if hit else 'Perdeu')

Veja funcionando no Repl.it | GitHub GIST
Comment: Poooo valeu, tirou minha dúvida fiz de outra maneira mas agora tenho outro problema. Quero dar pistas e dicas para o usuário. Criei dois estados 1: quente e 2: frio. Sempre que o estado 1 e 2 forem iguais, o programa deverá emitir uma mensagem informando ao jogador que o estado do seu chute continua o mesmo, mas que deu uma esquentada ou uma esfriada em relação ao palpite anterior. E queria criar mais 3 estados para o palpite: Fervendo (FV), Morno (MN) e Congelando (CG), obedecendo essa ordem: FV –MQ –QT –MO –FR –MF –CG. O código não acusa erro, massssss não fornece essas dicas.
Comment: @RenatoSilva isso parece ser problema para outra pergunta já
Comment: Farei outra pergunta e colocarei o código então, muito obrigado pela ajuda.
Comment: @RenatoSilva se a resposta lhe foi útil, busque votar e aceitá-la; veja como fazer em [Como e por que aceitar uma resposta?](https://pt.meta.stackoverflow.com/q/1078/5878)

Python Guess Game


Using Dynamic Variables in Velocity Templates

Question: I am using velocity templates to generate email templates and here I want to create tables for each 'tag' with respective values as table data.
I am passing a List tags with details of the tags including tagName, using which I am passing the respective List for each tag. (If tagName = "test", I am passing the data for the test table as $test)
As shown I have set the data of each table to $arrayobjs, but the table does not display the rows as I think it doesnt iterate through the $arrayobs. Please help me iterate through the data and set the data to the coloumns.
P.S.-Although I am able to print the value of $tags[0]
, $arrayobjs[0] does not print a value
    #set ($d = '$')
        #foreach($tag in $tags)
        #set ($var = "${d}${tag.tagName}")
        #set ($arrayobjs = "#evaluate($var)")

                     $tag.tagName

 COL1

 COL2

 COL3

 COL4

 COL5

 COL6

                    #foreach($o in $arrayobjs)

  $o.col1

  $o.col2

  $o.col3

  $o.col4

  $o.col5

  $o.col6

                    #end

            #end

Comment: What is the output of `$arrayobjs` and `$arrayobjs.class.name`?
Comment: $arrayobjs outputs the complete list of objects.
$arrayobjs.class.name outputs String
Answer: After almost 2 years I suggest the following answer :-)
#set ($d = '$')
#set ($h = '#')

#foreach($tag in $tags)
    #set ( $temp = "${h}set ( ${d}var = ${d}${tag.tagName} )" )
    #evaluate($temp)

    ## html code for table header

    #foreach($o in $var)
        ## table rows
    #end
#end

Comment: Thank you so much! P.S. https://stackoverflow.com/a/17107653/470749 also helped me understand.


Convert json to csv but break subitem into there own line using javascript

Question: Good day, I'm trying to convert json data into a csv file. Currently when the csv file is generated it does not place items with child onto their own line.
Below is a diagram of how the data should appear within the csv file.

┌──────────────┬───────────────────────┬───────────────────┬──────────────┬────────────┐
│     Name     │    Social Packages    │   Product Title   │ Product Cost │ Total Cost │
├──────────────┼───────────────────────┼───────────────────┼──────────────┼────────────┤
│ Bruce Lee    │ None                  │ Sample title      │         2500 │      17100 │
│              │ None                  │ Another title     │          600 │            │
│              │ None                  │ Yet another title │        14000 │            │
│ Superman     │ 12 Week Starter       │ None              │            0 │       2215 │
│ Batman       │ 26 Week Premium       │ Sample Title      │         4500 │       6758 │
│ Wonder Woman │ 123 Marketing Starter │ Title name        │            0 │       4575 │
│              │ 26 Starter            │ None              │         2500 │       8750 │
└──────────────┴───────────────────────┴───────────────────┴──────────────┴────────────┘

This a sample of the data im currently working with
[
   {
      "Name": "Bruce Lee",
      "SocialPackages": ["None", "None", "None"],
      "ProductTitle": ["Sample title", "Another title", "Yet AnotherTitle"],
      "ProductCost": [2500, 600, 1400],
      "TotalCost": 17100
   },
   {
      "Name": "Bruce Lee",
      "Social Packages": ["None"],
      "ProductTitle": ["Sample title"],
      "ProductCost": [2500],
      "TotalCost": 4580
   },
   {
      "Name": "Bruce Lee",
      "SocialPackages": ["None", "None", "None"],
      "ProductTitle": ["Sample title", "Another title", "Yet AnotherTitle"],
      "ProductCost": [2500, 600, 1400],
      "TotalCost": 17100
   }
]

This is the functions i'm using to format the data into a user friendly version.
function convertToCSV(objArray) {
   var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
   var str = '';
   for (var i = 0; i < array.length; i++) {
         var line = '';
         for (var index in array[i]) {
         if (line != '') line += ','

         line += array[i][index];
         }
         str += line + '\r\n';
   }
   return str;
}

function exportCSVFile(headers, items, fileTitle) {
   if (headers) {
      items.unshift(headers);
   }
   // Convert Object to JSON
   var jsonObject = JSON.stringify(items);
   var csv = convertToCSV(jsonObject);
   var exportedFilenmae = fileTitle + '.csv' || 'export.csv';

   var blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
   if (navigator.msSaveBlob) {
         navigator.msSaveBlob(blob, exportedFilenmae);
   } else {
      var link = document.createElement("a");
      if (link.download !== undefined) {

         var url = URL.createObjectURL(blob);
         link.setAttribute("href", url);
         link.setAttribute("download", exportedFilenmae);
         link.style.visibility = 'hidden';
         document.body.appendChild(link);
         link.click();
         document.body.removeChild(link);
      }
   }
}

function download(){
   var headers = {
      userName: 'Name',
      socialPackages: "Social Packages",
      productTitle : "Product Title ",
      poroductCost: "Product Cost",
      totalCost: "Total Cost"
   },
   itemsFormatted = [],
   fileTitle = 'Export';

   // format the data
   campaignData.forEach((item) => {
      itemsFormatted.push({
      userName: item.userName,
      socialPackages: item.socialPackages,
      productTitle: item.productTitle,
      poroductCost: item.poroductCost,
      totalCost: item.totalCost
      });
   });

   // call the exportCSVFile() function to process the JSON and trigger the download
   exportCSVFile(headers, itemsFormatted, fileTitle);
}

Any pointer on how to modify the convertToCSV function to place the items with child onto a new line would be much appreciated.
Comment: Your json is not in correct format.
Comment: https://www.npmjs.com/package/json2csv
Answer: JSON data has some problem. In second JSON Object there is a space in "Social Packages". If that is corrected then the below code can be used to generate CSV as required.
function convertToCSV(objArray) {console.log(objArray)
    var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
    var str = '';
    for (var i = 0; i < array.length; i++) {
        var line = '';
        for (var index in array[i]) {
            if (line != '') line += ','
            line += array[i][index];
        }
        str += line + '\r\n';
    }
    return str;
}

function exportCSVFile(headers, items, fileTitle) {
    if (headers) {
        items.unshift(headers);
    }
    // Convert Object to JSON
    var jsonObject = JSON.stringify(items);
    var csv = convertToCSV(jsonObject);
    var exportedFilenmae = fileTitle + '.csv' || 'export.csv';

    var blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
    if (navigator.msSaveBlob) {
        navigator.msSaveBlob(blob, exportedFilenmae);
    } else {
        var link = document.createElement("a");
        if (link.download !== undefined) {
            var url = URL.createObjectURL(blob);
            link.setAttribute("href", url);
            link.setAttribute("download", exportedFilenmae);
            link.style.visibility = 'hidden';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
    }
}

function download(){
    var headers = {
        userName: 'Name',
        socialPackages: "Social Packages",
        productTitle : "Product Title ",
        poroductCost: "Product Cost",
        totalCost: "Total Cost"
    },
    itemsFormatted = [],
    fileTitle = 'Export';

// format the data
campaignData.forEach((item) => {console.log(item)
    if (item.SocialPackages.length == 1) {
        itemsFormatted.push({
            userName: item.Name,
            socialPackages: item.SocialPackages,
            productTitle: item.ProductTitle,
            poroductCost: item.ProductCost,
            totalCost: item.TotalCost
        });
    } else {
        for (i = 0; i < item.SocialPackages.length; i++) {
            var itemName = ' ';
            var itemCost = ' ';
            if(i == 0) {
                itemName = item.Name;
                itemCost = item.TotalCost;
            }
            itemsFormatted.push({
                userName: itemName,
                socialPackages: item.SocialPackages[i],
                productTitle: item.ProductTitle[i],
                poroductCost: item.ProductCost[i],
                totalCost: itemCost
            });
        }
    }
});

Comment: Sorry for the late reply, thank you very much it does exactly what expected.


What to do when you don't trust the sheet music (or guitar tab)?

Question: I'm working on learning a piano tune from a book of sheet music.
There are 1-2 bars that just seem wrong to me, to the point of distraction. Having lost trust in the correctness, I'm not motivated to learn the piece.
I'll follow-up via other avenues about the specifics, but generally speaking, what strategies are there for a student who has lost trust in a piece of sheet music (or guitar tab)?
Edit:
At the risk of invoking moderators' wrath & down-votes, several people have asked me to post.
I'm working on a version of the theme from Mission: Impossible. It is in 5/4 with key signature of C (Tim points out the piece is in G minor). I realize that the piece is quite dissonant but I'm struggling with 2 bars in the right-hand, marked in red.
The first bar shown is the ending of the first right-hand descending motif; the last bar shown is the beginning of second, sibling motif.
I appreciate those that have suggested "listen to the piece, use your ear to transcribe the part", but I don't have that ability, and it simply shifts the question to "how do I trust my ear?".
Comment: I play it the way I want to and/or think it really is.
Comment: "iffy" isn't necessarily wrong - I think it would be appropriate to post your example. The correct answer depends on it really.
Comment: Is this classical music or pop/rock? I ask because classical pieces are sometimes in published editions where "editors" have messed with the piece to some extent, or even made mistakes. And pop/rock tunes are sometimes poor arrangements (in my opinion) and not written by the original songwriter...
Comment: Can you post those 1-2 bars so we have a reference along with the name of the song?
Comment: I would love to post, but I asked in the chat room and they said that it was "iffy" in terms of violating the spirit of the site - http://music.stackexchange.com/help/on-topic  . So I posted this general question instead. (IMHO, I'm not asking to identify notes in the song, I'm asking if the sharps/flats are correct in 2 bars from a book that cost $20.)
Comment: Get a recording of it, listen to it, and transcribe it yourself.
Comment: Okay, I looked at Chat, and saw that you are working on a simplified arrangement of the Mission Impossible theme song.  Could you tell us the measure number where it sounds funny to you?  If you are able to identify a particular note that sounds wrong, please share that as well.  Thanks.
Comment: I've posted the music. I appreciate everyone's input on this.
Comment: @MichaelEaster Look at several other editions / versions of the music.  If your copy is different from theirs, you know there is an error, if not, then you're music is fine and your ear is a little wonky. :)
Comment: You do mean ascending rather than descending motif? And you are playing the B as a Bb, and is it in Cminor? If so, why aren't there 3 flats at the beginning?
Comment: @Tim The sheet music excerpt starts approximately here: https://youtu.be/iq-YeD4L-bg?t=25s . The key signature is C. I now believe that the sheet music is OK (per answer below). (I don't know if it matches the Youtube link but that isn't my question).
Comment: That example is in G min.
Comment: It looks like a reasonable transcription IMHO.  I've played an arrangement or two in concert bands as well as seen the show and movies a few times.  There are lots of variations used throughout them and I am sure that these chords sound familiar.
Answer: Ok, given the example, the upper phrase you highlight is a whole-note ascending minor third with the lower note doubled in the bass (the first note is a b flat due to there being a b flat at the start of the bar), the second phrase is a chromatically ascending minor third with the lower note doubled in the bass logically leading to the next bass note.
So the consistency of upper and lower staff and the respective interval moved and the fact that either phrase are out of whack with the underlying tonality very much make it likely that what has been written here has been written intentionally and is not a typo.
Now if your impression from listening to the original is markedly different, there is a certain likelihood that the transcriber put in something that he considered a good idea.  i have several versions of music where the small print makes clear that they are an interpretation of the original rather than a faithful transcription.  For something like a Simon&Garfunkel collection for fingerpicking it is more commonly than not a total nuisance that you did not get the original accompaniment but rather something with the melody line crammed in as well and the rather characteristic accompaniment only present in shreds if at all.
And if you additionally get "it seemed like a good idea" passages in as well, it can be quite annoying to come to the conclusion that you wasted your money.
I do not know the original, and an actual verbatim comparison would likely be somewhat out of the scope of StackExchange.  From the passages you quoted I consider it highly likely that those phrases are written intentionally in that manner.  Whether they were written originally in that manner is a different question.
Comment: I'm accepting this answer because I came to the same conclusion before I read this post. I studied the notes in terms of theory, and found them to be consistent (i.e. minor-3rds, doubled in the bass). Also, I realized that, as I was learning the fingering, I was accenting one part too long (the final F# in the 2nd red section), and as though it was the end of the phrase. That was throwing me off completely.
Answer: First thing to do is to listen to a recording - or several different ones - of the particular piece. This will give you a more accurate idea of how it goes. Or at least how others think it should go. Chords, dots and particularly tab on various sites on the internet are sometimes the product of amateurs, with little grounding in what they're doing. Thus questions like these. Other sites simply copy stuff across, with the inaccuracies intact : no great help, really.
Use your ears, get used to listening and playing what you hear. In the end it is of much greater value to you than trying to play from someone's (inaccurate, maybe) written music.
I used to find this problem also when backing artistes - the music wasn't actually written properly in some cases, so the old ears had to come back into the equation. Years of relying more on those than what the music tells you to play helped a lot.
Answer: Like you - I have come across sheet music and tabs that I did not find sounded like the song they were supposed to represent.  What I have learned is that in many cases, the sheet music you buy or find on-line, is nothing more than someones interpretation of a particular song or their own personal translation.  Often they contain some inaccuracies.
I don't trust anyone else's interpretation of a piece I want to learn.  I use those interpretations as a starting point.  Often a good portion of the author's interpretation or translation works well and sounds very authentic.  But more often than not, there are parts that I don't feel sound the way I hear the music on the recording.
So I listen to the recording and (sometimes through trial and error) arrive at my own translation or interpretation of how it should be played.  If you aren't able to do that yet, find someone to help you learn how to find the correct notes and/or chords from listening to a recording of the piece.
As Jacob said in his answer, if you don't really care to learn the piece, there is no reason to spend time translating it yourself by ear. I only learn pieces that I am specifically interested in being able to perform.
Good luck.
Answer: Play it how you think it should be played.  Just because it's in a book doesn't mean it's correct and you can't change it.  It could also be good ear training.
If you are self learning, there isn't anything preventing you from totally skipping the song, if you still aren't motivated.
Comment: And if you have a teacher, tell them about your issue, and they can either tell you what the reasoning is behind the way it's written, or skip it. Or both.
Answer: Just one thing to keep in mind: when you find something sounds utterly wrong, it may just be that you're reading the notation wrong.  I find that a particular trap are keyboard fugues from Bach where there is modulation back and forth in a measure and an accidental that occured at the start of the measure is not repeated close to its end even though it is a mere accident that the accidental has not been resolved in the mean time and the second note is not even in the same voice as the first.
In such cases, the autograph from Bach tends to be quite more liberal with accidentals than modern editions which turn the reading into an intellectual challenge.
I am afraid that more of my initial readings turned out to be wrong than I discovered actually wrong editions, so it's always worth making doubly sure that you read the notation correctly before suspecting notation error.
Which does occur, of course.
Answer: This seems like the original version:

I think part of the problem with "trusting your ears" is that your piano version is very simplified. In the original it sounds to me like the chords you underlined were three notes, F-Ab-C F#-A-C# and Bb-Db-F C-Eb-G. That gives quite a different sound, especially if you are playing the top notes of the right hand as if they were "the tune" (which they aren't - the bass line is "the tune" in so far as there is a tune at all.)
This looks like a more advanced piano arrangement, with more complete chords - but I've only looked at the first (free preview) page of it. http://www.musicnotes.com/sheetmusic/mtd.asp?ppn=MN0091182
Answer: Use your ear to figure out how the music should sound. This also includes knowing the style of the music noting that what sounds somewhat "wrong" in some contexts may sound "right" in others. Music is often mis-transcribed into sheet music.
Some performances may differ. I learned "San Antonio Rose" from both sheet music and Bob Wills' recordings. There is a common I,IV,II7,V7 (or more analytically I,IV,V7/V,V7) but I have heard some piano bar pianists play with a jazzier sounding I,IV,ii,V7.


Fazer com que site abra apenas em mobile

Question: preciso que meu site abra em apenas dispositivos móveis, pois é um app hibrido que tanto servira como webview ou Progressive Web App.
Como posso fazer que meu site abra apenas em dispositivos móveis ?
Comment: baita gambiarra

 `if(screen.width > 700){
     location.href  = "https://";
  }`
Comment: Possível duplicata de [quero saber se existe alguma forma de identificar se é pc e celular e exibir um codigo diferente pra cada](http://pt.stackoverflow.com/questions/131677/quero-saber-se-existe-alguma-forma-de-identificar-se-%c3%a9-pc-e-celular-e-exibir-um)
Comment: Qual é a linguagem que tens no servidor? e o que deve acontecer quando um utilizador se liga com um dispositivo não mobile?
Comment: php, redirecionar pra outra url
Comment: consegui fazer só que de uma forma horrivel.   if(screen.width > 700){ location.href = "etc.." }
Comment: haha :) qual é essa forma horrivel?
Comment: Ñão é assim tão mau, no browser essa é uma das maneiras mais simples.
Answer: Uso uma classe em php pra detectar se é mobile ou não:
<code>    <?php

function mobile_device_detect($iphone=true,$android=true,$opera=true,$blackberry=true,$palm=true,$windows=true,$mobileredirect=false,$desktopredirect=false){
  $mobile_browser   = false; // set mobile browser as false till we can prove otherwise

  $user_agent       = $_SERVER['HTTP_USER_AGENT']; // get the user agent value - this should be cleaned to ensure no nefarious input gets executed

  $accept           = $_SERVER['HTTP_ACCEPT']; // get the content accept value - this should be cleaned to ensure no nefarious input gets executed

  switch(true){ // using a switch against the following statements which could return true is more efficient than the previous method of using if statements

    case (preg_match('/ipod/i',$user_agent)||preg_match('/iphone/i',$user_agent)); // we find the words iphone or ipod in the user agent

      $mobile_browser = $iphone; // mobile browser is either true or false depending on the setting of iphone when calling the function

      if(substr($iphone,0,4)=='http'){ // does the value of iphone resemble a url

        $mobileredirect = $iphone; // set the mobile redirect url to the url value stored in the iphone value

      } // ends the if for iphone being a url

    break; // break out and skip the rest if we've had a match on the iphone or ipod

    case (preg_match('/android/i',$user_agent));  // we find android in the user agent

      $mobile_browser = $android; // mobile browser is either true or false depending on the setting of android when calling the function

      if(substr($android,0,4)=='http'){ // does the value of android resemble a url

        $mobileredirect = $android; // set the mobile redirect url to the url value stored in the android value

      } // ends the if for android being a url

    break; // break out and skip the rest if we've had a match on android

    case (preg_match('/opera mini/i',$user_agent)); // we find opera mini in the user agent

      $mobile_browser = $opera; // mobile browser is either true or false depending on the setting of opera when calling the function

      if(substr($opera,0,4)=='http'){ // does the value of opera resemble a rul

        $mobileredirect = $opera; // set the mobile redirect url to the url value stored in the opera value

      } // ends the if for opera being a url

    break; // break out and skip the rest if we've had a match on opera

    case (preg_match('/blackberry/i',$user_agent)); // we find blackberry in the user agent

      $mobile_browser = $blackberry; // mobile browser is either true or false depending on the setting of blackberry when calling the function

      if(substr($blackberry,0,4)=='http'){ // does the value of blackberry resemble a rul

        $mobileredirect = $blackberry; // set the mobile redirect url to the url value stored in the blackberry value

      } // ends the if for blackberry being a url

    break; // break out and skip the rest if we've had a match on blackberry

    case (preg_match('/(palm os|palm|hiptop|avantgo|plucker|xiino|blazer|elaine)/i',$user_agent)); // we find palm os in the user agent - the i at the end makes it case insensitive

      $mobile_browser = $palm; // mobile browser is either true or false depending on the setting of palm when calling the function

      if(substr($palm,0,4)=='http'){ // does the value of palm resemble a rul

        $mobileredirect = $palm; // set the mobile redirect url to the url value stored in the palm value

      } // ends the if for palm being a url

    break; // break out and skip the rest if we've had a match on palm os

    case (preg_match('/(windows ce; ppc;|windows ce; smartphone;|windows ce; iemobile)/i',$user_agent)); // we find windows mobile in the user agent - the i at the end makes it case insensitive

      $mobile_browser = $windows; // mobile browser is either true or false depending on the setting of windows when calling the function

      if(substr($windows,0,4)=='http'){ // does the value of windows resemble a rul

        $mobileredirect = $windows; // set the mobile redirect url to the url value stored in the windows value

      } // ends the if for windows being a url

    break; // break out and skip the rest if we've had a match on windows

    case (preg_match('/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|vodafone|o2|pocket|kindle|mobile|pda|psp|treo)/i',$user_agent)); // check if any of the values listed create a match on the user agent - these are some of the most common terms used in agents to identify them as being mobile devices - the i at the end makes it case insensitive

      $mobile_browser = true; // set mobile browser to true

    break; // break out and skip the rest if we've preg_match on the user agent returned true

    case ((strpos($accept,'text/vnd.wap.wml')>0)||(strpos($accept,'application/vnd.wap.xhtml+xml')>0)); // is the device showing signs of support for text/vnd.wap.wml or application/vnd.wap.xhtml+xml

      $mobile_browser = true; // set mobile browser to true

    break; // break out and skip the rest if we've had a match on the content accept headers

    case (isset($_SERVER['HTTP_X_WAP_PROFILE'])||isset($_SERVER['HTTP_PROFILE'])); // is the device giving us a HTTP_X_WAP_PROFILE or HTTP_PROFILE header - only mobile devices would do this

      $mobile_browser = true; // set mobile browser to true

    break; // break out and skip the final step if we've had a return true on the mobile specfic headers

    case (in_array(strtolower(substr($user_agent,0,4)),array('1207'=>'1207','3gso'=>'3gso','4thp'=>'4thp','501i'=>'501i','502i'=>'502i','503i'=>'503i','504i'=>'504i','505i'=>'505i','506i'=>'506i','6310'=>'6310','6590'=>'6590','770s'=>'770s','802s'=>'802s','a wa'=>'a wa','acer'=>'acer','acs-'=>'acs-','airn'=>'airn','alav'=>'alav','asus'=>'asus','attw'=>'attw','au-m'=>'au-m','aur '=>'aur ','aus '=>'aus ','abac'=>'abac','acoo'=>'acoo','aiko'=>'aiko','alco'=>'alco','alca'=>'alca','amoi'=>'amoi','anex'=>'anex','anny'=>'anny','anyw'=>'anyw','aptu'=>'aptu','arch'=>'arch','argo'=>'argo','bell'=>'bell','bird'=>'bird','bw-n'=>'bw-n','bw-u'=>'bw-u','beck'=>'beck','benq'=>'benq','bilb'=>'bilb','blac'=>'blac','c55/'=>'c55/','cdm-'=>'cdm-','chtm'=>'chtm','capi'=>'capi','comp'=>'comp','cond'=>'cond','craw'=>'craw','dall'=>'dall','dbte'=>'dbte','dc-s'=>'dc-s','dica'=>'dica','ds-d'=>'ds-d','ds12'=>'ds12','dait'=>'dait','devi'=>'devi','dmob'=>'dmob','doco'=>'doco','dopo'=>'dopo','el49'=>'el49','erk0'=>'erk0','esl8'=>'esl8','ez40'=>'ez40','ez60'=>'ez60','ez70'=>'ez70','ezos'=>'ezos','ezze'=>'ezze','elai'=>'elai','emul'=>'emul','eric'=>'eric','ezwa'=>'ezwa','fake'=>'fake','fly-'=>'fly-','fly_'=>'fly_','g-mo'=>'g-mo','g1 u'=>'g1 u','g560'=>'g560','gf-5'=>'gf-5','grun'=>'grun','gene'=>'gene','go.w'=>'go.w','good'=>'good','grad'=>'grad','hcit'=>'hcit','hd-m'=>'hd-m','hd-p'=>'hd-p','hd-t'=>'hd-t','hei-'=>'hei-','hp i'=>'hp i','hpip'=>'hpip','hs-c'=>'hs-c','htc '=>'htc ','htc-'=>'htc-','htca'=>'htca','htcg'=>'htcg','htcp'=>'htcp','htcs'=>'htcs','htct'=>'htct','htc_'=>'htc_','haie'=>'haie','hita'=>'hita','huaw'=>'huaw','hutc'=>'hutc','i-20'=>'i-20','i-go'=>'i-go','i-ma'=>'i-ma','i230'=>'i230','iac'=>'iac','iac-'=>'iac-','iac/'=>'iac/','ig01'=>'ig01','im1k'=>'im1k','inno'=>'inno','iris'=>'iris','jata'=>'jata','java'=>'java','kddi'=>'kddi','kgt'=>'kgt','kgt/'=>'kgt/','kpt '=>'kpt ','kwc-'=>'kwc-','klon'=>'klon','lexi'=>'lexi','lg g'=>'lg g','lg-a'=>'lg-a','lg-b'=>'lg-b','lg-c'=>'lg-c','lg-d'=>'lg-d','lg-f'=>'lg-f','lg-g'=>'lg-g','lg-k'=>'lg-k','lg-l'=>'lg-l','lg-m'=>'lg-m','lg-o'=>'lg-o','lg-p'=>'lg-p','lg-s'=>'lg-s','lg-t'=>'lg-t','lg-u'=>'lg-u','lg-w'=>'lg-w','lg/k'=>'lg/k','lg/l'=>'lg/l','lg/u'=>'lg/u','lg50'=>'lg50','lg54'=>'lg54','lge-'=>'lge-','lge/'=>'lge/','lynx'=>'lynx','leno'=>'leno','m1-w'=>'m1-w','m3ga'=>'m3ga','m50/'=>'m50/','maui'=>'maui','mc01'=>'mc01','mc21'=>'mc21','mcca'=>'mcca','medi'=>'medi','meri'=>'meri','mio8'=>'mio8','mioa'=>'mioa','mo01'=>'mo01','mo02'=>'mo02','mode'=>'mode','modo'=>'modo','mot '=>'mot ','mot-'=>'mot-','mt50'=>'mt50','mtp1'=>'mtp1','mtv '=>'mtv ','mate'=>'mate','maxo'=>'maxo','merc'=>'merc','mits'=>'mits','mobi'=>'mobi','motv'=>'motv','mozz'=>'mozz','n100'=>'n100','n101'=>'n101','n102'=>'n102','n202'=>'n202','n203'=>'n203','n300'=>'n300','n302'=>'n302','n500'=>'n500','n502'=>'n502','n505'=>'n505','n700'=>'n700','n701'=>'n701','n710'=>'n710','nec-'=>'nec-','nem-'=>'nem-','newg'=>'newg','neon'=>'neon','netf'=>'netf','noki'=>'noki','nzph'=>'nzph','o2 x'=>'o2 x','o2-x'=>'o2-x','opwv'=>'opwv','owg1'=>'owg1','opti'=>'opti','oran'=>'oran','p800'=>'p800','pand'=>'pand','pg-1'=>'pg-1','pg-2'=>'pg-2','pg-3'=>'pg-3','pg-6'=>'pg-6','pg-8'=>'pg-8','pg-c'=>'pg-c','pg13'=>'pg13','phil'=>'phil','pn-2'=>'pn-2','pt-g'=>'pt-g','palm'=>'palm','pana'=>'pana','pire'=>'pire','pock'=>'pock','pose'=>'pose','psio'=>'psio','qa-a'=>'qa-a','qc-2'=>'qc-2','qc-3'=>'qc-3','qc-5'=>'qc-5','qc-7'=>'qc-7','qc07'=>'qc07','qc12'=>'qc12','qc21'=>'qc21','qc32'=>'qc32','qc60'=>'qc60','qci-'=>'qci-','qwap'=>'qwap','qtek'=>'qtek','r380'=>'r380','r600'=>'r600','raks'=>'raks','rim9'=>'rim9','rove'=>'rove','s55/'=>'s55/','sage'=>'sage','sams'=>'sams','sc01'=>'sc01','sch-'=>'sch-','scp-'=>'scp-','sdk/'=>'sdk/','se47'=>'se47','sec-'=>'sec-','sec0'=>'sec0','sec1'=>'sec1','semc'=>'semc','sgh-'=>'sgh-','shar'=>'shar','sie-'=>'sie-','sk-0'=>'sk-0','sl45'=>'sl45','slid'=>'slid','smb3'=>'smb3','smt5'=>'smt5','sp01'=>'sp01','sph-'=>'sph-','spv '=>'spv ','spv-'=>'spv-','sy01'=>'sy01','samm'=>'samm','sany'=>'sany','sava'=>'sava','scoo'=>'scoo','send'=>'send','siem'=>'siem','smar'=>'smar','smit'=>'smit','soft'=>'soft','sony'=>'sony','t-mo'=>'t-mo','t218'=>'t218','t250'=>'t250','t600'=>'t600','t610'=>'t610','t618'=>'t618','tcl-'=>'tcl-','tdg-'=>'tdg-','telm'=>'telm','tim-'=>'tim-','ts70'=>'ts70','tsm-'=>'tsm-','tsm3'=>'tsm3','tsm5'=>'tsm5','tx-9'=>'tx-9','tagt'=>'tagt','talk'=>'talk','teli'=>'teli','topl'=>'topl','tosh'=>'tosh','up.b'=>'up.b','upg1'=>'upg1','utst'=>'utst','v400'=>'v400','v750'=>'v750','veri'=>'veri','vk-v'=>'vk-v','vk40'=>'vk40','vk50'=>'vk50','vk52'=>'vk52','vk53'=>'vk53','vm40'=>'vm40','vx98'=>'vx98','virg'=>'virg','vite'=>'vite','voda'=>'voda','vulc'=>'vulc','w3c '=>'w3c ','w3c-'=>'w3c-','wapj'=>'wapj','wapp'=>'wapp','wapu'=>'wapu','wapm'=>'wapm','wig '=>'wig ','wapi'=>'wapi','wapr'=>'wapr','wapv'=>'wapv','wapy'=>'wapy','wapa'=>'wapa','waps'=>'waps','wapt'=>'wapt','winc'=>'winc','winw'=>'winw','wonu'=>'wonu','x700'=>'x700','xda2'=>'xda2','xdag'=>'xdag','yas-'=>'yas-','your'=>'your','zte-'=>'zte-','zeto'=>'zeto','acs-'=>'acs-','alav'=>'alav','alca'=>'alca','amoi'=>'amoi','aste'=>'aste','audi'=>'audi','avan'=>'avan','benq'=>'benq','bird'=>'bird','blac'=>'blac','blaz'=>'blaz','brew'=>'brew','brvw'=>'brvw','bumb'=>'bumb','ccwa'=>'ccwa','cell'=>'cell','cldc'=>'cldc','cmd-'=>'cmd-','dang'=>'dang','doco'=>'doco','eml2'=>'eml2','eric'=>'eric','fetc'=>'fetc','hipt'=>'hipt','http'=>'http','ibro'=>'ibro','idea'=>'idea','ikom'=>'ikom','inno'=>'inno','ipaq'=>'ipaq','jbro'=>'jbro','jemu'=>'jemu','java'=>'java','jigs'=>'jigs','kddi'=>'kddi','keji'=>'keji','kyoc'=>'kyoc','kyok'=>'kyok','leno'=>'leno','lg-c'=>'lg-c','lg-d'=>'lg-d','lg-g'=>'lg-g','lge-'=>'lge-','libw'=>'libw','m-cr'=>'m-cr','maui'=>'maui','maxo'=>'maxo','midp'=>'midp','mits'=>'mits','mmef'=>'mmef','mobi'=>'mobi','mot-'=>'mot-','moto'=>'moto','mwbp'=>'mwbp','mywa'=>'mywa','nec-'=>'nec-','newt'=>'newt','nok6'=>'nok6','noki'=>'noki','o2im'=>'o2im','opwv'=>'opwv','palm'=>'palm','pana'=>'pana','pant'=>'pant','pdxg'=>'pdxg','phil'=>'phil','play'=>'play','pluc'=>'pluc','port'=>'port','prox'=>'prox','qtek'=>'qtek','qwap'=>'qwap','rozo'=>'rozo','sage'=>'sage','sama'=>'sama','sams'=>'sams','sany'=>'sany','sch-'=>'sch-','sec-'=>'sec-','send'=>'send','seri'=>'seri','sgh-'=>'sgh-','shar'=>'shar','sie-'=>'sie-','siem'=>'siem','smal'=>'smal','smar'=>'smar','sony'=>'sony','sph-'=>'sph-','symb'=>'symb','t-mo'=>'t-mo','teli'=>'teli','tim-'=>'tim-','tosh'=>'tosh','treo'=>'treo','tsm-'=>'tsm-','upg1'=>'upg1','upsi'=>'upsi','vk-v'=>'vk-v','voda'=>'voda','vx52'=>'vx52','vx53'=>'vx53','vx60'=>'vx60','vx61'=>'vx61','vx70'=>'vx70','vx80'=>'vx80','vx81'=>'vx81','vx83'=>'vx83','vx85'=>'vx85','wap-'=>'wap-','wapa'=>'wapa','wapi'=>'wapi','wapp'=>'wapp','wapr'=>'wapr','webc'=>'webc','whit'=>'whit','winw'=>'winw','wmlb'=>'wmlb','xda-'=>'xda-',))); // check against a list of trimmed user agents to see if we find a match

      $mobile_browser = true; // set mobile browser to true

    break; // break even though it's the last statement in the switch so there's nothing to break away from but it seems better to include it than exclude it

  } // ends the switch

  // tell adaptation services (transcoders and proxies) to not alter the content based on user agent as it's already being managed by this script

  header('Cache-Control: no-transform');

  header('Vary: User-Agent, Accept');

  // if redirect (either the value of the mobile or desktop redirect depending on the value of $mobile_browser) is true redirect else we return the status of $mobile_browser

  if($redirect = ($mobile_browser==true) ? $mobileredirect : $desktopredirect){

    header('Location: '.$redirect); // redirect to the right url for this device

    exit;

  }else{

    return $mobile_browser; // will return either true or false

  }

} // ends function mobile_device_detect

?>
</code>
Ai no index do seu site faço assim:
<code><?php
    include('mobile_device_detect.php');
           mobile_device_detect(true,true,true,true,true,true,'../mobile/index.php',false); ?>
    <html>
        ...pagina com aviso que so funciona em mobile
    </html>
</code>
Comment: interessante... vou testar
Answer: Acho que não seria "apenas em dispositivos moveis" e sim responsivo.
Entendendo o seu lado, creio que você gostaria que ele fosse utilizado apenas em dispositivos mobile e caso algum desktop acesse não seja exibido certo?
Nunca vi um site apenas para mobile (inacessível via site).
Acho que seria interessante você desenvolver a aplicação encapsulada ao aplicativo (caso tenha) e não indexado aos mecanismos de busca.
Espero ter ajudado. Fico a disposição para maiores esclarecimentos.
Comment: Eu tenho isso. uma forma para usar com webview, mas eu queria utilizar também como pwa progressive web app


Flutter - How to put this string code into stateless widget or stateful widget?

Question: Example 1
Can someone show me how to add this Example 1 to stateless or stateful widget in Flutter?
Comment: https://stackoverflow.com/help/how-to-ask
Please go through this first
Answer: So you've come across the classic inability to use a variable you've just defined.
Here's the best solution:
Go ahead and define the variable in the class
class _MyHomePageState extends State<MyHomePage> {

  List<String> singleWord = "im so cool".split(" ");
  (...)

}

And then you can use that variable in any function. For example, the "initState" function is called once when the class is initiated, so we can put our usage of the function in that.
class _MyHomePageState extends State<MyHomePage> {

  List<String> singleWord = "im so cool".split(" ");

  @override
  void initState() {
    singleWord.forEach((e) => print(e));
    super.initState();
  }
 (...)

}

If you want to use the same function multiple times then just remove the @override and name the function something that makes sense. E.g. singleWordSplitPrint
However, please do NOT use the variable inside the build method as the build method is called way more than you think - especially when you're just starting out and your setState((){})'s aren't perfect!
Good luck!
Comment: Thank you i got it now! By the way if you don't mind i have another problem which is i tried to display the output in flutter app and fail to do so, do you know how?
Comment: @JoeJoe Could you give me a little more information on what exactly you tried to do? :)


Flutter Stripe does not showing payment sheet on ios device

Question: I'm attempting to integrate a Stripe payment using flutter_stripe package. but it is throwing an error
Error
Unhandled Exception: StripeException(error: LocalizedErrorMessage(code: FailureCode.Failed, localizedMessage: No payment sheet has been initialized yet, message: No payment sheet has been initialized yet, stripeErrorCode: null, declineCode: null, type: null))
(This error is showing only for ios device, but working fine on android device.)
services.dart
payNow() async {
try{
  Map<String, dynamic> stripeData = widget.paymentData;
  print("stripeData===== ${stripeData['stripeCustomerId']}");
  Stripe.publishableKey = Constants.stripeKey;
  Stripe.merchantIdentifier = Constants.merchantId;
  await Stripe.instance.applySettings();
  await Stripe.instance.initPaymentSheet(
    paymentSheetParameters: SetupPaymentSheetParameters(
        paymentIntentClientSecret: stripeData['paymentIntentSecret'],
        merchantDisplayName: 'Courses',
        customerId: stripeData['stripeCustomerId'],
        customerEphemeralKeySecret: stripeData['ephemeralKey'],
        applePay: true),
  );
  await Stripe.instance.presentPaymentSheet();
  widget.submitData();
} on Exception catch (e) {
  if (e is StripeException) {
    print("Error from Stripe: ${e.error.localizedMessage}");
  } else {
    print("Unforeseen error: $e");
  }
  rethrow;
}

}

main.dart
void main() async {
WidgetsFlutterBinding.ensureInitialized();
Stripe.publishableKey = Constants.stripeKey;
Stripe.merchantIdentifier= Constants.merchantId;
Stripe.urlScheme = 'flutterstripe';
await Stripe.instance.applySettings();
runApp(MyApp());
}

please help me to solve this error
Comment: stripeData = widget.paymentData;  Is it coming properly from the backend?
Comment: Yes, data is coming properly
Comment: Infact, payment sheet is showing in android device but not on ios device
Comment: Try `applePay: false` to make sure that there is no hidden integration problem with Apple.
Answer: I solved this problem by adding the merchantCountryCode parameter in initPaymentSheet().
Comment: That's very cool you've solved it by your own. I would suggest edit your question, or add your approach as a comment. this is the most common way and keep it clear for readers.


Clarification on tribonacci numbers exercise

Question: From what I know the Tribonacci sequence is given by:
T(n) = T(n-1) + T(n-2) + T(n-3)
My book says that "We can show by induction that for large enough n, the Fibonacci numbers  satisfy the inequality (1.6)n < F(n) < (1.7)n."
Which of these four functions is the largest that is eventually smaller than T(n)?
Select one:
a. $(1.9)^n$
b. $2^n$
c. $(1.7)^n$
d. $(1.8)^n$
I am not looking for the answer but for way to approach this. I am confused by what is actually asking.
Comment: are those meant to be exponents?
Comment: yes. Sorry I fixed that.
Comment: Actual condition for ${x^n \over T(n)} \to 0$ is $x^3-x^2-x-1 < 0$ (which gives answer (d)), but I don't know how you're supposed to get right result from Fibonacci sequence analysis.
Comment: The limiting ratio for the "Tribonacci" sequence will be $\approx 1.84$, the solution of greatest magnitude to the equation $x^3 - x^2 - x - 1 < 0$
Answer: I can show the powers of $2$ grow faster than $T(n)$.
If I start off $T(n-3)=2^{n-3},T(n-2)=2^{n-2},T(n-1)=2^{n-1}$ then
$$T(n)=T(n-1)+T(n-2)+T(n-3)=\frac{2^n}2+\frac{2^n}4+\frac{2^n}8=\frac782^n$$
So $T(n)$ has started to lag behind powers of $2$.
On the other hand, if I start them off $T(n-1)=1.5^{n-1}$, and so on, I find that $$T(n)=\frac{1.5^n}{1.5}+\frac{1.5^n}{1.5^2}+\frac{1.5^n}{1.5^3}>1.5^n$$
so $T(n)$ has started to leap ahead of $1.5^n$


Erro ao separar arrays em PHP

Question: Tenho uma classe de PHP responsável pelo envio de notas fiscais, no entanto ela retorna o seguinte erro, como se estivesse tentando passar um array pra variável:

[13-Mar-2018 14:08:26 America/Sao_Paulo] PHP Notice:  Array to string conversion in C:\...ToolsNFePHP.class.php on line 5212

Pelo código, a variável $msg já deveria enviar uma string, já tentei converter de Array para String, mas o erro continua.
Segue o código:
/**
 * pSetError
 * Adiciona descrição do erro ao contenedor dos erros
 *
 * @name pSetError
 * @param   string $msg Descrição do erro
 * @return  none
 */
private function pSetError($msg)
{
    $this->errMsg .= "$msg\n";
    $this->errStatus = true;
}

Isso acontece apenas nesse caso, outros objetos enviam funcionam normalmente. Acredito que possa estar agregando mais de uma mensagem de erro na mesma variável e ocasionando o erro, mas sem vê-lo não consigo corrigir.
Comment: Possível duplicata de [Erros de Array to string conversion in em função PHP](https://pt.stackoverflow.com/questions/282584/erros-de-array-to-string-conversion-in-em-fun%c3%a7%c3%a3o-php)
Comment: Na verdade você está tentando concatenar os valores do array e não explodi/separar. Provavelmente você está passando uma *String* para o método `pSetError`, enquanto o correto seria passar um *Array*.
Comment: O código parece correto o que pode estar errado é argumento na chamada do método.
Comment: Utilize uma *string* ao invés de um *array*. Você pode utilizar o `implode(",", $array);` antes de acessar a função.
Answer: O erro que está dando  ( Array to string conversion ), você ta tentando separar um uma String em um Array, que são coisas diferentes.
    private function pSetError($msg = array())
{
    $MsgErro = explode(',', $msg);
    $this->errMsg .= "$MsgErro\n";
    $this->errStatus = true;
}

implode — Junta elementos de uma matriz em uma string
  Implode
explode — Divide uma string em strings
  Explode

Explode e Implode serve para "Strings" e não Array, caso queria quebrar o Array em "pedaços", você pode usar o array_chunk. Com ele você pode quebrar em vários pedaços que desejar;
$input_array = array('a', 'b', 'c', 'd', 'e');
print_r(array_chunk($input_array, 2));
print_r(array_chunk($input_array, 2, true));

Saída do código acima:
Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
        )

    [1] => Array
        (
            [0] => c
            [1] => d
        )

    [2] => Array
        (
            [0] => e
        )

)
Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
        )

    [1] => Array
        (
            [2] => c
            [3] => d
        )

    [2] => Array
        (
            [4] => e
        )

)

Você pode também usar o array_slice
$input = array("a", "b", "c", "d", "e");

$output = array_slice($input, 2);      // returns "c", "d", and "e"
$output = array_slice($input, -2, 1);  // returns "d"
$output = array_slice($input, 0, 3);   // returns "a", "b", and "c"

print_r(array_slice($input, 2, -1));
print_r(array_slice($input, 2, -1, true));

O código a cima sairá assim:
Array
(
    [0] => c
    [1] => d
)
Array
(
    [2] => c
    [3] => d
}

Comment: Obrigado, reavaliando o código realmente ele deveria estar enviando uma string já, e não um array.
Comment: acabei editando a questão... acredito que agora fica mais claro.

Erro ao separar arrays em PHP


How to bind function fish shell plugin

Question: I'm trying to write a plugin for the fish shell but can't get it to work.
I have the following in a file called functions/codex.fish:
function create_completion
    commandline -a test
end

bind \cx create_completion

I installed the plugin using fisher:
tom@desktop-20-3 ~/g/b/z/update_insert (main)> fisher install ~/git/codex.fish/
fisher install version 4.3.1
Installing /home/tom/git/codex.fish
           /home/tom/.config/fish/functions/codex.fish
Updated 1 plugin/s

However when I try to run the function using Ctrl+x nothing happens.
What am I doing wrong?
Answer:
I have the following in a file called functions/codex.fish:

There's your problem. Fish functions are lazily loaded. A file called "codex.fish" will be loaded once a function called "codex" is executed for the first time.
So those bindings will only be defined after you've run "codex" once in that session (unless there's another codex.fish that has precedence, in which case they won't be defined at all).
Simply add the binding to config.fish, or one of the eagerly loaded files in ~/.config/fish/conf.d.
Answer: You don't need plugins to set up key bindings. Here is one way to do it:

Create your function:

function create_completion
     commandline -a test
end

Save it to disk:

funcsave create_completion

(This creates the file ~/.config/fish/functions/create_completion.fish; you can also do that manually.)

Run funced fish_user_key_bindings and add your binding:

function fish_user_key_bindings
    bind \cx create_completion
end

Now control-X should execute the function.
Comment: `fish_user_key_bindings` hasn't been necessary since fish 3.0. It'll still *work*, but nowadays you can also drop the `bind` statements directly into config.fish

How to bind function fish shell plugin


Add javascript to a specific node

Question: I want to add some extra javascript (few files stored in my account, and some inline javascript) for a specific node. Based on the answer to this question, I tried adding a few files to the node alias "insert-pub" by doing this in the template.php in /themes/garland (just trying out the garland theme for now):
  function garland_preprocess_node(&$vars) {
     // The line below was already there.
     $vars['submitted'] = $vars['date'] . ' — ' . $vars['name'];
     // Added the lines below.
     // Want to include my javascript files and inline scripts for specific nodes.
     $node =& $vars['node'];
     debug($node);
     debug($node->type);
     if ($node->type == 'insert-pub')
     {
          drupal_add_js('/sites/all/scripts/MyLib.js', array('type' => 'file', 'scope' => 'header'));
          drupal_add_js('/sites/all/scripts/Utils.js', array('type' => 'file', 'scope' => 'header'));
          drupal_add_js('var MyAjaxLib=new MyLib();
               function loadInput(){ alert("Hello"); }', 'inline');
     }
}

But I never see the links to the JS files or inline JS scripts in the source of the page, when I load the page in the browser by going to [www.mysite.com/insert-pub]. Where am I going wrong? Even the debug() calls above does not seem to print anything in the browser.
I am a Drupal 7 newbie, so looking forward to some hand-holding. Thanks.
Answer: The node type will always have an underscore as the separator (not a dash) between words so the test would be:
if ($node->type == 'insert_pub') {
  // ...
}

But it seems from your question you want to test the URL alias of the node, not the type. To do that you need to use drupal_get_path_alias() to get the node's alias, and see if it matches:
$current_node_alias = drupal_get_path_alias("node/$node->nid");
if ($current_node_alias == 'insert-pub') {
  drupal_add_js('...
}

Make sure you've cleared Drupal's caches so the new preprocess hook can be picked up by the system. That's the only reason I can think of to explain the calls to debug() not working, as they should.

Add javascript to a specific node


Setting a fragment weight attribute for different device resolutions

Question: I'm writing an Android application and for testing I have a 9" tablet with a 1024 * 600 resolution. I only have a few activities and they are all broken into 3 fragments. The top fragment has a weight of .1 and contains the title of the activity. The middle fragment has a weight of .7 and is a scrollview of table rows returned from a query. The bottom fragment has a weight of .2 and contains all the buttons and textviews for user input. I used match_parent and wrap_content with relative layouts where possible. Nothing is hard coded and it looks right.
When I install the app on a 10" tablet with a resolution of 1280 x 800 the bottom fragment takes up more real-estate and there is more empty space around the textviews and buttons. It doesn't look right.
What do I do to accommodate these different resolutions with respect to fragment weights? I read other threads that mentioned creating different folders for images/files and different dimens.xml files. Those threads seemed to address resolutions issues for images and margins.
I want to be able to control how much weight is set based on a screen resolution (low, med, high, etc.).
Answer: Look in the official doc for resource specifiers.  The things you're looking for are smallest width, available width, and available height.  You can bundle resources for certain screen sizes into buckets based on values you define, and use those value in your layouts.  Note that the values are in dp, not actual pixels.
Comment: Thanks @Doug Stevenson.  So I create those folders for each resolution and inside those folder I specify the smallest width, available width and available height.  I'm not sure what file(s) I put the values in?


AWS Glue AccessDeniedException Account  is denied access

Question: I am getting this message when I try to create a crawler on AWS Glue:
<code>{"service":"AWSGlue","statusCode":400,"errorCode":"AccessDeniedException","requestId":"RequestIDNumber","errorMessage":"Account <AccountID> is denied access.","type":"AwsServiceError"}</code>
already attached all those policies below to the IAM
All my Policies here
Already setup permissions to the AWS lake formation for the role too
Already created a custom policy kms to it too
And I am stucked, I cannot create a crawler!
I am in the root account, actually there`s no other account just the root, It's a super new account I created in AWS so I don't know what to do to be able to create this simple crawler
My ideia its to use it with dynamodb as data source
The message says there is something wrong with my account permission not with a role
Someone has an idea?
Thank you so much
Comment: The policies are for IAM role or your IAM user?
Comment: The role! I have just one user created and he has the following permissions: https://drive.google.com/file/d/1M-yntiS7UjrOcavLwoySTMLEbuvqrVCM/view?usp=sharing
Comment: my region is us-east-1
Comment: If your account is supper new, aws sometimes does not allow to access all its services immediately. Also using root account is a vary bad practice, which may explain why AWS cloud be limiting your account in the first place.
Answer: Not sure the reason, but loads of people have been having this issue. You can submit a ticket through AWS account support. I actually submitted two, including one through the unpaid support version and one through my paid account. They answered both tickets.
Basically, just tell them you need access to Glue and they should alter whatever it is to give you access. Sorry it's not a better answer, but I found no other useful information anywhere.
Answer: I propose to  try using a separate user and attaching the policy you created to it.


Evaluate $\lim_{t\rightarrow\infty}\frac{1}{t^{s+2}s+2}$ for $s+2\in\mathbb{R}^+$

Question: I would like to evaluate $$\lim_{t\rightarrow\infty}\frac{1}{t^{s+2}s+2}\tag{1}$$ for $s+2\in\mathbb{R}^+$. I think that the limit approaches $0$, but how may I prove this clearly?
It seems as though $s+2\gg 0$ as the closer $s+2$ is to $0$ the slower it converges to $0$.
Comment: What does mellin-transform even have to do with this?
Comment: @HasanSaad This is part of the result I get when finding the Mellin Transform of a function
Comment: Oh, okay, though I recommend you remove that tag as it's meaningless regarding the question at hand.
Answer: Assume $s>0$.
Let $X$ be the set of all numbers of the form $st^{s+2}$.
Assume $X$ is bounded above, then it must have a supremum $x$.
Thus, there exists a number $y$ such that
$\frac{x}{s+1}<s(\frac{y+1}{\sqrt[s+2]{s+1}})^{s+2}<x$ by the definition of the supremum and noting that  $s(\frac{y+1}{\sqrt[s+2]{s+1}})^{s+2}\in X$ by taking $t=\frac{y+1}{\sqrt[s+2]{s+1}}$
Multiplying all sides by $s+1$, we get
$x<s(y+1)^{s+2}<x(s+1)$
Thus, $x$ is not an upper bound, and thus the set is unbounded above, meaning that the limit of the denominator is $+\infty$ by noting that it the denominator is increasing as a function of $t$. Now, it is obvious that the limit is $0$.
The case where $s<0$ can be proved analogously by using the properties of boundedness below and infimum.
Answer: If $s=0$, then your limit is $\frac 1 2$. If $s<0$ then it is $\frac 1 {-\infty} = 0$. If $s>0$ then it is $\frac 1 \infty = 0$. Don't worry, just use the arithmetic rules for dealing with $\infty$, they are absolutely rigorous. It would be useful to specify whether $0 \in \mathbb R ^+$, since this notation may mean different things in different countries.
Comment: He said "prove this", not "handwavy understand" this...Even if you use $\frac{1}{\infty}$, the problem is that you haven't even proved that the denominator goes to $\infty$ which is technically the gist of the whole proof...
Comment: @HasanSaad: I beg to disagree. To me, a computation _is_ a proof, as long as it is correctly done (and mine is). Even in textbooks for simple results you will encounter something like "proof: straight computation".
Comment: @HasanSaad: Wait a second: you mean that the OP asked for a proof of the fact that $\lim \limits _{t \to \infty} t^n = \infty$ when $n>0$? Come on!...
Comment: That is actually what I understood from his question. I'm pretty sure he doesn't mean dividing by $\infty$... Though in any case, OP's question still seems pretty trivial and I have no idea why anyone would ask such a question...
Comment: Or maybe he got all confused because of the presence of $s$ or whatever...
Comment: @HasanSaad: I agree with you; since the OP was asking this question in the context of working with the Mellin transform, I assume that he has at least a basic understanding of real analysis. Anyway, it is the OP's duty to step in and clarify the meaning of his question, not ours.
Comment: I doubt OP will even come anymore...
Comment: @HasanSaad I had to go to class. No, I have not taken Real Analysis, which is why I was looking for some help. You guys sure have cleared it up though between your comments and answers. I realized after I asked it was probably a bit trivial and tried to fill in a bit where my confusion was.
Comment: @jm324354: Real Analysis is the basis of it all. It wouldn't make sense to take other mathematics subjects without studying the fundamentals. It would be a serious mistake that would leave you with a significant mathematical vulnerability. Please consider this when choosing your study program.
Comment: @AlexM. Thanks for your suggestions. I'm at a community college until the end of the year, when I will achieve my Assc. in math, after which I will transfer to a nearby university (and I WILL be taking Real Analysis and as many other higher-level courses they have to offer). I was looking at their math programs about 20 minutes ago and I can't wait to finish up and get to the good stuff.


c# linq if item is in list and get matching items from list

Question: If my list contains: english cat, french cat, japanese dog, spanish dog
and I have an item: dog
Not only do I want to see if the list contains my item, but return the items that match, so I would expect: japanese dog, spanish dog
I have got as far as seeing if the item is in the list using the following code:
if (myList.Any(myItem.ToLower().Contains)) { }

Comment: try this:  var movies = _db.Movies.Where(p => p.Genres.Intersect(listOfGenres).Any());
https://stackoverflow.com/questions/10667675/linq-where-list-contains-any-in-list
Comment: If it's a list of strings, then I think `List results = myList.Where(item => item.ToLower.Contains("dog");` would do the trick.
Answer: I think you are looking for something like this, using the where clause:
string filter = "dog";
IEnumerable<string> filteredItems = myList.Where(m => m.ToLower().Contains(filter.ToLower()));

Answer: var myList = new List<string>() { " japanese dog", "spanish dog", "english cat", "french cat" };
var dog = "Dog";

if (myList.Any(t=>t.Contains(dog.ToLower()))) {
    var result = myList.Where(t => t.Contains(dog.ToLower())).ToList();
}

Answer: I like to use regex and to do that such as for dogs:
var animals = new List<string>()
               { "japanese dog", "spanish dog", "english cat", "french cat" };

var dogs = animals.Where(type => Regex.IsMatch(type, "dog", RegexOptions.IgnoreCase))
                  .ToList();

// Returns {"japanese dog",  "spanish dog" }

Why Regex you may ask, because its flexible and powerful...let me show:
Let us do some more advance linq work by having them sorted using the ToLookup extension and regex such as
var sortedbyDogs
            = animals.ToLookup(type => Regex.IsMatch(type, "dog", RegexOptions.IgnoreCase));

which is grouped in memory like this:

Then just extract cats such as
var cats = sortedbyDogs[false].ToList()

then pass in true for dogs.

But why split it by a boolean, what if there are more animals? Lets add a lemur to the list such as … "french cat", "Columbian Lemur" }; we do this:
var sorted = animals.ToLookup(type => Regex.Match(type,
                                                  "(dog|cat|lemur)",
                                                  RegexOptions.IgnoreCase).Value);

Then to get our cats, here is the code:
sorted["cat"].ToList()


postfix TLS: handshake failure

Question: My new DSL provider is fastweb
cat /etc/postfix/main.cf
[...]
relayhost = smtp.fastwebnet.it:587
smtp_sasl_auth_enable = yes
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd

cat /etc/postfix/sasl_passwd
smtp.fastwebnet.it      email@example.com:pass

Sep  2 16:35:30 server1 postfix/cleanup[11161]: 26AC92820A0: info: header Subject: asd from local; from=<email@example.com> to=<firstname.lastname@example.com>
Sep  2 16:35:30 server1 postfix/cleanup[11161]: 26AC92820A0: message-id=<firstname.lastname@example.com>
Sep  2 16:35:30 server1 postfix/qmgr[11150]: 26AC92820A0: from=<email@example.com>, size=425, nrcpt=1 (queue active)
Sep  2 16:35:32 server1 postfix/smtp[11158]: SSL_connect error to smtp.fastwebnet.it[18.104.22.168]:587: -1
Sep  2 16:35:32 server1 postfix/smtp[11158]: warning: TLS library problem: error:14094410:SSL routines:ssl3_read_bytes:sslv3 alert handshake failure:../ssl/record/rec_layer_s3.c:1399:SSL alert number 40:
Sep  2 16:35:32 server1 postfix/smtp[11158]: 26AC92820A0: to=<email@example.com>, relay=smtp.fastwebnet.it[188.8.131.52]:587, delay=1.9, delays=0.12/0/1.8/0, dsn=4.7.5, status=deferred (Cannot start TLS: handshake failure)

Answer: You likely have this in your main.cf configuration:
   smtpd_use_tls = yes

comment it and you will solve the problem
Comment: did  you mean `smtp_use_tls`? I commented as you suggested and I couldn't log into postfix.  commenting out my alternative didn't solve the problem

postfix TLS: handshake failure


Uploading an image to linux server returning 500 error

Question: I have two server's server A and server B
I have a registration page which have username,*email*,password and an image.
I am using a simple php script to upload the image sent from an ios device.
I am able to register the new user to server A. Image upload works well in the following cases
Case 1: Uploading via HTML (Success)
Case 2: Uploading Via app (Success)

But when trying to upload the image to server B (LINUX server) image uploading failed.
Case 1: Uploading via HTML (Success)
Case : Uploading via app (FAILED)

I have made sure file permissions are 777. But still i am unable to upload the image to server. It is returning 500 Internal error.
Actually, The uploading to Server B used to work earlier. But all of a sudden it stopped working.
Can any one suggest me what more conditions should i check to make sure image will upload?
Answer: Try using CURL
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, array('file' => '@/path/file.txt'));
    curl_setopt($ch, CURLOPT_URL, 'http://server2/upload.php');
    curl_exec($ch);
    curl_close($ch);

Answer: Setting the permission on file alone won't solve the purpose.Make sure you have set directory for upload_tmp_dirin php.ini to writable by whatever user php is running.
Check with sys_get_temp_dir() what it returns,make sure returned path is writable.
If you can ssh to your linux server you check the permission on temp directory by following command
$ls -ld temp_dir_path_here

Of course there could be other problems causing the failure.You can get more information by checking you server error logs or set errors on by copying following snippet at top of your script
error_reporting(E_ALL);
ini_set('display_errors', 'on');

Remove above snippet when done.
Comment: Echoing temp dir is giving some encrypted folder name.
Comment: What exactly it's echoing?
Comment: YuIMg ,when i refresh folder name changes every time.
Comment: Ok `sys_get_temp_dir()` might be returning wrong value due to virtual-hosts problem.Still you should see relavant error in your log. What on page errors saying? Did you check your error logs?Else it would be difficult to tell the exact issue
Comment: Hmm i think its a .htacess file issue.


Derive Outer Measure from $\sigma$-Algebra

Question: It is well-known that an outer measure $\mu$ gives rise to a $\sigma$-algebra given by $$\mathcal A_\mu = \left\{Q\subseteq\Omega : \mu(X) = \mu(X\cap Q) + \mu(X\cap Q^\complement)\;\;\text{for each $X\subseteq \Omega$}\right\}.$$
Now, I wonder, given a $\sigma$-algebra $\mathcal F$, does that imply (maybe with some additional requirements?) that there exists an outer measure that fully describes $\mathcal F$.
In other words, can a $\sigma$-algebra be characterized by an outer measure and vice versa.
Comment: Have you correctly quoted the definition of $\mathcal A_\mu$? In particular, is it really $Q$ and not $X$ that you want the complement of?  And should $Q$ perhaps be an arbitrary subset of $\Omega$ rather than of $X$?
Comment: thank you, I mixed up some things while writing it down... sorry — it is fixed now.
Answer: I'll show the answer is "yes" for finite, countably infinite, and some nice uncountable spaces $\Omega$.
Precisely, the pairs $(\Omega,\mathcal{F})$ that I'll show it for are the ones such that there exist some collection $\{E_\alpha\}_\alpha$ of disjoint elements of $\mathcal{F}$ such that any element of $\mathcal{F}$ is a union of a subcollection of $\{E_\alpha\}_\alpha$. It's not too hard to show that any sigma-algebra for a finite or countably infinite $\Omega$ have this property. [Details at the end].
Suppose $\mathcal{F} = \sigma(\{E_\alpha\}_\alpha)$ for some collection of disjoint subsets $E_\alpha$ of $\Omega$. Define $\mu : \mathcal{P}(\Omega) \to [0,\infty]$ via $\mu(A) = \#\{\alpha: A \cap E_\alpha \not = \emptyset\}$. It's easy to see that $\mu$ is indeed an outer measure. We first show any set $F \in \mathcal{F}$ is $\mu$-measurable. Take $F \in \mathcal{F}$ and write $F = \cup_\beta E_{\beta}$ for some subcollection $\{\beta\}$ of $\{\alpha\}$. Take any $A \subseteq \Omega$. Then $\mu(A \cap F) = \#\{\alpha : A \cap F \cap E_\alpha\} = \#\{\beta : A \cap E_\beta \not = \emptyset\}$. And similarly, $\mu(A \cap F^c) = \#\{\alpha \not \in \{\beta\} : A \cap E_\alpha \not = \emptyset\}$. So, $\mu(A \cap F) + \mu(A \cap F^c) = \mu(A)$, as desired. Now take $F \not \in \mathcal{F}$. Then there is some $\alpha$ and $x,y \in E_\alpha$ such that $x \in F$ but $y \not \in F$. Letting $A = \{x,y\}$, we see that $\mu(A) = 1$ while $\mu(A \cap F)+\mu(A \cap F^c) = 1+1 = 2$. Therefore, each $F \not \in \mathcal{F}$ is not $\mu$-measurable.

I'll quickly show that any finite or countably infinite set $\Omega$ has the property described above. For each $x \in \Omega$, let $F_x = \cap \{F \in \mathcal{F} : F \ni x\}$. The crucial part is that $F_x \in \mathcal{F}$ if $\Omega$ is finite or countably infinite. If $\Omega$ is finite, this is obvious. If $\Omega$ is countably infinite, then although the intersection might be taken over an uncountable set, it's still easy to see that $F_x \in \mathcal{F}$, since we only need to intersect a countable number of $F$'s containing $x$ [think about this].
We show that for $x \not = y \in \Omega$ either $F_x = F_y$ or $F_x \cap F_y = \emptyset$. Let $F := F_x \cap F_y$ and suppose $F \not = \emptyset$. If $x \in F$, then by minimality, we must have $F = F_x$, which implies $F_x \subseteq F_y$. Then, unless $F_x = F_y$, we must have $y \not \in F_x$, in which case $F_y \setminus F_x$ is a smaller element of $F$ containing $y$, a contradiction. So, $x \not \in F$. But then $F_x \setminus F_y$ is an element of $\mathcal{F}$ containing $x$ and is a subset of $F_x$; so it must be $F_x$. But this means $F_x \cap F_y = \emptyset$, a contradiction.
Our collection $\{E_\alpha\}_\alpha$ is just $\{F_x : x \in \Omega\}$ (we remove duplicates). Each pair of sets in this collection are disjoint, and for any $A \in \mathcal{F}$, $A = \cup_{x \in A} F_x$.

I'm not sure whether any sigma-algebra has this disjoint collection property. I'll think more about it.
ADDED: I think a necessary and sufficient condition on $(\Omega,\mathcal{F})$ for the existence of such a $\mu$ is that for each $x \in \Omega$, the intersection of all elements of $\mathcal{F}$ containing $x$ lies in $\mathcal{F}$. We already showed this condition is sufficient. To see that it is necessary, it suffices to show that for each $x \in \Omega$ the set $\cap_{\substack{F \in \mathcal{F} \\ F \ni x}} F$ is $\mu$-measurable for any outer measure $\mu$ making each element of $\mathcal{F}$ $\mu$-measurable. The proof of this I think should be along the same lines as the proof that the set of all $\mu$-measurable sets form a sigma-algebra.


Drupal error. Drupal safe mode possible?

Question: I added organic groups module to a drupal website. For some reason the website crashed and gives the following error:
Fatal error: Unsupported operand types in /home/content/39/7384539/html/salvare12/sites/default/modules/og/includes/og.info inc on line 115

I removed the organic groups module manually and disabled it in the database. But then it gives a file missing error. I have uploaded the organic groups module once again but it does not work.
How can this be fixed? Is there some safe mode in drupal, to which i can revert when such an error occurs?
Comment: Have you run update.php in the URL?
Answer: Try deleting the row for the og module in the system table. Then run a query for each database table beginning with cache_:
TRUNCATE TABLE cache_*

This should make Drupal forget anything it knew about organic groups (this is how to clear the cache manually).
I'd suggest keeping your modules in the standard location which is /sites/all/modules rather than /sites/default. I don't know if thats part of the problem here but it might be.
Answer: Also, I'd get to know drush and use that to disable and uninstall (where available) modules until your site is back up again.


Differentiability of the function $f(z)=|z|^p z$($p>0$).

Question: Suppose $p>0$ in a real number, is the function $f (z) =|z|^p z$ a differentiable function? Moreover, if  $f (z) =|z|^p z$ is differentiable, dose $f$ belong to the space $C^{\left\lfloor p \right\rfloor,p-\left\lfloor p \right\rfloor}(\mathbb{C})$?
P.S. $\left\lfloor p \right\rfloor$ denotes the integer part of $p$.
Comment: Differentiable in what sense? It's real-differentiable, but complex-differentiable only in $z = 0$.
Answer: I assume it's real-differentiability; otherwise see DF's comment. When $p$ is an even integer, $f$ is a polynomial, hence infinitely differentiable. From now on I assume $p$ is not an even integer.
At $z\ne 0$, the function is infinitely smooth (chain rule encounters no obstacle). Observe the homogeneity: $f(tz)=t^{p+1}f(z)$ for $t>0$, and use it to conclude that the total derivative $Df$ is homogeneous of degree $(p+1)-1 = p$.
The $k$ order derivative is homogeneous of degree $p+1-k$.
A function that is homogeneous of degree $d$ is:

differentiable at $0$ (with zero derivative) if $d>1$
not differentiable at $0$ if $d<1$.
not differentiable at $0$ if $d=1$, unless it is a linear function. (The latter won't happen for us since $f$ is not a polynomial.)

All of the above are not hard to prove from the definition of derivative.
Since we begin with homogeneity $p+1$, where $p>0$, the derivative can be taken $\lceil p \rceil $ times before its degree of homogeneity becomes $\le 1$ and the music stops.
So, $f\in C^{\lceil p \rceil, p+1-\lceil p \rceil}$.
Comment: I have another question, dose the following inequality hold?   $$ \| f(u)-f(v) \|\leqslant C (|u|^p+|v|^p)|u-v|,$$ where $C$ is a constant independent of $u$ and $v.$
Comment: @user97573 Yes. Since $\|Df\|$ is homogeneous of degree $p$ (and bounded on the unit circle), it follows that $\|Df(u)\|\le C|u|^p$. Use the Mean Value Inequality $\|f(u)-f(v)\|\le (\sup_{[u,v]}\|Df\| )\,|u-v|$.


How can I find out if an SKTexture is the placeholder image

Question: In SpriteKit, if you load an image with the [SKTexture textureWithImageNamed:] method, it will first search your bundles, then atlases, if it fails to find your texture, it will then create a placeholder image and load it.
Is there a way to find out (without visually checking) if the loaded image is a placeholder?
This doesn't seem like a very "cocoa" way to handle this type of error.
developer.apple.com is down now, so I figured I would pose this question to SO.
Comment: Yes, use SpriteKit-QuickLook from github, then you can see private vars of the texture. There's an ivar that points to the original texture (atlas) if the texture is an atlas texture
Comment: Also, the MissingResource.png is 128x128 - you can compare the texture size if you don't use any textures of that size yourself.
Comment: Did you ever find a good way to do this?  I'm preloading textures and one in thirty launches I get Error Loading Image Resource for 3 or 4 textures.  I've been trying to find any way to find out with code if this happens and then reload them if it does.
Answer: You can check if the atlas contains the image. I created the following method in my AtlasHelper:
+(BOOL) isTextureWithName:(NSString *) name existsInAtlas:(NSString *)atlasName
{
    SKTextureAtlas *atlas = [SKTextureAtlas atlasNamed:atlasName];
    return [atlas.textureNames containsObject:name];
}

Answer: SKTexture has some private properties that would be helpful (see e.g. https://github.com/luisobo/Xcode-RuntimeHeaders/blob/master/SpriteKit/SKTexture.h), but in Swift and during development I'm using this:
extension SKTexture {
    public var isPlaceholderTexture:Bool {
        if size() != CGSize(width: 128, height: 128) {
            return false
        }

        return String(describing: self).contains("'MissingResource.png'")
    }
}

Attention!:
This only works, if you are using a SKTextureAtlas:
let t1 = SKTextureAtlas(named: "MySprites").textureNamed("NonExistingFoo")
// t1.isPlaceholderTexture == true

let t2 = SKTexture(imageNamed: "NonExistingBar")
// t2.isPlaceholderTexture == false

Comment: This question is a bit old, but I will accept this one.
Answer: Here is a Swift version of the answer:
guard let spriteNode = node as? SKSpriteNode,
      let nodeName = spriteNode.name
else { return }

let nextAtlas = SKTextureAtlas(
    named: "2ndPlayer-Skin2")

if nextAtlas.textureNames.contains(
   "\(nodeName)-Skin2.png") { // NEED FULL NAME

     let texture = nextAtlas.textureNamed(
                "\(nodeName)-Skin2")  // DONT NEED FULL

     spriteNode.texture = texture
     spriteNode.size = texture.size()
}

Thankfully this works, of course there's always some "way" right? ;)


Questions on evaluation of $\frac{\zeta'(s)}{\zeta(s)}$ at integer values of s

Question: Question (1): Evaluation at non-negative even integers

Is it true that
$$\frac{\zeta '(2 n)}{\zeta (2 n)}=f(n)\tag{1}$$
where
$$f(n)=-H_{2 n-1}-\frac{\zeta'(1-2 n)}{\zeta(1-2 n)}+\gamma+\log(2 \pi)\tag{2}$$
and $n\in \mathbb{Z}\land n\geq 0$?

Question (2): Evaluation at negative odd integers

Is it also true that
$$\frac{\zeta '(-2 n-1)}{\zeta (-2 n-1)}=g(n)\tag{3}$$
where
$$g(n)=-H_{2 n+1}-\frac{\zeta '(2 n+2)}{\zeta (2 n+2)}+\gamma +\log (2 \pi )\tag{4}$$
and $n\in \mathbb{Z}\land n\geq 0$?

The last column in the following table illustrates the error in formula (1) above associated with the evaluation of $\frac{\zeta'(s)}{\zeta(s)}$ at non-negative even integers. At $n=0$ the function $f(n)$ must be evaluated as $\underset{\epsilon\to 0}{\text{lim}}f(\epsilon)$.

$$\begin{array}{ccccc}
 n & 2 n & \frac{\zeta'(2 n)}{\zeta(2 n)} & f(n) & f(n)-\frac{\zeta'(2 n)}{\zeta(2 n)} \\
 0 & 0 & \log (2 \pi ) & \log (2 \pi ) & 0. \\
 1 & 2 & \frac{6 \zeta '(2)}{\pi ^2} & 12 \left(\frac{1}{12}-\log (A)\right)-1+\gamma+\log (2 \pi ) & 0. \\
 2 & 4 & \frac{90 \zeta '(4)}{\pi ^4} & -120 \zeta '(-3)-\frac{11}{6}+\gamma +\log (2 \pi ) & \text{5.551115123125783$\grave{ }$*${}^{\wedge}$-16} \\
 3 & 6 & \frac{945 \zeta '(6)}{\pi ^6} & 252 \zeta '(-5)-\frac{137}{60}+\gamma +\log (2 \pi ) & \text{2.220446049250313$\grave{ }$*${}^{\wedge}$-16} \\
 4 & 8 & \frac{9450 \zeta '(8)}{\pi ^8} & -240 \zeta '(-7)-\frac{363}{140}+\gamma +\log (2 \pi ) & \text{3.0531133177191805$\grave{ }$*${}^{\wedge}$-16} \\
 5 & 10 & \frac{93555 \zeta '(10)}{\pi ^{10}} & 132 \zeta '(-9)-\frac{7129}{2520}+\gamma +\log (2 \pi ) & \text{3.3306690738754696$\grave{ }$*${}^{\wedge}$-16} \\
 6 & 12 & \frac{638512875 \zeta '(12)}{691 \pi ^{12}} & -\frac{32760}{691} \zeta '(-11)-\frac{83711}{27720}+\gamma +\log (2 \pi ) & \text{6.661338147750939$\grave{ }$*${}^{\wedge}$-16} \\
 7 & 14 & \frac{18243225 \zeta '(14)}{2 \pi ^{14}} & 12 \zeta '(-13)-\frac{1145993}{360360}+\gamma +\log (2 \pi ) & \text{1.2212453270876722$\grave{ }$*${}^{\wedge}$-15} \\
 8 & 16 & \frac{325641566250 \zeta '(16)}{3617 \pi ^{16}} & -\frac{8160 \zeta '(-15)}{3617}-\frac{1195757}{360360}+\gamma +\log (2 \pi ) & \text{1.9984014443252818$\grave{ }$*${}^{\wedge}$-15} \\
 9 & 18 & \frac{38979295480125 \zeta '(18)}{43867 \pi ^{18}} & \frac{14364 \zeta '(-17)}{43867}-\frac{42142223}{12252240}+\gamma +\log (2 \pi ) & \text{3.1086244689504383$\grave{ }$*${}^{\wedge}$-15} \\
 10 & 20 & \frac{1531329465290625 \zeta '(20)}{174611 \pi ^{20}} & -\frac{6600 \zeta '(-19)}{174611}-\frac{275295799}{77597520}+\gamma +\log (2 \pi ) & \text{2.6645352591003757$\grave{ }$*${}^{\wedge}$-15} \\
\end{array}$$

The last column in the following table illustrates the error in formula (3) above associated with the evaluation of $\frac{\zeta'(s)}{\zeta(s)}$ at negative odd integers.

$$\begin{array}{ccccc}
 n & -2n-1 & \frac{\zeta'(-2n-1)}{\zeta(-2n-1)} & g(n) & g(n)-\frac{\zeta'(-2n-1)}{\zeta(-2n-1)} \\
 0 & -1 & -12 \left(\frac{1}{12}-\log (A)\right) & -\frac{6 \zeta '(2)}{\pi ^2}-1+\gamma+\log (2 \pi ) & 0. \\
 1 & -3 & 120 \zeta '(-3) & -\frac{90 \zeta '(4)}{\pi ^4}-\frac{11}{6}+\gamma +\log (2 \pi ) & \text{5.551115123125783$\grave{ }$*${}^{\wedge}$-16} \\
 2 & -5 & -252 \zeta '(-5) & -\frac{945 \zeta '(6)}{\pi ^6}-\frac{137}{60}+\gamma +\log (2 \pi ) & \text{2.220446049250313$\grave{ }$*${}^{\wedge}$-16} \\
 3 & -7 & 240 \zeta '(-7) & -\frac{9450 \zeta '(8)}{\pi ^8}-\frac{363}{140}+\gamma +\log (2 \pi ) & \text{3.0531133177191805$\grave{ }$*${}^{\wedge}$-16} \\
 4 & -9 & -132 \zeta '(-9) & -\frac{93555 \zeta '(10)}{\pi ^{10}}-\frac{7129}{2520}+\gamma +\log (2 \pi ) & \text{3.3306690738754696$\grave{ }$*${}^{\wedge}$-16} \\
 5 & -11 & \frac{32760}{691} \zeta '(-11) & -\frac{638512875 \zeta '(12)}{691 \pi ^{12}}-\frac{83711}{27720}+\gamma +\log (2 \pi ) & \text{6.661338147750939$\grave{ }$*${}^{\wedge}$-16} \\
 6 & -13 & -12 \zeta '(-13) & -\frac{18243225 \zeta '(14)}{2 \pi ^{14}}-\frac{1145993}{360360}+\gamma +\log (2 \pi ) & \text{1.2212453270876722$\grave{ }$*${}^{\wedge}$-15} \\
 7 & -15 & \frac{8160 \zeta '(-15)}{3617} & -\frac{325641566250 \zeta '(16)}{3617 \pi ^{16}}-\frac{1195757}{360360}+\gamma +\log (2 \pi ) & \text{1.9984014443252818$\grave{ }$*${}^{\wedge}$-15} \\
 8 & -17 & -\frac{14364 \zeta '(-17)}{43867} & -\frac{38979295480125 \zeta '(18)}{43867 \pi ^{18}}-\frac{42142223}{12252240}+\gamma +\log (2 \pi ) & \text{3.1086244689504383$\grave{ }$*${}^{\wedge}$-15} \\
 9 & -19 & \frac{6600 \zeta '(-19)}{174611} & -\frac{1531329465290625 \zeta '(20)}{174611 \pi ^{20}}-\frac{275295799}{77597520}+\gamma +\log (2 \pi ) & \text{2.6645352591003757$\grave{ }$*${}^{\wedge}$-15} \\
 10 & -21 & -\frac{276 \zeta '(-21)}{77683} & -\frac{13447856940643125 \zeta '(22)}{155366 \pi ^{22}}-\frac{18858053}{5173168}+\gamma +\log (2 \pi ) & \text{8.881784197001252$\grave{ }$*${}^{\wedge}$-15} \\
\end{array}$$
Comment: Don't know the answer but I imagine you'd want to start with $\log\zeta(s) = s\log 2 + (s-1)\log\pi + \log\sin(\pi s/2) + \log\Gamma(1 - s) + \log\zeta(1 - s)$. The derivative of the left side is $\zeta'(s)/\zeta(s)$ which is what you're exploring, though at integer values.
Answer: What do you get from the functional equation, $\Gamma'(1)/\Gamma(1)=-\gamma$ and $\Gamma(s+1)=s\Gamma(s)$
Answer: It is known that
$$
\zeta(1-s)=2^{1-s}\pi^{-s}\cos\left(\pi s\over2\right)\Gamma(s)\zeta(s)
$$
Taking logarithmic derivative on both side, we have
$$
-{\zeta'\over\zeta}(1-s)=-\log2\pi-\frac\pi2\tan\left(\pi s\over2\right)+{\Gamma'\over\Gamma}(s)+{\zeta'\over\zeta}(s)
$$
When $s=2n\ge0$, we have $\tan(n\pi)=0$, so
$$
-{\zeta'\over\zeta}(1-2n)=-\log2\pi+{\Gamma'\over\Gamma}(2n)+{\zeta'\over\zeta}(2n)
$$
For the Gamma term, plug in Weierstrass product that
$$
\Gamma(s)={e^{-s\gamma}\over s}\prod_{k=1}^\infty\left(1+\frac sk\right)^{-1}e^{s/k}
$$
we have
$$
{\Gamma'\over\Gamma}(s)=-\gamma-\frac1s+\sum_{k=1}^\infty\left(\frac1k-{1\over s+k}\right)
$$
so that
$$
\begin{aligned}
{\Gamma'\over\Gamma}(2n)
&=-\gamma-{1\over2n}+\sum_{k=1}^\infty\left(\frac1k-{1\over2n+k}\right) \\
&=-\gamma-{1\over2n}+\sum_{k=1}^{2n}\frac1k=-\gamma+H_{2n-1}
\end{aligned}
$$
Plugging this into the original equation, we get
$$
-{\zeta'\over\zeta}(1-2n)=-\log2\pi-\gamma+H_{2n-1}+{\zeta'\over\zeta}(2n)
$$
Rearranging this equation gives
$$
{\zeta'\over\zeta}(2n)=-H_{2n-1}-{\zeta'\over\zeta}(1-2n)+\gamma+\log2\pi
$$
Similar procedure can be done for $n<0$ by using
$$
\zeta(s)=2^s\pi^{s-1}\sin\left(\pi s\over2\right)\Gamma(1-s)\zeta(1-s)
$$


Is this a linear model?

Question:

mpg = mileage per gallon and
hp = horsepower

Why is this model a linear model despite having a square of horsepower in it?
Comment: Models are called linear when they are a linear function of the coefficients.
Comment: Ok i got the answer. For the model to be linear it needs to be linear in terms of parameters not the predictors. Here betas are parameters and horsepower is predictor
Comment: I'm voting to close this question topic because the OP answered it in a comment
Answer: In order to explain this, I would consider the following quadratic function.

By comparing this function with your function, x1 would be similar to your hp (horsepower).
Actually what we have really done is, we have created a new feature x2 where

By plugging this new feature to the above hypothesis we get the following function which is just like a linear model
Comment: i have posted the correct answer below.
Answer: Ok i got the answer. For the model to be linear it needs to be linear in terms of parameters not the predictors. Here betas are parameters and horsepower is predictor

Is this a linear model?


Use datasets from different locations and different projects in DBT

Question: I do know you can configure your default desired location in the profiles.yaml
default:
  target: default
  outputs:
    default:
      type: bigquery
      method: oauth
      dataset: default_dataset
      location: europe-west1

But then all the rest of the defined sources (Bigquery Datasets in my case) will have this same location. So I could not query a dataset located in europe-east2 anymore in this project
version: 2
sources:
  - name: dataset_in_asia_location
    tables:
      - name: incremental_table

There's nothing in the documentation for the sources (props nor configs)
So, how do you use a dbt source from a diferent location that the default one defined in the profiles.yaml?
Comment: If you set your dbt profile location to "EU" (multi-region) and then run the following, what do you get for the location column?

`SELECT schema_name, location FROM \`.INFORMATION_SCHEMA.SCHEMATA\``
Answer: The documentation of DBT states that DBT will use the default location unless you specify a custom project/database config.
my-profile:
 target: dev
 outputs:
   dev:
     type: bigquery
     method: oauth
     project: abc-123
     dataset: my_dataset

Additionally, in the .yaml location, it is recommended to use multi-region locations.
Comment: Thanks @Jose,  I do understand this too. Issue is when you have to mix/query data from datasets from different locations (dataset_1 in EU, dataset_2 in europe-west1)
Comment: @dinigo That's correct. That is why DBT recommends to use multi-region datasets or to use the amount of datasets on the same location.


Can a z-score be used to describe a cluster's homogeneity?

Question: As part of my thesis, we wanted to investigate the ability of using z-scores as indicators for the homogeneity of clusters (or speaking more generally of partitions of a vector). After some modelling I believe this is not entirely possible and I would like to get some opinions on this.
Suppose I have some 2D data with one predictor c and my cluster assignment cl, which splits c into 5 groups of exactly 20 elements. There is little variation among the elements of c in every cluster and every cluster contains a distinct set of elements of c(i.e. cluster 1 contains mostly ones, cluster 2 mostly twos, a.s.o.). I then want to compute each indivdual cluster's z-score based on c as follows:
# library(data.table)
# dat<-as.data.table(dat)
meanCl<-dat[,mean(c),by=cl][,V1,]
mean0<-sapply(1:1000,function(x){
              mean(sample(dat[,c,],20,replace=T))}
sd0<-sd(mean0)
mean0<-mean(mean0)
z<-(meanCl-mean0)/sd0

... i.e. I compute the mean of c for every subgroup in cl. I go on to compute the mean of 1000 clusters containing 20 random elements from the distribution of c. I then calculate every clusters' z-score by subtracting its mean from the mean of the random clusters' means and divide by the standard deviation in those means to get:
[1] -4.96401933 -4.05057547 -0.03142247  2.89159789  5.99730703

So even though all clusters are distinctly characterised in their internal distribution of c, the z-score for cluster 3 is basically 0, as its mean tends towards the mean of the sample distribution of c.
Typing this out, it makes sense to me to not be able to use a cluster's z-score as a predictor for its homogeneity, however, as intially stated, I would like some ideas on this.
Comment: Yeah. It sounds like your underlying assumptions are information theoretic. One possible metric can be found in Marina Meila, *Comparing Clusterings*, University of Washington Statistics Technical Report 418 and COLT 03 paper...ungated copy here ... http://www.stat.washington.edu/mmp/Papers/compare-colt.pdf. Another approach could be Andreas Brandmaier's complexity-based permutation distribution clustering for time series. He has several ungated papers out there and an R module, e.g., here ... https://www.jstatsoft.org/article/view/v067i05/v067i05.pdf
Comment: Are you trying to use z-score to describe homogeneity or uniqueness? You use different words in the title and in your closing paragraph.
Comment: The description of the theoretical process being used to create these 1,000 randomly chosen clusters is unclear. You should define "homogeneity" more explicitly and benchmark results against standard metrics. Are the draws of 20 elements from the same population or data, i.e., are these bootstrapped draws? Why only 1,000 draws? Why not 1,000,000? Why is there only 1 predictor?  Are five clusters always the result? Why five? A little more information would help. That said, if the elements in the clusters can be identified or tagged, why not track their diffusion in assignment across the draws?
Comment: @user77876 Yes, homogeneity is what I meant to write in the closing paragraph. I edited the wording accordingly.
Comment: @DJohnson You're correct, I was a little vague. I refer to homogeneity of a cluster as the number and quantitiy of different elements in a cluster relative to the number and quantity of elements in the base distribution. Some other metrics I can think of would be e.g. shannon's entropy. The random draws are indeed bootstrapped (I included replace=T in the code). 1,000 random draws were based on this publication http://www.pnas.org/content/102/43/15545.full. 5 clusters and 1 predictor was an arbitrary choice. Measuring diffusion is an interesting idea! Can you recommend a good reference?
Answer: Your intuition is correct: the z-score of a cluster's mean with respect to the means of the other clusters cannot be used to determine its homogeneity. The reason for this is twofold.

A cluster's homogeneity does not depend on other clusters. A cluster's homogeneity does not change depending on the location of the other clusters in the clustering; and
A cluster's mean does not capture the "spread" of the instances assigned to it. The clusters $(3, 3, 3, 3, 3)$ and $(-1, 0, 2, 5, 9)$ both have a mean value of 3 but have ranges, for example, of $0$ and $10$.

Thinking specifically about a cluster's homogeneity I would suggest that you consider internal measures of cluster quality. These measure how well a given clustering groups similar instances together while keeping different instances apart. Internal measures such as the Davies-Bouldin index, Dunn index and Silhouette coefficient all explicitly consider the "spread" of instances assigned to a cluster.
Davies-Bouldin index: $DB = \frac{1}{n} \sum_{i=1}^n \max{j \neq i} \text{ } (\frac{\sigma_i+\sigma_j}{d(c_i,_j)})$
With $n$ the number of clusters, $c_x$ the centroid of cluster $x$, $\sigma_{x}$ is the average distance of all elements in cluster $x$ to centroid $c_{x}$, and $d(c_{i},c_{j})$ is the distance between centroids $c_i$ and $c_j$.
Dunn Index: $D =\frac{\min{i,j} d(i,j)}{\max{k} d'{k}}$
With $d(i,j)$ the distance between clusters $i$ and $j$, and $d'(k)$ the intra-cluster distance of cluster $k$.
Silhouette coefficient for instance $i$: $s(i) = \frac{b(i)-a(i)}{\max{(a(i),b(i))}}$
With  $a(i)$ the average dissimilarity of $i$ with all other data within the same cluster, and $b(i)$ the lowest average dissimilarity of $i$ to any other cluster, of which $i$ is not a member. The silhouette coefficient of the clustering is the sum of $s(i)$ for all $n$ instances clustered.
Comment: Thanks for your comment. I was aware of the silhouette coefficient and some other metrics and will revert to those instead. I had just come across this idea and wanted to give it a try.


simplifying triple summations from series expansion

Question: I have the following equation I would like to extract $x^k$ out of
$$
\sum^\infty_{k=0}x^k \Gamma \bigg(l,\frac{ax-1}{a^2}\bigg)
$$
I start by expanding the incomplete gamma function, and then the ensuing exponential
$$
\begin{align}
&= \sum^\infty_{k=0}x^k\Gamma(l)e^{-\frac{ax-1}{a^2}}\sum^{l-1}_{m=0}\bigg(\frac{ax-1}{a^2}\bigg)^m\frac{1}{m!}\\
&=\Gamma(l)\sum^\infty_{k=0}x^k\sum^\infty_{n=0}\bigg(\frac{1-ax}{a^2}\bigg)^n\frac{1}{n!}\sum^{l-1}_{m=0}\bigg(-\frac{1-ax}{a^2}\bigg)^m\frac 1{m!}
\end{align}
$$
I'm then not sure how to proceed.
My attempt is to pull the terminal sum out front and change the starting index of $k$
$$
=\Gamma(l)\sum^{l-1}_{m=0}\sum^\infty_{k=m}x^k\bigg(-\frac{1-ax}{a^2}\bigg)^m\frac 1{m!}\sum^\infty_{n=0}\bigg(\frac{1-ax}{a^2}\bigg)^n\frac{1}{n!}
$$
I think then perhaps a binomial expansion of $1-ax$ to isolate $x$ and recombine as
$$
=\Gamma(l)\sum^{l-1}_{m=0}\sum^\infty_{k=m}\sum^m_{j=0}\begin{pmatrix} m \\ j
\end{pmatrix} (a^{-2})^j(a^{-1})^{m-j}\frac 1{m!}\sum^\infty_{n=0}\sum^n_{q=0}\begin{pmatrix} n \\ q
\end{pmatrix} \left(a^{-2}\right)^{q}\left(-a^{-1}\right)^{n-q}(x)^{m-j+k+n-q}\frac{1}{n!}
$$
I now have $x$ on its own, but have no idea how to pull it out front. I then want to reuse the exponential and incomplete gamma functions to tidy the resulting formula up. I'd imagine a quotient containing the incomplete gamma function as a final result.
** Edit **
In a similar (and simpler) example we would have
$$
\sum^\infty_{k=0} x^k \sum^n_{m=0}\frac{(nx)^m}{m!} = \sum^n_{m=0}\sum^\infty_{k=m}x^k\frac{n^m}{m!} = \sum^\infty_{k=0}x^k\sum^{(k,n)}_{m=0}\frac{n^m}{m!} = e^n\sum^\infty_{k=0}x^k\frac{\Gamma((k,n)+1,n)}{\Gamma((k,n)+1)}
$$
where $(k,n)$ denotes the lesser of $k$ or $n$. I wish to retain the sum over k and pull $x^k$ outside (if possible).
Answer: It is convenient to use the coefficient of operator $[x^n]$ to denote the coefficient of $x^n$.

We obtain for $j\geq 0$:
  \begin{align*}
[x^j]\sum^\infty_{k=0}&x^k\sum^\infty_{n=0}\left(\frac{1-ax}{a^2}\right)^n\frac{1}{n!}\sum^{l-1}_{m=0}\left(-\frac{1-ax}{a^2}\right)^m\frac 1{m!}\\
&=\sum_{k=0}^j[x^{j-k}]\sum^\infty_{n=0}\left(\frac{1-ax}{a^2}\right)^n\frac{1}{n!}\sum^{l-1}_{m=0}\left(-\frac{1-ax}{a^2}\right)^m\frac 1{m!}\tag{1}\\
&=\sum_{k=0}^j\sum_{n=0}^\infty \sum_{m=0}^{l-1}\frac{(-1)^m}{n!m!a^{2(n+m)}}[x^k](1-ax)^{n+m}\tag{2}\\
&=\sum_{k=0}^j\sum_{n=0}^\infty\sum_{m=0}^{l-1}\frac{(-1)^m}{n!m!a^{2^{(n+m)}}}[x^k]\sum_{r=0}^{n+m}\binom{n+m}{r}(-ax)^r\tag{3}\\
&\,\,\color{blue}{=\sum_{k=0}^j\sum_{n=0}^\infty \sum_{m=0}^{l-1}\binom{n+m}{k}\frac{(-1)^{m+j}}{n!m!a^{2(n+m)-k}}}\tag{4}
\end{align*}
Comment:

In (1) we select the coefficient of $x^j$ and apply the rule $[x^p]x^qA(x)=[x^{p-q}]A(x)$. We set the upper limit of the outer sum to $j$ since higher indices do not contribute to $[x^j]$.
In (2) we change the order of summation of the outer sum by letting $k\to j-k$ and do some rearrangements.
In (3) we expand the binomial as preparation for the next step.
In (4) we select the coefficient of $x^k$. Note that the double sum is zero as long as $n+m<k$.
Comment: @RedPen: Yes, it's exactly as you indicate.
Comment: @RedPen: There was a mistake when applying the *coefficient of* operator the first time. I've mixed up $k$ and $j$. This implies that we also cannot get rid of the outer sum. It's now corrected. Thanks. ... And yes, setting $k\to j-k$ applies then to each occurrence of $k$.
Comment: @RedPen: Many thanks for the bounty, this is very kind of you. Yes, the process is identical. You might find *[this answer](https://math.stackexchange.com/questions/2827331/to-prove-n-sum-limits-r-0n-1r-binomnr-n-rn/2827397#2827397)* and *[this one](https://math.stackexchange.com/questions/2830860/binomial-sums-from-bieberbach-conjecture/2837554#2837554)* helpful, which show the *coeffcient of* operator in action in slightly more complex applications.
Comment: Wow, thank you very much, I have never heard of this operator before! I'm not sure I understand (2) --> (3)? Could I still pull $\sum_k x^k$ out of this expression? (I will edit the question to show what I mean in more detail.) Once again, thank you for your time!
Comment: @RedPen: You're welcome. I've added a step which might be helpful.
Comment: thank you once again for your helpful edit. Would I be correct in thinking that this gives me the coefficient of the $j$th term? I could then write $\sum_{j=0}^\infty f_jx^j$ (where $f_j$ is your highlighted formula)? This would then be my closed form series?
Comment: In going from (1) to (2), when we change the index and the order of summation. How do we get $j$ from setting $k\rightarrow j-k$?  If there were terms present in $k$ in the equation, would they also convert to  $k\rightarrow j-k$ too?
Comment: Sorry to keep pestering you (I hope you don't mind me asking one more question). In a very similar problem, on step (2), I have $$\sum^j_{k=0}P(k)[z^{j-2k}]A(z)$$ If I choose $2k\rightarrow  j-k$ then $k\rightarrow (j-k)/2$, which doesn't seem good to have non-integer index. In this case, how can I proceed to re-order the summations?
Comment: (I would like to give you a bounty to say thank you for your help too!)
Comment: @RedPen: No worries. :-) In this case it might be more convenient to keep the exponent $j-2k$ without changing the order of the sum. In fact it depends on the structure of $A(z)$. If $A(z)$ is a power series, the upper limit of the sum is $\lfloor{j/2}\rfloor$ instead of $j$ to respect that $j-2k\geq 0$. Many thanks for your nice bounty offer, I do appreciate it. But, if you want to keep your rep, this would be also fine to me. (It's the idea which counts. :-))
Comment: Thank you for your reply! Ah, yes, that makes sense. I have $$[z^j] \sum^\infty_{k=0}P(k)z^{2k}\sum^\infty_{n=0}\left(\frac{1-ax}{a^2}\right)^n\frac{1}{n!}\sum^{l-1}_{m=0}\left(-\frac{1-ax}{a^2}\right)^m\frac 1{m!}$$ So, the process is identical apart from the sum over $k$ ends at $j/2$ and that $2k\rightarrow j-k$? (The bounty is yours, I really appreciate your help and for introducing this operator to me, but I can only award it in 24 hours). :)
Comment: @RedPen: Many thanks for granting the bounty! :-)