Python - Group duplicates in a list of lists by index

Question: I've seen a lot of questions about removing duplicates from a list and counting them. But I'm trying to find the best way to group them - for a list of lists.
Given this example I want to group by the third field:
[[1, "text", "name1", "text"],
 [2, "text", "name2", "text"],
 [3, "text", "name2", "text"],
 [4, "text", "name1", "text"]]

I'd like to get this:
[[[1, "text", "name1", "text"],
  [4, "text", "name1", "text"]],
 [[2, "text", "name2", "text"],
  [3, "text", "name2", "text"]]]

I can think of the naive way by looping through and just keeping track of what is found (O(n^2)). But I would assume there's a better way.
Answer: You could sorted and use groupby but that is O(n log n):
from operator import itemgetter
from itertools import groupby

print([list(v) for _,v in groupby( sorted(l,key=itemgetter(2)),itemgetter(2))])

Or use an OrderedDict grouping by the third element for an O(n) solution by using the third element as the key and appending the sublists as values. setdefault will handle the repeated keys:
from collections import OrderedDict

od = OrderedDict()

for sub in l:
    od.setdefault(sub[2],[]).append(sub)
from pprint import pprint as pp
pp(od.values())
[[[1, 'text', 'name1', 'text'], [4, 'text', 'name1', 'text']],
[[2, 'text', 'name2', 'text'], [3, 'text', 'name2', 'text']]]

If order does not matter you can use a defaultdict in place of the OrderedDict.
If order does not matter a defaultdict is by far the most efficient.
In [7]: from itertools import groupby

In [8]: from collections import OrderedDict, defaultdict

In [9]: l = [[1, "text", "name{}".format(choice(list(range(2000)))), "text"] for _ in xrange(40000)]

In [13]: from operator import  itemgetter

In [14]: timeit [list(v) for _,v in groupby( sorted(l,key=itemgetter(2)),itemgetter(2))]
10 loops, best of 3: 42.5 ms per loop

In [15]: %%timeit
od = defaultdict(list)
for sub in l:
    od[sub[2]].append(sub)
   ....:
100 loops, best of 3: 9.42 ms per loop

In [16]: %%timeit
od = OrderedDict()
for sub in l:
     od.setdefault(sub[2],[]).append(sub)
   ....:
10 loops, best of 3: 25.5 ms per loop

In [17]: lists = l

In [18]: %%timeit
   ....: groupers = set(l[2] for l in lists)
   ....: [filter(lambda x: x[2] == y, lists) for y in groupers]
   ....:

1 loops, best of 3: 8.48 s per loop

In [19]: timeit l = [filter(lambda x: x[2] == y, lists) for y in   set(l[2] for l in lists)]
1 loops, best of 3: 8.29 s per loop

So if order does not matter then defaultdict wins, groupby still performs pretty well as sort is still pretty cheap in comparison to a quadratic approach. As you can see filter's quadratic complexity performs badly as the data grows.
Comment: `for _,v in groupby` would be better!
Comment: @Kasra, yep. Too used to checking `if k`!
Comment: Yeah, I got similar results, with defaultdict fastest. I also like its code best, so it's my winner.
Comment: @StefanPochmann, yes, defaultdict is often faster, I have added answers where it has beaten numpy and pandas in certain situations, the only thing in this instance that would go against it would  be if the Order matters, either way worst case the OP can use the OrderedDict which still give a linear solution.
Comment: If the key items aren't just repeated and if you randomly shuffle the list first, I think groupby loses the speed test. It did for me.
Comment: How do the sublists look like?
Comment: @StefanPochmann, yes, you were right, still pretty efficient when order matters. Actually makes sense as I was dubious as to how the filter was doing so well.
Answer: Use sorted with element you want to sort on as key and itertools groupby to  group 'em:
>>> from itertools import groupby
>>> sl = sorted(your_list, key=lambda your_list: your_list[2])
>>> [list(v) for k,v in groupby(sl, key=lambda sl:sl[2])]
[[[1, 'text', 'name1', 'text'],
  [4, 'text', 'name1', 'text']],
 [[2, 'text', 'name2', 'text'],
  [3, 'text', 'name2', 'text']]]

Comment: Yes, that sorts it. What about the grouping?
Comment: didn't pay attention to grouping, you can use itertools groupby; updated the solution..
Answer: Here you go:
>>> lists = [[1, "text", "name1", "text"],
...  [2, "text", "name2", "text"],
...  [3, "text", "name2", "text"],
...  [4, "text", "name1", "text"]]
>>> groupers = set(l[2] for l in lists)
>>> groupers
set(['name2', 'name1'])
>>> l = [filter(lambda x: x[2] == y, lists) for y in groupers]
>>> pprint.pprint(l)
[[[2, 'text', 'name2', 'text'], [3, 'text', 'name2', 'text']],
 [[1, 'text', 'name1', 'text'], [4, 'text', 'name1', 'text']]]

You can of course write the whole grouping logic in a single line:
>>> l = [filter(lambda x: x[2] == y, lists) for y in set(l[2] for l in lists)]
>>> pprint.pprint(l)
[[[2, 'text', 'name2', 'text'], [3, 'text', 'name2', 'text']],
 [[1, 'text', 'name1', 'text'], [4, 'text', 'name1', 'text']]]

Answer: The easiest way of doing that is with the key argument of the sorted() function. In your example:
>>> a = [[1, "text", "name1", "text"],
         [2, "text", "name2", "text"],
         [3, "text", "name2", "text"],
         [4, "text", "name1", "text"]]
>>> sorted(a[:], key=lambda item:item[2])
>>> [[1, 'text', 'name1', 'text'],
     [4, 'text', 'name1', 'text'],
     [2, 'text', 'name2', 'text'],
     [3, 'text', 'name2', 'text']]
You can find more information about this argument on this link.
Comment: Where's the grouping?
Comment: Yes but that just sorts it. I think you'd need to groupby() next
Answer: The following function will quickly (no sorting required) group sub-sequences of any length by a key of specified index:
# given a sequence of sequences like [(3,'c',6),(7,'a',2),(88,'c',4),(45,'a',0)],
# returns a dict grouping sequences by idx-th element - with idx=1 we have:
# if merge is True {'c':(3,6,88,4),     'a':(7,2,45,0)}
# if merge is False {'c':((3,6),(88,4)), 'a':((7,2),(45,0))}
def group_by_idx(seqs,idx=0,merge=True):
    d = dict()
    for seq in seqs:
        if isinstance(seq,tuple): seq_kind = tuple
        if isinstance(seq,list): seq_kind = list
        k = seq[idx]
        v = d.get(k,seq_kind()) + (seq[:idx]+seq[idx+1:] if merge else seq_kind((seq[:idx]+seq[idx+1:],)))
        d.update({k:v})
    return d

In the case of your question, the key is the element having index 2, therefore
group_by_idx(your_list,2,False)

gives
{'name1': [[1, 'text', 'text'], [4, 'text', 'text']],
 'name2': [[2, 'text', 'text'], [3, 'text', 'text']]}

which is not exactly the output you asked for, but might as well suit your needs.


Difference between [ ] and [, , ] in python

Question: <code>#string indexing

import random

word = "index"
print "The word is:" , word, "\n"

high = len(word)
low = -len(word)

for i in range(10):
    position = random.randrange(low,high)
    print "word[", position, "]\t", word[position]

raw_input("\n\nPress the enter key to exit,")
</code>
I copy this from a book called "Guide to Programming with Python". I'm not sure why do we have to add two commas in
<code>[", position, "]
</code>
What does it mean? And why do i get error when I removed the two commas?
Comment: you're getting it wrong; `[", position, "]` is not a whole, what you're doing is just splitting part of different arguments. In the line where that appears the `print` function (statement) is being called with **four different arguments separated with commas**, the first arugment is the string `"word["`, the second one is the variable `position`, the third one another string `"]\t"` and finally the fourth one a variable `word[position]`. If you remove the commas you are completely breaking the Python syntax.
Comment: are you referring to the commas in `print "word[", position, "]\t", word[position]`? (because I don't see that bit anywhere else) - Those you need to separate arguments (for `print` in this case) as you have a string, a variable (integer), another string and a character (of a string variable)
Answer: In python3
<code>print("word[", position, "]\t", word[position])
</code>
"word[",  position , "[\t",  word[position] are arguments of print()


Spring Data Neo4j creates duplicate nodes

Question: I am using Spring Data Neo4j 3.3.1.RELEASE with Neo4j server 2.2.3.
My problem is there are some nodes which are duplicates of my entities but has only the indexed property in it.
My class looks something like this
@NodeEntity
@TypeAlias("Product")
public class Product {
    @GraphId
    private Long graphId;
    @Indexed(indexName="productId", unique=true, indexType=IndexType.SIMPLE)
    private String productId;
    private String productType;
    ...
}

When a new node is created, I first check if there is an existing one and update it if it exists, otherwise create a new one.
Product product = productRepository.findByProductId(productId);
if (product == null) {
    product = new Product(productId);
}
...
productRepository.save(product);

The repository interface.
public interface ProductRepository extends GraphRepository<Product> {
    public Product findByProductId(String productId);
}

In Neo4j, the entity is created to a node with all the properties. But some nodes also have a duplicate node which only contain the productId. The thing is this doesn't happen to all the nodes. As of now we have about 120,000 nodes and as much as 30 nodes have this duplicate. Every time we re-ingest the data there are duplicates. Right now we only have 2 duplicate nodes.
One more thing, upon checking the duplicate nodes, it seems that they have a node ID in sequence which I think that they are created together when I save the entity.
EDIT:
Upon investigation, it seems that the unique constraint is not applied to the productId. The problem seems to be from @Indexed annotation. If I used unique and indexName in the same annotation, only the indexName is applied and not the constraint. Now if I use either indexName or unique SDN can create one of it and I must create the other via the Neo4j webconsole which is kind of annoying. I know that in SDN 4.x.x index maintenance will not be part of the code and should be handled externally. Is this something that we need to do now since SDN 3.3.x does not handle it correctly?
Answer: indexName and indexType are only used to define legacy indexes (which are now deprecated), and unique is only used to define the uniqueness constraint for schema indexes. The two index types are mutually exclusive.
If you want to impose a uniqueness constraint, you need to just use unique.
Comment: Thank you. I found that in order to create an index with unique constraint I only needed to annotate the field with `@Indexed(unique=true)`. When I do that, the constraint will be created and the index will be created as well.
Comment: I did up vote it. unfortunately it says I need 15 reputations before my vote can be displayed.
Comment: OK, thanks for trying :-) Looks like someone else did it anyway.


Im using entityforms to make events on a Calendar. How can i prevent duplicated dates?

