How To Simulate Publication Replication In SQL 2005 Express?

Question: I have a client that has several geographically dispersed installations of a 3rd party commercial product that logs data to their own instances of an SQL Express database (GE's CIMPLICITY HMI if you are interested).  He now wants to collect the logging data to central DB for long term storage (IE the local installations will keep a 3 month rolling log of their own data, but the central location will keep a 5 year rolling log of all data.  And total data generation is probably less than 100MB per month).  The table structures will be kept the same in both the remote and local DBs so that the same/similar reports can easily be run on al the data.
If these were full SQL installations then I believe that I could have used publication replication to solve the problem.  But I am dealing with Express editions on the remote ends, (though I will have a full edition to play with at the central location).
So I am looking for how best to simulate publication replication on an Express DB using 3rd party tools (and not having to bang out custom code of my own).  To balance the low data throughput, 3 of the installations are actually connect back home via a VPN running over DSL, so there is an expectation of link drop outs.  This isn't seen as a big problem as long as the remote data eventually gets centrally logged.
(One possible solution is to convert all the express editions to full editions, but I believe that would be $$ prohibitive, and would be an administration headache to boot.  So I am not even considering that at the moment)
Thanks for your help
Peter
Anyone????!?!?
Crickets
Edit
I've decided to go with a custom code solution that uses MSMQ to perform queuing on the remote side.  I probably could have used SSIS to do the same thing, but for me it was jut as easy to roll my own.
Answer: If you can enable the TCP Protocol on the SQL Express Editions and add a user account to the remote stations, you could use Job Agent on the main SQL box to pull down all of the data. Maybe backup and restore (which seems like a bad idea given limited bandwidth).  You could use triggers on the remotes and push the updates to the main site, but I am not sure how that would work over a "lossy" VPN connection.  Just getting the SQL boxes to see each other will probably be the hardest part.  Once you do that, it opens up lots of different options.
Info to enable TCP on SQL Express 2005:
http://blogs.msdn.com/b/sqlexpress/archive/2005/05/05/415084.aspx
We do something similar with the HMI on some industrial equipment we have, but the connections are all over the local network.  Our DBA wrote a few scripts to grab what we needed using "insert into" and leaves a copy on the main SQL box.
Comment: I'd say that this would be one of the better custom approaches if I had to roll my own.  I ended up looking at linked servers and I think I can write T-SQL that does retries for data.
Comment: That is what we ended up doing.  The good part is that you can select data from remote tables and do a select into into the local tables.  Which is nice because then you are only moving over the missing data and not the whole table.. And of course, once you work out a stored proc that works, just dump it in agent and let it have at it..
Comment: I'll give it to you for making mer think again about a custom solution.
Comment: The good part is that its flexible enough and if the data structure is simple it should be a piece of cake.  Now if its complicated, it might be worth going to standard as your time might be more expensive than just buying the MSSQL licenses and be done with it..

Thanks for the answer points and good luck!


Need to control order of method expectation based on the expectation of a property being set

Question: I have the following example that does not behave in the way I would expect.
public abstract class Example
{
    public abstract string Foo();

    public List<string> Bar()
    {
        PreMethod();

        var list = new List<string>();

        var stack = new Stack<string>();
        foreach (var item in Stuff)
        {
            stack.Push(item);
        }

        while (stack.Any())
        {
            SomeThing = stack.Pop();
            var f = Foo();
            list.Add(f);
        }

        PostMethod();
        return list;
    }

    public abstract void PreMethod();

    public abstract void PostMethod();

    public abstract IEnumerable<string> Stuff { get; }

    public abstract string SomeThing { set; get; }
}

[TestClass]
public class ExampleTest
{
    private Example example;

    private MockRepository mocks;

    [TestInitialize]
    public void InitializeTest()
    {
        mocks = new MockRepository();
        example = MockRepository.GeneratePartialMock<Example>();
    }

    [TestMethod]
    public void BarTest()
    {
        using (mocks.Ordered())
        {
            example.Expect(e => e.PreMethod());
            example.Expect(e => e.Stuff).Return(new[] { "One", "Two" });

            using (mocks.Unordered())
            {
                using (mocks.Ordered())
                {
                    example.Expect(e => e.SomeThing).SetPropertyWithArgument("One");
                    example.Expect(e => e.Foo()).Return("one");
                }

                using (mocks.Ordered())
                {
                    example.Expect(e => e.SomeThing).SetPropertyWithArgument("Two");
                    example.Expect(e => e.Foo()).Return("two");
                }
            }

            example.Expect(e => e.PostMethod());
        }

        mocks.ReplayAll();

        var actual = example.Bar();
        Assert.AreEqual(2, actual.Count);
        Assert.AreEqual("two", actual[0]);
        Assert.AreEqual("one", actual[1]);
    }
}

So, the expectation is that by putting the calls to Something and Foo inside of using(mocks.Ordered) that Foo will return the value based on what Something was just set to, but the test fails because the resulting list actually has "one", then "two".  When I debug I see that after Something is set to "Two" the call to Foo returns "one".  Basically I just want to make the return of Foo to be connected to what Something was set to, but without knowing the order that they will be set (basically this test shouldn't be effected by changing the code to use a Queue instead of a Stack).
Answer: So the first thing I found out is that ordering does not work with the AAA style.  Second I discovered that I can achieve what I'm looking for by using WhenCalled.
    [TestMethod]
    public void BarTest()
    {
        example.Expect(e => e.PreMethod());
        example.Expect(e => e.Stuff).Return(new[] { "One", "Two" });
        example.Expect(e => e.SomeThing)
            .SetPropertyWithArgument("One")
            .WhenCalled(obj => example.Expect(e => e.Foo()).Return("one"));
        example.Expect(e => e.SomeThing)
            .SetPropertyWithArgument("Two")
            .WhenCalled(obj => example.Expect(e => e.Foo()).Return("two"));
        example.Expect(e => e.PostMethod());

        var actual = example.Bar();

        Assert.AreEqual(2, actual.Count);
        Assert.AreEqual("two", actual[0]);
        Assert.AreEqual("one", actual[1]);
        example.VerifyAllExpectations();
    }

By putting the expectations inside of the WhenCalled it ensures that the expectations happen in the expected order.


Apache timeout instead of webpage

Question: instead of the desired webpages I get timeouts. If I try to get a page with wget on the server itself it works fine, but if I want to connect with a browser I get a timeout.
s15312615:/etc/apache2 # netstat -l
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State
tcp        0      0 *:ssh                   *:*                     LISTEN
tcp        0      0 localhost.localdom:smtp *:*                     LISTEN
tcp        0      0 *:www-http              *:*                     LISTEN
tcp        0      0 *:ssh                   *:*                     LISTEN
tcp        0      0 *:snpp                  *:*                     LISTEN
Active UNIX domain sockets (only servers)
Proto RefCnt Flags       Type       State         I-Node Path
unix  2      [ ACC ]     STREAM     LISTENING     8857   private/verify
unix  2      [ ACC ]     STREAM     LISTENING     8863   private/proxymap
unix  2      [ ACC ]     STREAM     LISTENING     8866   private/smtp
unix  2      [ ACC ]     STREAM     LISTENING     8869   private/relay
unix  2      [ ACC ]     STREAM     LISTENING     8875   private/error
unix  2      [ ACC ]     STREAM     LISTENING     6037   @/var/run/hald/dbus-aXRNnAXQQw
unix  2      [ ACC ]     STREAM     LISTENING     5897   /var/run/acpid.socket
unix  2      [ ACC ]     STREAM     LISTENING     8034   /var/run/mcelog-client
unix  2      [ ACC ]     STREAM     LISTENING     8018   /var/run/nscd/socket
unix  2      [ ACC ]     STREAM     LISTENING     8019   /var/run/.nscd_socket
unix  2      [ ACC ]     STREAM     LISTENING     8878   private/discard
unix  2      [ ACC ]     STREAM     LISTENING     8881   private/local
unix  2      [ ACC ]     STREAM     LISTENING     8884   private/virtual
unix  2      [ ACC ]     STREAM     LISTENING     8887   private/lmtp
unix  2      [ ACC ]     STREAM     LISTENING     5991   @/var/run/hald/dbus-98LA968QdN
unix  2      [ ACC ]     STREAM     LISTENING     8890   private/anvil
unix  2      [ ACC ]     STREAM     LISTENING     8893   private/scache
unix  2      [ ACC ]     STREAM     LISTENING     8896   private/maildrop
unix  2      [ ACC ]     STREAM     LISTENING     8845   private/rewrite
unix  2      [ ACC ]     STREAM     LISTENING     8899   private/cyrus
unix  2      [ ACC ]     STREAM     LISTENING     8848   private/bounce
unix  2      [ ACC ]     STREAM     LISTENING     8902   private/uucp
unix  2      [ ACC ]     STREAM     LISTENING     8851   private/defer
unix  2      [ ACC ]     STREAM     LISTENING     8905   private/ifmail
unix  2      [ ACC ]     STREAM     LISTENING     8854   private/trace
unix  2      [ ACC ]     STREAM     LISTENING     8908   private/bsmtp
unix  2      [ ACC ]     STREAM     LISTENING     8911   private/procmail
unix  2      [ ACC ]     STREAM     LISTENING     8914   private/retry
unix  2      [ ACC ]     STREAM     LISTENING     8917   private/proxywrite
unix  2      [ ACC ]     STREAM     LISTENING     8840   public/cleanup
unix  2      [ ACC ]     STREAM     LISTENING     8860   public/flush
unix  2      [ ACC ]     STREAM     LISTENING     8872   public/showq
unix  2      [ ACC ]     STREAM     LISTENING     5964   /var/run/dbus/system_bus_socket

Output from iptables:
s15312615:/etc/apache2 # iptables -L
Chain INPUT (policy DROP)
target     prot opt source               destination
ACCEPT     all  --  anywhere             anywhere
ACCEPT     all  --  anywhere             anywhere            state ESTABLISHED
ACCEPT     icmp --  anywhere             anywhere            state RELATED
input_ext  all  --  anywhere             anywhere
input_ext  all  --  anywhere             anywhere
LOG        all  --  anywhere             anywhere            limit: avg 3/min burst 5 LOG level warning tcp-options ip-options prefix `SFW2-IN-ILL-TARGET '
DROP       all  --  anywhere             anywhere

Chain FORWARD (policy DROP)
target     prot opt source               destination
LOG        all  --  anywhere             anywhere            limit: avg 3/min burst 5 LOG level warning tcp-options ip-options prefix `SFW2-FWD-ILL-ROUTING '

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination
ACCEPT     all  --  anywhere             anywhere
ACCEPT     all  --  anywhere             anywhere            state NEW,RELATED,ESTABLISHED
LOG        all  --  anywhere             anywhere            limit: avg 3/min burst 5 LOG level warning tcp-options ip-options prefix `SFW2-OUT-ERROR '

Chain forward_ext (0 references)
target     prot opt source               destination

Chain input_ext (2 references)
target     prot opt source               destination
DROP       all  --  anywhere             anywhere            PKTTYPE = broadcast
ACCEPT     icmp --  anywhere             anywhere            icmp source-quench
ACCEPT     icmp --  anywhere             anywhere            icmp echo-request
LOG        tcp  --  anywhere             anywhere            limit: avg 3/min burst 5 tcp dpt:ssh flags:FIN,SYN,RST,ACK/SYN LOG level warning tcp-options ip-options prefix `SFW2-INext-ACC-TCP '
ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:ssh
DROP       all  --  anywhere             anywhere            PKTTYPE = multicast
DROP       all  --  anywhere             anywhere            PKTTYPE = broadcast
LOG        tcp  --  anywhere             anywhere            limit: avg 3/min burst 5 tcp flags:FIN,SYN,RST,ACK/SYN LOG level warning tcp-options ip-options prefix `SFW2-INext-    DROP-DEFLT '
LOG        icmp --  anywhere             anywhere            limit: avg 3/min burst 5 LOG level warning tcp-options ip-options prefix `SFW2-INext-DROP-DEFLT '
LOG        udp  --  anywhere             anywhere            limit: avg 3/min burst 5     state NEW LOG level warning tcp-options ip-options prefix `SFW2-INext-DROP-DEFLT '
DROP       all  --  anywhere             anywhere

Chain reject_func (0 references)
target     prot opt source               destination
REJECT     tcp  --  anywhere             anywhere            reject-with tcp-reset
REJECT     udp  --  anywhere             anywhere            reject-with icmp-port-unreachable
REJECT     all  --  anywhere             anywhere            reject-with icmp-proto-unreachable

How can I solve this?
///EDIT
httpd.conf
### Global Environment ######################################################
#
# The directives in this section affect the overall operation of Apache,
# such as the number of concurrent requests.

# run under this user/group id
Include /etc/apache2/uid.conf

# - how many server processes to start (server pool regulation)
# - usage of KeepAlive
Include /etc/apache2/server-tuning.conf

# ErrorLog: The location of the error log file.
# If you do not specify an ErrorLog directive within a <VirtualHost>
# container, error messages relating to that virtual host will be
# logged here.  If you *do* define an error logfile for a <VirtualHost>
# container, that host's errors will be logged there and not here.
ErrorLog /var/log/apache2/error_log

# generated from APACHE_MODULES in /etc/sysconfig/apache2
Include /etc/apache2/sysconfig.d/loadmodule.conf

# IP addresses / ports to listen on
Include /etc/apache2/listen.conf

# predefined logging formats
Include /etc/apache2/mod_log_config.conf

# generated from global settings in /etc/sysconfig/apache2
Include /etc/apache2/sysconfig.d/global.conf

# optional mod_status, mod_info
Include /etc/apache2/mod_status.conf
Include /etc/apache2/mod_info.conf

# optional cookie-based user tracking
# read the documentation before using it!!
Include /etc/apache2/mod_usertrack.conf

# configuration of server-generated directory listings
Include /etc/apache2/mod_autoindex-defaults.conf

# associate MIME types with filename extensions
TypesConfig /etc/apache2/mime.types
DefaultType text/plain
Include /etc/apache2/mod_mime-defaults.conf

# set up (customizable) error responses
Include /etc/apache2/errors.conf

# global (server-wide) SSL configuration, that is not specific to
# any virtual host
Include /etc/apache2/ssl-global.conf

# forbid access to the entire filesystem by default
<Directory />
    Options None
    AllowOverride None
    Order deny,allow
    Deny from all
</Directory>

# use .htaccess files for overriding,
AccessFileName .htaccess
# and never show them
<Files ~ "^\.ht">
    Order allow,deny
    Deny from all
</Files>

# List of resources to look for when the client requests a directory
DirectoryIndex index.php index.html index.htm index.html.var

### 'Main' server configuration #############################################
#
# The directives in this section set up the values used by the 'main'
# server, which responds to any requests that aren't handled by a
# <VirtualHost> definition.  These values also provide defaults for
# any <VirtualHost> containers you may define later in the file.
#
# All of these directives may appear inside <VirtualHost> containers,
# in which case these default settings will be overridden for the
# virtual host being defined.
#
#Include /etc/apache2/default-server.conf

# Another way to include your own files
#
# The file below is generated from /etc/sysconfig/apache2,
# include arbitrary files as named in APACHE_CONF_INCLUDE_FILES and
# APACHE_CONF_INCLUDE_DIRS
Include /etc/apache2/sysconfig.d/include.conf

### Virtual server configuration ############################################
#
# VirtualHost: If you want to maintain multiple domains/hostnames on your
# machine you can setup VirtualHost containers for them. Most configurations
# use only name-based virtual hosts so the server doesn't need to worry about
# IP addresses. This is indicated by the asterisks in the directives below.
#
# Please see the documentation at
# <URL:http://httpd.apache.org/docs-2.2/vhosts/>
# for further details before you try to setup virtual hosts.
#
# You may use the command line option '-S' to verify your virtual host
# configuration.
#
#Include /etc/apache2/vhosts.d/*.conf
Include /etc/apache2/vhosts.d/_vhost-master.conf

# Note: instead of adding your own configuration here, consider
#       adding it in your own file (/etc/apache2/httpd.conf.local)
#       putting its name into APACHE_CONF_INCLUDE_FILES in
#       /etc/sysconfig/apache2 -- this will make system updates
#       easier :)
AddOutputFilter INCLUDES .shtml
AddType text/html .shtml
AddType application/x-httpd-php .php
AddType application/x-httpd-php-source .phps

iptables -L -v
Chain INPUT (policy DROP 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
   10  3008 ACCEPT     all  --  lo     any     anywhere             anywhere
13599  889K ACCEPT     all  --  any    any     anywhere             anywhere            state ESTABLISHED
    0     0 ACCEPT     icmp --  any    any     anywhere             anywhere            state RELATED
 2900  537K input_ext  all  --  eth0   any     anywhere             anywhere
    0     0 input_ext  all  --  any    any     anywhere             anywhere
    0     0 LOG        all  --  any    any     anywhere             anywhere            limit: avg 3/min burst 5 LOG level warning tcp-options ip-options prefix `SFW2-IN-ILL-TARGET '
    0     0 DROP       all  --  any    any     anywhere             anywhere

Chain FORWARD (policy DROP 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
    0     0 LOG        all  --  any    any     anywhere             anywhere            limit: avg 3/min burst 5 LOG level warning tcp-options ip-options prefix `SFW2-FWD-ILL-ROUTING '

Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
   10  3008 ACCEPT     all  --  any    lo      anywhere             anywhere
13313 5996K ACCEPT     all  --  any    any     anywhere             anywhere            state NEW,RELATED,ESTABLISHED
0     0 LOG        all  --  any    any     anywhere             anywhere                limit: avg 3/min burst 5 LOG level warning tcp-options ip-options prefix `SFW2-OUT-ERROR '

Chain forward_ext (0 references)
 pkts bytes target     prot opt in     out     source               destination

Chain input_ext (2 references)
 pkts bytes target     prot opt in     out     source               destination
     1280  452K DROP       all  --  any    any     anywhere             anywhere            PKTTYPE = broadcast
    0     0 ACCEPT     icmp --  any    any     anywhere             anywhere                icmp source-quench
   10   461 ACCEPT     icmp --  any    any     anywhere             anywhere                icmp echo-request
    7   392 LOG        tcp  --  any    any     anywhere                 anywhere                limit: avg 3/min burst 5 tcp dpt:ssh flags:FIN,SYN,RST,ACK/SYN LOG     level warning tcp-options ip-options prefix `SFW2-INext-ACC-TCP '
        8   452 ACCEPT     tcp  --  any    any     anywhere             anywhere            tcp dpt:ssh
    0     0 DROP       all  --  any    any     anywhere             anywhere            PKTTYPE = multicast
    0     0 DROP       all  --  any    any     anywhere             anywhere            PKTTYPE = broadcast
 1288 67240 LOG        tcp  --  any    any     anywhere             anywhere            limit: avg 3/min burst 5 tcp flags:FIN,SYN,RST,ACK/SYN LOG level warning tcp-options ip-options prefix `SFW2-INext-DROP-DEFLT '
    0     0 LOG        icmp --  any    any     anywhere             anywhere            limit: avg 3/min burst 5 LOG level warning tcp-options ip-options prefix `SFW2-INext-DROP-DEFLT '
    1   438 LOG        udp  --  any    any     anywhere             anywhere            limit: avg 3/min burst 5 state NEW LOG level warning tcp-options ip-options prefix `SFW2-INext-DROP-DEFLT '
 1602 84345 DROP       all  --  any    any     anywhere             anywhere

Chain reject_func (0 references)
 pkts bytes target     prot opt in     out     source               destination
    0     0 REJECT     tcp  --  any    any     anywhere             anywhere            reject-with tcp-reset
    0     0 REJECT     udp  --  any    any     anywhere             anywhere            reject-with icmp-port-unreachable
    0     0 REJECT     all  --  any    any     anywhere             anywhere            reject-with icmp-proto-unreachable

///EDIT2
uname -a
Linux s15312615 18.104.22.168-0.2-default #1 SMP 2011-04-06 18:11:26 +0200 x86_64 x86_64 x86_64 GNU/Linux

If I try to open port 80 with
iptables -A INPUT -p tcp dport html -j ACCEPT
iptables -A OUTPUT -p tcp sport html -j ACCEPT

I get
Bad argument `dport'
Try `iptables -h' or 'iptables --help' for more information.

With
iptables -A INPUT -p tcp -m tcp --dport 80 -j ACCEPT

the command gets accepted but it changes nothing.
Comment: What's your Apache httpd.conf for your MPM?
Comment: added httpd.conf
Answer: It doesn't look like you are allowing incoming connections on port 80 in your iptables settings, but it's hard to tell without seeing output from iptables -L -v.  Allow incoming port 80 to your firewall rules and it will likely work.
Comment: added iptables -L -v

How would I allow port 80?
Answer: Indeed the firewall was the problem.
In yast2 I went to -> Securtiy and Users -> Firewall -> Allowed Services and added http Server and voila it worked!

Apache timeout instead of webpage


Minio Distributed Mode Error All ServerPool Must Have Same Deployment ID

Question: I've been trying to setup Minio server in Distributed Mode using 2 nodes, but everytime I tried, I always get error "All serverPools should have same deployment ID expected xxx, got yyy".
I'm setting up minio on Ubuntu servers.
I followed the instruction in Minio official docs here, but I can't find any mention of this error or any tutorial to make the Deployment ID the same.
Does anybody know what this is or how to make the deployment ID the same?
Thanks!
Answer: I've typically seen this happen when users attempt to do something similar to the following:

Start MinIO with minio server http://minio.example.net/mnt/disk-{1...4}
Later try to 'migrate' to distributed mode as minio server http://minio-{1...4}.example.net/mnt/disk-{1...4}

The second command is an entirely different topology, and results in a new deployment ID. When MinIO checks the existing backend disks, it sees that there is existing metadata, with a deployment ID that was generated based on the original topology. It then throws an error.
We would need to know quite a bit more about what you are attempting here - whether this is a fresh deployment, what MinIO version you are using, what the startup command was, etc, before being able to debug any further. But the above would be my guess as to what the issue is.
If this is a fresh deployment and you have no data to be concerned with, you can completely clean the backend drives of all data - including the .minio.sys folder at each path - and go from there. If you keep having the same issue with completely empty backend drives, then that is a little more unusual, and might be better suited as a Github issue so we can try to track that down further.


How to get item text from CheckedListBox to ListBox without repeating the before text? VB.net

Question: I have a CheckedListBox of 10 names A to J (it's a string but here I'm just using abc), and I want to make it so that every time a user check something, the text will be shown in the listbox simultaneously. I have tried this:
For i = 0 To chklistbxDrugAvailableList.Items.Count - 1
            Dim drugs As String = CType(chklistbxDrugAvailableList.Items(i), String)
            If chklistbxDrugAvailableList.GetItemChecked(i) Then
                listbxYourOrder.Items.Add(drugs)
            End If
           'drugs = nothing
Next

But when I check A,B,C the text in the Listbox got repeated like so:
A
A
B
A
B
C

I don't know why this is happening. I didn't declare drugs as an array. Even when I used the drugs = nothing, it still give repeated values.
What should I do? Sorry if this is a noob question.
Comment: @preciousbetine now nothing is showing up in the listbox. Besides, I want a list of all checked items. If I clear the listbox everytime, only 1 item will appear, right?
Comment: @preciousbetine thankyou it works now. Can you answer so I can accept? And can I ask why use clear? The listbox already empty before I check the items.
Comment: Simply clear the listbox before adding new items i.e before the loop  - `listbxYourOrder.Items.Clear()`.
Comment: *"nothing is showing up in the listbox"*. You're supposed to clear it before the other code, not after. *"only 1 item will appear"*. How could that be the case when you have code that adds all the checked items?
Comment: well, try the answer below and accept that if it works!
Answer: Here is how I would do the whole thing:
Private Sub CheckedListBox1_ItemCheck(sender As Object, e As ItemCheckEventArgs) Handles CheckedListBox1.ItemCheck
    'Clear the current ListBox contents.
    ListBox1.Items.Clear()

    'Get the indexes of the currently checked items.
    Dim checkedIndices = CheckedListBox1.CheckedIndices.Cast(Of Integer)()

    'Add the current index to the list if the item is being checked, otherwise remove it.
    checkedIndices = If(e.NewValue = CheckState.Checked,
                        checkedIndices.Append(e.Index),
                        checkedIndices.Except({e.Index}))

    'Get the checked items in order and add them to the ListBox.
    ListBox1.Items.AddRange(checkedIndices.OrderBy(Function(n) n).
                                           Select(Function(i) CheckedListBox1.Items(i)).
                                           ToArray())
End Sub

or like this:
Private Sub CheckedListBox1_ItemCheck(sender As Object, e As ItemCheckEventArgs) Handles CheckedListBox1.ItemCheck
    'Get the indexes of the currently checked items.
    Dim checkedIndices = CheckedListBox1.CheckedIndices.Cast(Of Integer)()

    'Add the current index to the list if the item is being checked, otherwise remove it.
    checkedIndices = If(e.NewValue = CheckState.Checked,
                        checkedIndices.Append(e.Index),
                        checkedIndices.Except({e.Index}))

    'Get the checked items in order and add them to the ListBox.
    ListBox1.DataSource = checkedIndices.OrderBy(Function(n) n).
                                         Select(Function(i) CheckedListBox1.Items(i)).
                                         ToArray()
End Sub

The difference is that, because the second option uses data-binding, the first item in the ListBox will be selected by default.
The reason that it needs to be a bit verbose is that the ItemCheck event is raised before the item is checked or unchecked. For that reason, we need to get the currently checked items first and then either add or remove the current item, depending on whether the current item is being checked or unchecked.
EDIT:
Here's an option that doesn't require clearing the ListBox:
Private Sub CheckedListBox1_ItemCheck(sender As Object, e As ItemCheckEventArgs) Handles CheckedListBox1.ItemCheck
    Dim item = CheckedListBox1.Items(e.Index)

    If e.NewValue = CheckState.Checked Then
        ListBox1.Items.Add(item)
    Else
        ListBox1.Items.Remove(item)
    End If
End Sub

The issue with that is that the items will appear in the ListBox in the order you checked them, rather than the order they appear in the CheckedListBox. The other options keep the items in the same order in both lists.
Answer: If I understand your question I would this:
   lstbxYourOrder.Items.Clear()
   For Each l As String In chklistbxDrugAvailableList.CheckedItems
         listbxYourOrder.Items.Add(l)
   Next


Best way to float images in Bootstrap with margin and responsiveness?

Question: I am new to Bootstrap and wondering what the best way to float images in Twitter Bootstrap 3 is. I have an image that can either be floated left or right of text content, but on a very small screen (ie. mobile) I want it to take up the full width. I also want some margin between image and content which I have had to add inline.
So far I have code something like this:

Test of main image and gallery...

This ends up looking something like this:

This looks okay but doesn't meet my need for taking full width on a very small screen.
Note that I would like the text to flow around (including under) the image too, rather than it just being a column. Hopefully this is possible.
Answer: There are two ways to do this:

Split the text image and text to its right into columns.

http://jsfiddle.net/Er5gV/
Add this CSS: img {width: 100%;}

Lorem ipsum Magna sed cillum occaecat exercitation do ad consectetur ut qui mollit pariatur irure veniam cillum ut reprehenderit consectetur amet reprehenderit elit incididunt enim tempor proident magna dolore amet occaecat enim proident dolor magna eu.

Lorem ipsum Magna sed cillum occaecat exercitation do ad consectetur ut qui mollit pariatur irure veniam cillum ut reprehenderit consectetur amet reprehenderit elit incididunt enim tempor proident magna dolore amet occaecat enim proident dolor magna eu.

Lorem ipsum Magna sed cillum occaecat exercitation do ad consectetur ut qui mollit pariatur irure veniam cillum ut reprehenderit consectetur amet reprehenderit elit incididunt enim tempor proident magna dolore amet occaecat enim proident dolor magna eu.

The other way is to use a float and then control it with a media query.
http://jsfiddle.net/2pGew/
img {
    float: left;
    margin-right: 1.5em;
}

@media (max-width: 768px) {
    img {
        display: block;
        float: left;
        margin: 0;
        margin-bottom: 1.5em;
        width: 100%;
    }
}

Lorem ipsum Magna sed cillum occaecat exercitation do ad consectetur ut qui mollit pariatur irure veniam cillum ut reprehenderit consectetur amet reprehenderit elit incididunt enim tempor proident magna dolore amet occaecat enim proident dolor magna eu.

Lorem ipsum Magna sed cillum occaecat exercitation do ad consectetur ut qui mollit pariatur irure veniam cillum ut reprehenderit consectetur amet reprehenderit elit incididunt enim tempor proident magna dolore amet occaecat enim proident dolor magna eu.

Lorem ipsum Magna sed cillum occaecat exercitation do ad consectetur ut qui mollit pariatur irure veniam cillum ut reprehenderit consectetur amet reprehenderit elit incididunt enim tempor proident magna dolore amet occaecat enim proident dolor magna eu.

Comment: Thanks, I used your second example. I thought Bootstrap might have already had something to do this.


Modelling categorical variable

Question: I am a beginner with statistics and R and have no clue on how to model my data. I have collected information on seed traps (ID) that includes the habitat type (Hab) and different measures of distances. Also I have applied a modularity analysis, so that the seeds traps are grouped into modules. My dataset is as follow:
ID    Hab  Module    DistEdge    MeanDist1    MeanDist2    MeanDist3
F48    F       A         21.768       24.941          6.033            27.642
F50    F       E         35.666       60.505          149.927        48.582
F52    F       B         12.243       103.041        72.908          102.375
N02    N      B         58.681       129.59          127.344        131.383
N17    N      B         62.829       72.827          76.736          77.644
N22    N      B         89.207       78.719          75.005          81.176
N33    N      A         23.288       35.48            25.317          36.931
N40    N      B         36.734       62.234          30.68            61.885
N47    N      E         60.443       66.367          150.892        55.097

I am looking for a way to analyze if there is any correlation between the Module classification and the other variables. My difficulties here are:
1 - is there a way to model my data where Module is the response variable (something like Module~Hab*DistEdge*MeanDist1) ? If so, which model should I use (I only have a bit of experience with glm) and which distribution?
2 - Is that a problem if I have different types of predictor variable (factor and numerical)?
Answer: Since module appears to be a categorical variable with multiple levels, one usual model would be multinomial logistic regression. In 'R' this is available with the multinom function in the nnet package.

Modelling categorical variable


Method parameter not being recognized

Question: My code looks like this:
void Update()
{
  if (Input.GetKeyDown(KeyCode.G) && questCount == 6)
  {

    Score(sumFinal);

  }
}

public int Score(int sumFinal)
{
sumFinal = dCount - rCount;
return sumFinal;
}

Visual Studio tells me sumFinal doesn't exist in the current context.
How can I return sumFinal within Update() successfully? Am I understanding parameters correctly?
Additional Question:
Below further down the Score() function, I set text to certain values:
public int Score(int sumFinal)
{
sumFinal = dCount - rCount;
return sumFinal;

if (sumFinal == 5 && questCount >= 5)
{
labelText.text = "results";
}
}

When calling this function in Update(), is there a way I can run both the if statement and the sumFinal subtraction equation separately? In short, how do I segment the function, and call only specific parts of it? Should the return type be set to void?
Comment: The problem is exactly as described in the error message. You are using the identifier `sumFinal`, but no such identifier exists in that context. See e.g. duplicate and numerous other Stack Overflow questions addressing the exact error message. Also see the language documentation, especially https://learn.microsoft.com/en-us/dotnet/csharp/methods and https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/variables
Answer:
Visual Studio tells me sumFinal doesn't exist in the current context. How can I return sumFinal within Update() successfully? Am I understanding parameters correctly?

The method Score looks great! However, when you call it Score(sumFinal); you need to make sure that you're passing a value to the method. In your case you may have forgotten to have a field with the value at the top of the class.

is there a way I can run both the if statement and the sumFinal subtraction equation separately?

Sure! What you could do, since you don't actually give Score any value when you call it, you can remove that parameter and just return the value that it calculates.
The we could separate updating the text to another method called UpdateTextBox() that takes the result of Score() to determine if it should change the text or not
public class YourUnityClass : MOnoBehaviour
{
    int questCount = 0;

    int sumFinal = 0; // make sure that if you need to access this variable between methods that this field exists

    int dCount = 0;

    int rCount = 0;

    public TextMesh labelText;

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.G) && questCount == 6)
        {
            // calculate and save the score
            sumFinal = Score();

            // check the score, and update the text if necessary
            UpdateTextBox(sumFinal);
        }
    }

    public int Score()
    {
        // calculate the score
        return dCount - rCount;
    }

    public void UpdateTextBox(int sumFinal)
    {
        // check to see if the score is high enough to change
        // the text
        if (sumFinal == 5 && questCount >= 5)
        {
            labelText.text = "results";
        }
    }
}

