Não consigo validar a extensão da imagem usando o charAt

Question: Estou tentando fazer uma validação simples na extensão das imagens que vão ocorrer o upload, porém não está dando muito certo até o momento, poderiam me ajudar?
Segue o código que estou tentando fazer funcionar.
var aoptionFoto = document.getElementById("optionsFotoImg").value;
var aopcDemaisTemFoto = ['Sim', 'Não'];
var ainput13 = document.getElementById("OutroTipoImagemFile").value == "";
var validaExt = ['jpg', 'png','gif', 'jpeg'];
var extImagem = ainput13.charAt(ainput13.length-3);

if(aoptionFoto == 'Sim' && ainput13 == true){
      swal({
        title: "Ops.. Algo está errado !",
        text: "Para finalizar a compra é necessario fazer o upload da imagem.",
        button: "Continuar",
      });
      document.formMonteCaixa.OutroTipoImagemFile[0].focus();

    }else if(aoptionFoto == 'Sim' && ainput13 == false && extImagem != validaExt){
      swal({
        title: "Ops.. Algo está errado !",
        text: "Para finalizar a compra é necessario fazer o upload da imagem com extensões valida.",
        button: "Continuar",
      });
      document.formMonteCaixa.OutroTipoImagemFile[0].focus();

  }else{
    document.getElementById('BlocoDeEnvioEmailPag').style.display = 'block';
  }

Faça o upload da imagem

            <input name="OutroTipoImagemFile" id="OutroTipoImagemFile" accept="image/*" type="file">

O erro que retorna no console é esse:
Uncaught TypeError: ainput13.charAt is not a function
    at FinalizarCompra ((index):407)
    at HTMLButtonElement.onclick ((index):753)
Comment: Tem erro no código.
Answer: Você está comparando valores errados. O charAt também está pegando apenas 1 caractere na string. Faça o seguinte, use split e .pop() para pegar a extensão (o split quebra o nome do arquivo em array e o pop() pega o valor do último index da array, que é justamente a extensão):
var ainput = document.getElementById("OutroTipoImagemFile").value;
var ainput13 = ainput == "";
var validaExt = ['jpg', 'png','gif', 'jpeg'];
var extImagem = ainput.split(".").pop().toLowerCase();

E aqui:
}else if(aoptionFoto == 'Sim' && ainput13 == false && extImagem != validaExt){

Você altera para:
}else if(aoptionFoto == 'Sim' && ainput13 == false && !~validaExt.indexOf(extImagem)){

Para verificar se a extensão existe na array.
Código completo:
var aoptionFoto = document.getElementById("optionsFotoImg").value;
var aopcDemaisTemFoto = ['Sim', 'Não'];
var ainput = document.getElementById("OutroTipoImagemFile").value;
var ainput13 = ainput == "";
var validaExt = ['jpg', 'png','gif', 'jpeg'];
var extImagem = ainput.split(".").pop().toLowerCase();

if(aoptionFoto == 'Sim' && ainput13 == true){
      swal({
        title: "Ops.. Algo está errado !",
        text: "Para finalizar a compra é necessario fazer o upload da imagem.",
        button: "Continuar",
      });
      document.formMonteCaixa.OutroTipoImagemFile[0].focus();

    }else if(aoptionFoto == 'Sim' && ainput13 == false && !~validaExt.indexOf(extImagem)){
      swal({
        title: "Ops.. Algo está errado !",
        text: "Para finalizar a compra é necessario fazer o upload da imagem com extensões valida.",
        button: "Continuar",
      });
      document.formMonteCaixa.OutroTipoImagemFile[0].focus();

  }else{
    document.getElementById('BlocoDeEnvioEmailPag').style.display = 'block';
  }

Faça o upload da imagem

            <input name="OutroTipoImagemFile" id="OutroTipoImagemFile" accept="image/*" type="file">

Comment: Funcionou, muito obrigado !
Comment: Corrigi o código porque não estava reconhecendo a extensão jpeg por ter 4 caracteres.


How to validate dynamic table when using ajax post

Question: I am trying to add jQuery validation to the dynamic table in my application. Here is my code .

            First Name
            Last Name

            <input type=text name="fname_new[0]" class="table_input" />
            <input type=text name="lname_new[0]" class="table_input" />

  <input type="button" name="submit" value="Submit" id="submit" />

On clicking on add button I am adding the row by jquery
  $("#AddLine").click(function () {
  var row = "
<input name=fname_new[" + num_rows + "] type=text class='table_input' />	<input name=lname_new[" + num_rows + "]type=text class='table_input' />
";
      $("#table").append(row);
            num_rows++;
    });

Here I am submitting the form using ajax post. The form is submitted like this
<input type="button" id="savebutton" value="save'/>

On clicking the button the form is posted like this
 $.ajax({
            url: '@Url.Action("", "MyCOntroller")',
            type: 'POST',
            data: formdata,
            datatype: 'json',
            success: function (response) {
                $('#UserMessage').html(response.UserMsg);

            },
            error: function (error) {
            }
        });

I want to validate the dynamic table using jQuery, Can someone please tell me how to validate before posting through ajax.
Comment: Validate what? The the textbox has a value? That it matches a regex?
Answer: It depends on various things. Such as what do you want to validate? What framework are you using?
If, for example, you want to validate that a value must be entered, you need to add an attribute to the input: data-val-required="The xxxxx field is required". Then before calling your ajax function check that the data is valid using if ($('#yourFormId').valid()). You will also need a data validation message display which I can't currently remember the syntax for.
There are various things that can be validated rather than just that a field is required. You should look up jQuery validation as there I already plenty of information that is very easy to find.
If you are using ASP.Net MVC, then you should be looking at unobtrusive validation. You can then add data annotations to your models such as [Required] and the necessary attributes will be automatically put in when using Html.EditorFor, etc. Again, this is very easy to find information on.


Infimum of inner product over a closed subspace

Question: Let $M\subset H$ a closed linear subspace of a Hilbert space H. Suppose $f \in H$ but $f \not\in M^{\perp}$. Show that
$$ \inf_{x\in M,\|x\|=1} (f,x)$$
is attained and the min is unique.
So what I've tried so far was to use extreme value theorem. I know that the closed unit circle is compact with respect to $\sigma(H,H^*)$ due to reflexivity and $M$ is weakly closed as well so the intersection would be weakly compact, EVT would come in here until I realized the infimum is only over the shell intersect M, so my idea stops there.
I also tried constructing a sequence $(f,x_n)$ converging to the infimum, since M is also reflexive and each $x_n$ has norm 1, there exists a weakly convergent subsequence. If $x$ is the weak limit and $\|x\|=1$, I would be done. But I don't know how to show $\|x\|=1$, I do know however $\|x\| \leq 1$ simply by weak convergence.
Just looking for a hint!!
Thank you!
Comment: $\inf \langle f, x \rangle = - \sup \langle f, x \rangle$, so this closely relates to the projection theorem. In particular, it might be helpful to write down which vector actually attains the infimum in question.
Comment: Brezis Exercise 5.11. (For future readers coming from this reference.)
Answer: You are almost there. As you said we know that the unit ball is weak* compact, so by the EVT there exists $u$ in the closed unit ball so that $\inf_{\|x\|\leq 1}(f,x)=(f,u)$. We also note that $f\neq 0$ so $u\neq 0$. Set $\alpha=1/\|u\|$. We claim that $\inf_{\|x\|=1}(f,x)=(f,\alpha u)$. Assume not: Then there exists a $v$ on the unit sphere such that $(f,v)<(f,\alpha u$). Then $\frac{1}{\alpha}(f,v)<(f,u)$, meaning that $(f,\|u\|v)<(f,u)$, which contradicts the choice of $u$.
This approach, however, is not the best approach in order to see uniqueness. We need to exploit the geometry of the Hilbert space. Note that we can write $f=P_Mf+P_{M^\perp}f$. Thus for any $x\in M$ we have $(f,x)=(P_Mf,x)$. Combining this with Cauchy-Schwarz, we see that
$$\inf_{\|x\|=1}(f,x)\geq-\|P_Mf\|.$$
Clearly this infimum is achieved at $x=\frac{-P_Mf}{\|P_Mf\|}.$ Finally we remember that equality is achieved in Cauchy-Schwarz if and only if the two elements are linearly dependent. I.e. for any $x,y\in H$ $|(y,x)|=\|y\|\|x\|$ if and only if $x=\alpha y$. As any ray only intersects the unit sphere at a unique point, we are done.
Comment: ahhh right. Dang, I was so close, just unwilling to commit to the idea hahaha. Thank you so much tho!
Comment: @Asukev We have all been there!
Comment: would you know how to show uniqueness? Just a hint would be fine.
Comment: @Asukev Sorry my last hint was actually sending you down a difficult path. See the edit.
Comment: forgot to update this, but I found another way. Assuming two points along the sphere are both minimizers then taking any convex combination will give a line of points in the ball that are equal to the min. But if you normalize points along this line, then you get an even smaller minimum, which is the contradiction


Limits involving indeterminate forms

Question: I am trying to find $\lim_{x \to \infty} (\ln x)^{1/x}$ and I have gotten it to $\lim\limits_{x \to \infty} \frac{1}{x \ln x}$.
The answer is $1$ and I just can't figure out why.
Comment: you can write your limit as y = .... and then take the ln on both sides. You can then rewrite your limit appropriately for Hospital's Rule. The outcome of that limit is 0 and from lny=0 follows y=1
Comment: Not sure exactly how that result relates to the given problem. I can see if you take the ln on both sides, you get lnx in the numerator and an x in the denom. That limit is zero.
Answer: Hint: if $x\gt 1$, then $(\ln x)^{1/x}=\exp\left(\frac{\ln(\ln x)}{x}\right)$
The behaviour of $\frac{\ln(\ln x)}{x}$ for large $x$ can be found in various ways, for example by using L'Hospital's Rule. Then use the cotinuity of the function $\exp(t)$.

Limits involving indeterminate forms


Converting RSS to JSON adds strange characters

Question: I'm trying to get an JSON version off the CNN Entertainment RSS feed, but it appears the Google AJAX script is adding strange characters. I looked into URL encoding which I know is important, but I don't think I'm using any characters that need encoding. Plus, the feed converter has no problems with the regular "edition." It's the "edition_entertainment" that seems to cause the problem.
http://ajax.googleapis.com/ajax/services/feed/load?v=2.0&q=http://rss.cnn.com/rss/edition_entertainment.rss
For example, the feed has strange slashes and added characters"

still singing those \"Frozen\" tunes over a year later, you'll have a brand new set of
  tunes in the not-too-distant future.\u003cimg src\u003d\
Answer: This is all standard encoding.
The original is:
"Frozen". Since json uses the " itself, the encoding enters a \ before each quote.
The \u003cimg src\u003d\" was
Comment: Thanks, this makes sense. I think JSON turns a quote into `\"` But what about `\u003cimg`?
Comment: The \u003cimg should be read as \u003c img which is < img (spaces added for clarity).
Once encoding is used, all special characters are encoded according to the standard.
Comment: Got it. So it's just encoding some HTML, no big deal. Thanks.


Problem with changing properties of :hover

Question: I'm unable to change background-color of list items to black while :hover.
one the other hand there is no problem with changing color.

.nav li {
  display: inline-block;
  height: 100%;
  padding: 0px 35px;
  border-width: 0 1px 1px 0px;
  border-color: white;
  border-style: solid;
  box-sizing: border-box;
  line-height: 37px;
  background: linear-gradient(rgb(81, 59, 192) 26%, rgb(183, 172, 237))
}

.nav li:hover {
  background-color: black;
  color: black;
}

Lorem

Ipsum

dolor

amet

Comment: my advice is to not use the shorthand of background unless necessary. As for your question just change the background to background-image and set it to none when :hover
Answer: Your background color is behind your linear gradient. Change it from background-color to just background if you want to override the entire background.
Answer: The background shorthand property sets a number of different properties.
A linear-gradient is a type of background-image not a background-color.
Setting background-color: black appears to have no effect because it is covered up by the background-image.
Remove the image (background-image: none) so you can see the colour.

.nav li {
  display: inline-block;
  height: 100%;
  padding: 0px 35px;
  border-width: 0 1px 1px 0px;
  border-color: white;
  border-style: solid;
  box-sizing: border-box;
  line-height: 37px;
  background: linear-gradient(rgb(81, 59, 192) 26%, rgb(183, 172, 237))
}

.nav li:hover {
  background-color: black;
  background-image: none;
  color: black;
}

Lorem

Ipsum

dolor

amet

Comment: Ok, thanks.  Now is working, but when I incrased transition time i can notice of quick flash of white color before it moves to desired color.


How do you choose what bass notes to play using a lead sheet

Question: My problem is that if I look at the chords of a lead sheet (treble staff) almost none of my bass notes sound right -- not even the roots, 3rds, 5ths or 7ths.
Take a slow song like the old standard The Wayward Wind, popularly sung by Gogi Grant. The first page's chords shown are C, C7, F, Fm, G7. The bass only plays a note on beats 1 and 3.
I believe she's singing in a different key, but even if I try any, most of the roots still sound bad.
Shouldn't it be easy to play good-sounding bass notes on beats 1 and 3 of such a simple song? I'm sure not having much luck....
Thx.
Link to the song:
Comment: Mods - please check this out. 5 dvs, usual lack of explanation for ANY. Someone's playing silly games?
Comment: If you are trying to play with recording that is available online, linking to it might be helpful?  What key are you trying to play in?  Note that sometimes recordings are sped up, or slowed down such that you'd have to tune between notes to match it.
Comment: I'd be surprised if she is singing in a different key. Can I suggest that they maybe de-tuned a little to support her voice and are actually playing different notes than those notated ? Its not uncommon to detune by a semitone, early U2 is commonly recorded to an e flat tuning. Thats maybe why it may sound wrong to you
Comment: "nothing sounds right..." explain more about what you're doing. Playing what? bass, piano? Your playing doesn't sound right with what? the record? just the bass line? bass against chords? Are you sure you're tuned properly? Etc.
Comment: Link to the song: [youtube.com/watch?v=2cQUVtbztEs](http://Link%20to%20the%20song:%20youtube.com/watch?v=2cQUVtbztEs%20Thanks,%20everyone.) (Copy and paste if necessary.) Thanks, everyone.
Comment: You are not asking for the bass line that is played in the video, yes? You ask which notes can be played to this chords to have a fitting bass line?
Comment: What do mods think? It's a phenomenon that's never ocurred in all the years I've visited. Could be that all the answers (and the question) are completely wrong - but I doubt it.
Comment: Be nice to have at least a comment from a mod or two! Or have they joined Monica...
Answer: You couldn't go wrong with a simple: C,G,C,G,F,C,F,C,G,D,G,D here. The melody (which I don't remember that well) may be dissonant against the accompaniment if the phrases (at least the last phrase) resolves nicely.
I'd probably not get away with it in some bands but I might play C,Bb,A,G followed by F,C,Bb,Ab,G,D,G. The first phrase gets the C7 anticipated (the piece doesn't depend on the C-C7 but uses the C7 to go to F. Cf. Crazy Arms or Twist Again the the contrast of a triad vs a seventh matters.) With a little work, I try to get the Ab from the Fm chord in just to have a half-step approach to the G (not sure this would work.)
With a livelier walking bass (on all 4 beats or at least 1,3,4 like a rumba) there are other possibilities.
Answer: C C/E F F/Ab G G/B (the bass plays root not and 3rd - also possible with passing tones: 1231 on  each beat)
Alternativ the bass line could be C Bb A Ab G B  C but this shouldn't be doubled in another voice.
Comment: There must be a music expert round here who knows more than all others. But it seems he isn't able to poste an answer ... ;)
Comment: Honestlly, no, the asylum is missing one, and he's ended up here!
Answer: The version I just listened to was coming over in key B. Maybe a strange key for an orchestra, but that's it. So trying to follow key C chords on any instrument just won't work.
Listen to the recording, and there's a basic 1 and 5 played on bass. It has to work, on beats 1 and 3. It cannot not work! It's the simplest bass line possible, really. I think your problem is the tuning discrepancy.
Incidentally, while Gogi is in key B, Patsy Cline is in key A♭, and Frank Ifield was in key E♭. Seems no-one does it in key C...
Answer: Jazz chord symbols assume root position chords.
C7 means play C in the bass.
If there is an inversion with another chord tone in the bass, it is indicated with a slash.
C7/G means play G in the bass.
Sometimes people don't use the slashes and apparently expect you to know when common progressions use inversions.
Like this...