Question: I am developing a Booking System and I am having a issue i.e. How can I prevent duplicate events to be registered ?
Right now I am using:
Calendar and Date for the event management and Entity Form for the booking system.
Users book a date and a time (for example: 09 / 10 / 2014, 14:30 and this is done with the Date field)
The problem I am facing that I don't want to let the users book a date and hour that is already selected. How can I prevent that?
For example: If an user books 09 / 10 / 2014, 14:30, no other user can book for the same date and time. How can i achieve this? Entity Forms has the option to set rules (via the rules module) but my knowledge on rules is not that good. Hope someone could give me a hint. Thanks in advance.
Comment: Does [Unique Field](https://www.drupal.org/project/unique_field) help you?
Answer: You could do this with Entity Rules, VBO, and Entityform if you are using 2.x(if not should upgrade).
It actually would an advanced Rule but here are the general steps.

Make a VBO View that has date time contextual filter. You would want to return any Entityform Submission that matched.
Make an Entity Rules Validation Rules.
Within Rule check the Number of results of the View from step #1 when you send it the date value of the current Entityform Submission.
If any results are returned then you have found a Entityform Submission that is for the existing date.

You would have to learn how to use Rules, Entity Rules, and VBO.
Comment: Great I am glad it worked out for you!


Is Drop-kick allowed when free kick is awarded inside the box

Question: On Sunday, in Liverpool vs United, on 93rd minute Mata was given offside, both the refs had given offside (they showed offside signs and ref whistles too). Alisson caught the ball and took a drop-kick (kicking the ball through his hands) which assisted Salah and resulted in the goal.
As per my knowledge, an INDIRECT FREEKICK is awarded for an offside. So how did Alisson take it as drop-kick and even after whistling and showing offside sign, how was he allowed to take it? (Ref did not show advantage).

So my question is, is drop-kick allowed for an offside if it is in the box?
Comment: Possibly related: https://sports.stackexchange.com/q/24550/15589
Comment: @F1Krazy I did not talk about Salah being offside. He wasn't. Salah's offside is not in the question.
Comment: That's why I said "related" and not "duplicate". It's about the same goal and claims the ball was in open play at the time. Maybe that question was wrong though.
Comment: Who decides if the ball is in open play or not? The keeper caught it and it's not about the goal here. it's about how the offside freekick was taken.
Comment: do you have a video source on whether the whistle was blown? If it was not, the goal is pefectly fine. Even if there was offside, the referee could have decided to let the game continue as possession turned over anyway.
Comment: That's what I'm asking. The Ref did not give an advantage signal but gave an offside signal and allowed it to continue. Why this?
Comment: NBC has this on their highlight reel.  https://youtu.be/Y4-NjhgsUSY?t=724
Answer: The whistle was not blown, at all.
Play was never stopped.
No player was penalised for offside.
There was never a free kick.
Alisson played the ball legally to Salah in the same way he and every other goalkeeper does regularly.


pushing new project changes to github not working

Question: So I'm completely new to git and github but gradually learning.
I went through a tutorial and pushed an existing project up to my git hub.
I've now made some changes to the project and want to push these new changes up to github again. What is the process??
I've been trying a few things but it's not working as easy as I thought. Getting a lot of errors.
I used this method for the first push:
git remote add origin remote repository URL
git push origin master

I tried the same again  it isn't working, in the hints it mentions git pull which I'm researching now.
So I've staged and committed everything I need and then wrote this git command to push changes:
git push origin master

These are the hints I got back:
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushin
hint: to the same ref. You may want to first integrate the remote changes
hint: (e.g., 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

Comment: Add the output or any other error
Comment: Show the output of `git remote -v`, please
Comment: possible duplicate of [What does "Git push non-fast-forward updates were rejected" mean?](http://stackoverflow.com/questions/4684352/what-does-git-push-non-fast-forward-updates-were-rejected-mean)
Answer: Have you added and commited your changes in your local repo?
First of all, use the git status command in your local repo to see if all your changes are commited and ready to be pushed.
About the pull msg, maybe you local repo is not synced with your remote.
Try git pull origin master in order to sync both.
Comment: thanks for your answer really helped me. i'm going to look myself but could you give me a brief explanation of what git pull origin master does?
Comment: The `git pull origin master` fetch all the update code from your remote repo to your local.


Como remover marcadores específicos de um googlemap

Question: Então, este app funciona assim: o usuário insere uma jornada que vai do ponto C (coleta) para o ponto E (entrega).
Estes pontos são mostrados no mapa, na forma de marcadores, como na figura abaixo.

Agora eu preciso remover os marcadores ao clicar no X.
O conceito geral é assim: vou fazer uma lista contendo (String ID, Marker marcadorDe, Marker marcadorPara) e cada novo marcador adiciona uma linha a esta lista no método addMarker().
Dai, o método removeMarker(String ID) vai recuperar os marcadores relativos ao ID e remove-los do mapa, quando o usuário exclui a jornada.
Minha pesquisa indicou diversas abordagens possíveis. Poderia criar uma classe, uma lista, um hashmap, etc.
Gostaria da opiniões sobre a melhor forma de fazer isso e se possivel, exemplos de código.
Note que a adição dos marcadores já funciona e a remoção do registro também. E justamente neste momento que eu vou chamar o método removeMarker().
Acho que a questão pode ser resumida em: Qual a melhor maneira de criar uma lista com tipos String, Marker, Marker?
Comment: Justo. Deu certo.
Comment: Por que não usa o id do registo na tabela do banco para id do marker?
Comment: o ID já é o id da tabela. Não quero reconstruir o mapa a cada exclusão. Então, ao montar o mapa, o app guarda uma lista com cada par de marcadores e o ID do registro para usar mais tarde, na exclusão. Minha questão é justamente, qual seria a melhor forma de guardar estes valores: criando array, objeto, hashmap, etc? O que vc acha?
Comment: Normalmente o que se usa é um HashMap. Use o id como key e, como valor, um objecto de uma classe que guarde os dois Marker.
Answer: A solução ficou assim.
No listener do botão excluir (X) do adaptador do recyclerView, deletamos o registro e em seguida, chamamos o método na MainActivity:
holder.ivDelete.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ...
            ...
            runDbHelper.deleteRow(runId);
            ((MainActivity) v.getContext()).removeMarkersFromMap(runId);
            ...
            ...
        }
    });

O método de remoção na MainActivity, recebe o ID e repassa para o fragmento:
public  void removeMarkersFromMap(String ID) {
    if (ID != null) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        MarkersFragment mFragment = null;
        if (getResources().getConfiguration().orientation == ORIENTATION_LANDSCAPE) {
            mFragment = (MarkersFragment) fragmentManager.findFragmentById(R.id.markersMapPanel);
        } else if (getResources().getConfiguration().orientation == ORIENTATION_PORTRAIT) {
            mFragment = (MarkersFragment) fragmentManager.findFragmentById(R.id.viewpager);
        }
        if (mFragment != null) {
            mFragment.removeMarkers(ID);
        }
    }

}

Este, por sua vez, executa o método no fragmento do mapa que exclui o(s) marcador(es).
public void removeMarkers(String id){

    MarkersPair markersPair = markersPairHashMap.get(id);
    if(markersPair != null){
        if(markersPair.collect != null) {
            markersPair.collect.remove();
        }
        if(markersPair.delivery != null) {
            markersPair.delivery.remove();
        }
    }
}

e, finita la comedia!
Answer: Tenho uma tela que exibe alguns pontos num mapa; de acordo com a ação do usuário é preciso atualizar esse mapa escondendo/exibindo alguns marcadores. O que fizemos foi manter os pontos já carregados e controlar estas ações no javascript.
var marcadores = {}; //seria array de [ID] -> marcadores

...
function LimparMarcadores () {
    for (var i = 0; i < marcadores[id].length; i++) {
        if (marcadores[id][i] != "0")
            marcadores[id][i].setMap(null);
    }

    marcadores[id] = [];
}

Comment: A pergunta refere as tags `Android` e `java`.


Hide table row with value of option box in wordpress with jquery

Question: I have a table with an input field in a table row and an option boxe and I want, that the
 with the input field only appears when a specific value in the option box are selected. So far I have the following coding, it hides my
 with the input field, but never displays it again.
 $script = <<< EOF

EOF;
        echo $script;

    echo '
';
    echo '
';
    echo '      ';
    echo '          <select name="sports">';
    echo '              <option>Baseball</option>';
    echo '              <option id="sel_rugby">Rugby</option>';
    echo '              <option>Soccer</option>';
    echo '              <option>Sailing</option>';
    echo '              <option id="sel_climbing">Climbing</option>';
    echo '          </select>';
    echo '      	';
    echo '
';
    echo '
';
    echo '      ';
    echo '          <input name="sports_cl_rg" />';
    echo '      	';
    echo '
';
    echo '
';

BR & thx,
mybecks
Answer: It would be better if you put id in all options or compare them by the text instead of id it will be event better. I mean use Climbing instead of sel_climbing. Also give id to select to access it as you may have many selects on the page. I changed it to work as you code but you can follow my recommendation if you like. Demo available here JsFiddle
 $('select').change(function() {
 alert($('#sports option:selected').text());
    $('#row_sports').hide(); //works
   if($('#sports option:selected').attr('id') == "sel_rugby" || $('#sports option:selected').attr('id') == "sel_climbing"){
     $('#row_sports').show();

 }else{
    $('#row_sports').hide();
 }
});

Answer:

use change function too.. here it works
Answer: Try this code:


Ruby: How to DRY up similar model attribute calls

Question: I have a User model with a number of very similar properties that I want to list without typing each on in individually.
So, rather than:
"eye color: #{@user.his_eye_color}"
"hair color: #{@user.his_hair_color}"
"height: #{@user.his_height}"
"weight: #{@user.his_weight}"
...

"eye color: #{@user.her_eye_color}"
"hair color: #{@user.her_hair_color}"
"height: #{@user.her_height}"
"weight: #{@user.her_weight}"
...

I'd like to do a block or something (Proc? Lambda? Still a touch unclear what those are...):
['eye color','hair color','height','weight',...].do |stat|
   "#{stat}: #{@user.her_(stat.underscore)}"
end

['eye color','hair color','height','weight',...].do |stat|
   "#{stat}: #{@user.his_(stat.underscore)}"
end

I know that what I just wrote above is mystical, magical, and wholly and completely WRONG (the @user.his_(stat.underscore) part), but what could I do that's like this? I basically need to call my Model's attributes dynamically, but I'm unsure how to do this...
Any help would be really appreciated!
Answer: ['eye color','hair color','height','weight',...].do |stat|
   "#{stat}: #{ @user.send(:"her_#{stat.tr(" ","_")}") }"