Comment: Please do not encourage users when they post [chameleon questions](https://meta.stackexchange.com/questions/43478/exit-strategies-for-chameleon-questions).
Comment: Thanks! That brings up some very valuable information, I'll keep that in mind. I appreciate it.
Comment: It works! Thank you for helping a newbie programmer

Method parameter not being recognized


Coefficient of $x^5$ in $(1+x)^{21} + (1+x)^{22} + ... + (1+x)^{30}$

Question: How do I find the coefficient of $x^5$ in the expansion of $(1+x)^{21} + (1+x)^{22} + ... + (1+x)^{30}$?
Comment: The coefficient of $x^5$ will be

$$\sum_{n=21}^{30}\binom n5$$
Comment: Just use the formula for sum of a geometric series.....and then obtain the required coefficient from the result of this sum.
Answer: Use binomial theorem we have : the coefficient of $x^5$ in $(1+x)^n$ is $\binom{n}{5}$. Then we have:
$$\sum_{i=21}^{30}\binom{i}{5}=682017$$
Answer: $$\sum_{n=21}^{30}(1+x)^n=(1+x)^{21}\cdot\dfrac{(1+x)^{9+1}-1}{(1+x)-1}=\dfrac{(1+x)^{21}\{(1+x)^{10}-1\}}x$$
So, we need the coefficient of $x^6$ in $$(1+x)^{21}\{(1+x)^{10}-1\}=(1+x)^{31}-(1+x)^{10}$$
which will be $$\binom{31}6-\binom{21}6$$

Alternatively, the coefficient of $x^5$ will be
$$\sum_{n=21}^{30}\binom n5$$
We can use the Pascal's rule to equate the two seemingly different results.
Comment: Could you please explain the first method in more detail? I am not able to understand it.
Comment: @SachinChaudhary, See https://en.wikipedia.org/wiki/Geometric_progression and pinpoint your confusion.
Answer: We have
$(1+x)^n=\sum_{k=0}^{n}\binom{n}{k}x^k$,
hence the coefficient of $x^5$ is $\binom{n}{5}$.
Threrfore the coefficient you are looking for is given by
$\binom{21}{5}+\binom{22}{5}+...+\binom{30}{5}$


Why can't we use back propagation in "Hard attention" but we can use it in "RELU" function and max-pooling?

Question: RELU, argmax function(in hard attention) and max-pooling are non-differentiable functions but We use back-propagation with RELU and max-pooling without any problems.  What does make "Hard attention" different than them?
Comment: Because hard attention randomly samples attention from a given set of attention weights, so you need to run multiple samples and then average the response before applying backpropagation. See here for example: https://jhui.github.io/2017/03/15/Soft-and-hard-attention/
Answer: The gradient of argmax is zero almost everywhere and undefined where it is not zero. Gradients need to be nonzero if you want any weight updates to happen
The gradient of maxpooling is nonzero almost everywhere. The gradient of relu is also nonzero for all positive inputs. When all inputs to a relu unit are negative, backprop fails and the unit will stop updating. This is known as a "dying relu", although it isn't a huge problem in general.
Comment: I think that the gradient of maxpooling is zero almost everywhere too, I read [the derivative of min function](https://math.stackexchange.com/questions/150960/derivative-of-the-fx-y-minx-y) the derivative of min looks like max. Or Did you mean that in convolution neural networks, the derivative of maxpooling is zero everywhere in local regions in the pooling layers but it's not a problem on the whole layer because we apply the maxpooling operation on the entire input?
Comment: @floyd the gradient of maxpooling is not zero almost everywhere
Answer: Hard-attention is a good biological inductive bias to try to build an attentive mechanism into neural networks.
Unfortunately, it would necessarily map into the "arg max" function, to return the position of the input with the biggest attention score.
The "argmax" function is not differentiable, as you point out in your question.
However, the "max" function used in ReLU and MaxPool is, in fact, piecewise-differentiable.
$$\max(x,y) = {x + y + |x - y|\over 2} = \begin{cases}{x, x \gt y\\ y, x \lt y}\end{cases}$$


setTimeout not working on click event with Packery

Question: I am trying to add a delay to the resetItems method in Packery. I have added a timeout to the function below, but it still triggers immediately on click.
What am I missing? Should it wrap around the line below as well? I tried that but then the function didn't work at all (but then I'm not saying I did it right...)
var $container = $('.packery');

$container.packery({
itemSelector: '.item',
gutter: 0
});

$(".reset").bind("click", function() {
setTimeout(function(){
    $('container').addClass('active');},1500);
    $container.packery();
    return false;
});

Answer: You need to specify the delay in a setTimeout.
setTimeout(function(){
    $('#container').addClass('active').packery();
    return false;
},1000); // 1 second

The delay is specified in miliseconds. Otherwise it defaults to zero (see step 5) and just defers it to the next time timers fire.
Comment: The delay is specified after ('active') at 1500. I removed it and placed it where you did, and now the function doesn't, um, function
Comment: @PaulAston Can you create a fiddle illustrating your issue? The timeout belongs where I put it :)
Comment: While I was making a fiddle, I made the change suggested by @ Radney Aaron Alquiza and then implemented your timing change. It works!