...versus this...
Comment: Second bar in 1st version doesn't reflect the second bar in the 2nd version too well, although I realise that's not the point.


Java's Monetary and Currency Operation - JSR 354

Question: I was just curious if anyone knew whether JSR 354 will have an official implementation as part of any future JDK.

JDK 11 JavaDocs
JSR354 Reference Implementation

When I search JDK 11 docs online - it doesn't look like Monetary and MonetaryAmount classes aren't included. But the implementation of JSR 354 exists in Github under jsr354-ri.
Does it mean that I can write my own implementation, if I don't want to follow the reference implementation? My purpose is to support additional currencies e.g. Chinese Yuan Renminbi (Offshore) CNH which has no official ISO recognition, but it's well known.
Thanks,
Comment: Authors of javamoney are here on SO and subscribed to the tag jsr354 so this is kinda official support forum and it's ok to ask those questions.
Comment: I'm voting to close this question as off-topic because it is asking about future plans of an off-site third party software vendor. Contact the vendor directly to ask them about their roadmap.
Answer: Thanks for the input so far. As one of the designated new Maintenance Leads (also see Transfer Ballot) allow me to give a more formal answer from our side.
As you may know, Oracle has removed many features from Java 11, JavaFX probably the most prominent "victim" which was released into an Open Source ecosystem backed by a couple of other companies, a few Oracle employees and other members of the community.
JavaMoney, the wider project behind JSR 354 and some of its extensions has always played a similar role. After the Transfer Ballot, there is one company (Trivadis) and 2 Individual EG Members as Maintenance Leads. Plus a lot of others contributed extensions including large names like Red Hat or Zalando.
So JSR 354 and a likely follow-up (aka JavaMoney 2.x) compliment Java SE similar to how OpenJFX, Apache NetBeans or other Open Community efforts do without being an integral part of the JDK. I spoke to an Oracle employee familiar with OpenJDK at Eclipse Community Day and he confirmed, this was also in Oracle's interest to focus on core features of the JDK while other vendors and communities provide additional features around it.
Plus with a future Money JSR under the "iterative" release plan developed for the JDK itself, but open to an other JSR we plan to offer regular releases at a pace that matches the needs of the community. Should say Italy or another country lose its place in the Eurozone due to excessive debt or another "Brexit" like situation happen, then currencies for those countries will change. And an independent Money JSR can immediately respond to that by providing the necessary changes without having to wait for the JDK.
Answer:
Initially JavaMoney was targeted to be included into JDK but then it was decided to make it as JavaEE spec. As you may know starting from JDK11 the JavaEE classes aren't a part of JDK and they should be installed as any other usual dependency i.e. via Maven.
Yes, you can add any custom currencies and this is supported out of the box. You need to add an instance of CurrencyProviderSpi as described in the tutorial Registering Custom Currencies.


One hot representation giving error of index

Question: I am trying to understand one hot representation by the following function. I have printed each and every single line of this function.But I'm getting an error only at the last line that the index is out of bound. I'm unable to understand the reason.How can I fix this problem?
def dense_to_one_hot(labels_dense, num_classes):
    num_labels = labels_dense.shape[0]
    index_offset = np.arange(num_labels) * num_classes
    labels_one_hot = np.zeros((num_labels, num_classes))
    labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1
    return labels_one_hot

labels_dense = np.arange(475000)
print labels_dense.shape
num_classes=10
num_labels = labels_dense.shape[0]
print num_labels
index_offset = np.arange(num_labels) * num_classes
print index_offset
print len(index_offset)
print 'index offset is '+str(index_offset.shape)
labels_one_hot = np.zeros((num_labels, num_classes))
print labels_one_hot.shape
x= labels_dense.ravel()
print x
print x.shape
plus= index_offset+x
print plus
print plus.shape
labels_one_hot.flat[plus]=1

Answer: For the others, the PO was referring to a the example from Tensorflow working with MNIST data, check out the official source code.
labels_dense is a numpy array which is supposed to store elements where each is a class identifier (like 0 represent images labeled as "zero", 9 represents images labeled as "nine").
Here is how the default test data labels look like:
In [20]: labels   # same as labels_dense
Out[20]: array([7, 2, 1, ..., 4, 5, 6], dtype=uint8)

In your own code, you generated labels_dense in the right size, but wrong way:
In [34]: labels_dense
Out[34]: array([ 0, 1, 2, ..., 474997, 474998, 474999])