end

['eye color','hair color','height','weight',...].do |stat|
   "#{stat}: #{ @user.send(:"his_#{stat.tr(" ","_")}") }"
end

This should work. You can always use send to call method on object, and generate that method name on the fly as string
Comment: If nothing else, `stat` is a string so you could always use `stat.tr(' ','_')` to convert them if you can't get `.underscore` working.
Comment: I knew there must be something like this I was missing... however, `.underscore` seems to have stopped working, thus the call fails. Any idea why that is?
Comment: underscore is possibly only available from ActiveSupport in Rails. I don't think it's available in the standard Ruby String API.
Answer: If you're using ActiveRecord in Rails you can also use the Object#[] method to get the values of attributes dynamically
['eye color','hair color','height','weight',...].do |stat|
   "#{stat}: #{ @user[ "her_#{ stat.underscore }"]}"
end

Comment: I am using Rails, and this method works too... except I still don't have access to `.underscore`.
Comment: According the the Rails API underscore will turn "EyeColor" to "eye_color" but leave "eye color" alone.
Comment: I used bta's comment from the other answer with your Object#[] method and it works and it looks very clean! Thanks!


Switch keys and value and Preserve entries with no value

Question: I have this array:
'tab1' => '',
'tab2' => '',
'tab3' => 'active'

I want to do array_flip to swap the keys with the values, but the entries with an empty value are not kept.
How do I let PHP assign integer keys for me (like with an indexed array)?
Thanks
Edit:
To clarify things a bit, this is what I want:
0 => 'tab1'
1 => 'tab2'
'active' => 'tab3'

Comment: you cant have empty or duplicate key's, so what is the desired outcome?
Comment: Is it possible that you need `array_key` function instead?
Comment: @sectus if I use `array_key`, then how will I be able to preserve the "active" entry?
Comment: @jasonszhao, I do not know because I do not know what do you trying to achieve.
Answer: Directly through array_flip it's not possible. I think you want like this:-
<?php

$array1 = array('tab1' => '','tab2' => '','tab3' => 'active');

$array2 = array();
foreach($array1 as $key =>$value){
    if(empty($value)){ // Or $value ==''
        $array2[] = $key;
    }else{
        $array2[$value] = $key;
    }

}

echo "
";print_r($array2);die;
?>

Output:- http://prntscr.com/79ge6z
Comment: It's better to use one of php fiddle services instead of screenshots. For example: http://3v4l.org/vUtj9
Comment: Thanks @anantkumarsingh. But perhaps using `empty()`?
Comment: I hope you get your solution.
Comment: Yes, @anantkumarsingh I just wanted to see if others had something to add


bugzilla + configure to use microsoft exchange mail server as smtpserver

Question: Try to setup bugzilla on linux, below are the setup configuration:

CentOS v6.4 32bit
Bugzilla v4.2.5

Installation seem ok and bugzilla working, but when configuring bugzilla to send email whenever bug reported/edited, bugzilla just not sending any email out. Below is the configuration on bugzilla administrator > Parameters > Email:

mail_delivery_method : SMTP
mailfrom : [valid email address]
smtpserver : [valid email domain name]
smtp_username : [valid email address]
smtp_password : [valid email password]

The smtp server is microsoft exchange server. Whenever I file a new bug, there's a error log created at /var/log/httpd/error_log

[Tue Apr 30 15:25:25 2013] [error] [client x.x.x.x] [Tue Apr 30
  15:25:25 2013] post_bug.cgi: Use of uninitialized value
  $ENV{"FLOCK_FORKING_USE"} in string eq at lib/File/Flock/Forking.pm
  line 13., referer: http://x.x.x.x/bugzilla/enter_bug.cgi?product=Test

No email received at all.
Wonder what's went wrong...
Answer: This issue was being solved by my helpful colleague, thanks to him.
Bugzilla come with a mail queuing service call "jobqueue.pl", this service installed automatically during installing the missing components (I believe as I never install this jobqueue.pl manually).
There will be a service installed by bugzilla as well at /etc/init.d/bugzilla.queue.
"jobqueue.pl" and "bugzilla.queue" actually the same thing.
In the bugzilla installation and configuration guide, never mention about this. I didn't check if either service has chkconfig on when start up as I didn't reboot my bugzilla server after installed. So I "chkconfig bugzilla-queue on" manually.

If you configured email settings on bugzilla web-admin and tried submitted new bug, then email is created at mysql DB "bugs" > table "ts_job". So first you have to clear out this table first as those data may be not valid.

DELETE FROM ts_job;

Configure administrator > Parameters > Email settings correctly.
Run or restart it if already running.

/etc/init.d/bugzilla-queue start

File a new bug will see email send out. But some how still see the error log created at /var/log/httpd/error_log

[Wed May 08 10:19:31 2013] [error] [client x.x.x.x] [Wed May  8 10:19:31 2013] post_bug.cgi: Use of uninitialized value $ENV{"FLOCK_FORKING_USE"} in string eq at lib/File/Flock/Forking.pm line 13., referer: http://x.x.x.x/bugzilla/enter_bug.cgi

Email can be received finally with the error log above still appear.


Problem regarding installation of angular cli for node.js

Question: Can you please suggest what I should do next, I am stuck here for a while and nothing seems to work.
Answer: The package.json is missing from the root directory of the project. Please check for package.json.


Slice indexing weird edge case

Question: In Go slice indices use half-open range.  For a[low:high] the slice includes a[low] but exclude a[high].  Ref: https://tour.golang.org/moretypes/7.  Another way to think of it is it goes from a[low] to a[high-1] inclusive.
But take a look at this code.  You can run it at: https://play.golang.com/p/DSLs7V8gom0
func main() {
    t := []int{5}
    fmt.Println(t)
    fmt.Println(t[0:0])
    fmt.Println(t[1:1])
}

If you ran the code you can see that both t[0:0] and t[1:1] are valid and allowed.
t[0:0] means includes t[0] (which exists) but stop before t[0] (which is t[-1] which does not exist).
t[1:1] means includes t[1] (which does not exist) but stop before t[1] (which is t[0] which exists).
In both cases one of the indices refer to something that doesn't exist, i.e. index out of range ==> yet syntactically perfect and allowed in Golang!!
Yet if you try any other index, such as t[2], the compiler will expectedly complain loudly.
Comment: Your question is not clear. It's allowed because the spec explicitly describes it as a valid expression with specific behaviour https://golang.org/ref/spec#Slice_expressions
Comment: *"t[1:1] means includes t[1] (which does not exist)"*, True `t[1]` does not exits, however `t[1:1]` and `t[1]` are not the same types of expressions, one is a slice expression the other an indexing expression, see the link provided by zerkms. And the pertinent sentence in that spec is this one: *"For slices, the upper index bound **is the slice capacity cap(a) rather than the length**."* See https://play.golang.com/p/29n1_0K4oS0 and https://play.golang.com/p/TTTPeVqGWtr
Comment: *"Another way to think of it is it goes from a[low] to a[high-1] inclusive."* That's the wrong way to think about it. As explained in the [link](https://tour.golang.org/moretypes/7) you've provided: *"`a[low : high]` This selects a half-open range which includes the first element, **but excludes the last one**."* "Excluding" `high` is something very different from "indexing" `high-1`.
Comment: @zerkms Thanks, yes it's valid per spec.  I guess what I got hung up on is the way I think about it which mkopriva nicely pointed out and corrected.
Comment: @mkopriva This helped changed the way I view things "Excluding high is something very different from "indexing" high-1".  It's subtle but does explain away the perceived weirdness.  Thanks!
Answer: You need to think of a range as starting at the lower value and stopping when you reach the upper value. The upper can never be less than the lower but they can be any valid index or the one past the end - ie 0 or 1 in your example.
So t[0:0] means start then stop immediately giving a zero-length range.  Eg:
t[0:0] and t[1:1] are valid zero length slices
t[0:1] is a slice of length 1
t[2:2] and t[1:0] are invalid
I explain in detail about the advantages of half-open ranges and not making zero a special case in my blog - eg see http://devmethodologies.blogspot.com/2012/12/asymmetric-bounds-and-zero-based.html
Comment: Thanks Andrew.  I guess what I got hung up on is the way I view the half-open range, which @mkopriva nicely pointed out and corrected.  "Excluding high is something very different from "indexing" high-1". It's subtle but does explain away the perceived weirdness.

Slice indexing weird edge case


arrange m balls in to n baskets

Question: How can I write a given natural number into sum of required (m) natural numbers?
Example:
10=2+8+0 here m=3
Let n_i be the values i:e 2,8,0 in the above example.
I want to know whether any method exists for finding ∏_i^m▒n_i ! = minimum for a given (m) & natural number.
Comment: You should check the use of Latex for typesetting symbols.
Answer: Let us assume that each basket has different name. The problem of  $n$ baskets and $m$ balls can be transformed into a problem of permutating a string consisting of $n+1$ 1 and $m$ 0 where the head and tail of must be 1.
For example,
head--->1 0 0 0 0 0 0 ... 1 1 1 1 1 1 1 ... 1 0 1 0 1 0 ... 1<---tail
So actually we need to permutate $n-1$ 1 and $m$ 0.
Thus the answer is $\frac{(n-1+m)!}{(n-1)! m!}$

arrange m balls in to n baskets


Changing price based on option

Question: Hi I am trying to change the price based on whatever is been selected from the options... I dont know if to do it using JavaScript on ajax and any how will I be able to do it please...

Price:
<?php echo $row['Standard_price']; ?>

The price is selected from a database as a standard price for the item and I want it to change(NOT ON THE DATABASE) when someone select from the options below

td for="length" width="160">size*:

<select name="size" class="small">
<option value="£25.00">12 size</option>
<option value="£30.00">14 size(+£30.00)</option>
<option value="£40.00">18 size(+£40.00)</option>
<option value="£45.00">20 size(+£45.00)</option>
<option value="£80.00">28 size(+£80.00)</option
</select>

i choose 18 inch which is £40 i want it to change the price to £40 and also if i ech0
$length = $_POST['length'];

It should tell me 18 inch (+£40.00) NOT £40.00
Because on my cart it will be
product name: blue nike shoes
size: 18 inch (+£40.00)
Unit price: £40.00
qty:1
total price: £40.00