[http://jsfiddle.net/Bp3Gr/11/](http://jsfiddle.net/Bp3Gr/11/)
Comment: Gah. It was a 50/50 split. Both of you supplied a vital bit. What's worse - not accepting an answer or selecting one when both were right?
Comment: @PaulAston probably accept the one which was closer to solving your issue.
Answer: your $('container') selector is wrong?
if it's an ID, add # before the name.
it it's a class, add . before the name.
EDIT:
the guy above me mentioned the delay, but it's obvious you already have that (1500).
your curly braces just are not indented.
Comment: I thought the container was defined in the var, but I changed it to $('.packery') anyway. No success though, still fires immediately.
Comment: if you want to use the $container you declared on top,
you can reference and add jquery functions to it by doing
$container.addClass('active');
now, if you have firebug, can you console.log('test') inside the settimeout function if it really is running? you might also want to console.log($container) if it really is being referenced.
Comment: That was a real help. Changing to $container.addClass('active'); and then making the delay changes below, has solved the problem.
Comment: the thing is, Benjamin's code breaks the settimeout() because you already have 1500 after adding the class, and then he added 1000 at the end. the 1000 is a floating partner because settimeout is already closed.. anyway, accept whomever u like. :)


Couldn't read row 0, col -1 from CursorWindow?

Question: I have a problem while using a database. When I run my SQLView.java, I get a fatal exception:
java.lang.RuntimeException: Unable to start activity      ComponentInfo{com.jacob.eindproject/com.jacob.eindproject.SQLView}:     java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow.  Make sure     the Cursor is initialized correctly before accessing data from it.

Hopefully someone can help me. I'll post all my database- related code. Please tell my when you need something more, and don't hesitate to ask for more info!
I think there is something wrong with my columns, can't find out what.
Also, I've read ALL related questions on this website, but I can't find out where I should declare my columns and what to add/change. Somebody know how to? :)
To begin: my Database class:
    package com.jacob.eindproject;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;