You see? I am glad your code did not work, otherwise, it might create a 0.5M*0.5 M ~ 50B cells... phew..
The rest of the code is pretty straightforward but I just want to add a bit more intermediate steps to show how labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1 works. Also, instead of using 475K records, I suggest start using 3 record to prove the idea.
In [35]: labels_dense = labels[:3]
In [36]: labels_dense
Out[36]: array([7, 2, 1], dtype=uint8)
In [37]: num_classes = 10
In [38]: num_labels = labels_dense.shape[0]
In [39]: index_offset = np.arange(num_labels) * num_classes
In [40]: index_offset
Out[40]: array([ 0, 10, 20])
In [41]: labels_one_hot = np.zeros((num_labels, num_classes))
In [42]: labels_one_hot
Out[42]:
array([[ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.]])
In [43]: index_offset + labels_dense.ravel()
Out[43]: array([ 7, 12, 21])
In [44]: labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1
In [45]: labels_one_hot
Out[45]:
array([[ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.,  0.,  0.],
       [ 0.,  0.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.]])

Also, at this stage, your code has nothing to do with Tensorflow at all, if you label your question with numpy or even Python in general, you will get help much faster and probably better.
Reference: flat, ravel, arange, zeros
Comment: Thank you so much for such a detailed explanation. Now I got the error in my code that's why my algorithm was giving poor efficiency on both training and test test. Can you please explain explain that how can I convert my label_dense [0,1,  ... 474999] into labels formate that you mentioned. In my code I start labelling from 1 uptil 24, but when I shuffle data both training set and labels. I shuffle their row index as sample.shape[0] that's why I'm getting error.
Comment: @R.ali, I don't think I understand what you want. "how can I convert my label_dense into labels format you mentioned?"
Comment: row = sample.shape[0]
label = np.array([1 for i in range(row)])
for i in range(1,100):
 k4_label = i+1
 label_file = np.array([k4_label for i in range(row)])
 label= np.append(label,label_file, axis=0)sample.shape[0]==label.shape[0]
shuffled_sample.shape[0] == shuffled_label.shape[0]
Comment: I mean my label range is [0,.... 474999] and in minist label range is [0,....9]. In my code I'm assigning label 1 to 1000 sample and label2 to other 1000 samples. Similarly I assign 24 labels. But when I append then as I mentioned above then num_labels = labels_dense.shape[0] will be 24000. how to fix this problem
Comment: can you please tell me how to map label_dense=[0,1,....474999] into labels[7,2,....4,5,6]
Comment: @R.ali, frankly speaking, I think the answer to that question might be too long to fit into a comment and it is more so a question of how to read the mnist.tar.gz file instead of one hot encoding which I suggest you open up another question.
Comment: can you please tell me how to fix that error? Because labels_dense =array([ 0, 1, 2, ..., 474997, 474998, 474999]) will always start from 0 up to the range of labels. I'm not sure what modification is needed in the code


Pass array variable to and from a nested bash script

Question: I have a main script (main.bash)
#!/bin/bash
var=10                 #Variable to pass to the nested script
./nested.bash $var     #Pass 'var' to the nested script, which outputs the 'list' array
echo $list             #echo the output of the nested script

The nested script (nested.bash) is:
#!/bin/bash
if [ $1 == 10 ] ; then
    list=(10-10 20-01 30-03 40-01 50-05)
fi
export list

I used export, but it is not working. How can 'nested.bash' pass list array to 'main.bash'?  More generally, how can this be done?
Comment: You can only export variables to child processes, not the parent process.
Answer: The simplest solution is to source the script with .. This runs it in the current shell process instead of in a child process, which means the outer script can see the changes made by the nested script.
main
#!/bin/bash
var=10
. ./nested.bash "$var"
echo "${list[@]}"

nested.bash
if [ "$1" == 10 ]; then
    list=(10 20 30 40 50)
fi

Notes:

Executables should generally not have an extension. The caller doesn't need to know if the script is written in bash or python or is a compiled C program. Prefer main to main.bash.

Sourced scripts, on the other hand, should have an extension since they need to be executed in a particular interpreter. Name the inner script nested.bash.

Always quote variable expansions.

Array expansion is "${list[@]}". If you write $list you'll only get the first element.

You don't have to pass "$var" in and reference it as "$1" in the nested script. You can reference "$var" directly if you like.
Answer: You can't export variables to a parent process. export is only used to pass variables to child processes. It's also not possible to export arrays.
The way to send data back to the parent process is through standard output, using command substitution.
main.bash:
#!/bin/bash
var=10
list=($(./nested.bash "$var"))
echo "${list[@]}"

nested.bash:
#!/bin/bash
if [ $1 == 10 ] ; then
    list=(10 20 30 40 50)
fi
echo "${list[@]}"

Comment: It is a risky method to pass arrays like this. Bash has better ways to pass lists as `null` or ASCII FS `\37` delimited entries to be read-back with `mapfile -d '' list < <(nested.bash)` or `mapfile -d $'\37' list < <(nested.bash` having `nested.bash` do `printf %s\\0 "${list[@]}"` or `printf %s\\37 "${list[@]}"`. The ASCII FS method can also work with older bash having only `read -a` and no `mapfile`, as `read -a` cannot read `null` delimited entries all at once, since it uses the `IFS` variable for record separation.


Looking at the fretboard is ruining my stage presence

Question: When I play live with my rock band, I have to look at the guitar neck constantly, which is really bad to my stage presence. Whenever I stop looking, little mistakes start to show up. I really enjoy the music I'm playing, but the need to stand there staring at the neck really is a problem for me to move around and feel comfortable.
What can I do about this?
Comment: The simple answer is: practice playing without looking at the fretboard. It might seem hard at first, but it is just the sort of thing many other instrumentalists have to do when sight-reading. Practice, practice, practice ...
Comment: I'll add: try practicing in the dark, so you can't easily see the fretboard. For example, typing on the computer late at night in the dark helped my touch-type skills.
Comment: Practice playing while looking yourself in the eye in a mirror. Then practice playing while recording video of yourself on your cell phone, while looking straight at the lens. Play back the video and confirm that you don't look away from the lens. When you get on stage, find a place in the audience where you can look and try to keep eye contact with people (if the stage lighting permits this).
Comment: What does your performance routine includes and how does your neck-looking habit affect it? You could always develop a stage persona that doesn't bother looking his instrument.
Comment: Have a read of this question for a perspective on why it really doesn't ruin stage presence! http://music.stackexchange.com/q/1446/104
Answer: I understand where you are coming from.  I used to have the same problem.  To overcome this takes a concerted effort and dedicated practice.
You must develop muscle memory so that you can put your brain and fretting hand on auto pilot.  To internalize the movements needed to play a song, take one part at a time.  Play it over and over while looking at the fret board and be sure you are able to play it comfortably and smoothly with no mistakes.
Then try playing it with your eyes closed or in a dark room.  At first you will miss some notes or barre chord positions.  Keep practicing over and over - one section at a time until you can play the song in the dark.
It was a big help for me to learn to play without looking at the fret board.  Not only can I make eye contact with my audience, but I don't have to worry about if dim stage lighting will not let me see the fret markers.
I recommend playing a section over and over while looking - and then try to play it with your eyes closed or just looking at something other than your guitar neck.  Then if you mess up you can open your eyes and see what you are doing wrong and make the needed adjustment.
Once you are able to play the whole song with your eyes closed, try it in a dark room so you don't even have the option to open your eyes.  Once you are able to play the song in pitch black darkness, you have it - and will never need to look at the fret board again for that song.
EDIT: Your brain will lock in to the positions on the fret board instinctively with enough practice.  To prove this, close your eyes and touch the tip of your nose.  Try your ear lobe.  These are things your brain locked into when you were a baby.  Or another example - most folks can find the snooze button on their alarm clock while half asleep without turning on the light or even opening their eyes.
I find that I unconsciously touch base with where the headstock joins the neck as a frame of reference from time to time to get my bearings (similar to placing your first fingers on the home keys on your keyboard before touch typing).  You can feel that spot on the neck because there is an change in the angle and also can feel the nut with your first finger.
One final tip.  Some folks will put stick-on round labels (dots) on certain reference points on the back of the neck so they can feel them as they slide their hand up and down the neck. The larger ones stick better.  Don't do this on a vintage guitar - but if you play your work horse guitar on stage - give it a shot.
Comment: Good advice here. I'll add one thing that my guitar teacher taught me: ideally, your fingers should be essentially right up against the backs of the frets -- you'll feel them. Of course, not every finger will be in that position every time, but at least one finger should be there. That gives you a tactile anchor you can use to place the rest of your fingers. You'll know you're getting it when your hand position just feels right. You'll know your hand is in the right spot by feel.
Comment: Pretty much what @rockinCowboy has said here. Practice practice practice. You'll be thankful when playing gigs with bad lighting (pretty much every gig).
Answer: One possible approach - which is what I would do but not necessarily the best - is the following.
Do as you would do when you have to read the music (and thus can't watch the fretboard as @OldJohn points out):

Get sheet music, or transcribe the piece yourself.
Fire up a metronome at a comfortable speed and look at the music, not at the fretboard.
Progressively raise the metronome speed.
Remove the music
Profit!
Comment: My variation of this is to practice while watching TV.  You'll miss the show if you have to look at the fretboard.
Answer: Another idea, if you don't want to read tab or sheet music, is to focus on your right hand and strumming/picking hand and don't look up the neck.
It takes practice and time for your fingers to naturally find their positions on the neck.  There's no real shortcuts except consistency in your practice (eg. always playing the chord with the same hand positioning), and more practice.


Encryption Algorithm for PHP & Servelts

Question: We are developing a web application using php/java servlets. i would like to pass encrypted variable from  PHP application to Servlet using $GET[] method and decryption from there.
Is there any encryption algorithm to use in both languages?
Edited**
How can i Use Mcrypt Algorithm to do this?
Regards
Answer: Yes, use SSL, preferably with client side certificates.
Comment: Cant we do it  server side using in encryotion algorithm like mcrypt?
Comment: Yes, however you are likely to make a whole host of errors and would better be served with SSL/TLS.
Answer: Any encryption algorithm can be used in any language. For HTTP requests the best option would be to use HTTPS - it will require configuration, rather than coding.
Comment: @Yann yeah, I know java has built in security, but I couldn't see that this particular algorithm is supported.
Comment: can we use mcrypt algorithm to encrypt decrypt in php and servlts
Comment: I guess. You'd have to implement it in java r look for an existing implementation. Looks like Resin has one: http://www.caucho.com/resin-4.0-javadoc/com/caucho/quercus/lib/mcrypt/Mcrypt.html
Comment: @Bozho: Java contains inbuilt security, or you can use bouncy castle. mcrypt is simply a library in use by PHP. I still strong do not suggest this route for the inexperienced.
Comment: @Bozho: mcrypt is not an algorithm. Its a library containing several well known symmetric algorithms.
Comment: aha, thanks: des, blowfish, arcfour, enigma, ghost, LOKI97, RC2, serpent, threeway, twofish, wake, XTEA. Then the OP should decide which one

Encryption Algorithm for PHP & Servelts


Role based permissions for api access in middleware NextJS

Question: Is there a way to do role based permissions in middleware?
I'm asking this because I was hoping that there would be a way to call getSession in middleware.
Otherwise I would need to implement a helper function hasPermissions(req), import it and call it in every single file and I'm trying to avoid that
Thanks
Answer: if you do not want to use third party authenticatio server and you want to do on your own, you could write this with using cookeis and jwt.
1- when users logins set a jwt token. In next.js when user logins, make a request to api function and api function should handle the login process:
import jwt from "jsonwebtoken";

const handleLoginWithEmail = async (e) => {
  e.preventDefault();
  if (email) {
    try {
      //... add your logic, set state
      // make a
      const response = await fetch("/api/login", {
        method: "POST",
        headers: {
          // pass this if you are using passwdrdless or other service that needs token
          Authorization: `Bearer ${ifToken}`,
          "Content-Type": "application/json",
        },
      });
    } catch (error) {
      console.error("Something went wrong logging in", error);
    }
  }
};

your api function should create a jwt
export default async function login(req, res) {
  if (req.method === "POST") {
    try {
      // if there is
      const auth = req.headers.authorization;
      // add your logic
      const token = jwt.sign(
        {
          ...metadata,
          iat: Math.floor(Date.now() / 1000),
          exp: Math.floor(Date.now() / 1000 + 7 * 24 * 60 * 60),
          // I just create a custom object
          "roles": {
            "allowed-roles": ["user", "admin"],
            "default-role": "user",
            // you could decide the role based on email or userId. write your logic
            "role":"user"
          },
        },
        process.env.JWT_SECRET
      );
      // set the token
      setTokenCookie(token, res);
      res.send({ done: true });
    } catch (error) {
      console.error("Something went wrong logging in", error);
      res.status(500).send({ done: false });
    }
  } else {
    res.send({ done: false });
  }
}

2- write a set cookie function used in above api function
import cookie from "cookie";

const MAX_AGE = 7 * 24 * 60 * 60;

export const setTokenCookie = (token, res) => {
  const setCookie = cookie.serialize("token", token, {
    maxAge: MAX_AGE,
    expires: new Date(Date.now() + MAX_AGE * 1000),
    secure: process.env.NODE_ENV === "production",
    path: "/",
  });
  res.setHeader("Set-Cookie", setCookie);
};

3- write a verify token function
import jwt from "jsonwebtoken";

export async function verifyToken(token) {
  if (token) {
    const decodedToken = jwt.verify(token, process.env.JWT_SECRET);
    console.log("decodedToken",decodedToken)
    // get the token role from decodedToken
    const userId = decodedToken?.issuer;
    return {userId,role};
  }
  return null;
}

4- Finally in _middleware.js function:
export async function middleware(req, ev) {
  console.log("ev in middleware", ev);
  const token = req ? req.cookies?.token : null;
  const {userId,role} = await verifyToken(token);
  // got the role and add logic for role
}


Check if string (or split string) contains any words from list

Question: I have a Twitter bot that needs to ignore tweets that contain certain blacklisted words.
This works, but only if the words in the tweet are exactly as they're seen in the list of blacklisted words.
timeline = filter(lambda status: not any(word in status.text.split() for word in wordBlacklist), timeline)

I want to make sure that tweets can't bypass this by putting symbols or adding additional characters around a word, such as bypassing blacklisted word "face" by appending "book" to the end of it, like so "facebook".
How do I do this in a way that fits within my filter's lambda?
Comment: Sounds like a job for regular expressions.
Comment: What does "putting symbols" mean?
Comment: An example along with expected output would be more appropriate.
Comment: @J0HN Sorry, I didn't mean replacing characters with symbols, just appending them.
Comment: Nothing to be sorry about - I asked for clarification, you responded when you have time. Everyone is happy :)
Answer: You can make use of re here.
import re
timeline = filter(lambda status: not any(re.findall(r"[a-zA-Z0-9]*"+word+r"[a-zA-Z0-9]*",status.text) for word in wordBlacklist), timeline)