The unit price and size will change depending on what you choose from the options. please help. I have everything else working but its just getting the price to change depending on the option and also get the size you choose from the option.
If no one still understands me...
try buying a shoe from any site that sells and pick your size... although the price id the same for all sizes but in the cart it tells you want choose.
In my case the size have different prices and i want it show on the cart what size you choose and also the price for that size.
Maybe the way i am doing it is wrong but i know it is possible to do it because i have seen it on some sites that sells items which different lengths or shapes price are different from one another.
Comment: If I understand right, when someone selects a length (let's say 14 inch), you want to get get `14 inch (+£30.00)`. Am I right?
Comment: You could simplify your life by removing the currency symbol from the value. This will save you the step of parsing a numeric value from the string before every math operation.
Comment: @GeorgeCummins I'm trying to figure if what he wants is just to add the value of the option to the base price with a `+` operator.
Comment: Basically i have an item and that item comes in different sizes and each size has different prices. So when the user select the size they want, the default price will change and in the size it will tell them what size they choose.
Answer: Edit
Version with an additionnal field :JSFiddle
Version with original fields   :JSFiddle

with an additionnal field
I added a row to see the item size alone:
HTML add-on

  Item:
  12 inch

Javascript
function addCharge(select, elemIndex)
{
  var item = select.getElementsByTagName('option')[elemIndex];
  var price = document.getElementById('pricetag');
  var finalPrice = "";

  /* Getting the price and showing it up */
  finalPrice = parseFloat(item.text.substring(11, item.text.length-1));

  /* We set a default £25.00 value */
  if(isNaN(finalPrice)) finalPrice = "25";

  /* we add decimal */
  price.innerHTML="£"+finalPrice+".00";

  /* Getting the size and showing it up */
  var size = item.text.substring(0,7);
  var sizeDOM = document.getElementById('item');
  sizeDOM.innerHTML = size;
}

with original fields
Javascript
function addCharge(select, elemIndex)
{
  var item = select.getElementsByTagName('option')[elemIndex];
  var price = document.getElementById('pricetag');
  var finalPrice = "";

  /* Getting the price and showing it up */
  finalPrice = parseFloat(item.text.substring(11, item.text.length-1));

  /* We set a default £25.00 value */
  if(isNaN(finalPrice)) finalPrice = "25";

  /* we add decimal */
  price.innerHTML="£"+finalPrice+".00";

  /* Getting the size and showing it up */
  var size = " ("+item.text.substring(0,7)+")";
  price.innerHTML += size;

}

New: With input fields
New HTML
<input type="hidden" id="itemPrice" name="itemPrice"/>
<input type="hidden" id="itemLength" name="itemLength"/>

New JavaScript
var itemPriceDOM = document.getElementById('itemPrice');
var itemLengthDOM = document.getElementById('itemLength');

/* we add decimal */
itemPriceDOM.value = finalPrice;

/* Getting the size and showing it up */
var size = item.text.substring(0,7);
itemLengthDOM.value = size;
price.innerHTML += " ("+size+")";

See the new JSFiddle !
Comment: Ghilied if you echo length you will the whatever that in the value i dont want to show whats in the value but ..inch (+£..) because on the admin or staff end they wouldnt be able to tell what size show it was
Comment: Also if they select an item that is +£45 the £25.00 should change to £45 because default price for 12 inch is £25 and 14 inch is £30.
Comment: Okay I get it, so the price in parenthesis is the default price for each item. Maybe should you add a "description" field in your database for each cart item (that is filled by the item specs: size, length, whatever you want), this way the staff could know the ID of the item and its specific size. I'm working on something, watch my future update in a few minutes.
Comment: @Ian Take a look at my answer (it only contains new stuff, I deleted all the old content it had).
Comment: Ghillied thanks but i can't seems to be able to pass the pricetag and size to cart.php even though i have added name="pricetage" and name="size"
Comment: @Ian: It's because the fields are not `input`(s), I made an update at the END of this actual answer, take a look at it please.
Answer: You need to implement something like this:

   Price:
   <?php echo $row['Standard_price']; ?>

<select name="title" id="priceDropDown" class="small">
  <option<?php fillSelect('size','','',true); ?> DISABLED value="">Select size</option>
  <option<?php fillSelect('size','12'); ?> value="25">12 size(+£25.00)</option>
  <option<?php fillSelect('size','14'); ?> value="25">14 size(+£30.00)</option>

</select>

In this example I'm using jQuery.
Comment: thanks not what i wanted I want it to change the price but when it echo i want it to echo 12 size(+£25.00) not 25 because I am going to post 12 size(+£25.00 to the cart
Comment: Take a look at my last edit :). Is that what you were looking for ?
Comment: thats not what I was looking for.... basically I want the prices t change as it drop down but when i $title= $_POST['title']; I want to post for example 12 size(+£25.00 not the value 25. If that makes senses
Comment: Probably I'm not understanding you right, but you can set the option value attribute to "12 size(+£25.00)", wrap the select in a form and add the following attribute to the select tag: onchange="$(this).parent().submit()".
Comment: I personally recommend using something like `` (or `` if you do not have short tags support) as a way to separate concerns. Your `fillValue()` (renamed here to `getSelectValue()` to describe what it does) is unnecessarily printing data, while it could simply return it (and this way it could be used outside the templates).
Comment: @Ian: Just remove "`value="25"`" from this code and the browser will send the content of the `` tag instead. The server will receive exactly the same as the user sees.
Comment: try buying a shoe from any site that sells and pick your size... although the price id the same for all sizes but in the cart it tells you want choose.
In my case the size have different prices and i want it show on the cart what size you choose and also the price for that size.

Changing price based on option


MSG 137: When declaring variales DECLARE/SET/QUERY must be run at the same time

Question: Call me a noob -- or maybe I wasn't asking the right question, but I looked all over SO for a solution around why I was getting SQL Server's Msg 137 error even though I declared my variable.
Msg 137, Level 15, State 1, Line 1
Must declare the scalar variable "@myVar".

There are a lot of questions out there that address this question but in different contexts and, to be honest, most people have much more technical issues when they get this error such as variable being out of bounds. So this question/answer is more for beginners who are just testing out declaring/setting/using variables.
These are the queries I was running when hitting the error. Finally, a colleague brought light to the issue (see answer below).
declare @myVar varchar(20);
set @myVar = 'hello';
print @myVar;

Answer: It turns out the reason I was getting the error is because I was running the code line by line.
As it turns out, variables only exist for the duration of the query (batch), so once I ran the declare query, the variable had been wiped out of memory. SQL Server Pro was able to shed further light on my issue, which talks about local-only variable support in T-SQL.

T-SQL supports only local variables. A local variable is available only in the batch that created it. A batch is a T-SQL statement (or group of statements) that SQL Server parses as a unit. Each client tool or interface has its own way of specifying where a batch ends. For example, in Query Analyzer, you use the GO command to specify where the batch ends.

Also there are a lot of answers for pre-SQL Server 2008 where you declare and set separately
DECLARE @myVar VARCHAR(100);
SET @myVar = 'Some Value';

but 2008+ allows you to declare and set variables on the same line.
DECLARE @myVar VARCHAR(100) = 'Some Value';


Is possible to change path to server certificate in AWS IAM

Question: I have a problem to use my server certificate in CloudFront of AWS. When I added my server certificate I didn't know that if I'm going to use it in the CloudFront, I needed to add the param --path /cloudfront/.
Is it possible change only this parameter without delete and add again?
Thanks
Answer: Apparently, you can:
<code>$ aws iam update-server-certificate
          --server-certificate-name <value>
          --new-path <value>
</code>
http://docs.aws.amazon.com/cli/latest/reference/iam/update-server-certificate.html


Caching an intermediate dataframe when there is only one action

Question: In Spark, let's say that I have a dataframe that undergoes some 100 transformations and then there is a single action applied. Will caching an intermediate dataframe help under any circumstances? I can see that caching will help when there is more than one action applied on a dataframe but how about a single action?
To clarify:
I have a dataframe A using which I obtain 2 different dataframes B and C. Then I do a union of B and C to form D on which I apply an action. Imagine this happening in a very complicated scenario with lots of branches. Will caching A speed up the process?
Answer: Caching a DataFrame has no benefit on the first time it needs to be evaluated (in fact it actually has a performance cost and obviously increases memory use).  It's only on reuse that caching helps.
If you split A into B and C, then use both B and C, you've just used A twice, so caching it will help.
Number of Actions is not an important measure, what matters is the execution path.


convolution is well-defined and differentiable for continuous $f$ and differentiable $g$ with compact support

Question:
Let $f$ be a continuous function from $\mathbb{R} \rightarrow \mathbb{R}$. Let $g \in C^1(\mathbb{R})$ with compact support. Prove that the convolution function $$(f*g)(x)=\int f(x+t)g(t) \,dt$$ is well-defined and lies in $C^1(\mathbb{R})$. Furthermore, prove that if $g \in C^k(\mathbb{R})$ then $f*g \in C^k(\mathbb{R})$.

To prove that $f*g$ is well-defined, do I show that if $x_1=x_2$ then $(f*g)(x_1)=(f*g)(x_2)$? Besides this, I am unsure how to approach this problem. I have never learned the concept of convolution before. Any idea how to do this problem?
Comment: I think the term "well-defined" here has a different meaning. I think you're supposed to show that the integral is finite for every $x$.
Comment: To be well defined means that the integral is well defined.
Comment: Well-defined means here that $f *g$ is actually a function, i.e. the integral actually exists.
Answer: To prove that the convolution is well-defined you must show that it's finite for every $x \in \mathbb{R}$. I'll assume that the integration is over $\mathbb{R}$. So, because $g$ has compact support, there is a $K \subset \mathbb{R}$ compact such that $g(x)=0, \forall x \in K^c$. So we have that $$ (f*g)(x)= \int_{\mathbb{R}}f(x+t)g(t)\,dt=\int_{K}f(x+t)g(t)\,dt$$
Because both functions are continuous they are bounded in compacts, so there is $M, N >0$ such that $ f(x+t)<M$, $g(t)<N, \forall t \in K$. Furthermore, because $K$ is compact, there is some $R >0$ such that $K \subset [-R,R] $ So:
$$\int_K f(x+t)g(t)\,dt < MN\int_K\,dt <MN \int_{[-R,R]}dt<2RMN < +\infty$$
Now we have to show that the convolution of our functions defines a $C^1(\mathbb{R})$ function. Well, if we do $u=x+t$ :
$$(f*g)(x)=\int_{\mathbb{R}}f(u)g(u-x)\,du$$
Now, You can calculate the derivative of $(f*g)(x)$ using the definition!
$$\lim_{x\rightarrow x_0}\frac{(f*g)(x)-(f*g)(x_0)}{x-x_0}= \lim_{x\rightarrow x_0}\int_K\frac{f(u)(g(u-x)-g(u-x_0))}{x-x_0} \, du $$
We can pass the limit inside the integral in this case, by the dominated convergence theorem, so
$$(f*g)'(x_0)= -\int_Kf(u)g'(u-x_0)\,du = -\int_K f(x_0+t)g'(t) \, dt$$
This is a continuous function, you can see that using an $\epsilon-\delta$ argument with the help of the inequality $|\int f \, d\mu| \leq \int|f|\,d\mu$ and noting that you are in a compact set.
Remark 1: Note that is a minus sign there, it appeared because of your definition of convolution that forced my choice of change of variables above. If you change your definition for a $f(x-t)$, there will be no sign at all!
Remark 2: To the case where $g \in C^k(\mathbb{R})$ you can continue calculating the derivatives.
Comment: That was very neat. Thank you!


Alternating rows using css grids and nth-child

Question: I am working on a product grid with an alternating row pattern like this.

The color containers represent what I think the rows should look like.
Basically there are two products on the first row, and one product on the second row, repeating infinitely. I've been trying to do it with css grids + nth child, but I can't seem to get it right. Here's what I have so far:

.container {
  display: grid;
  grid-template-columns: 1fr 2fr;
  grid-column-gap: 0;
  width: 70vw;
  margin: 0 auto;
}

.item:nth-child(3n+3) {
  grid-column: auto / span 2;
  background-color: #e2a7de;
}

/*just for debugging*/
.container{grid-gap:5px;}
.item{background-color: #ffa900;padding: 10px;text-align:center;}

    X

    X

    X

    X

    X

My brain can't wrap around combining grids and nth-child to create this layout. I'm also open to a better way of creating this 2-1-2 pattern if anyone has other suggestions. Thank you!
Answer: You can simplify your code like below:

.container {
  display: grid;
  grid-auto-columns: 1fr; /* all columns equal */
  width: 70vw;
  margin: 0 auto;
}

.item:nth-child(3n) {
  grid-column: span 2; /* span and create two columns*/
  background-color: #e2a7de;
}

/*just for debugging*/
.container{grid-gap:5px;}
.item{background-color: #ffa900;padding: 10px;text-align:center;}

    X

    X

    X

    X

    X

Answer: Update the grid-template-columns to be 1fr 1fr

.container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-column-gap: 0;
  width: 70vw;
  margin: 0 auto;
}

.item:nth-child(3n+3) {
  grid-column: auto / span 2;
  background-color: #e2a7de;
}

/*just for debugging*/
.container{grid-gap: 5px;}.item {background-color: #ffa900;padding: 10px;text-align: center;}

    X

    X

    X

    X

    X


Can all Nginx vhosts share the same ssl_session_cache?

Question: To me, the Nginx docs about how ssl_session_cache works, is a bit unclear. I'm wondering if this:
ssl_session_cache shared:SSL:10m;

declared either in the http block, or in each server (i.e. virtual host) block, results in 1) one single global cache named SSL, 10 MB large. Or 2) in one 10 MB cache per server, with combined size of all caches = num servers x 10 MB.
The docs:

shared
  a cache shared between all worker processes. The cache size is
  specified in bytes; one megabyte can store about 4000 sessions. Each
  shared cache should have an arbitrary name. A cache with the same name
  can be used in several virtual servers.

If there'll be just one single cache, then I'd like to multiply its size with the number of servers. So, if I have 5 servers (i.e. 5 virtual hosts), then I'd place ssl_session_cache in the http block and:
ssl_session_cache shared:SSL:50m;   # 10 * 5 = 50

So, the question: Does ssl_session_cache shared:SSL:10m; create one 10 MB cache per server, or one 10 MB cache for all servers?
If it's per server, then is there no way to configure one single global cache, for all servers, instead? (If not possible, then why not, in case anyone knows?) Seems to me as if that would result in more efficient memory usage. (Because one server with many clients, could then use the memory that would otherwise have been dedicated to some other server that might have zero clients for the moment.)
Comment: Did you ever find an answer for this?
Comment: @HassanBaig Not yet, no. Maybe if one studies the source code.
Answer: Looking at the implementation of ssl_session_cache by ngx_http_ssl_session_cache in nxg_http_ssl_module.c, it creates one shared memory zone named "SSL", i.e. one ssl session cache.
Any subsequent call to ssl_session_cache retrieves the previously configured shared memory zone named "SSL", instead of creating a new one (cmp. ngx_shared_memory_add in ngx_cycle.c).

This can easily be verified by configuring different sizes for the same name like so:
...
ssl_session_cache shared:SSL:4m;

server {
    ...
    ssl_session_cache shared:SSL:50m;
}

This results in an error message such as:
[emerg] the size 52428800 of shared memory zone "SSL" conflicts with already declared size  4194304 in /etc/nginx/nginx.conf:37

Details  (KajMagnus added)
The shared memory zone gets added here:
  sscf->shm_zone = ngx_shared_memory_add(cf, &name, n,
                                         &ngx_http_ssl_module);

and as you can see, different names result in different caches being created. So, one can have many different shared memory caches, each one with its own unique name. However, each server, can use only one shared SSL memory zone — there's just one shm_zone per SSL server config, on the ngx_http_ssl_srv_conf_t *sscf structure.

tl;dr
Whether a SSL session cache is declared at http or server level does not matter. The same cache is used as long as the same name is assigned to the cache. To prevent an error message for caches with the same name the same size must be used throughout.
Comment: Thanks! I've been wondering for many years. I edited the answer and added a little bit details.


How to get reference to another object on other column on same row in a table in Javascript?

Question: I want to set disabled=false for the input box on 3rd column when a user 'check' the checkbox on the 2nd column on Same row
And again disable if user 'uncheck' the checkbox.
   <!DOCTYPE html>

Check the checkbox to display which type of form element it is.

Item1
<input type="checkbox" onclick="myFunction(this)">
<input type='number' disabled>

Item2
<input type="checkbox" onclick="myFunction(this)">
<input type='number' disabled>

Item3
<input type="checkbox" onclick="myFunction(this)">
<input type='number' disabled>

I tried with this  reference but that have not gave me any solution.
So how can i get the reference to the input box from the checkbox?
I browsed internet but have not get any solution .
Comment: When calling myFunction the event (onclick) is passed which has a property "target".
Answer: You could give the inputs an id attribute for later addressing this element.

function myFunction(item) {
  var x = document.getElementById(item);
  x.disabled = !x.disabled;
}

Check the checkbox to display which type of form element it is.

    Item1
    <input type="checkbox" onclick="myFunction('itemInput1')">
    <input type="number" id="itemInput1" disabled>

    Item2
    <input type="checkbox" onclick="myFunction('itemInput2')">
    <input type="number" id="itemInput2" disabled>

    Item3
    <input type="checkbox" onclick="myFunction('itemInput3')">
    <input type="number" id="itemInput3" disabled>

With Element.closest, as @August mentioned and Document.querySelector

function myFunction(element) {
  var x = element.closest('tr').querySelector('input[type="number"]');
  x.disabled = !x.disabled;
}

Check the checkbox to display which type of form element it is.

    Item1
    <input type="checkbox" onclick="myFunction(this)">
    <input type="number" disabled>

    Item2
    <input type="checkbox" onclick="myFunction(this)">
    <input type="number" disabled>

    Item3
    <input type="checkbox" onclick="myFunction(this)">
    <input type="number" disabled>

Comment: Really this is so simple to implement , I was thinking so complex so i just missed this easy solution.  But Still this may be not helpful  if i have thousand of rows. I have to set id for each of the item.  Is there any other  dynamic solution?
Comment: thank this is the perfect answer what i searching. Thnx agin very much
Answer: Don't go back to DOM with document.getElementById to get your element, there is no point of doing that.
Try to use the event reference, when calling myFunction the event (onclick) is passed which has property "target".
To understand better do console.log(item); inside the function.
From there, inside your function you could do item.target.closest('tr') to identify the parent of the cell.

Documentation for closest() method
Comment: Would you please give a long example please
Comment: It giving result: TypeError: item.target is undefined


Dependency between quantitative and categorial variable

Question: I have a data set with a categorical variable $C$ (approx. 8 levels) and a quantitative variable $X$. I suspect that $X$ and $C$ are strongly dependent. How can I verify this hypothesis?
My approach would be to 'bin' $X$ in order to obtain about the same number of categories as for $C$ and then use a test for contingency tables.
Once I have established depedency I would like to find 'the natural order' of the categories of $C$ implied by $X$, or even to assign distances between the levels of $C$, based on the numeric scale of $X$. Can this idea be made rigorous? Does it make sense?
Comment: A *poor man's* approach to backing into this concern would be to treat *X* as a dependent variable and *C* as independent thus making them amenable to ANOVA. By taking the square root of the resulting R-square value from that simple model their correlation can be derived.
Answer: ALL  EDITED:
The poster has made clear in the comments below that they are looking for a test of association that doesn't assume one variable is independent and one is dependent.
This is probably a duplicate of this Cross Validated question.  There is some helpful discussion there.  There are some good option at this other CV question.
To meet the Poster's criteria, maybe one approach would be to use an extended version of the Cochran-Armitage test that allows for more than two categories.  For this test, one variable is ordinal and the other is nominal, arranged in a contingency table, so it would still require reducing the quantitative variable to an ordinal one, perhaps with some binning.  But I think this approach is closer than reducing the continuous variable to a categorical one.  From what I read, it's a test of association that doesn't assume that one variable is dependent.
An appropriate measure of association for the ordinal/nominal case may be Freeman's theta.
An appropriate measure of association for the interval/nominal case may be eta-squared.
Comment: Thank you for your answer. From my understanding all proposed tests would treat C as independent and X as dependent variable, i.e try to explain X by observations of C. Are there any 'symmetric' measures of association between X and C or is this too much to ask for?
Comment: I updated my answer.
Comment: Thanks again. I think your answer was informative even before the edit. Maybe you should combine old + new answer into a single one.


google maps api geocoding

Question: This question is regarding the google Maps API geocoding, I'm able to geocode an address and show the location, but this works when the address is valid.
When it's not valid(there is an error),right now, I'm showing a smart message which says there is an error retrieving the location, but the requirement is to show the nearest possible location to the entered address.
How do I get the marker on next best location?
here's what I've tried:
Split the address, based on commas, and geocode each substring, and get the marker on the 1st match, but this resulted in some huge errors.
What I'm thinking of doing now is:
geocode the zip-code using yahoo maps API, but the only problem is I don't think it will be close to what the user has entered as his address.
Any solutions?
Comment: +1 Finding the nearest location of a location you can't find sounds hard :) Giggle!
Comment: haha, yes, it's very funny what clients expect ! wish I could mail them your comment!:)
Answer: Tarun , i am not sure which google api you are using. But Google geocoding api does allow for partial address searches and returns matches sorted by best fit. So displaying best location should be really simple. Take a look at this link below. It returns xml but you can ask for json by replacing xml in url with json. All you have to do insert your partial address in this url.
http://maps.googleapis.com/maps/api/geocode/xml?address=holly%20hall&sensor=false
So if this url doesnt give you any results, then its probably safe to assume that address doesn't exist.
Hope that hepls
Comment: just started working on it! so, probably missed it while a quick read through the API doc, will give that a try and acknowledge ! :)
Comment: thanks a lot, it's working when I tried it manually, just need to implement it now !
Answer: I'm by no means an expert of Google Maps, but I would try something like this:
1). Get the zip code
2). Try to find the street within this zip code
If found, mark the street itself and be happy with that.
Comment: okay, I'm in India, and I'm not sure if google maps is yet developed(up-to-date) for Indian street addresses ! will give it a try :) thanks for the tip !