import java.sql.*;

public class Database {

    public static final String KEY_ROWID = "_id";
    public static final String KEY_NAME = "persons_name";
    public static final String KEY_HOTNESS = "persons_hotness";

    private static final String DATABASE_NAME = "Databasedb";
    private static final String DATABASE_TABLE = "peopleTable";
    private static final int DATABASE_VERSION = 1;

    private DbHelper ourHelper;
    private final Context ourContext;
    private SQLiteDatabase ourDatabase;

    private static class DbHelper extends SQLiteOpenHelper{

        public DbHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
            // TODO Auto-generated constructor stub
        }

        @Override //I create it here, right?
        public void onCreate(SQLiteDatabase db) {
            db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
                    KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                    KEY_NAME + " TEXT NOT NULL, " +
                    KEY_HOTNESS + " TEXT NOT NULL);"
        );

        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
            onCreate(db);
        }

        public void close(Database database) {
            // TODO Auto-generated method stub

        }
    }

    public Database(Context c){
        ourContext = c;
    }

    public Database open() throws SQLException{
        ourHelper = new DbHelper(ourContext);
        ourDatabase = ourHelper.getWritableDatabase();
        return this;
    }

    public void close() {

    ourHelper.close();
}

    public long createEntry(String name, String hotness) {
        ContentValues cv = new ContentValues();
        cv.put(KEY_NAME, name);
        cv.put(KEY_HOTNESS, hotness);
        return ourDatabase.insert(DATABASE_TABLE, null, cv);

    }

    public String getData() {
        // TODO Auto-generated method stub
        String[] columns = new String[]{ KEY_ROWID, KEY_NAME, KEY_HOTNESS};
        Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
        String result = "";

        int iRow = c.getColumnIndex(KEY_ROWID);
        int iName = c.getColumnIndex(DATABASE_NAME);
        int iHotness = c.getColumnIndex(KEY_HOTNESS);

        for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
            result = result + c.getString(iRow) + " " + c.getString(iName) + " " + c.getString(iHotness) + "\n";

        }

        return result;
    }
}