You can also use re.escape() over word if word can contain some escape characters
If you expect symbols as well ,try
timeline = filter(lambda status: not any(re.findall(r"\S*"+word+r"\S*",status.text) for word in wordBlacklist), timeline)

Comment: How does it help against "putting symbols"? If I do understand OPs the intention right, `b0t` and `bot` should be treated as the same word. But I might be msitaking.
Comment: I would love to see a small regex-based fix for that, even if OP didn't mention that. By that, I mean using numbers, punctuation and other stuff instead of letters, aka l33t sp3/\k.
Comment: @J0HN if word is `bot` and text has `sdfdbot213123` this can be detected...i have edited for it..... but `bot` changed to `b0t` is tough considering there would be many scenarios
Comment: That's exactly what I mean. :) OP haven't yet answered my question about what he exactly meant, so it might make sense to wait for the nswer.
Comment: @J0HN as of now this answer stands valid as per the trivial example shown by OP :)
Answer: You can construct a regular expression based on the blacklist:
from itertools import ifilterfalse
import re

wordBlacklist = ['face', 'hello']

r = re.compile('|'.join(map(re.escape, wordBlacklist)))

...
timeline = list(ifilterfalse(lambda status: r.search(status.text), timeline))

Answer: Instead of filter, you can use a list comprehension, which is the same idea with a slightly different syntax, and then use regular expressions for the filtering, as your example is beyond the capabilities of string operations:
import re
blacklist = re.compile('face|friend|advertisement')
timeline = [word for word in status.split() if not blacklist.search(word)]
# filter version of this command:
timeline = filter(lambda word: not blacklist.search(word), status.split())

Now timeline will return a list of words that don't have any match to your blacklist within them, so "facebook" would be blocked because it matches "face", "friendly" would be blocked because it contains "friend", etc. However, you are going to need to get fancier for things like "f*acebook" or other tricks-- these would bypass the filter currently. Try out regex and get comfortable with them, and you can really make pretty fancy filters. Here is a good practice site for regex.


How can I prove this inequality? [...]

Question: $3^{n+m}+n^2+m^2>2^{n+m+2}-2n(m+2)-4(m+1)$ where $n,m \ge 1$ and are integres.
I haven't written a proof with two variables yet so this caught me off-guard. I would appreciate any hints and suggestions! Or even some links to questions that deal with a similar proof.
Thanks!
Comment: *Hint.* You can see that $n^2+m^2+2n(m+2)+4(m+1)=n^2+2n(m+2)+(m+2)^2=(n+m+2)^2$. It suffices to show that $3^{n+m}+(n+m+2)^2>2^{n+m+2}$. You may regard $t:=m+n$ and show the inequality $3^t+(t+2)^2>2^{t+2}$ by induction on $t$.
Comment: There seems to be lots of extraneous terms. It suffices to prove that $3^{n+m}>2^{n+m+2}$ for large $n,m$ and deal with the small cases more carefully
Comment: Just an idea: $n^2 + m^2 > 2^{n+m+2} - 2nm - 4n - 4m -4 - 3^{n+m}$ is equivalent to $(n+m)^2 > 2^{n+m+2} - 3^{n+m} - 4(n+m) - 4$. Now put $k = n+m$ so the inequality simplifies to $k^2 > 2^{k + 2} - 3^k - 4k - 4$, which could be simplified further
Answer: Do it in two steps by fixing first one term than the other.  So to do it by induction.
Base case: $n = m = 1$
$3^{n+m} +n^2 +m^2 = 3^2+1+1 =11$ and $2^{m+n+2} -2n(m+2) -4(m+1)= 2^4 - 2*6-4*2= 16-12-8=- 4$
First induction step:  Assume it is true for a specific $n$ and $m$.  Prove it is true for $n$ and $m+1$.
$3^{n+(m+1)} + n^2 + (m+1)^2 = 3^{n+m}\cdot 3 + n^2 + m^2 + 2m + 1 = [3^{n+m} + n^2 + m^2] + [2\cdot 3^{n+m} + 2m + 1]$
while $2^{(m+1) + n+2} -2n((m+1)+2) - 4((m+1)+1)=2\cdot 2^{m+n+2}- 2n(m+2) - 2n -4(m+1) - 4= [2^{m+n+2}- 2n(m+2) -4(m+1)]+[2^{m+n+2}- 2n-4]$
Now $3^{n+m} + n^2 + m^2 > 2^{m+n+2}- 2n(m+2) -4(m+1)$ and $2\cdot 3^{n+m} + 2m + 1> 2^{m+n+2}- 2n-4$ so
$3^{n+(m+1)} + n^2 + (m+1)^2>2^{(m+1) + n+2} -2n((m+1)+2) - 4((m+1)+1)$.
.....
The base case and that first induction step proves our first result:
Result 1: For $n = 1$ and $m \in \mathbb N$ then $3^{n+m} +n^2 +m^2 > 2^{m+n+2} -2n(m+2) -4(m+1)$.
Now we do a second induction step: Is we assume it is true for a specific $m$ and $n$ prove it is true for $m$ and $n+1$.
$3^{(n+1)+m+1} + (n+1)^2 + (m+1)^2 = 3^{n+m}\cdot 3 + n^2 +2n + 1+ m^2= [3^{n+m} + n^2 + m^2] + [2\cdot 3^{n+m} + 2n + 1]$
while $2^{n + (n+1)+2} -2(n+1)(m+2) - 4(m+1)=2\cdot 2^{m+n+2}- 2n(m+2) - 2(m+2) -4(m+1)= [2^{m+n+2}- 2n(m+2) -4(m+1)]+[2^{m+n+2}-2(m+2)]$
Now $3^{n+m} + n^2 + m^2 > 2^{m+n+2}- 2n(m+2) -4(m+1)$ and $2\cdot 3^{n+m} + 2n + 1> 2^{m+n+2}-2(m+2)$ so
That proves the second induction step.
Combine that with result 1) we have the result holds for any $n,m$

How can I prove this inequality? [...]


Why is the equivalent Cauchy sequence in a topological group well-defined?