google maps api geocoding


Average face - algorithm

Question: Quesion and code is at the end
I hope this question belongs here and not to the TCS's stack.
I am trying to go through algorithms in Turk and Pentland's "Eigenfaces for Recognition".
On page 74 one can read (last paragraph of left column):

Let the training (...) The average face of the set is defined by [*]

Where [*] is an equation saying that average face is equal to sum of images divided by it's count. In order to use this equantion I created python script using OpenCV and numpy.
On page 75 there is Figure 1. which should represent average face from Figure 1. (pg. 74) and this is what I am trying to achieve.
As a face set I am using all faces from Faces94.
When I calculate traditionall average (1/M*sum) the result looks like this:

which is far away from expected, mostly because of those wierd 'spots'.
However, when I calculate average like there was more faces than actually is (e.g. 1/(2*M) * sum) result looks more accurate:

I think there is some problem in converting int8<->int but I cannot prove it.
If anyone can spot any problem with the code please let me know even if it is not solution.
Question: what am I doing wrong / what to do to get better results.
Here is the code:
<code>import numpy as np
import glob
import cv2
from cv2 import imread

dir = "../images/faces94/**/**.jpg"

files = list(glob.iglob(dir, recursive=True))
img = np.zeros(imread(files[0],0).shape)
img = img.astype('int')
for i in range(len(files)):
    img += imread(files[i],0).astype('int')