The SQLite class, to fix the input:
package com.jacob.eindproject;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.View.OnClickListener;

public class SQLite extends Activity implements View.OnClickListener {

    Button sqlUpdate, sqlView;
    EditText sqlName, sqlHotness;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sqllite);
        sqlUpdate = (Button) findViewById(R.id.bSQLUpdate);
        sqlName = (EditText) findViewById(R.id.etSQLName);
        sqlHotness = (EditText) findViewById(R.id.etSQLHotness);

        sqlView = (Button) findViewById(R.id.bSQLopenView);
        sqlView.setOnClickListener((android.view.View.OnClickListener) this);
        sqlUpdate.setOnClickListener((android.view.View.OnClickListener) this);
    }

    public void onClick(View arg0) {
        switch (arg0.getId()) {
        case R.id.bSQLUpdate:

            boolean didItWork = true;
            try{
            String name = sqlName.getText().toString();
            String hotness = sqlHotness.getText().toString();

            Database entry = new Database(SQLite.this);
            entry.open();
            entry.createEntry(name, hotness);
            entry.close();

            }catch (Exception e ){
                didItWork = false;

            }finally{
                if (didItWork){
                    Dialog d = new Dialog(this);
                    d.setTitle("Heak Yeay");
                    TextView tv = new TextView(this);
                    tv.setText("Succes");
                    d.setContentView(tv);
                    d.show();
            }
        }

            break;
        case R.id.bSQLopenView:
            Intent i = new Intent("com.jacob.eindproject.SQLVIEW");
            startActivity(i);

        }
        }

    public void onClick(DialogInterface arg0, int arg1) {
        // TODO Auto-generated method stub

    }

    }

After that, my SQLView class, to view the input from the SQLite class:
package com.jacob.eindproject;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class SQLView extends Activity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sqlview);
        TextView tv = (TextView) findViewById(R.id.tvSQLinfo);
        Database info = new Database(this);
        info.open();
        String data = info.getData();
        info.close();
        tv.setText(data);

    }

}

Now, my xml files:
SQLView.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="wrap_content">

    <TableLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/tableLayout1">

        <TableRow>

                <TextView android:text="@string/Names" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1"/>

                <TextView android:text="@string/Hotness" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1" />

        </TableRow>

    </TableLayout>

        <TextView android:id="@+id/tvSQLinfo" android:layout_width="fill_parent" android:layout_height="fill_parent" android:text="@string/info"/>

</LinearLayout>

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

    <TextView
        android:id="@+id/Naam"
        android:text="@string/Naam"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall" />

    <EditText
        android:id="@+id/etSQLName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    </EditText>

    <TextView
        android:id="@+id/hotness"
        android:text="@string/hotnessscale"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
    />

    <EditText
        android:id="@+id/etSQLHotness"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    </EditText>

    <Button
        android:id="@+id/bSQLUpdate"
        android:text="@string/Update"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" ></Button>

    <Button
        android:id="@+id/bSQLopenView"
        android:text="@string/View"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
    ></Button>

</LinearLayout>

The Menu class, to fix the menu, with an OnListItemClick (there are some other activities in there, such as Overgewicht. Don't mind these, I guess..?):
package com.jacob.eindproject;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class Menu extends ListActivity implements OnItemClickListener {

    String classes[] = { "BMI- Calculator", "Ondergewicht", "Gezond Gewicht", "Overgewicht", "Database", "Bekijk Database"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setListAdapter(new ArrayAdapter<String>(Menu.this, android.R.layout.simple_list_item_1, classes));
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
    //Positie 0 is het eerste item (dus de BMI-Calculator.)
    super.onListItemClick(l, v, position, id);

    switch(position)
    {
    case 0:
    Intent openStartingPoint = new Intent(getApplicationContext(),MainActivity.class);
    startActivity(openStartingPoint);
    break;

    case 1:
    Intent openOndergewicht = new Intent(getApplicationContext(),Ondergewicht.class);
    startActivity(openOndergewicht);
    break;

    case 2:
    Intent openGezondgewicht = new Intent(getApplicationContext(),Gezond_gewicht.class);
    startActivity(openGezondgewicht);
    break;

    case 3:
    Intent openOvergewicht = new Intent(getApplicationContext(),Overgewicht.class);
    startActivity(openOvergewicht);

    break;

    case 4:
    Intent openDatabase = new Intent(getApplicationContext(),SQLite.class);
    startActivity(openDatabase);

    break;

    case 5:
    Intent openViewdatabase = new Intent(getApplicationContext(),SQLView.class);
    startActivity(openViewdatabase);

    break;

    }

    }

    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        // TODO Auto-generated method stub

    }
}

My Android Manifest file: (again, I've declared some other things, don't mind these!)
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.jacob.eindproject"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

        <activity
            android:name="com.jacob.eindproject.Menu"
            android:label="@string/app_name" >
        </activity>

        <activity
            android:name="com.jacob.eindproject.Inleiding"
            android:label="@string/app_name" >
                    <intent-filter>
                            <action android:name="android.intent.action.MAIN" />
                            <category android:name="android.intent.category.LAUNCHER" />
                    </intent-filter>
        </activity>

        <activity
            android:name="com.jacob.eindproject.MainActivity"
            android:label="@string/app_name" >
                     <intent-filter>
                            <action android:name="android.intent.action.MAIN" />
                            <category android:name="android.intent.category.DEFAULT" />
                    </intent-filter>
        </activity>

        <activity
            android:name="com.jacob.eindproject.Ondergewicht"
            android:label="@string/app_name" >
        </activity>

        <activity
            android:name="com.jacob.eindproject.Gezond_gewicht"
            android:label="@string/app_name" >
        </activity>

        <activity
            android:name="com.jacob.eindproject.Overgewicht"
            android:label="@string/app_name" >
        </activity>

        <activity
            android:name="com.jacob.eindproject.Database"
            android:label="@string/app_name" >
                    <intent-filter>
                            <action android:name="com.jacob.eindproject.DATABASE" />
                            <category android:name="android.intent.category.DEFAULT" />
                    </intent-filter>
        </activity>

        <activity
            android:name=".SQLView"
            android:label="@string/app_name" >
                    <intent-filter>
                            <action android:name="com.jacob.eindproject.SQLVIEW" />
                            <category android:name="android.intent.category.DEFAULT" />
                    </intent-filter>

        </activity>

        <activity
            android:name="com.jacob.eindproject.SQLite"
            android:label="@string/app_name" >
                    <intent-filter>
                            <action android:name="com.jacob.eindproject.SQLITE" />
                            <category android:name="android.intent.category.DEFAULT" />
                    </intent-filter>
        </activity>

    </application>

</manifest>

At last, my LogCat, to show you the error:
12-14 11:04:18.227: E/AndroidRuntime(1577): FATAL EXCEPTION: main
12-14 11:04:18.227: E/AndroidRuntime(1577): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.jacob.eindproject/com.jacob.eindproject.SQLView}: java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow.  Make sure the Cursor is initialized correctly before accessing data from it.
12-14 11:04:18.227: E/AndroidRuntime(1577):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
12-14 11:04:18.227: E/AndroidRuntime(1577):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
12-14 11:04:18.227: E/AndroidRuntime(1577):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
12-14 11:04:18.227: E/AndroidRuntime(1577):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
12-14 11:04:18.227: E/AndroidRuntime(1577):     at android.os.Handler.dispatchMessage(Handler.java:99)
12-14 11:04:18.227: E/AndroidRuntime(1577):     at android.os.Looper.loop(Looper.java:137)
12-14 11:04:18.227: E/AndroidRuntime(1577):     at android.app.ActivityThread.main(ActivityThread.java:5103)
12-14 11:04:18.227: E/AndroidRuntime(1577):     at java.lang.reflect.Method.invokeNative(Native Method)
12-14 11:04:18.227: E/AndroidRuntime(1577):     at java.lang.reflect.Method.invoke(Method.java:525)
12-14 11:04:18.227: E/AndroidRuntime(1577):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
12-14 11:04:18.227: E/AndroidRuntime(1577):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
12-14 11:04:18.227: E/AndroidRuntime(1577):     at dalvik.system.NativeStart.main(Native Method)
12-14 11:04:18.227: E/AndroidRuntime(1577): Caused by: java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow.  Make sure the Cursor is initialized correctly before accessing data from it.
12-14 11:04:18.227: E/AndroidRuntime(1577):     at android.database.CursorWindow.nativeGetString(Native Method)
12-14 11:04:18.227: E/AndroidRuntime(1577):     at android.database.CursorWindow.getString(CursorWindow.java:434)
12-14 11:04:18.227: E/AndroidRuntime(1577):     at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:51)
12-14 11:04:18.227: E/AndroidRuntime(1577):     at com.jacob.eindproject.Database.getData(Database.java:95)
12-14 11:04:18.227: E/AndroidRuntime(1577):     at com.jacob.eindproject.SQLView.onCreate(SQLView.java:16)
12-14 11:04:18.227: E/AndroidRuntime(1577):     at android.app.Activity.performCreate(Activity.java:5133)
12-14 11:04:18.227: E/AndroidRuntime(1577):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
12-14 11:04:18.227: E/AndroidRuntime(1577):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
12-14 11:04:18.227: E/AndroidRuntime(1577):     ... 11 more

Hopefully someone takes the time to help me. I'm allready very thankfull to the ones that take a look at it. Thanks everybody in advance.
Jacob
Answer: String[] columns = new String[]{ KEY_ROWID, KEY_NAME, KEY_HOTNESS};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
String result = "";