Question: I was reading chapter 10 of Atiyah where I met the notion of
equivalent Cauchy sequences for topological groups.
Atiyah does not explain the reason why equivalent Cauchy sequences indeed give a equivalence relation. I can manage to prove the reflexivity and symmetry of this relation. But I failed to work out the transitivity.
Can anyon help me on this? Thank you.
FYI. A Cauchy sequence of a topological group $G$ is a sequence $(x_n)_{n \in \mathbb{N}}$ such that for any open neighbourhood $U$ of $0$ (the identity of $G$), there is $N \triangleq N(U)$ such that for any $n,m > N, x_n-x_m \in U$.
And we say that two Cauchy sequences $(x_n)$ and $(y_n)$ are equivalent if $x_n-y_n$ converges to $0$, that is, for every open neighbourhood $U$ of $0$, there is $N$ such that for all $n > N, x_n-y_n \in U$.
I can see that for any open neighbourhood $U$ 0f $0$, if we can find an open neighbourhood $V$ of $0$ such that $V+V \subset U$, then the transivity will be proved. But, indeed how to explain the existence of such $V$?
Answer: This is a standard theorem on topological groups, and follows from the continuity
of the group operation. I'll write that as addition, and assume the operation is commutative, but the argument works for non-commutative groups too.
As addition is continuous, then if $U$ is an open neighbourhood
of $0$ then $W=\{(a,b)\in G\times G:a+b\in U\}$ is an open neighbourhood of
$(0,0)$ in $G\times G$. By definition of the product topology, there are
open neighbourhoods $V_1$ and $V_2$ of $0$ with $V_1\times V_2\subseteq W$.
Let $V=V_1\cap V_2$. It is an open neighbourhood of $0$ and
$V\times V\subseteq W$, that is $a+b\in U$ for all $a$, $b\in V$.
Answer: The existence of such a $V$ follows from the definition of continuity of $+$ at $(0,0)$:
There is a basic open neighbourhood $U_1 \times U_2$ that contains $(0,0)$ such that $+[U_1 \times U_2] = U_1 + U_2 \subseteq U$
Now use $V=U_1 \cap U_2$.
This works in any topological group.


Custom Marker Properties in Android

Question: With the google map api, for every marker I create i want to have a custom property that will state more information about that location. Is it possible for me to add a custom property? Or do i have to make a separate class?
Maybe something like this?
Marker m = mMap.addMarker(new MarkerOptions()
            .position(new LatLng(lati, longi))
            .title(title)
             .snippet(snippet)
            .customProperty1(true));

If I was to make a new class, code snippets would be greatly appreciated !
Comment: which type properties you actual want?
Answer: you can create custom marker and add details in it.
you can pass information in title or snippet only and use it in your custom marker
mapView.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {

            // Use default InfoWindow frame
            @Override
            public View getInfoWindow(Marker arg0) {
                return null;
            }

            // Defines the contents of the InfoWindow
            @Override
            public View getInfoContents(Marker arg0) {

                // Getting view from the layout file info_window_layout
                View v = getActivity().getLayoutInflater().inflate(R.layout.layout_mapinfo, null); // my custom view

                // Getting the position from the marker
                //   LatLng latLng = arg0.getPosition();

                // Getting reference to the TextView to set latitude
                TextView tvLat = (TextView) v.findViewById(R.id.tv_lat);

                // Getting reference to the TextView to set longitude
                TextView tvLng = (TextView) v.findViewById(R.id.tv_lng);

                // Setting the latitude
                tvLat.setText(arg0.getTitle());

                // Setting the longitude
                AppSession.setIconTypeface(tvLng);
                tvLng.setText(Html.fromHtml(arg0.getSnippet()));

                // Returning the view containing InfoWindow contents
                return v;

            }
        });

layout_mapinfo.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical">

    <TextView
        android:id="@+id/tv_lat"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textStyle="bold"
        android:gravity="center_horizontal"

        />

    <TextView
        android:id="@+id/tv_lng"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
         android:textStyle="bold"
        android:layout_gravity="center"
        android:gravity="center"

        />

</LinearLayout>

how to pass value in titles and snippet and how to interprete it in your custom view is depended on your requirement.
hope this will help.
Note : This snippet is for example purpose.
Comment: Hmm I understand, however if snippet only accepts a string value, how do I add multiple properties in a snippet through an array or something. Could you provide  some samples for that?
Comment: Yes you can pass comma separated values in string and split it in array in adaptor.  Check how to convert string to array @J.Tey

Custom Marker Properties in Android


Boost phoenix or lambda library problem: removing elements from a std::vector

Question: I recently ran into a problem that I thought boost::lambda or boost::phoenix could help be solve, but I was not able to get the syntax right and so I did it another way. What I wanted to do was remove all the elements in "strings" that were less than a certain length and not in another container.
This is my first try:
std::vector<std::string> strings = getstrings();
std::set<std::string> others = getothers();
strings.erase(std::remove_if(strings.begin(), strings.end(), (_1.length() < 24 &&  others.find(_1) == others.end())), strings.end());

How I ended up doing it was this:
struct Discard
{
    bool operator()(std::set<std::string> &cont, const std::string &s)
    {
        return cont.find(s) == cont.end() && s.length() < 24;
    }
};

lines.erase(std::remove_if( lines.begin(), lines.end(), boost::bind<bool>(Discard(), old_samples, _1)), lines.end());

Comment: In your "ended up doing" code snippet, there's no need for Boost Bind.  Just pass the set (reference) to the Discard constructor.
Answer: You need boost::labmda::bind to lambda-ify function calls, for example the length < 24 part becomes:
bind(&string::length, _1) < 24

EDIT
See "Head Geek"'s post for why set::find is tricky.  He got it to resolve the correct set::find overload (so I copied that part), but he missed an essential boost::ref() -- which is why the comparison with end() always failed (the container was copied).
int main()
{
  vector<string> strings = getstrings();
  set<string> others = getothers();
  set<string>::const_iterator (set<string>::*findFn)(const std::string&) const = &set<string>::find;
  strings.erase(
    remove_if(strings.begin(), strings.end(),
        bind(&string::length, _1) < 24 &&
        bind(findFn, boost::ref(others), _1) == others.end()
      ), strings.end());
  copy(strings.begin(), strings.end(), ostream_iterator<string>(cout, ", "));
  return 0;
}

Comment: D'oh! Of course... thanks for the hint, I'll add that to mine too.
Answer: The main problem, other than the bind calls (Adam Mitz was correct on that part), is that std::set<std::string>::find is an overloaded function, so you can't specify it directly in the bind call. You need to tell the compiler which find to use, like so:
using namespace boost::lambda;
typedef std::vector<std::string> T1;
typedef std::set<std::string> T2;

T1 strings = getstrings();
T2 others = getothers();

T2::const_iterator (T2::*findFn)(const std::string&) const=&T2::find;
T2::const_iterator othersEnd=others.end();

strings.erase(std::remove_if(strings.begin(), strings.end(),
    (bind(&std::string::length, _1) < 24
        && bind(findFn, boost::ref(others), _1) == othersEnd)),
    strings.end());

This compiles, but it doesn't work properly, for reasons I haven't yet figured out... the find function is never returning others.end(), so it's never deleting anything. Still working on that part.
EDIT: Correction, the find function is returning others.end(), but the comparison isn't recognizing it. I don't know why.
LATER EDIT: Thanks to Adam's comment, I see what was going wrong, and have corrected the problem. It now works as intended.
(Look at the edit history if you want to see my full test program.)


Como adicionar métodos personalizado em todos os serviços do spring data

Question: Eu Implementei métodos em um Repository para todos os meus repositórios filhos tenha os mesmo métodos. Abaixa vai o código de como eu implementei um Repository Personalizado
Esta é a interface:
 @NoRepositoryBean
 public interface BaseMyRepository<T, ID extends Serializable> extends JpaRepository<T, ID>{

     List<T> findCustomNativeQuery(String sqlQuery);
 }

Este é a implementação da classe:
 public class BaseMyRepositoryImpl<T, ID extends Serializable> extends SimpleJpaRepository<T, ID> implements BaseMyRepository<T, ID>{

     private final EntityManager entityManager;

     public BaseMyRepositoryImpl(JpaEntityInformation entityInformation, EntityManager entityManager){
         super(entityInformation, entityManager);
         this.entityManager = entityManager;
     }

     @Transactional
     @Override
     public List<T> findCustomNativeQuery(String sqlQuery) {
         List<T> lista = entityManager.createNativeQuery(sqlQuery, this.getDomainClass()).getResultList();

         return lista;
     }

 }

Este é o meu repositório (Repository):
 public interface MyRepository extends BaseMyRepository<SmaempreEntity, Integer>{

 }

Agora eu preciso saber se é possível fazer o código abaixo. Abaixo eu exemplifiquei do que eu preciso.
 @Service
 @Transactional
 public class MyBaseService<R extends BaseMyRepository, E> {

     @Autowired
     private R;

     public List<E> findAll() {
         return R.findAll();
     }

    public List<E> findCustomNativeQuery(String sqlQuery) {
         return R.findCustomNativeQuery(sqlQuery);
     }
 }

 public class MyService extends MyBaseService<MyRepository, MyEntity> {

 }

Answer: Só de olhar assim é meio complicado, mas acredito que funcionaria.
Você tentou rodar o projeto e deu algum erro? Se sim, posta aqui o erro que podemos te ajudar melhor.
Answer: Eu consegui executar a classe de acordo com o que eu precisei acima. Abaixo vai o código e usei pra executar.
 public class BaseMyService<R extends BaseMyRepository, E> {

     public String COLUMNS_RESUME = null;

     @Autowired
     private final R baseMyRepository;

     public BaseMyService(R myRepository) {
         this.baseMyRepository = myRepository;
     }

     public List<E> findAll() {
         return baseMyRepository.findAll();
     }

     public List<E> findCustomNativeQuery(String sqlQuery) {

         return baseMyRepository.findCustomNativeQuery(sqlQuery);
     }
 }

 @Service
 @Transactional
 public class MyService extends BaseMyService<MyRepository, MyEntity>{

     public MyService(MyRepository myRepository) {
         super(myRepository);
     }
 }

Dessa forma eu consegui customizar uma classe de serviços onde eu posso estender ela e usar os mesmos métodos em todos os serviços.


Mirroring Docker Traffic to Different Port in Same Container