img = np.divide(img,len(files)*2) # HERE you can change it to np.divide(img,len(files)) in order to see bad result
img = np.mod(img,128)
img = img.astype(np.int8)

cv2.imshow("image", img)
cv2.waitKey(0)
</code>
Comment: Well I would encourage you to post that with those other relevant details in an answer post. Good job on finding those! :)
Comment: @Divakar this is the correct answer, please post it as an answer so I can accept it as such.
In addition I had to change modulo from 128 to 256 :)
Answer: Thanks to @Divakar I found two problems in my code.

Image arrays in opencv are based on uint8 not int8
I was doing modulo (np.mod(img,128)) and because of it my image was ranged from 0 to 127 and should be from 0 to 255.

Average face - algorithm


How to switch to another TabView in swiftUI?

Question: I know this question has been asked before and I found a few of them but mine is slightly different.
I found this for example:
Programmatically change to another tab in SwiftUI
which works fine if you have the struct ContentView: View {...} and struct FirstView: View {...} on the same Swift file.
But in my project, I have the struct ContentView: View {...} in 1 Swift file and struct FirstView: View {...} in another separate swift file.
for that reason, when I use @Binding var tabSelection: Int in my FirstView() file, I get this error in my ContentView file: Argument passed to call that takes no arguments
Could someone please advice on this issue?
Comment: It would not make any deference in result at all, you probably running in another issue! could you show your real used code?
Comment: @swiftPunk, its a large code. let me see if I can minify it.
Answer: For example, if you try this example it would working! It would not make any deference in result at all if you put them in deferent files!
File ContentView:
import SwiftUI

struct ContentView: View {
    @State private var tabSelection = 1

    var body: some View {
        TabView(selection: $tabSelection) {

            FirstView(tabSelection: $tabSelection)
                .tabItem {
                    Text("Tab 1")
                }
                .tag(1)

            SecondView(tabSelection: $tabSelection)
                .tabItem {
                    Text("Tab 2")
                }
                .tag(2)
        }
    }
}

File FirstView:
import SwiftUI

struct FirstView: View {

    @Binding var tabSelection: Int

    var body: some View {

        Button(action: { tabSelection = 2 }) { Text("Change to tab 2") }

    }
}

File SecondView:
import SwiftUI

struct SecondView: View {

    @Binding var tabSelection: Int

    var body: some View {

        Button(action: { tabSelection = 1 }) { Text("Change to tab 1") }

    }
}


Duvida sobre content activity

Question: Sempre que crio minha segunda Activity, é gerado dois layouts para ela. No meu caso foi o activity_pincipal e content_principal.
Por que isso ocorre?
Answer: São os arquivos para design do seu aplicativo, o content é o conteudo que você coloca dentro do aplicativo como textviews list views etc.
Comment: E quanto ao activity_principal? Que tipo de coisas posso fazer com o ele?
Comment: activity man é o design da "pagina inicial" do seu app e o content é o conteudo

Duvida sobre content activity


what is the rank of the multiplication transformation $A$ if $AX=PX$ and $P$ has rank $m$?

Question: Consider the vector space consisting of all linear transformations on a vector
space $V$, and let $A$ be the (left) multiplication transformation that sends each transformation $X$ on $V$ onto $PX$, where $P$ is some prescribed transformation on $V$.
If $P$ has rank $m$, what is the rank of $A$?
$Source$: Halmos Finite demensional vector space, Section 50 Rank and nullity, exercise #3
Now from the question, I think that means $AX=PX$.
If $P$ has rank $m$, then $A$ must have the same rank, $m$.
Am I right? I am quite sure I have miss something. I don't think Halmos would ask such a simple question.
Please can you help, thank you very much.
Answer: You're misunderstanding the question: we start with a vector space $V$. Then, we consider the vector space of all linear transformations from $V$ to $V$. To be clear, let's give this its own name, let's say $W$. (This space is normally denoted $\mathrm{End}(V)$, because it consists of endomorphisms of $V$.)
Again, just to be clear, each element of $W$ is a different linear transformation from $V$ to $V$.
Now, having chosen some specific $P:V\to V$, we consider a linear transformation $A:W\to W$. The rule defining $A$ is that when we input a linear transformation $X:V\to V$, we output the new linear transformation $PX:V\to V$, that is, the composition of the maps
$$V\xrightarrow{\;\;X\;\;}V\xrightarrow{\;\;P\;\;}V\\
\xrightarrow[PX]{\qquad\qquad\qquad}$$
The question is asking you what the rank of the linear transformation $A:W\to W$ is. To start with, you should understand that $\dim(W)=\dim(V)^2$ (think about the dimension of a space of $n\times n$ matrices).
Comment: thanks a lot for answering. The rank of $A$ is the dimension of the range of $A$ by definition, so the rank of $A$ is the dimension of $W$. now since $P$ has the rank $m$, so the range of $P$ has deminsion $m$, that is $V$ has demension $m$. so the rank of $A$ is $m^2$. Am I right?
Comment: The rank of a linear transformation **is** the dimension of its range, but the range is ***different*** than the codomain. [See this Wikipedia article](http://en.wikipedia.org/wiki/Codomain). So for example, if we consider the linear transformation $f:\mathbb{R}^3\to\mathbb{R}^3$ defined by
$$f(x_1,x_2,x_3)=(x_1,0,0)$$
the rank of $f$ is $1$, not $3$. Do you understand?
Comment: oh, sorry about that. yeah, I understand what you meant now. re-read the question. I noted that $A$ send $X$ *onto* $PX$, so the range of $A$ is the set of all the linear transformation $PX$, and we know $P$ has range with the dimension $m$. I am not sure how to continues from here, can you give a bit more hint?
Comment: Are you aware of the rank-nullity theorem? You can use the fact that
$$n^2=\dim(W)=\mathrm{rank}(A)+ \mathrm{nullity}(A)=\dim(\mathrm{range}(A)) +\dim(\mathrm{kernel}(A))$$
Can you figure out which linear transformations $X:V\to V$ have the property that $A(X)=PX$ is the zero linear transformation? Those $X$'s comprise the kernel of $A$.
Comment: yes, I am awared of the rank-nullity theorem. I believe $A$ is $1-1$ if and only if $nullity(A)$ is the set of the zero linear transformation. That means if $A$ is 1-1 then $PX$ is the zero linear transformation, and so the range of $PX$ (which also is the range of $P$) has only one element. I have think about this quite a while, still not sure which way i should go.it seems I go the wrong direction.
Comment: I recommend to try thinking about an example. Let $V=\mathbb{R}^2$, so that $W$ is the space of $2\times 2$ matrices (therefore $\dim(W)=4$), and let $P=\bigl[\begin{smallmatrix} 3 & 1\\ 6 & 2\end{smallmatrix}\bigr]$. Figure out which matrices $X=\bigl[\begin{smallmatrix} x_1 & x_2\\ x_3 & x_4\end{smallmatrix}\bigr]$ have the property that $PX=\bigl[\begin{smallmatrix} 0 & 0\\ 0 & 0\end{smallmatrix}\bigr]$. The collection of those $X$'s is the kernel of $A$, since it is the collection of elements of $W$ that $A$ sends to the zero element of $W$.
Comment: it looks there are infinitely many such $X$ exist, for example \begin{pmatrix}11\\-3 -3\\ \end{pmatrix} is one of then, and then any multiplication of this matrix also would give us $PX = 0$. sorry, i am really have not clue.
Comment: The goal is to find the dimension of the subspace
$$\mathrm{kernel}(A)=\{X\in W: PX=0\}$$
The dimension of $W$ is $4$, so you know that the dimension of $\mathrm{kernel}(A)$ is somewhere between $0$ and $4$. You'll want to figure out the conditions on the numbers $x_1,x_2,x_3,x_4$ that are imposed by the statement that
$$PX=\begin{bmatrix}
3 & 1\\ 6 & 2\end{bmatrix}\begin{bmatrix}
x_1 & x_2\\ x_3 & x_4\end{bmatrix}=\begin{bmatrix}
0 & 0\\ 0 & 0\end{bmatrix}$$
Comment: oh, so the statement would gives us two equation: $3x_1+x_3=0$, and $3x_2+x_4=0$. that means $x_3$ depends on $x_1$ and $x_4$ depends on $x_2$ or vice verse. so we only need two elements to form the base, so the dimension of $kernel(A)$ is 2. is that what I need to do? But then what's the rank of $P$ to do with the solution in the original question?
Comment: i think maybe is this: for the kernel of $A$ is $X$ send every vector to zero, so that $PX$ also send every vector to zero, so $kernel(A)=Kernel(PX)$, and since the rank of $P$ is $m$, the rank of $PX$ also is $m$. so $dim(W)=rank(PX)+nullity(PX)$ as well. so $nullity(A)=nullity(PX)=n^2-m$, and so $rank(A)=n^2-(n^2-m)=m$. is that right?
Comment: Unfortunately no, you're very confused. $A$ is a map from $W$ to $W$, whereas $X$ (and therefore $PX$) are maps from $V$ to $V$, so it makes no sense to say $\mathrm{kernel}(A)=\mathrm{kernel}(PX)$. To be honest, I think your best course of action right now is to review more fundamental concepts in linear algebra (and possibly the general facts about sets and functions).
Comment: thanks a lot for your comment. just could you tell me the solution for this question for now?


Personal user folders in a Share

Question: I had to do a restore of a fileserver and the permissions got lost for our personal folders.
Structure is like this.
\fileserver\share\usernames.
I need to set permissions so that each user has access to only their folders.
Thank you for your help
Comment: So add the permissions. What's the trouble?
Answer: Assuming that all folders in the /share/ directory represents user names, you can use:
<code> for dir in /share/*/; do
        # strip trailing slash
        homedir="${dir%/}"
        # strip all chars up to and including the last slash
        username="${homedir##*/}"

        case $username in
        *.*) continue ;; # skip name with a dot in it
        esac

        chown -R "$username" "$dir"
    done