int iRow = c.getColumnIndex(KEY_ROWID);
int iName = c.getColumnIndex(DATABASE_NAME);

Your cursor doesn't have a column with name DATABASE_NAME. You probably meant KEY_NAME for this getColumnIndex() call which in this forms returns -1 and attempting to get data with such an index will cause the exception you've seeing.
Comment: Yes, you have a *table* named `DATABASE_TABLE` and a column `KEY_NAME`. Your query cursor has three columns `KEY_ROWID`, `KEY_NAME`, `KEY_HOTNESS`. None of these is `DATABASE_NAME` you're trying to get the column index for.
Comment: Huh? But I declare it here, right? In Database.java, in line 35 - 40 (see edit?).
Comment: @user3104217 Yes exactly


Group By Days Laravel Eloquent

Question: Não estou conseguindo agrupar dados por dias diferentes.
Tenho alguns comunicados cadastrados e com o padrão Created_at e Updated_at
gostaria de mostrar esses comunicados Separados dia a dia..
VIEW
@foreach($messages as $message)

            {{  $message->updated_at }}

 ...

                    {{ $message->message }}

                    ...

    @endforeach

TENTATIVA DE AGRUPAR POR DIA CONTROLLER
public function timeline(Request $request){
    $messages = Message::where('type_send', 1)->groupBy(function($date){
        return Carbon::parse($date->created_at)->format('D');
    });

    return view('messages.timeline', compact('messages'));
}

NÃO ESTA FUNCIONANDO ERRO

EDIT CONTROLLER
public function timeline(Request $request){
    $messages = Message::orderBy('created_at', 'desc')->get()
        ->groupBy(function($date) {
            return Carbon::parse($date->created_at)->format('M d'); // grouping by day
        });
    return view('messages.timeline', compact('messages'));
}

DUMP EM $messages NA VIEW

Eu gostaria agora de listar as mensagens separadas por mes, qual seria a solução?
VIEW
Eu consegui mostrar o dia do mês, mas agora eu quero listar dentro as mensagens com o mesmo dia do mês

    @foreach($messages as $message)

            {{  $message->first()->updated_at }}

                            ...

    @endforeach

Comment: @VirgilioNovic Minha view esta como o print que eu te mostrei, apenas consegui colocar os dias do mês que tem mensagens, mas não conseguir por as mensagens dentro, teria de usar um foreach dentro de outro foreach? Olha o Edit
Comment: Então, o erro é o seguinte: ele espera um parâmetro texto (ou múltipla colunas separadas por virgula), o que você fez não é suportado Se quer agrupar por dia a estratégia tem que ser outra porque do jeito que você também fez está faltando algumas coisas nessa SQL (builder)
Comment: eu estou o dia todo tentando fazer isso e não consigo, o que eu deveria alterar?
Comment: Qual é a SQL que precisa fazer?
Comment: da uma olhada no edit @VirgilioNovic
Comment: Vamos explicar o que você fez, trouxe um massa de dados em `SQL` e depois na classe `Collection` agrupou os dados, ou seja, teve dois esforço (talvez só com a SQL já daria certo). você quer agrupar por mês? ou mês e Ano? eu ainda estou na duvida o que realmente quer, se poderia colocar um exemplo atual da sua base e o qual resultado espera?
Comment: Eu quero listar todas as mensagens separadas por dia do mês, mostrar uma vez o dia do mês e todas mensagens desse dia do mês. conforme o outro edit meu com o resultado da visualização, se você reparar @VirgilioNovic no dia Mar 21 eu tenho 6 mensagens e no dia Mar 22 eu tenho 1 mensagens
Comment: Então me parece que tem o resultado só não consegue imprimir? na sua View está como? ou não fez nada lá?
Answer: Precisa buscar a chave e depois a coleção da respectiva chave:
@foreach($messages as $key => $message)

        {{  $key }}

    @foreach($message as $item)

 ...

                    {{ $item->message }}

                    ...

    @endforeach
@endforeach

isso é mediante ao seus comentários.
Comment: Perfeito! Funcionou, o que seria a $key?
Comment: `$key` é a chave do seu `array` precisa dela para imprimir o cabeçalho e dentro dela que tem o `collection` que precisa utilizar no seu código. @GabrielAlves

Group By Days Laravel Eloquent


How to show a views count for nodes that ar not available to anonymous users

Question: I made a view which displays a count for nodes in a nodetype. But anonymous users don't have access to nodes in that type. Those users should be able to view the count. Is there a way to achieve this?
Answer: Go to edit screen of your view. In right column, Advanced section, click Query settings.
Check Disable Query Rewritting. Now Drupal permissions will not affect views results.
Comment: @caskraker no shame - everything is easy once you know it.
Comment: Thanx for the quick reply, Molot. Shame on me, i should have known this.


checking ifeq for variable in makefile

Question: Following is not working, do you know why?
Note: CURRENT_CLUSTER is not 'my-local-cluster' and stil fails.
check-env:
    ifeq ($(CURRENT_CLUSTER), 'my-local-cluster')
        $(error CURRENT_CLUSTER is local $(CURRENT_CLUSTER), should be production cluster)
    endif