Question: I am using docker containers on CentOS to simulate devices on the network and have two tools that are to run inside each of those containers to simulate communication with actual network devices.  Individually, either tool works inside the docker containers and can communicate with the outside world via one port we'll call 8000 here, but due to both attempting to use 8000, they are unable to run simultaneously.  To resolve this, I am looking to mirror traffic on 8000 to another port we'll call 8001 here so that one tool can run on 8000 while the other receives its packets on 8001.  In my Dockerfile, I EXPOSE both of these (though do not publish them in the run command).
Poking around the internet, I found this.  Attempting to adapt it to my purposes, I ended up with the below, which I execute from within docker exec -it <container> bash.  By my primitive understanding, it should copy the message to a different localhost IP's port 8000 while letting the original message through, then pass the duplicate packet back to 127.0.0.1:8001.
iptables -t mangle -A PREROUTING -p UDP --dport 8000 -j TEE --gateway 127.0.0.2
iptables -t nat -A PREROUTING -d 127.0.0.2 -p UDP --dport 8000 -j DNAT --to 127.0.0.1:8001

This does not appear to be working.  Running a tool on 8001 caused it to miss all packets I threw at 8000 from the outside world.
Similarly, I found this one, and tried adapting it to the below, but it doesn't seem to work either, and trying to get netcat running properly in a container has proven to be quite the headache.
iptables -A PREROUTING -t mangle -p tcp ! -s 127.0.0.1 --dport 8000 -j TEE --gateway 127.0.0.1
iptables -A OUTPUT -t nat -p tcp -s 127.0.0.1/32 --dport 8000 -j DNAT --to 127.0.0.1:8001

I am new to both docker and iptables, so any explanation of the underlying mechanisms of what is going wrong here would be greatly appreciated.
Answer: After a great deal of effort, the following solution was discovered that needs to run inside the container:
sysctl -w net.ipv4.conf.eth0.route_localnet=1
iptables -t mangle -A PREROUTING -i eth0 -p UDP --dport 8000 -j TEE --gateway 127.0.0.1
iptables -t nat -A PREROUTING -p UDP --dport 8000 -j DNAT --to-destination 127.0.0.1:8001

The key thing missing was the sysctl command to be run inside the container to allow things in the first place.  Then, it needed to be eth0 instead of the previous solutions as otherwise you would end up with infinite loops.


Handle database connection exception via custom handler

Question: I want to catch the database connection exceptions with a custom handler. I have already built an handler which is overriding the default logger factory, but now I want to use that custom handler to log database exceptions, without hacking the core.
I can see the connection driver uses the following code in open().
try {
  $pdo = new \PDO($dsn, $connection_options['username'], $connection_options['password'], $connection_options['pdo']);
}
catch (\PDOException $e) {
  if ($e->getCode() == static::DATABASE_NOT_FOUND) {
    throw new DatabaseNotFoundException($e->getMessage(), $e->getCode(), $e);
  }
  if ($e->getCode() == static::ACCESS_DENIED) {
    throw new DatabaseAccessDeniedException($e->getMessage(), $e->getCode(), $e);
  }
  throw $e;
}

I am not sure how I can catch the exception and log it using the handler. How can I achieve this?
Answer: To handle the logging for a specific exception implement an exception subscriber with a priority higher than 50, so that it runs before Drupal\Core\EventSubscriber\ExceptionLoggingSubscriber:
src/EventSubscriber/ExampleExceptionSubscriber
namespace Drupal\mymodule\EventSubscriber;

use Drupal\Core\Database\DatabaseAccessDeniedException;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\KernelEvents;

/**
 * Example for catching a DatabaseAccessDeniedException
 */
class ExampleExceptionSubscriber implements EventSubscriberInterface {

  /**
   * @var \Drupal\Core\Logger\LoggerChannelFactoryInterface
   */
  protected $logger;

  public function __construct(LoggerChannelFactoryInterface $logger) {
    $this->logger = $logger;
  }

  public function onException(GetResponseForExceptionEvent $event) {
    $exception = $event->getException();
    if ($exception instanceof DatabaseAccessDeniedException) {
      $this->logger->get('php')->error('Custom logging message');
      $response = new Response('Custom error message', 500);
      $event->setResponse($response);
    }
  }

  public static function getSubscribedEvents() {
    $events[KernelEvents::EXCEPTION][] = ['onException', 60];
    return $events;
  }
}

mymodule.services.yml
services:
  mymodule.exception.subscriber:
    class: Drupal\mymodule\EventSubscriber\ExampleExceptionSubscriber
    arguments: ['@logger.factory']
    tags:
      - { name: event_subscriber }

If you don't set a response this subscriber only logs the error and the response is set by a subscriber with a lower priority. In this case you get two log entries, one from your subscriber and one from ExceptionLoggingSubscriber, because the dispatcher runs the event subscribers until one returns a response. Logging does not stop this.
Another option would be to extend ExceptionLoggingSubscriber, put the custom code in ExceptionLoggingSubscriber::onException and call the parent method to run standard logging when your custom code doesn't apply. Instead of putting the service in mymodule.services.yml you need to swap the existing service in the container then, see https://www.drupal.org/docs/8/api/services-and-dependency-injection/altering-existing-services-providing-dynamic-services
You find more infos about exception handling here How do handle exceptions?
Comment: thanks @4k4, that looks promising, however I tried but it seems my subscriber is not getting called, I will debug. Thanks again, a big big help :)
Comment: hi @arpitr . Did you manage to get a solution for this? My subscriber is not being called as well
Comment: Thank you for this. I eventually got it to work by putting qoutes around the class in the servives.yml file. ```'\Drupal\magri_rest\EventSubscriber\ExceptionsSubscriber'```
Comment: @tendaitakas, this is strange that you needed to do this, I can't find any *.services.yml file with class names in quotes.
Comment: I corrected it when I saw this [article](https://www.drupal.org/docs/8/creating-custom-modules/subscribe-to-and-dispatch-events).


Is there any complete tutorial for setting up a full QEMU-KVM from hypervisor to host through command line ?

Question: I've found parts about how to use virt-install from scratch or almost like http://virt-tools.org/learning/install-with-command-line/
However I'm stuck at connecting to the VM through virsh once the first part is done. Most tutorial use graphical client, I would like to be able to do it on a remote server which has no UI layer. Is it even possible ?
Answer: The simplest solution is for you to install virt-manager on your local machine. You can use it to connect to libvirt on the remote machine and then open the remote VMs' graphical consoles.
Comment: virt-manager can tunnel libvirt over SSH, so all you really need is to set up authorized SSH keys and go.
Comment: That sounds like a neat solution. I'll try it and provide you with some feedback.


Calculo em php dando erro

Question: No meu site tenho o seguinte código para calcular descontos:
$valor_a_ser_calculado =$_POST['loc']; // valor original
$quantos_porcento = 75/100; //isso equivale a 7%
$loc = $quantos_porcento * $valor_a_ser_calculado . "\n";

só que está dando o seguinte erro:
PHP Warning:  A non-numeric value encountered in /home/jp/public_html/orcamento.php on line 6

Gostaria de saber como resolver isso
Comment: `$loc = ($quantos_porcento * $valor_a_ser_calculado ). "\n";`
Comment: Separe a parte numérica da parte string com parenteses. Além disso, verifique se o valor do POST está correto antes de mais nada.
Comment: Coloquei os parentes e deu erro, e sim o valor do post está correto.
Comment: A onde eu tenho que colocar os parentes exatamente?
Answer: Você tem dois problemas imediatos no código: Não está verificando se o valor do POST está correto, e misturando multiplicação com concatenação. Teste com isto:
$valorasercalculado = $_POST['loc']; // valor original
echo "Valor original: $valorasercalculado
";

$quantos_porcento = 75/100; //isso equivale a 7.5%
echo "Porcentagem: $quantosporcento
";

$loc = $quantos_porcento * $valor_a_ser_calculado;
echo "Resultado: $loc
";

Neste caso, somente terá warnings se algum dos valores não for numérico.
O ideal seria repensar algo nesse sentido:
$valorasercalculado = isset($_POST['loc']) ? $_POST['loc'] : 0;

Ou mesmo
if (!isset($_POST['loc'])) die 'Valor não fornecido';

logo no começo do código.
Como bem lembrado pelo colega @RafaelSalomao, o PHP tem uma função específica para testar se um valor é numérico. Juntando as duas idéias:
if (!isset($_POST['loc'])) die 'Valor não fornecido';
if (!is_numeric($_POST['loc'])) die 'O valor precisa ser numérico';

(lembrando que o ! antes da função significa "not", nos casos acima, se o valor NÃO for setado, o script para. Se o valor NÃO for numérico, o script também para).
Manual:

http://php.net/manual/pt_BR/function.isset.php

http://php.net/manual/pt_BR/function.is-numeric.php
Comment: Bacco o mérito da resposta é seu! Apenas sugeri uma edição utilizando a função is_numeric do php para validar o valor enviado por POST. Lembrando que deverá também validar essa condição em seu formulário.
Comment: Bacco muito obrigado funcionou perfeitamente, valeu aí.
Comment: @RafaelSalomão agradeço a intenção, fique à vontade para propor uma resposta alternativa (múltiplas respostas são bem-vindas no site, desde que complementares). Inicialmente minha intenção foi apenas fazer com que o autor verifique os parâmetros.
Comment: @JoãoPedroAlmeida vou melhorar um pouco a resposta, vale notar que o colega Rafael Salomão sugeriu o uso de is_numeric para que você veja se o valor passado é realmente um número.
Comment: @RafaelSalomão acrescentei sua sugestão de uma outra forma, grato.
Comment: Ok, Irmão, ficou luxo!
Comment: @RafaelSalomão mas se quiser complementar com outra resposta, é bem-vindo!
Comment: @RafaelSalomão valeu cara, as duas respostas foram boas porém a do bacco deu mais certo para o meu caso.

Calculo em php dando erro


Exim4 Smart Host Relay

Question: I am running Exim 4.71. I want to:

Route all email from A.com through mail.A.com
Route all email from [B-E].com through mail.B.com
Send all other email directly.

Here is the configuration I have that doesn't work like I hoped:

domainlist a_domains = a.com
domainlist b_domains = b.com : c.com : d.com : e.com

begin routers

smart_route_a:
  driver = manualroute
  domains = +a_domains
  transport = remote_smtp
  route_list = +a_domains mail.a.com
  no_more

smart_route_b:
  driver = manualroute
  domains = +b_domains
  transport = remote_smtp
  route_list = +b_domains mail.mollenhour.com
  no_more

dnslookup:
  driver = dnslookup
  domains = ! +local_domains
  transport = remote_smtp
  ignore_target_hosts = 0.0.0.0 : 127.0.0.0/8
  no_more

When I send an email e.g. with PHP's mail() or Zend_Mail_Transport_Smtp setting both From: and Return-Path: as email@example.com, the smart_route_a router is not used, the dnslookup is used instead. Disabling dnslookup results in no mail being sent.
From the logs it appears that email sent to email@example.com uses smart_route_a, but the same email sent from email@example.com to firstname.lastname@example.com is sent using dnslookup.
How do I make email from firstname.lastname@example.com be relayed via mail.a.com?
Answer: Use a conditional like
route_list = * "${if match{$header_from:}{\N.*\.a\.com$\N} {mail.a.com}}"

domains = only checks the destination domain not the source domain.

Exim4 Smart Host Relay


How to add root user in nis passwd file?

Question: One of the sys admins accidentally moved aside /etc/passwd... doh!
Restoring the file from backup doesn't work... it errors out because root user does not exist.
I've got NIS running at this site and serving the passwd/group/shadow files and I tried to add a root user but I can't get this to propogate (I tried different values for MINUID and MINGID). I understand why NIS would want to avoid doing such a thing, but, errrm, HELP!
The server is running CentOS 5.6 and it doesn't have a CD/DVD drive so I can't reboot onto a rescue CD.
Any suggestions?
Comment: Have you the ability to boot it remotely via an .ISO file as you can on most HP servers via iLO or Dell via DRAC?
Comment: Hell, PXE boot the thing into a rescue environment.  However you got the OS installed in the first place, you can use that same method to get a rescue environment.
Answer: I'm sure there is some way to try shoehorning the root user onto it, but if you're desperate to get it working again in a minimal timeframe my method of getting it to work would be a USB thumbdrive or USB CD-drive that you can boot from with a rescue CD; either of these should be readily available and by the time you find a way to use a clever workaround you probably could have been back from the local retailer with the drive and the download of a rescue distro waiting at your desktop.
You don't mention more information on the server but there's a possibility that it's not running RAID (or the system drive isn't RAIDED)? If that's the case you can remove the drive and mount it in another system and alter the file there. Depending on how critical the system is you can try mounting the drive and controller in another system to bring the whole RAID volume up as another drive.
You might want to consider getting the USB drive as a backup to your recovery process for that server in the future. Your problems may be human error this time but that doesn't preclude drive corruption in the future causing similar issues.
Comment: I was hoping to avoid rebooting the server as it is a production machine. But also this server (IBM System X 3650) has 2 megaraid controllers and the BIOS was a nasty piece of work - there is a problem with it such that it had to be cajoled/hacked into seeing the root partition on the local disk. So frankly I am not that confident that once I am on a rescue CD, the BIOS will be able to recognise (and allow me to mount) the local root partition. And I am also concerned that if there is no root UID, would the machine even be able to boot again? So I would like to try the NIS hacking if possible.
Comment: Womble suggested PXE boot if it supported it, which could work too but assumes you have an environment set up to do so (or you will need to take time to get that working), or you would have to look at what security fixes are available but not applied to your server to "break" into it. If your backups are truly truly up to date you could find some filesystem gurus to try getting raw disk access, if you have a user with permissions to edit the raw drive and try restoring the file with a hex editor...but if it's RAIDed there's not way I'd ever consider it more than a nanosecond.
Comment: How would you have planned to restore the system from backup otherwise? It should have some way of booting to restore from bare metal; it may allow a selective restore from a boot environment as well.
Comment: (I know you don't want to reboot it, but if you're trying to hot-fix it in untested ways, you're risking your data and system integrity in the process; a half-hour of downtime from a reboot/restore is probably better than a day of downtime from a goofed MacGuyverism on the filesystem, especially if you're in panic mode and may overlook something in the process)
Comment: I did install with PXE boot/kickstart, and the root drive is mirrored. But what you guys don't know is that this BIOS is about as friendly as a hungry alligator. If I reboot, I am not sure I will be able to recover in a reasonable time (hell it took 2 weeks working with IBM to get an OS installed, I have never met such a broken BIOS before).   NIS is already serving passwd/group/shadow information, it *has* to be able to serve a 0 UID somehow... Then again maybe I don't have any other option but to wrestle with the alligator.  Thanks for all your help with this I very much appreciate it!
Comment: sorry unrelated, but you seem to be an expert. would you mind viewing my question? https://serverfault.com/questions/905235/nis-password-map-root-user
Answer: You might try temporarily editing the NIS Makefile on the NIS master server.  Where it currently says
passwd.byname: $(PASSWD) $(SHADOW) $(YPDIR)/Makefile
        @echo "Updating $@..."
        @$(UMASK); \
        $(MERGER) -p $(PASSWD) $(SHADOW) | \
           $(AWK) -F: '!/^[-+#]/ { if ($$1 != "" && $$3 >= $(MINUID) && $$3 !=$(NFSNOBODYUID)) \
           print $$1"\t"$$0 }' | $(DBLOAD) -i $(PASSWD) \
                -o $(YPMAPDIR)/$@ - $@
        -@$(NOPUSH) || $(YPPUSH) -d $(DOMAIN) $@