</code>
Test this script in safe place , check if the user is the owner of her folder.
Comment: It is for Server 2008 R2.
Answer: Additional information will be required to assist you. What type of environment are you working in? Is it Windows, Linux, OSX, or NAS device? Do you have the database of users on Windows Active Directory? You can pretty much create a file server from a workstation, server, or network device but you will need to create all the usernames and passwords for the clients (users).
If this is a NAS box, create usernames and passwords that match the usernames the individuals use to login to their perspective computer.
There are two sets of permissions. One would be the share permission which allows the user to connect to the share. There are three types of share permissions: Full Control, Change, and Read.
The second set of permission is the folder permissions. Create folders with name of the user.  You will give each user full permission to their individual folder.
Comment: Server 2008 R2 is the environment. Structure is \\fileserver\share\username. AD profiles are set to connect to \\fileserver\share\username.
Comment: I've tried many tutorials without success. It either ends up with everyone having access to everyone's folders or no one having access to any folders.
Comment: Change the share permission to READ for Everyone rather than Full Control.  Then change the permission on the NTFS  permission so only the user has access to the individual folder.   Check out https://support.randomsolutions.nl/380508-Security-Recommendations-for-Roaming-User-Profiles-Shared-Folders and https://docs.microsoft.com/en-us/windows-server/storage/folder-redirection/deploy-roaming-user-profiles

Personal user folders in a Share


CakePHP Validator not working form entity

Question: I want to perform a htmlspecialchars with no quotes in my entity save.
Code:
$post['body'] = htmlentities($this->request->getData('body'), ENT_NOQUOTES);

Validator doesn't work on save.
How to make it work?
Thanks
Answer: The h() method is just a wrapper for htmlspecialchars() more information on that can be found in the Cake API https://book.cakephp.org/3.0/en/core-libraries/global-constants-and-functions.html#h
h(string $text, boolean $double = true, string $charset = null)

The long and short of it is that the first parameter for those functions is a string and you are passing in an array of data. If you wanted to strip those out you could override the patchEntity() with your own or individual run the special chars function on each elements
Edit: Added more clear example to keep validation
You can use the withData to set the response data and still use patch entities. for instance.
$data = $this->request->withData('body', htmlentities($this->request->getData('body'), ENT_NOQUOTES))

And then patch/validate the entity using the new request object.
patchEntity($post, $data)

Comment: If I try  $post['body'] = htmlentities($this->request->getData('body'), ENT_NOQUOTES); the validator doesn't work. Is there any way to make it work - even when the body is the same as the getData?
Comment: You can use the withData to set the response data and still use patch entities. for instance `$data = $this->request->withData('body', htmlentities($this->request->getData('body'), ENT_NOQUOTES))` then use the patch entities with $data as the request. I will edit my post with a more clear example
Comment: Thanks for the reply. I am getting Cannot convert value to string when using $reply['body'] = $this->request->withData('body', htmlentities($this->request->getData('body'), ENT_NOQUOTES));
Comment: @KlaasWaas withData() does not return a string it returns a response object if I recall correctly. Look at my example I updated, it shows the correct usage.
Comment: Sorry for wasting your time. I am now using htmlentities on the view.
Comment: @KlaasWaas not a waste of time at all. Glad you got everything working!


Making an axios get request and using React useState but when logging the data it still shows null

Question: When I make a request to an API and setting the state to the results from the Axios request it still shows up null. I am using React useState and setting the results from the request and wanting to check to see if its coming through correctly and getting the right data its still resulting into null. The request is correct but when I use .then() to set the state that is the issue I am having.
Below is the component that I am building to make the request called Details.js (first code block) and the child component is the DetailInfo.js file (second code block) that will be displaying the data. What am I missing exactly or could do better when making the request and setting the state correctly display the data?

import React, {useEffect, useState} from 'react';
import { Col, Container, Row } from 'react-bootstrap';
import axios from 'axios';
import { getCookie } from '../utils/util';

import DetailInfo from '../components/DetailInfo';
import DetailImage from '../components/DetailImage';

const Details = () => {

    const [ countryData, setCountryData ] = useState(null);
    let country;
    let queryURL = `https://restcountries.eu/rest/v2/name/`;

    useEffect(() => {
        country = getCookie('title');
        console.log(country);
        queryURL += country;
        console.log(queryURL);
        axios.get(queryURL)
        .then((res) => {
            console.log(res.data[0])
            setCountryData(res.data[0]);
        })
        .then(() => {
            console.log(countryData)
        }
        );

    }, [])

    return (
        <>
            <Container className="details">
                <Row>
                    <Col sm={6}>
                        <DetailImage />
                    </Col>
                    <Col sm={6}>
                        <DetailInfo
                        name={countryData.name}
                        population={countryData.population}
                        region={countryData.region}
                        subRegion={countryData.subRegion}
                        capital={countryData.capital}
                        topLevelDomain={countryData.topLevelDomain}
                        currencies={countryData.currencies}
                        language={countryData.language}
                        />
                    </Col>
                </Row>
            </Container>
        </>
    )
}

export default Details;

The child component below......

import React from 'react';

const DetailInfo = (props) => {
    const {name, population, region, subRegion, capital, topLevelDomain, currencies, language} = props;
    return (
        <>detail info{name}{population} {region} {capital} {subRegion} {topLevelDomain} {currencies} {language}</>
    )
}