Comment: In the example above the `ifeq` is indented.  That's what I was referring to.  If you don't indent `ifeq` it will be evaluated when the makefile is read.  As long as the condition is static (doesn't rely on the specific recipe or order in which the makefile is read) then it will work.  But if `CURRENT_CLUSTER` is a target-specific variable, or depends itself on automatic variables like `$@` or `$*`, or is reset to a different value after this rule is defined, then it won't work.
Comment: There are many errors here. First, `makefile` will compare everything on both part of the `,` in the `if(n)eq`, meaning that `ifeq (s, s)` will fail because of the space, such as `ifeq (s,'s')` because of `'`. Also, `$(error ...)` is supposed to appear outside of the recipe. It stops the compilation before the target is called
Comment: @Zelnes: no, it is part of the recipe. It will be expanded (and fail) only when make expands the recipe, just before passing it to the shell, and only if the conditional passes.
Comment: @Zelnes: `$(error ...)` can perfectly be used in the recipe, for instance to force it to fail in unsupported situations.
Comment: @RenaudPacalet Wouldn't it fail before the recipe is reached ?
Comment: The problem is you can't use `ifeq` etc. which are _make_ constructs, inside a recipe which is passed to the shell for parsing.  By "inside a recipe" I mean, indented with a TAB character so that it is part of the recipe commands.  You could put it "in a recipe" but not indented with TAB, but it'll be parsed when the makefile is parsed not when the recipe is invoked.  If you want a test to happen inside the recipe, you have to use shell constructs like `if ...; then ... fi` etc.
Comment: @MadScientist: I just tested with GNU Make 4.2.1. If the conditional is **not** indented but the `$(error ...)` is, make fails if and only if `CURRENT_CLUSTER=my-local-cluster` **and** `check-env` is invoked. I also tested with an `else` and it worked as expected. And if another goal is invoked, make does not fail, even if the conditional passes. Is there something I missed here?
Comment: @MadScientist: agreed.
Comment: It must be left justified, no tabulation.
Answer: Maybe what you want would be something like :
check-env:
ifeq ($(CURRENT_CLUSTER),my-local-cluster)
    $(error CURRENT_CLUSTER is local $(CURRENT_CLUSTER), should be production cluster)
endif
    @echo Whatever

all:
    @echo "Still good"

This will produce this result :
$ make check-env CURRENT_CLUSTER=my-local-cluster
Makefile:220: *** CURRENT_CLUSTER is local my-local-cluster, should be
$ make all CURRENT_CLUSTER=my-local-cluster
Still good
$ make check-env CURRENT_CLUSTER=anything
Whatever

Comment: Note: as @MadScientist noted, this works only if the condition is static. It may be important to keep this in mind.

checking ifeq for variable in makefile


Erro formulario login (front)

Question: estou fazendo uma tela de login e cadastro, mas o que era pra ser 2 em 1 acaba separando, fica o formulario de sign up em baixo do login.
Html

    Login
  Sign Up

    Login in with facebook

    log in with Google

<form class="email-login">

    <input type="email" placeholder="Email"/>

    <input type="password" placeholder="Password"/>

    <button>Log in</button>

    Forgot password?

</form>
<form class="email-signup">

    <input type="email" placeholder="Email"/>

    <input type="password" placeholder="Password"/>

    <input type="password" placeholder="Confirm Password"/>

    <button>Sign Up</button>

</form>

o css
body{
            background-color: #1cbb9b;
          }
          .login-box{
            position:relative;
            margin: 10px auto;
            width: 500px;
            height: 380px;
            background-color: #fff;
            padding: 10px;
            border-radius: 3px;
            -webkit-box-shadow: 0px 2px 3px 0px rgba(0,0,0,0.33);
          -moz-box-shadow: 0px 2px 3px 0px rgba(0,0,0,0.33);
          box-shadow: 0px 2px 3px 0px rgba(0,0,0,0.33);
          }
          .lb-header{
            position:relative;
            color: #00415d;
            margin: 5px 5px 10px 5px;
            padding-bottom:10px;
            border-bottom: 1px solid #eee;
            text-align:center;
            height:28px;
          }
          .lb-header a{
            margin: 0 25px;
            padding: 0 20px;
            text-decoration: none;
            color: #666;
            font-weight: bold;
            font-size: 15px;
            -webkit-transition: all 0.1s linear;
            -moz-transition: all 0.1s linear;
            transition: all 0.1s linear;
          }
          .lb-header .active{
            color: #029f5b;
            font-size: 18px;
          }
          .social-login{
            position:relative;
            float: left;
            width: 100%;
            height:auto;
            padding: 10px 0 15px 0;
            border-bottom: 1px solid #eee;
          }
          .social-login a{
            position:relative;
            float: left;
            width:calc(40% - 8px);
            text-decoration: none;
            color: #fff;
            border: 1px solid rgba(0,0,0,0.05);
            padding: 12px;
            border-radius: 2px;
            font-size: 12px;
            text-transform: uppercase;
            margin: 0 3%;
            text-align:center;
          }
          .social-login a i{
            position: relative;
            float: left;
            width: 20px;
            top: 2px;
          }
          .social-login a:first-child{
            background-color: #49639F;
          }
          .social-login a:last-child{
            background-color: #DF4A32;
          }
          .email-login,.email-signup{
            position:relative;
            float: left;
            width: 100%;
            height:auto;
            margin-top: 20px;
            text-align:center;
          }
          .u-form-group{
            width:100%;
            margin-bottom: 10px;
          }
          .u-form-group input[type="email"],
          .u-form-group input[type="password"]{
            width: calc(50% - 22px);
            height:45px;
            outline: none;
            border: 1px solid #ddd;
            padding: 0 10px;
            border-radius: 2px;
            color: #333;
            font-size:0.8rem;
            -webkit-transition:all 0.1s linear;
            -moz-transition:all 0.1s linear;
            transition:all 0.1s linear;
          }
          .u-form-group input:focus{
            border-color: #358efb;
          }
          .u-form-group button{
            width:50%;
            background-color: #1CB94E;
            border: none;
            outline: none;
            color: #fff;
            font-size: 14px;
            font-weight: normal;
            padding: 14px 0;
            border-radius: 2px;
            text-transform: uppercase;
          }
          .forgot-password{
            width:50%;
            text-align: left;
            text-decoration: underline;
            color: #888;
            font-size: 0.75rem;
          }

E ADICIONEI ESSE JS
$(".email-signup").hide();
$("#signup-box-link").click(function(){
  $(".email-login").fadeOut(100);
  $(".email-signup").delay(100).fadeIn(100);
  $("#login-box-link").removeClass("active");
  $("#signup-box-link").addClass("active");
});
$("#login-box-link").click(function(){
  $(".email-login").delay(100).fadeIn(100);;
  $(".email-signup").fadeOut(100);
  $("#login-box-link").addClass("active");
  $("#signup-box-link").removeClass("active");
});

eu adicionei a query, não sei o que pode ser, quem puder ajudar
Answer: Em vez de esconder o segundo formulário com $(".email-signup").hide(); seria muito melhor e mais coerente esconder no próprio CSS:
.email-signup{
   display: none;
}

Exemplo:

//$(".email-signup").hide();
$("#signup-box-link").click(function(){
  $(".email-login").fadeOut(100);
  $(".email-signup").delay(100).fadeIn(100);
  $("#login-box-link").removeClass("active");
  $("#signup-box-link").addClass("active");
});
$("#login-box-link").click(function(){
  $(".email-login").delay(100).fadeIn(100);;
  $(".email-signup").fadeOut(100);
  $("#login-box-link").addClass("active");
  $("#signup-box-link").removeClass("active");
});
body{
   background-color: #1cbb9b;
 }
 .login-box{
   position:relative;
   margin: 10px auto;
   width: 500px;
   height: 380px;
   background-color: #fff;
   padding: 10px;
   border-radius: 3px;
   -webkit-box-shadow: 0px 2px 3px 0px rgba(0,0,0,0.33);
 -moz-box-shadow: 0px 2px 3px 0px rgba(0,0,0,0.33);
 box-shadow: 0px 2px 3px 0px rgba(0,0,0,0.33);
 }
 .lb-header{
   position:relative;
   color: #00415d;
   margin: 5px 5px 10px 5px;
   padding-bottom:10px;
   border-bottom: 1px solid #eee;
   text-align:center;
   height:28px;
 }
 .lb-header a{
   margin: 0 25px;
   padding: 0 20px;
   text-decoration: none;
   color: #666;
   font-weight: bold;
   font-size: 15px;
   -webkit-transition: all 0.1s linear;
   -moz-transition: all 0.1s linear;
   transition: all 0.1s linear;
 }
 .lb-header .active{
   color: #029f5b;
   font-size: 18px;
 }
 .social-login{
   position:relative;
   float: left;
   width: 100%;
   height:auto;
   padding: 10px 0 15px 0;
   border-bottom: 1px solid #eee;
 }
 .social-login a{
   position:relative;
   float: left;
   width:calc(40% - 8px);
   text-decoration: none;
   color: #fff;
   border: 1px solid rgba(0,0,0,0.05);
   padding: 12px;
   border-radius: 2px;
   font-size: 12px;
   text-transform: uppercase;
   margin: 0 3%;
   text-align:center;
 }
 .social-login a i{
   position: relative;
   float: left;
   width: 20px;
   top: 2px;
 }
 .social-login a:first-child{
   background-color: #49639F;
 }
 .social-login a:last-child{
   background-color: #DF4A32;
 }
 .email-login,.email-signup{
   position:relative;
   float: left;
   width: 100%;
   height:auto;
   margin-top: 20px;
   text-align:center;
 }
 .u-form-group{
   width:100%;
   margin-bottom: 10px;
 }
 .u-form-group input[type="email"],
 .u-form-group input[type="password"]{
   width: calc(50% - 22px);
   height:45px;
   outline: none;
   border: 1px solid #ddd;
   padding: 0 10px;
   border-radius: 2px;
   color: #333;
   font-size:0.8rem;
   -webkit-transition:all 0.1s linear;
   -moz-transition:all 0.1s linear;
   transition:all 0.1s linear;
 }
 .u-form-group input:focus{
   border-color: #358efb;
 }
 .u-form-group button{
   width:50%;
   background-color: #1CB94E;
   border: none;
   outline: none;
   color: #fff;
   font-size: 14px;
   font-weight: normal;
   padding: 14px 0;
   border-radius: 2px;
   text-transform: uppercase;
 }
 .forgot-password{
   width:50%;
   text-align: left;
   text-decoration: underline;
   color: #888;
   font-size: 0.75rem;
 }

.email-signup{
   display: none;
}

    Login
  Sign Up

    Login in with facebook

    log in with Google

<form class="email-login">

    <input type="email" placeholder="Email"/>

    <input type="password" placeholder="Password"/>

    <button>Log in</button>

    Forgot password?

</form>
<form class="email-signup">

    <input type="email" placeholder="Email"/>

    <input type="password" placeholder="Password"/>

    <input type="password" placeholder="Confirm Password"/>

    <button>Sign Up</button>

</form>

Erro formulario login (front)


Why is my intuition wrong that one of two archers win in a tournament?

Question: The probability of Robin and Tuck hitting a target respectively are $0.45$ and $0.38$.  For each round of the tournament, each archer must shoot simultaneously at their targets. A player wins the tournament if in a round, one archer hits the target while the other does not. If both or neither archers hit the target, then the tournament is continued with another round and this process is repeated. Intuitively, I feel that the probability that Robin wins the tournament is $p=\frac{0.45}{0.38+0.45}\approx0.5421686%$, but to be on the safe side, I did the below:

Consider the two cases in which Robin wins the tournament:
Either a) Robin wins on his first shot, or b) Robin ties on his first shot but wins on the $n^{\text{th}}$ round, $n > 1$.
Let $p$ denote the probability that robin wins.
Case a: If Robin wins on his first shot, that means he hit the target and Tuck missed the target. The probability of this is $(0.45)(1-0.38)=0.279$
Case b: The probability that no one wins on the first round is the probability that no one hits the target plus the probability that both hit the target, which is $(1-0.45)(1-0.38)+(0.45)(0.38)=0.512$. After the first round, when the second round starts, it is as if the entire tournament has just started. Therefore, after a tie in the $1^{\text{st}}$ round, Robin still has the same probability $p$ of winning on the $n^{\text{th}}$ round where $n>1$. Thus the probability that Robin ties the 1st round and wins some round after that is $0.512p$.
Adding cases a and b gets that $p = 0.279 + 0.512p$. Solving for $p$ yields around  $0.5717213115$.