try changing that awk line to remove the tests for MINUID and NFSNOBODYUID, eg
           $(AWK) -F: '!/^[-+#]/ { if ("" == "") \

and similarly in the section for passwd.byuid, remake the passwd maps, and see if the root entry is now in there with ypcat passwd.
Comment: Nice try! But unfortunately I get an error which I can't figure out how to fix:  Updating passwd.byname...
/bin/sh: -c: line 1: syntax error: unexpected end of file
gmake[1]: *** [passwd.byname] Error 2
gmake[1]: Leaving directory `/var/yp/nis.cambridge.scr.slb.com'
make: *** [target] Error 2
Comment: sorry unrelated, but you seem to be an expert. would you mind viewing my question? https://serverfault.com/questions/905235/nis-password-map-root-user


(python) I keep getting an IndexError: string index out of range

Question: I am trying to solve the question
Implement the mapper, mapFileToCount, which takes a string (text from a file) and returns the number of capitalized words in that string. A word is defined as a series
of characters separated from other words by either a space or a newline. A word is capitalized if its first letter is capitalized (A vs a).
and my python code currently reads
def mapFileToCount(s):
    lines = (str(s)).splitlines()
    words = (str(lines)).split(" ")
    up = 0
    for word in words:
        if word[0].isupper() == True:
            up = up + 1
    return up

However I keep getting the error IndexError: string index out of range
please help
Comment: don't do `str(lines)` this is an array, print it and you'll see
Comment: Start your interpreter. Enter `lines = str("hello world").splitlines()` and `words = (str(lines)).split(" ")`, then look at what `lines`, `str(lines)`, and `words` are. (And don't sprinkle `str` over the code.)
Comment: You probably have a word which is an empty string `''` as a result of the split.
Answer: For now

given Hi huy \n hi you there
lines will be ['Hi huy ', ' hi you there']
words will be ["['Hi", 'huy', "',", "'", 'hi', 'you', "there']"] as you use the str(lines) to split on

I'd suggest you split on any whitespace at once with words = re.split("\s+", s).

Then the problem of IndexError comes in cases like Hi where are you__ (_ is space), when you split there will be an empty string at the end, and you can't access the first char char of this, so just add a condition in the if

if word because 0-size word are False, and other True
if word[0].isupper() for you test

import re
def mapFileToCount(s):
    words = re.split("\s+", s)
    up = 0
    for word in words:
        if word and word[0].isupper():
            up = up + 1
    return up

Answer: The string index out of range means that the index you are trying to access does not exist in a string. That means you're trying to get a character from the string at a given point. If that given point does not exist , then you will be trying to get a character that is not inside of the string.
In your code its that word[0].


Get submitted value of a select list error on #options - Drupal 7

Question: I have seen this block of code in a few places as the correct method:
<code>$selected_index = $form_state['values']['select_field'];
$display_value = $form['select_field']['#options'][$selected_index];
</code>
So here is my code for it:
<code>$key1 = $form_state['values']['field_setup_time3'];
$reservationStartPadding = $form['field_setup_time3']['#options'][$key1];
</code>
But I get this error with my code:
<code>Notice: Undefined index: #options in ... blah blah blah
</code>
I am using a List (integer) running a select list with 4 options in it. Is options not the right choice here? I just need the numerical value from the user selected dropdown list when they submit the calendar booking.
Thanks!
Comment: when you use the Devel module and `dpm()` every variable you've created ... what do you see ? For example in your code add: `dpm($selected_index);dpm($display_value);dpm($key1);dpm($reservationStartPadding);` ... i bet you something has a `value` you've assumed is a Number, but is something else (the string `#options`).
Comment: After installing devel read [this](http://drupal.stackexchange.com/questions/27767/why-is-hook-form-alter-so-messy-in-d7/27784#27784), it should help to explain why the options aren't where you're trying to find them
Answer: Thanks to tenken and Clive I was able to figure it out.
<code>$key1 = $form_state['values']['field_setup_time3'];
</code>
This line outputted as a string. Since I was only using integers in my select list, the label and key value were the same. I removed both lines of code and replaced it with this (after some playing around with devel):
<code>$reservationStartPadding = $form_state['values']['field_setup_time3']['und'][0]['value'];
</code>
This outputted the value as a number and not as a string. I was able to use it from there in my future code correctly.


Rails RESTful to_xml - how to achieve connectedness?

Question: After reading the book RESTful Web Services by Leonard Richardson and Sam Ruby, it seems to me, that the to_xml method of rails is not as restful as it should be. Specifically, the book introduces the Resource Oriented Architecture, one of the tenets of which is connectedness: Representations of a resource should contain not only the data of the resource, but also links to other resources.
However, when rails scaffolds a resource, it implements requests for a xml representation by deferring to [model]#to_xml. This method does not have access to the normal path helpers, so any links to other resources are only indicated by their ids, not by their uris.
I have solved this problem for now, but the solution doesn't seem very robust: Given a Employer resource with nested Employees, the following code (sort of) adds uris to their xml serialization:
class Employee < ActiveRecord::Base

  include ActionController::UrlWriter

  belongs_to :employer

  def to_xml(options = {})
    options[:procs] = [ Proc.new {|options| options[:builder].tag!('uri', employer_employee_path(employer, self)) } ]
    if options[:depth].nil?
      options[:depth] = 1
    end
    if options[:depth] != 0
      options[:depth] -= 1;
      options[:include] = [:employer]
    end
    super(options)
  end
end

class Employer < ActiveRecord::Base

  include ActionController::UrlWriter

  has_many :employees

  def to_xml(options = {})
    options[:procs] = [ Proc.new {|options| options[:builder].tag!('uri', employer_path(self)) } ]
    if options[:depth].nil?
      options[:depth] = 1
    end
    if options[:depth] != 0
      options[:depth] -= 1;
      options[:include] = [:employees]
    end
    super(options)
  end
end

The UrlWriter allows me to properly create the path of a resource (not the full uri, though. The domain will have to be pasted on to the path by the clients of my web service). Now the models are responsible for their own uri, and for including the representation of any connected resource. I use the :depth option to avoid recursing endlessly.
This method works, but as stated before, it doesn't seem quite right, with all the duplication. Has anybody else had the same problem and does anybody else have a better idea of how to get uris in the xml representation?
Answer: You could use the :methods option to include additional values. For example.
# in controller
employer.to_xml(:include => :employees, :methods => [:uri])

class Employee < ActiveRecord::Base
  include ActionController::UrlWriter
  belongs_to :employer

  def uri(options = {})
    polymorphic_path([employer, self])
  end
end

class Employer < ActiveRecord::Base
  include ActionController::UrlWriter
  has_many :employees

  def uri(options = {})
    polymorphic_path(self)
  end
end

Notice I'm using polymorphic_path here. This is a more generic path method which you might find more abstractions through.
However, I do not think this is that great of a solution. Including UrlWriter in the model is messy and can take a long time if you have a large number of routes. An alternative is to make the "uri" a simple accessor method.
# in model
attr_accessor :uri

And then you can set the uri for the model(s) in the controller. Unfortunately that is pretty messy too.
employer.uri = polymorphic_path(employer)
employer.employees.each { |e| e.uri = polymorphic_path([employer, e]) }
employer.to_xml(:include => :employees, :methods => [:uri])

Comment: I agree, that including UrlWriter in the model is messy. Even the UrlWriter namespace indicates, that it is logically a part of the controller, not the model. I guess the overarching problem is that in the case of xml, the model is left in charge of its own representation.
Comment: Exactly. I think the XML presentation belongs in the view layer which makes sense if it needs to include URL paths etc. You could probably make a generic render_xml method which behaves like to_xml but is run in the scope of a view so it has access to all helpers.
Comment: BTW, if you do end up calling "include ActionController::UrlWriter" in every model, its best to call it in ActiveRecord::Base just once. Startup times will be much better if there are a lot of routes (but, still I don't recommend this in general).
Answer: Yes... this belongs in the view. Why not use the built in XML Builder?
#in controller
respond_to do |format|
  format.xml  # show.xml.builder
end

Then simply create a show.xml.builder file like so
# in show.xml.builder
xml.instruct!
xml.employer do
  xml.name @employer.name
  ...
  xml.uri polymorphic_path(employer)
end

Answer: Putting a bunch of Builder code in your controller is kind of unsatisfying to me. Plus then you can't use Array#to_xml, which is pretty concise and convenient.
How about something like this:
#things_controller.rb
def index
  render :xml=>Thing.all.to_xml(:thing_url=>thing_url('#{self.code}'))
end

#thing.rb
def to_xml(options={})
  if thing_url = options[:thing_url]
    thing_url = eval('"'+CGI.unescape(options.delete(:thing_url))+'"')
  end
  super do |builder|
    builder.tag!('thing-url', thing_url) if thing_url
  end
end


why t-sql patindex not work with declared variable?

Question: why this query is not work correctly?
declare @s nvarchar
set @s = 'abcd'
select patindex('%b%', @s)

it is return zero.
Comment: i accept every usefull question
Answer: It works if you add a size to your initial declaration of the varchar:
declare @s nvarchar(10)
set @s = 'abcd'
select patindex('%b%', @s)

Comment: +1 - beat me to it! Will keep my answer anyway for it's pointer to reference on similar related gotchas
Answer: It's because if you don't define the size of the NVARCHAR variable, it will be defaulting to size 1. So @s will only ever contain 'a'.
You need to always be careful, to make sure you define the sizes explicitly as different scenarios behave differently as I blogged here.
So, just change
DECLARE @s NVARCHAR

to (e.g.)
DECLARE @s NVARCHAR(20)


how to set smtp for drupal

Question: I am working on Drupal 6  my php.ini settings are:
SMTP = localhost
smtp_port = 25

in module in am using
function article_mail($key, &$message, $params) {
  switch ($key) {
    case 'invitation':
      // note: data can be passed to this function in the $params array
      $message['subject'] = t('EMAIL SUBJECT');
      $message['body'] = t('MESSAGE BODY');
      break;
  }
}

and in code i use
$params = array(  'myVar' => 'data you would like in your message and/or subject',);
drupal_mail('article', 'invitation', 'email@example.com', language_default(), $params);

but it gives

warning: mail(): Failed to connect to mailserver at "localhost" port
  25, verify your "SMTP" and "smtp_port" setting in php.ini or use
  ini_set() in C:\Program Files (x86)\Apache Software
  Foundation\Apache2.2\htdocs\benthamdirect\includes\mail.inc on line
  193. Unable to send e-mail. Please contact the site administrator if the problem persists.

Can anyone suggest where I am going wrong?
Answer: Try the SMTP module to send mails via SMTP:

This module allows Drupal to bypass the PHP mail() function and send email directly to an SMTP server. The module supports SMTP authentication and can even connect to servers using SSL if supported by PHP.
Answer: The error message indicates that no SMTP server is running on your localhost. Test this (as shown here), and install and configure a SMTP server like postfix if needed. Once your local SMTP server is tested successfully outside of Drupal, come back and test mail sending from within Drupal.
Running an own SMTP server on localhost can be meaningful for development, but for production sites, it is quite a headache nowadays to set it up so that it delivers all mail successfully rather than appearing as a spam server to major e-mail providers (GMail, Hotmail etc.). That's where the SMTP module and similar Drupal modules come in: you then can use a third-party SMTP server, which works fine if the e-mail volume is low to moderate.
Comment: This is the correct answer. "What am I doing wrong?" "With your code, nothing, but you need to have an SMTP server on your computer."

how to set smtp for drupal


How do I store a string as an array in a Cocoa property list?

Question: I am trying to save two strings. One string needs to be saved as type ARRAY in the pList and the second string needs to be saved as String in the Array.
I can use the code:
[dictionary setObject:(id)anObject forKey:(id)aKey>]
but it doesn't save it correctly. I can cast one of the strings as an array, but it still doesn't work right.
What is the proper method for saving an array to the pList?
Here is what my pList looks like:
<dict>
<key>Test One</key>
<array>
    <string>A13#</string>
</array>
<key>Another Test</key>
<array>
    <string>1111111111</string>
</array>
<key>Test Three</key>
<array>
    <string>2222222222</string>
</array>
<key>Final Test</key>
<array>
    <string>3333333333</string>
</array>
</dict>

here is the method I am using to try to
-(void)writeToFile:(NSString *)s1{
    NSBundle *bundle = [NSBundle mainBundle];
NSString *plistPath = [bundle pathForResource:@"saved" ofType:@"plist"];

NSMutableDictionary *dictionary = [[[NSDictionary alloc] initWithContentsOfFile:plistPath] mutableCopy];
NSString *tempString = [NSString stringWithFormat:@"1234567"];
[dictionary setObject:tempString forKey:s1];

[dictionary writeToFile:plistPath atomically:YES];
}

Comment: What do you mean by saving a string as an array?
Answer: You can't cast or otherwise convert a string into an array; they're separate, distinct objects. It's the same as if in real life you try to turn your dog into a station wagon, it isn't happening.
Instead, put your dog inside the station wagon (or put your string(s) inside an array). You can create the array with [NSArray arrayWithObjects:@"string1", @"string2", nil];. Stick that inside your dictionary for a given key, along with your final string for another key, save it, and you'll have a plist with an array of one or more strings.
Also, in your code example your dictionary is leaking memory. Read up on memory management in Objective-C, you're going to run into lots of crashes and performance issues until you understand it well.
Comment: In fact, you can't cast ANY object from one class to another.
Comment: Not true, you can if the object you're casting can actually behave as the class it's being casted to. For example, say you have an NSMutableArray object stored in an `NSArray* array` pointer. If you try to call `-removeLastObject` on it, the compiler will use static typing and inform you that an NSArray won't respond to that message. However, you can do `[(NSMutableArray*)array removeLastObject] just fine. You'll run into problems if `array` is actually an NSArray, or if you cast an object stored in an `id` variable to an incompatible class, such as strings to arrays.
Answer: You an convert a string to a single element array with
[NSArray arrayWithObject:str];

So if you want your plist to contain entries as arrays of strings, and you want just a single string as an element, then you do something like:
[dictionary setObject:[NSArray arrayWithObject:tempString] forKey:s1];

I don't actually no why you would want it this way unless you want to allow for multiple strings per key at some other time.
Also, as Marc mentioned, you are leaking the initial (unmutable) dectionary you create.  Read the memory management rules at http://developer.apple.com/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmRules.html.
Further, you should never write inside your application's bundle.  For one thing, your application may be on a write protected volume or the current user may not have permissions to change it.  For another, the file would then be shared by all users.  And for a third, it would break the code signing.  Instead, write the file to either the Preferences folder or the Application Support folder.
And finally, if these are intended to be user preferences of some sort, then you should use the preferences system, which allows configuring defaults and stores the preferences in the preferences folder for you.  See http://developer.apple.com/documentation/Cocoa/Conceptual/UserDefaults/UserDefaults.html for more information.
Answer: The correct way to save an NSArray (by itself) to a plist file is as follows:
NSArray* anArray = ...;
[anArray writeToFile:@"/path/to/file.plist" atomically:YES];

However, you can't save an NSString as an array. Given the XML plist you provided, if you want to add entries with the same format, you can use this much simpler code:
- (void) writeToFile:(NSString *)string {
  NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"saved" ofType:@"plist"];
  NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithContentsOfFile:plistPath];
  [dictionary setObject:[NSArray arrayWithObject:@"1234567"] forKey:string];
  [dictionary writeToFile:plistPath atomically:YES];
}

This also avoids a memory leak in your code, where the receiver of -mutableCopy escapes with a retain count of 1. (This isn't a problem under GC, but it's still bad practice.) You shouldn't need to use +[NSString stringWithFormat:], just use a string literal. If you want to use a different as the string in the array, you can either pass it in as an additional parameter, grab it from another method, etc.
This method is still brittle in that it only stores one string in the array matched with the given key — also, the method name would be better if it were more indicative of exactly what it does. Also, if there will only ever be one string value for each key, you might consider revising the plist to omit the arrays entirely, since it just chews up space and complicates the code.
Comment: Note that in this case, although +dictionaryWithContentsOfFile is a convenience constructor on NSDictionary, it is inherited by NSMutableDictionary, and will return an instance of the receiver class. This works for other mutable/immutable classes in Foundation, such as NS(Mutable)String, NS(Mutable)Array, etc.