export default DetailInfo;
Comment: Does this answer your question? [useState set method not reflecting change immediately](https://stackoverflow.com/questions/54069253/usestate-set-method-not-reflecting-change-immediately)
Answer: Ultimately, the problem comes down to not handling the intermediate states of your component.
For components that show remote data, you start out in a "loading" or "pending" state. In this state, you show a message to the user saying that it's loading, show a Spinner (or other throbber), or simply hide the component. Once the data is retrieved, you then update your state with the new data. If it failed, you then update your state with information about the error.
const [ dataInfo, setDataInfo ] = useState(/* default dataInfo: */ {
  status: "loading",
  data: null,
  error: null
});

useEffect(() => {
  let unsubscribed = false;

  fetchData()
    .then((response) => {
      if (unsubscribed) return; // unsubscribed? do nothing.
      setDataInfo({
        status: "fetched",
        data: response.data,
        error: null
      });
    })
    .catch((err) => {
      if (unsubscribed) return; // unsubscribed? do nothing.
      console.error('Failed to fetch remote data: ', err);
      setDataInfo({
        status: "error",
        data: null,
        error: err
      });
    });

  return () => unsubscribed = true;
}, []);

switch (dataInfo.status) {
  case "loading":
    return null; // hides component
  case "error":
    return (

        Failed to retrieve data: {dataInfo.error.message}

    );
}

// render data using dataInfo.data
return (
  /* ... */
);

If this looks like a lot of boiler plate, there are useAsyncEffect implementations like @react-hook/async and use-async-effect that handle it for you, reducing the above code to just:
import {useAsyncEffect} from '@react-hook/async'

/* ... */

const {status, error, value} = useAsyncEffect(() => {
  return fetchData()
    .then((response) => response.data);
}, []);

switch (status) {
  case "loading":
    return null; // hides component
  case "error":
    return (

        Failed to retrieve data: {error.message}

    );
}

// render data using value
return (
  /* ... */
);

Answer: Because state only update when component re-render. So you should put console.log into useEffect to check the new value:
useEffect(() => {
    country = getCookie('title');
    console.log(country);
    queryURL += country;
    console.log(queryURL);
    axios.get(queryURL).then(res => {
        console.log(res.data[0]);
        setCountryData(res.data[0]);
    });
}, []);

useEffect(() => {
    console.log(countryData);
}, [countryData]);

Comment: While this would help OP log whenever `countryData` changes, it doesn't solve OP's "reading property of `null`" error on the first render cycle.
Answer: useState does reflecting its change immediately.
I think that it would be probably solved if you set countryData to second argument of useEffect.
useEffect(() => {
        country = getCookie('title');
        console.log(country);
        queryURL += country;
        console.log(queryURL);
        axios.get(queryURL)
        .then((res) => {
            console.log(res.data[0])
            setCountryData(res.data[0]);
        })
        .then(() => {
            console.log(countryData)
        }
        );

    }, [countryData])

Comment: Adding the variable the `useEffect` call modifies as shown here would create an infinite loop.
Answer: The issue is, as samthecodingman, pointed out, an issue of intermediate data. Your component is being rendered before the data is available, so your child component needs to re-render when its props change. This can be done via optional chaining, an ES6 feature.
import React, { useEffect, useState } from "react";
import DetailInfo from "./DetailInfo";
import { Col, Container, Row } from "react-bootstrap";
import axios from "axios";

const Details = () => {
  const [countryData, setCountryData] = useState({});
  let country = "USA";
  let queryURL = `https://restcountries.eu/rest/v2/name/`;

  useEffect(() => {
    console.log(country);
    queryURL += country;
    console.log(queryURL);
    axios
      .get(queryURL)
      .then((res) => {
        console.log(res.data[0]);
        setCountryData(res.data[0]);
      })
      .then(() => {
        console.log(countryData);
      });
  }, []);

  return (
    <Container className="details">
      <Row>
        <Col sm={6}>
          <DetailInfo
            name={countryData?.name}
            population={countryData?.population}
            region={countryData?.region}
            subRegion={countryData?.subRegion}
            capital={countryData?.capital}
            language={countryData?.language}
          />
        </Col>
        <Col sm={6}></Col>
      </Row>
    </Container>
  );
};

export default Details;

Checkout my Codesandbox here for an example.


snakemake wildcard scoping between rules

Question: I've read the docs on rules, the FAQ, and this question, but I still can't tell: if a wildcard foo is defined in rule bar, can its values be accessed in rule baz?
Comment: It is possible to pass values between rules using [this trick](https://snakemake.readthedocs.io/en/stable/project_info/faq.html#i-want-to-pass-variables-between-rules-is-that-possible), but the docs there imply that wildcards don't pass values between rules.
Comment: This answer is on a very similar topic and it says that wildcards do not take the same values from one rule to the next. https://bioinformatics.stackexchange.com/a/11137/1708
Answer: If I understood your question correctly, the answer should be "no".
By using a wildcard in the rule you just define the pattern that can be applied to many different files. For example, in this rule you define the a way to produce files whose filenames match a pattern "new_name{n}.txt", where {n} can be any string:
rule example:
    input: "old_name{n}.txt"
    output: "new_name{n}.txt"
    shell: "cp input output"

For sure this rule will be regarded only if the file "old_name{n}.txt" exists with the same string {n} used.
Returning back to your question: how could you access the value if this is just a pattern that may be applied to different values?
Another possible interpretation of your question is that you need to know all the values (all the inputs) the rule bar was applied to. In this case you probably need to employ checkpoint: this is the way to delay the pattern application until the part of pipeline finishes. But even in this case you wouldn't be accessing "the values of wildcard" explicitly.
Comment: I am just looking for the reasoning behind what you have said, in particular your first sentence: *If I understood your question correctly, the answer should be "no".* For example, did you find some documentation that describes wild-card scoping? Did you test out an example? Or is this just common sense to you?
Comment: *how could you access the value if this is just a pattern that may be applied to different values?* I was imagining something like this: when a value matches {foo} in `rule bar`, it then also appears as that value in `baz`. (I'm glad this doesn't happen, but from the docs, I couldn't tell.)
Comment: Your answer makes sense, but do you have an example or any documentation to support it?
Comment: @eric_kernfeld. The wildcards in different rules are independent from each other. The rest of your question is open-ended. Please describe a concrete problem you are trying to solve, and I'll try to find the docs for you.
Answer: I'm not sure I'm answering your question and what follows may not be entirely correct... Snakemake only cares that you have one and only one path that leads to the requested files (i.e., the files defined in the first rule, usually called all).
If rule bar defines wildcards that can to lead to the final output, then yes, those wildcards are visible to the following rules.
In the script below we ask for files A.txt and B.txt. To produce A.txt we don't need any wildcard. To produce B.txt we need to pass by wildcard {wc} defined in rule bar and used in rule B. Note that wildcard {sample} doesn't appear at all outside rule all. Note also that rule bar produces two files, B.tmp and C.tmp, but rule B only needs B.tmp. (You should be able to dry-run this script with snakemake -p -n)
rule all:
    input:
        expand('{sample}.txt', sample= ['A', 'B']),

rule A:
    output:
        'A.txt',
    shell:
         "touch {output}"

rule bar:
    output:
        expand('{wc}.tmp', wc= ['B', 'C'])
    shell:
        r"""
        touch {output}
        """

rule B:
    input:
        '{wc}.tmp',
    output:
        '{wc}.txt',
    shell:
        r"""
        touch {input} {output}
        """

Comment: I tried this out. When I replace `{wc}` in `rule B` with `{other}`, it still works. Also, the file `C.txt` is not created. So it seems that the wildcard's values from `bar` (which are `['B', 'C']`) are *not* visible in `rule B`. In other words, your example is very helpful. May I edit your answer to reflect the behavior I am observing versus the behavior my question would predict?


Hibernate multiple relationships doesn't work

Question: When I create 2 one-to-one relationships in the end only one of the 2 is saved the other one becomes null.
In the sql trace you can see MFUITVOERINGJOIN only saves 2 id's when it should be saving 3 :S
Is there something wrong here?
@Entity
@Table(name = "STUD1630651.MFUITVOERING")
public class Uitvoering {

@Id
@GeneratedValue(strategy=GenerationType.AUTO, generator="my_entity_seq_gen")
@SequenceGenerator(name="my_entity_seq_gen", sequenceName="HIBERNATE_SEQUENCE_UITVOERING")
@Column(name = "ID")
private int id;

@Column(name = "DATUM")
private String datum;

@Column(name = "SCHOUWBURG")
private String schouwburg;

@OneToOne(cascade=CascadeType.ALL)
@JoinTable(name="MFUITVOERINGJOIN",joinColumns=
{@JoinColumn(name="UITVOERINGID")},
inverseJoinColumns={@JoinColumn(name="DIRIGENTID")})
private Dirigent dirigent;

@OneToOne(cascade=CascadeType.ALL)
@JoinTable(name="MFUITVOERINGJOIN",joinColumns=
{@JoinColumn(name="UITVOERINGID")},inverseJoinColumns=
{@JoinColumn(name="MUZIEKSTUKID")})
private Muziekstuk muziekstuk;

public Uitvoering(String datum, String schouwburg, Dirigent dirigent, Muziekstuk muziekstuk){
    this.datum = datum;
    this.schouwburg = schouwburg;
    this.dirigent = dirigent;
    this.muziekstuk= muziekstuk;
}

//GETTERS AND SETTERS

SQL Trace:
Hibernate: select dirigent0_.ID as ID1_3_0_, dirigent0_.KLASSE as KLASSE2_3_0_, dirigent0_.LAND as LAND3_3_0_,  dirigent0_.NAAM as NAAM4_3_0_, dirigent0_.RICHTING as RICHTING5_3_0_ from STUD1630651.MFDIRIGENT dirigent0_ where  dirigent0_.ID=?
Hibernate: select muziekstuk0_.ID as ID1_5_1_, muziekstuk0_.GENRE as GENRE2_5_1_, muziekstuk0_.TITEL as    TITEL3_5_1_, muziekstuk0_1_.INSTRUMENTID as INSTRUME2_0_1_, instrument1_.ID as ID1_4_0_, instrument1_.HOEVEELHEID   as HOEVEELH2_4_0_, instrument1_.NAAM as NAAM3_4_0_ from STUD1630651.MFMUZIEKSTUK muziekstuk0_ left outer join    MFMUZIEKSTUKJOIN muziekstuk0_1_ on muziekstuk0_.ID=muziekstuk0_1_.MUZIEKSTUKID left outer join    STUD1630651.MFINSTRUMENT instrument1_ on muziekstuk0_1_.INSTRUMENTID=instrument1_.ID where muziekstuk0_.ID=?
Hibernate: select HIBERNATE_SEQUENCE_UITVOERING.nextval from dual
Hibernate: insert into STUD1630651.MFUITVOERING (DATUM, SCHOUWBURG, ID) values (?, ?, ?)
Hibernate: insert into MFUITVOERINGJOIN (MUZIEKSTUKID, UITVOERINGID) values (?, ?)

Answer: I think you are using @OneToOne annotation in the wrong place.
As I know one-to-one annotation is used when two tables have the same primary key columns.
A one-to-one shows for a record in table A(parrent) there must be one and only one record in table B(child). In database level this is achieved by having a foreign key of A in B table, when this  foreign key column(s) in B table is(are) marked as primary key of B.
Technically it is not possible to have more than one one-to-one relation in child table.
So in your question MFUITVOERING as child table have its owned primary key called ID (field with sequence values).  The two foreign keys of MFUITVOERINGJOIN in MFUITVOERING are representation of ManyToOne relationship. You need to use @ManyToOne annotation.


Trying to get property of non-object/ Php codeigniter

Question: I can't seem to figure about what is wrong with this code. thank yu for your help.
 I am getting error messages:
A PHP Error was encountered

Severity: Notice

Message: Trying to get property of non-object

Filename: views/members.php

Line Number: 24

My model:
public function show_user()
{
    $this->db->select('');
    $this->db->from('users');
    $this->db->where('email',$this->input->post('email'));

    $q=$this->db->get('');

    if($q->num_rows() > 0 )
    {
        $data = array();

        foreach($q->result() as $row)
        {
            $data=$row;
        }

        return $data;
    }
}

My controller:
public function members()
{
    if ($this->session->userdata('is_logged_in'))
    {
        $this->load->model('model_users');
        $data['member'] = $this->model_users->show_user();
        $this->load->view('members', $data);
    }
    else
    {
        redirect('main/restricted');
    }
}

My view:
echo "
 Congratulations you are logged in!!
";
foreach($member as $row)
{
    echo $row->Name. "
";
    echo $row->email. "
";
}

So this my code. I want to display user information from database but I am getting errors. please help me..
Answer: You only need to return $q-result();
 if($q->num_rows() > 0 )
 {
   return $q-result();
 }

Comment: Thank you my error was solved but I didnot get the output as i expected. I want the email and name of only that user who has just logged in instead i got output of all names and email of the database users....  can you help me in that??
Comment: @Sushmita, From your query ,You will get all users having the email address you proided will return
Answer: I'm not sure what your database looks like but I suspect this is because either the Name or email properties don't exist on the $row object.  Are you sure your field in your users table is called Name or is it name (lowercase)?  If its lowercase your code should be.
foreach($member as $row)
{
    echo $row->name. "
"; //Changed this line
    echo $row->email. "
";
}

Also your foreach loop on your model is a bit pointless.  You might as well remove it and just do
return $data->row;


Drupal form API date popup

Question:
Possible Duplicate:
How to remove format description in date_popup form field?

Hi I am creating a drupal 6 module and I have used drupal form API date popup fields to allow users to enter date. Everything is going on fine but I am getting a format description for date popup field as FORMAT 23/05/2012. I don't know how to remove this description.As shown in the image below
Answer: To make a correct format you can make use of <code>#default_value</code>
See here

Description: Format a date selection box. The #default_value will be
  today's date if no value is supplied. The format for the #default_value and the #return_value is an array with three elements with the keys: 'year', month', and 'day'. For example, array('year' =>
  2007, 'month' => 2, 'day' => 15)
Comment: As you can see in the above image I want to remove the text "Format 23/05/2012" from the display
Comment: I think you can make it work using the Display field settings in nodes Manage Display page admin/content/node-type//display
Comment: But I have used drupal form API and created a date popup form field for this
Comment: In that case try unset or override `#description` field
Answer: try CSS to remove it. insert some body and page classes.

Drupal form API date popup