What accounts for the discrepancy between my intuition and my reasoning above? Is my reasoning flawed?
Comment: I don't see why your "intuition" is intuitive. You are trying to find the probability that someone wins by taking the probability that he gets a hit divided by the sum of two probabilities(that are not mutually exclusive events), which I cannot find a good interpretation for.
Comment: The quantity you are almost calculating is the fraction of the time that Robin hits his target given that *either* player hits their target. This is actually $\frac{0.45}{0.38+0.45-0.38 \cdot 0.45}$, using independence and inclusion-exclusion. Note that without this inclusion-exclusion step, the denominator could easily be larger than $1$, which would make no sense. But this quantity isn't what you want, because it includes the cases where they both hit their target. You want the probability that Robin hits his target given that Tuck does not.
Comment: Curiously enough, if $0.38$ and $0.45$ were instead the rates of [exponentially distributed](https://en.wikipedia.org/wiki/Exponential_distribution) random variables (the most meaningful continuous-time variant of this problem), your formula would have been correct.
Answer: Take an example where the probability of Robin and Tuck hitting a target respectively are $0.9$ and $1.0$. Your method would give the probability of Robin winning being $\dfrac{0.9}{0.9+1.0}$ when the true probability is $0$.
Going back to your original probabilities of hitting of $0.45$ and $0.38$, you would do better saying the probability of Robin winning overall might be $\dfrac{0.45\times(1-0.38)}{ 0.45\times(1-0.38) + 0.38\times(1-0.45)}$ by looking at the decisive and mutually exclusive events of one hitting and the other not. This gives your $0.5717\ldots$
Comment: +1 In my experience, taking extreme values is a very good way to see if your intuition is wrong. Also, never use your intuition when doing probability.
Answer: Whatever the probability distribution of the number of rounds, on any round Robin wins with probability $\propto r\bar t$ and loses with $\propto \bar rt$, hence the ratio
$$\frac{r\bar t}{r\bar t+\bar rt}=\frac{0.45\cdot0.62}{0.45\cdot0.62+0.55\cdot0.38}\approx0.572$$ as the game ends with probability $1$.
Answer: The easiest way to get there is to say the chance that exactly one of them hits the target is $0.45(1-0.38)+(1-0.45)0.38=.488$  The chance that Robin wins given that somebody did is $\frac {0.45(1-0.38)}{0.488}\approx 0.57172$ which matches your second calculation.
The error in your intuitive calculation is that Tuck loses more of his hits to ties because Robin is more accurate, so his chance of winning should be less than $1-0.542$
Answer: I thought visual illustration might be helpful.


Is it orthodox to use the pedal when playing Bach on the piano?

Question: It is my understanding that Bach's keyboard works were written for the harpsichord, and thus no (damper) pedal is used while playing Bach on the harpsichord.
On the piano however, I have heard recordings of concert pianists using no pedal whatsoever and others who do seem to use the pedal (albeit rather conservatively). Is it orthodox to play Bach's keyboard works with a pedal or should I abstain from using it?
Comment: Possible duplicate of, or at least quite some overlap with: [How accurate are the pedal indications of Bach - Busoni, solo piano works?](http://music.stackexchange.com/questions/12696/how-accurate-are-the-pedal-indications-of-bach-busoni-solo-piano-works)
Comment: @CalebHines I don't believe it is a duplicate. Although I didn't state it, I am using the Bach-Gesellschaft edition (which has no pedal markings), and the question wasn't about pedal notation, but about the use of pedal in general.
Comment: Granted. But the answers there do deal with the more general issues involved with using a pedal in Bach, and therefore, much of the information there may be of use to you.
Comment: This consideration does not only hold for harpsichord pieces; early pianofortes didn't come **close** to the dynamic range we have these days, so in general, pedal and dynamic markings in 'old' pieces should be regarded with caution. The [Wikipedia page](http://en.wikipedia.org/wiki/Piano#The_modern_piano) on pianos has a lovely sound comparison.
Answer:
orthodox: adherence to accepted norms

Is playing Bach like Glenn Gould orthodox or not? Some will swear by what he does with Bach and probably say yes, while others will cry out loud "Nooooooo"!
I think answering your question about using the pedal with Bach faces the same dilemma: since Bach isn't there to tell you what he would like to have heard when transcribing his harpsichord or organ pieces to the piano, it is a matter of interpretation deemed to change somewhat with the culture and your own sensibility.  More importantly, what is deemed as an acceptable interpretation will vary with the piece, the instrument it was composed for, and what people have gotten to accept over time.  A few examples:

Prelude 1: Many will play it with the pedal on, only changing it every couple of measures.  Since all notes within that measure build on one simple harmony, it does not change the main intent of the piece.  It doesn't muddy things out too much or  prevent you from hearing a second or third voice that isn't there to start with.  So you can say using the pedal two measures at a time for that piece is orthodox as in "accepted by a large part of the community today"
A fugue: Silences are as important as the notes themselves to define the melody in this form and using the pedal for too long will generally extend notes or link some voices together in a way that Bach clearly did not want.  Press the pedal to help yourself linking one voice and disregard the complexity of the other voices and you will likely create an interpretation that doesn't respect the intent of the composer and isn't deemed orthodox.  Use it parsimoniously to make some transitions clearer in one of the voices without muddying the rest and preserving the symmetry between the voices, and people will likely consider that you are making a good use of the piano to enhance the original work of Bach, making your interpretation "orthodox" by most standards.
To finish, I will take one of my favorite piece of Bach at the present time: a transcription or a prelude by Siloti interpreted by Gillels here.  That piece is conventionally played twice, once letting the right hand lead the melody, the second time letting the chords resonate.  It is absolutely delicious and both versions are completely different, something that wasn't Bach's original intent, that is only possible on a piano, and that is yet widely accepted today as "the" right (orthodox) interpretation of that piece.

So there you have it: I believe using the pedal for Bach can definitely be considered orthodox but there is a context to it.
Comment: A couple of comments: 1) with regards to WTC I Prelude 1, the notation used was a common shorthand for held arpeggiation, so the use of pedal is by no means at odds with historical practice - the notes would have been manually held longer in the right hand than notated on the keyboards of the day; and 2) Bach/Silotti ≠ Bach - there are considerable changes (in key, in SATB order of the voices, etc.) between Silotti's arrangement and the original in Wilhelm Friedemann's Klavierbüchlein. This wasn't necessary to make the work playable on the piano - the original is quite playable. (more...)
Comment: That's not to say that what Silotti did is "out-of-bounds": I've done similar; Bach most assuredly did similar himself (and quite often). It's just not necessarily a good guide to Bach performance to use a free arrangement that was written very specifically for the piano.
Comment: @Patrx2 Thanks for pointing out the use of held arpeggiation notation. I didn't know. Yes Bach/Silotti isn't a guide to Bach's performance itself but my intent in quoting that piece was to provide an example of an interpretation of Bach that may still be considered "orthodox" and still in touch with the soul of the original piece even though it deviated considerably from the original writing from Bach.
Answer: Based on the recordings and concerts I've heard over the years, in the modern era, it is very common and not at all ridiculed to use pedals lightly to enhance the melodic lines and help out the legato. There are some, like Simone Dinnerstein, who make heavy use of the pedal, but she has many fans in her own right, and she does have some really great interpretations of Bach.
My personal interpretation is that since you're playing Bach on the piano-- a very different instrument than the harpsichord-- you should concentrate on making it sound good on the piano. Realize that changing instruments requires adjustments as you face a different set of instrumental constraints. For example, the carillon is an instrument in which you cannot choose precisely how long the notes sustain; yet, amongst carillonneurs Bach is a perennial favorite and frankly incredibly awesome-sounding, despite not being able to be as "detached" as the harpsichord.
Answer: Well, the pedals suffer the same problem as the bellows of an accordion: they apply to all voices equally.  So their use for effect gets in the way of polyphonic articulation.  As an example, there does not seem to be a musical problem with using the sustain pedal in the Prelude #1 in the Well-Tempered Clavier, but you can't really make coherent use of it in the following Fugue #1.
Now both form one unit.  The question is whether you want to be performing this unit in two different execution styles.  In the end, that is an artistic choice.
Answer: The first rule of Bach: Everyone thinks that the way that they learned to play it is the best way. Show 25 people 8 bars of bach and you could get 25 different answers on how to play it.
I think there's a certain amount of validity in learning to play it two ways - first, from a historically relevant context, and second, using whatever interpretation you feel is best (based on listening to different recordings, experimenting, and any existing standards established by modern musicians.) If you're learning from the perspective of "I need this for an audition piece", then find out who you're going to be auditioning for and listen to their recordings, noticing any patterns of choice that they may take. This applies to pedals, grace notes, and any other things that you may notice.
Answer: I play Bach on both my harpsichord and my piano. They are very different instruments. Trying to copy the sound of a harpsichord with piano or vise-versa is folly. One must simply try to produce a musical interpretation with the tool at hand (pun intended). As we have no recordings of Bach playing anything, we are left with academic reasoning of scholars and our own common sense in the moment (in which we must consider the acoustic, the audience, the instrument, and all other variables) in order to arrive at a reasonable choice.
In practice, I use no pedal, some, or quite a bit on piano.....depending on these variables.
There is no definitive answer then.
(The same is true for temperament.....I use an unequal temperament at home on both piano and harpsichord.....but the last public performance with the harpsichord (as continuo with orchestra) the musicians struggled with period tuning, so I was forced to alter the instrument to equal temperament. Everyone was happier with the sharp thirds and homogenized quality key to key of et....so who am I to argue for historical accuracy in that setting?)
Comment: In using unequal temperament does that mean that in some keys, the pieces sound more in tune than others?
Comment: @Tim, yes. The comma is distributed unequally so as to favour the "near" keys (i.e., in around C major). That means that white-key tonalities will sound quite a bit purer than those with more black keys (and quite a bit purer than 12-TET), whereas each key will have a distinctive "colour". In the case of re-entrant tunings that distribute the comma so as to avoid wolf fifths, all keys will be usable and distinctive; non-re-entrant mean tone tunings do have wolf fifths in the keys that are distant from C, but they were designed for music that never modulated that far.
Answer: I have found that every time there was a harmonic change meaning every time you could possibly insert a chord over a group change the pedal good luck


2D object recognition using MATLAB

Question: Have you any idea about implementing 2D object recognition with MATLAB?
Which characteristics of objects can feed a neural network?
It's my training data-set (provided by ETH University of Switzerland)
What is the start point?
There are 5 view of each object, and whole objects are 66.
Comment: please be more specific, at the current moment the question is too vague. Also it is better to give a preview of data in the question. I for one am very wary of downloading unknown archive files from the internet.
Comment: question on SO: http://stackoverflow.com/questions/6817684/object-recognition-using-matlab
Comment: I like [this paper](http://ieeexplore.ieee.org/xpl/freeabs_all.jsp?arnumber=4409066); it lists most of important keywords, has some nice ideas itself and contains state-of-art from 2007.
Comment: I edited the question.
Comment: I suppose you have the data imported in Matlab, so can you post the preview of data as an output from Matlab prompt.
Comment: it would also help a lot if you provided the context of your problem. 2D object recognition is very vague. One or two sentences of what are you actually trying to achieve would clarify things a lot. Sorry for nagging.
Comment: I've specified number of objects and pictures of each object in 5 different pose (some of them http://img193.imageshack.us/img193/7148/capturewa.png). I want to train a neural network with this set of pictures and after finishing the learning phase of neural network use that neural network to detect those specified objects in a new given picture.
Comment: I asked this question there.
Comment: http://stackoverflow.com/questions/6817684/object-recognition-using-matlab/6821670#6821670 didn't address your question ?!
Comment: it helped. But i some codes may help more
Answer: People tend to use DHOG (Dense Histograms of Orientations of Gradient), which is closely related to SIFT and other image description method for this purpose. There is another commonly used image description method called SURF.
You can take a look at VLFeat.

2D object recognition using MATLAB


How to set the tabs on node pages to always display in the site's default language?

Question: I don't want $tabs to be translated. How can I set the tabs on node pages to always display in default site language?
I've tried admin language module however the setting that works in that prevents menu items from been translated.
Is there a way to manually set the rendered language in the tpl?
Answer: You can use this function (inspired from this solution wich was for Drupal 6)
<code>/**
 * Reverse translation: find source string for a given translated string.
 */
function rt($string) {
  global $language;
  $langcode = $language->language;
  $query = db_select('locales_source', 'ls');
  $query->leftJoin('locales_target', 'lt', 'ls.lid = lt.lid');
  $query->fields('ls', array('source'));
  $query->condition('lt.language', $langcode);
  $query->condition('lt.translation', $string);
  $result = $query->execute();
  $records = $result->fetchAssoc();

  return $records ? $records['source'] : $string;
}
</code>
Then via hook_menu_local_tasks_alter
<code>/**
 * Implements hook_menu_local_tasks_alter().
 */
function mymodule_menu_local_tasks_alter(&$data, $router_item, $root_path) {
  foreach ($router_item['page_arguments'] as $key => $argument) {
    if (is_object($argument) && isset($argument->type)) {
      foreach ($data['tabs'][0]['output'] as $key => $value) {
        $data['tabs'][0]['output'][$key]['#link']['title'] = rt($value['#link']['title']);
      }
    }
  }
}
</code>
Comment: This worked great thanks :)
Tried to prevent the translation before it populated the tabs array but looks like it does that through I18n before getting to the template file.