Q:

C: how to apply a sequence of variables to a function?

In C, is there a way to call a function with arguments stored in some array? I'm a C newbie, I'm not even sure if this is right but e.g.:
void f0(int a) { ... };
void f1(int a, int b) { ... };
void f2(int a, int b, int c) { ... };

int array[5][2][?] = [
    [&f0, [5]],
    [&f1, [-23, 5]],
    [&f2, [0, 1, 2]],
    [&f2, [1235, 111, 4234]],
    [&f0, [22]]
];

int i;
for (i = 0; i < 5; i++) {
    APPLY?(array[i][0], array[i][1])
}

PS: What kind of structure should I use when the array's items vary in length?
In Python, this would be:
def f0(a): ...
def f1(a, b): ...
def f2(a, b, c): ...

array = [
    (f0, (5,)),
    (f1, (-23, 5)),
    (f2, (0, 1, 2)),
    (f2, (1235, 111, 4234)),
    (f0, (22,))
]

for f, args in array:
    apply(f, args)

A:

It's possibly to have variable arity functions in C, but the mechanism is clunky and has certain restrictions, namely, there must be at least one fixed parameter, and you need to be able to tell from the fixed parameters or from the variable parameters themselves where the end of the variable list is.
A more typical solution, one that plays to C's strengths rather than its weaknesses, is something like this example. (Updated with function pointers.)
#include <stdio.h>

void f1(int, int *);
void f2(int, int *);

struct BoxOfInts {
    void (*f)(int,int *);
    int howMany;
    int theNumbers[4];
} intMachine[] = {
    {f1, 1,  { 5,  }},
    {f2, 2,  { -23, 5  }},
    {f1, 3,  { 0, 1, 2  }},
    {f2, 3,  { 1235, 111, 4234  }},
    {f1, 1,  { 22,  }},
    { 0 }
};

void dispatch(void)
{
    for(struct BoxOfInts *p = intMachine; p->f; ++p)
        (*p->f)(p->howMany, p->theNumbers);
}

void f1(int howMany, int *p)
{
    while (howMany-- > 0) {
        int t = *p++;
        printf("f1 %d %d\n", howMany, t);
    }
}

void f2(int howMany, int *p)
{
    while (howMany-- > 0) {
        int t = *p++;
        printf("f2 %d %d\n", howMany, t);
    }
}

int main()
{
  dispatch();
  return 0;
}


Q:

Is it practical to breed new cultivars at home?

Is it sensible and possible for a home gardener to attempt to create new cultivars (e.g. of citrus) via manual/controlled pollination in a home garden without specialist equipment?
For instance, if I wanted to cross two different apple cultivars is it easily achievable without using specialist equipment to prevent the flowers from being accidentally fertilised by the wrong pollen?

A:

Yes, it is doable. The more crosses you do, the more likely you will come up with something good. The more cultivars that exist for whatever you are breeding the less likely you will come up with an improvement.
Smaller plants would be amenable to home breeding. Large trees like apples would be difficult to come up with an improvement over other varieties.


Q:

out.write runs several times but resulting file is empty

I am developing in Java SE on NetBeans 7.3.1 on Windows 7.
I am trying to write a set on numbers, one on each line, to an ASCII text file.
            FileWriter fstream = new FileWriter(outputFileName, false); //false tells to not append data.
            BufferedWriter out = new BufferedWriter(fstream);
            for (int i=0; i<numBins; ++i){
                String str=Integer.toString(hist[i]);
                str.concat("\n");
                out.write(str);
            }
            br.close();

numBins is 6 and the program runs through without any errors. I check tih the debugger and
 out.write(str);

is called 6 times.  hist[i] are small integral numbers.  For some reason, the resulting file is empty and of zero size.

A:

Close your BufferedWriter Object
 FileWriter fstream = new FileWriter(outputFileName, false); //false tells to not append data.
            BufferedWriter out = new BufferedWriter(fstream);
            for (int i=0; i<numBins; ++i){
                String str=Integer.toString(hist[i]);
                str.concat("\n");
                out.write(str);
            }
            out.close();


Q:

Django - how to transfer user input from views.py to models.py?

I am trying to create a Django app that allows a user to select a file name from a drop down menu and upload the file. Regardless of what the user has named their file, I will receive that file saved as whatever they selected on the drop down plus the date. I cannot seem to get my drop downs to show. Hours of reading the documentation, multiple stack overflow posts, and trial and error have not helped. * Does anyone know how to get the user-selected drop down value from views.py to models.py to be inserted into the uploaded file's path? *
On another note, I am sure there are other issues with my code, being a Django newb, so please point them out if you see them.
models.py
from django.db import models
from datetime import datetime
import os

def update_filename(instance, filename):
    path = "documents/"
    format = '{0}_{1}.csv'.format(vc, datetime.today().strftime('%Y%m%d'))
    #note that vc is defined in views.py but I am not sure how to transfer this to models.py
    #*************************************************************
    return os.path.join(path, format)

class Document(models.Model):
    docfile = models.FileField(upload_to= update_filename) #/%Y/%m/%d')
    #value_chains = (('coffee', 'coffee'),('tea', 'tea'),)
    dropdown = models.CharField(max_length=20, choices=(('coffee', 'coffee'),('tea', 'tea'),))

forms.py
from django import forms
from .models import Document

def validate_file_extension(value):
        if not value.name.endswith('.csv'):
            raise forms.ValidationError("Only CSV file is accepted")

class DocumentForm(forms.ModelForm):
    docfile = forms.FileField(label='Select a file', validators=[validate_file_extension])
    value_chains = (('coffee', 'coffee'),('tea', 'tea'),)
    dropdown = forms.ChoiceField(choices=value_chains, required=True)

    class Meta:
        model = Document
        fields = ['dropdown']

views.py
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.views.generic.edit import CreateView

from .models import Document
from .forms import DocumentForm

def list(request):
    # Handle file upload
if request.method == 'POST':
    #bind the data to the form
    form = DocumentForm(request.POST, request.FILES)
    if form.is_valid():
        #**** vc is defined here ************************************
        vc = form.cleaned_data['dropdown']
        newdoc = Document(docfile = request.FILES['docfile'])
        newdoc.save()

        # Redirect to the document list after POST
        return HttpResponseRedirect(reverse('file_upload_app.views.list'))

# if a GET (or any other method) we'll create a blank form:
else:
    form = DocumentForm() # A empty, unbound form. This is what we can expect to happen the first time we visit the URL.

# Load documents for the list page
documents = Document.objects.all()

# Render list page with the documents and the form
return render_to_response(
    'file_upload_app/list.html',
    {'documents': documents, 'form': form},
    context_instance=RequestContext(request)
)

list.html
<form action="{% url "list" %}" method="post" enctype="multipart/form-data">
                    {% csrf_token %}
                    {{ form.dropdown }}

                            Note: the uploaded file must be in
                            .CSV
                            format and contain a column labeled "A" which contains
                            only
                            numbers.

{{ form.non_field_errors }}

{{ form.docfile.label_tag }} {{ form.docfile.help_text }}

                        {{ form.docfile.errors }}
                        {{ form.docfile }}

<input type="submit" value="Upload"/>

                </form>

                    {% if documents %}

Files on server:

                                {% for document in documents %}

{{ document.docfile.name }}

                                {% endfor %}

                    {% else %}

No documents.

A:

I found the solution, denoted by the **** below:
models.py:
from django.db import models
from datetime import datetime
import os

value_chains = (
    ('coffee', 'coffee'),
    ('tea', 'tea'),
    )

def update_filename(instance, filename):
    path = "documents/"
    #*************************************************************
    #use instance to access the instance of Document's CharField function, which is defined below
    format = '{0}_{1}.csv'.format(instance.dropdown, datetime.today().strftime('%Y%m%d'))
    #*************************************************************
    return os.path.join(path, format)

class Document(models.Model):

    docfile = models.FileField(upload_to= update_filename)
    dropdown = models.CharField(max_length=20, choices=value_chains)

    class Meta:
        permissions = (("access_file_upload_app", "Access file upload tool."),)

views.py:
from django.shortcuts import render_to_response, redirect
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required
from django.conf import settings

from .models import Document
from .forms import DocumentForm

@login_required
def doc_upload_view(request):
    if request.user.has_perm('file_upload_app.access_file_upload_app') and settings.VC_ENABLED == 'Y':
        # Handle file upload
        if request.method == 'POST':
            form = DocumentForm(request.POST, request.FILES)
            if form.is_valid():
                #********************************************************
                # make sure to pass the dropdown value to the Document call:
                newdoc = Document(docfile = request.FILES['docfile'], dropdown = form.cleaned_data['dropdown'])
                #********************************************************

                newdoc.save()

                # Redirect to the document list after POST
                return HttpResponseRedirect(reverse('file_upload_app.views.doc_upload_view'))
        else:
            form = DocumentForm() # An empty, unbound form

        # Load documents for the list page
        documents = Document.objects.all()

        # Render list page with the documents and the form
        return render_to_response(
            'file_upload_app/doc_upload_view.html',
            {'documents': documents, 'form': form},
            context_instance=RequestContext(request)
        )
    else:
        return redirect('/home/')

forms.py:
from django import forms
from .models import Document

def validate_file_extension(value):
        if not value.name.endswith('.csv'):
            raise forms.ValidationError("Only CSV file is accepted")

class DocumentForm(forms.ModelForm):

    value_chains = (('coffee', 'coffee'),('tea', 'tea'),)

    docfile = forms.FileField(label='Select a file', validators=[validate_file_extension])
    dropdown = forms.ChoiceField(choices=value_chains, required=True )

    class Meta:
        model = Document
        fields = ('dropdown',)

doc_upload_view.html:

                <form action="{% url "doc_upload_view" %}" method="post" enctype="multipart/form-data">
                    {% csrf_token %}

                    {{ form.dropdown }}

{{ form.non_field_errors }}

{{ form.docfile.label_tag }} {{ form.docfile.help_text }}

                        {{ form.docfile.errors }}
                        {{ form.docfile }}

<input type="submit" value="Upload"/>

                </form>

                    {% if documents %}

Files on server:

                                {% for document in documents %}

{{ document.docfile.name }}

                                {% endfor %}

                    {% else %}

No documents.

                    {% endif %}


Q:

Akka actor granularity

I am trying to wrap my head around Akka/actors for the first time, and am a bit confused over the granularity of each Actor's responsibilities.
In my app there are Widgets that can be registered/unregistered with a WidgetRegistrar. To register itself with the Registrar and Widget is passed to the registerWidget method:
interface WidgetRegistrar {
    public void register(Widget w);
}

When a Widget attempts to register, a verification process occurs. If this process passes, then the Widget presents a URL that must be constantly (once a second) polled and checked (with an HTTP GET) to make sure that URL is still healthy.
My question here is: how should this work load be spread amongst actors?
I can think of several different strategies right off the bat:

WidgetRegistrar actor that first somehow delegates to the WidgetVerifier actor (see below), and if verified, updates the WidgetChecker actor with the newly-registered/verified Widget
WidgetVerifier actor that verifies a Widget attempting to register itself
1 master WidgetChecker that checks a URL for each registered/verified Widget

Or a different strategy:

WidgetRegistrar actor that first somehow delegates to the WidgetVerifier actor (see below), and if verified, somehow instantiates a new WidgetChecker actor (see below)
WidgetVerifier actor that verifies a Widget attempting to register itself
1 WidgetChecker for each registered/verified Widget

Or a different strategy:

WidgetRegistrar actor that verifies Widgets right there on the spot (instead of delegating out to a separate actor), and if verified, updates the WidgetChecker actor with the newly-registered/verified Widget
1 master WidgetChecker that checks a URL for each registered/verified Widget

...the list of variations goes on and on.
So I ask: what is the granularity of an Akka actor, and how do I know when I should break functionality out into another actor and somehow connect the two actors?

A:

Akka ideology is 'let it crash', so it's best to isolate potentially dangerous functionality into a separate actor.
How i would do that - sample actor hierarchy:
/master
    /validator
        /authentication
        /capability
    /registrar
        /widget1
        /widget2
        /widget3

Assuming that you may want to have more functionality in your registrar other than register/unregister for a single widget, it's would be good to separate widgets under specific root - so, for instance, if your widget has functionality like 'update', you invoke this logic in /registrar/widget1, and if update has failed, widget1 actor will die. Depending on your needs you may want to require either to reregister the widget, or set the supervisor hierarchy to restart the widget actor automatically.
With validators/verifiers and other logic - you can build either pipeline (sequential processing) or scatter-gather (parallel) on your validators, for instance:

/master sends to /validator a message AttemptRegister(WidgetInfo)
/validator sends this message to all of its children (e.g. through ask pattern), and is expecting Accept(WidgetInfo) or Reject(WidgetInfo) - if there are no rejections - it will send RegisterWidget to /registrar and registrar will spawn a new /registrar/widget2.

Of course, it all depends on the concrete use case - for instance:

Can validation crash or block? Then you would need to have /validator/capability/doOrDieActor1
Do you need sequential processing/pipeline? you may want to implement this sequence like ../authentication will send Pass or Fail to ../authorization that will send it to capability etc - and only the final actor will send ValidationSucceeded to /validator, which will in turn send RegisterWidget event to registrar


Q:

x11vnc is slow, but using only 10% of available bandwidth

I am using x11vnc over 15Mbit/s network with 20ms latency. When the screen is changing a lot x11vnc is slow - for example when I switch a tab in a browser, it takes almost two seconds until the view is fully redrawn.
The strange thing is that max connection speed of x11vnc is even during slow redrawing only about 10% of the available bandwidth. Why is x11vnc not using available bandwidth to speed the redrawing up? For example scp is using 100% of available bandwidth without problems.
How can I identify what is the bottleneck for x11vnc on my system? So far I think:

10% network usage => network is not a bottleneck
fb read rate: 601 MB/sec => reading fb is not a bottleneck

Any ideas how can I further profile x11vnc and find out what is causing a slowdown?
For example is there any switch for x11vnc to show how much data it is handling and how long it takes to grab a screen, process and compress it and send it over the network?

A:

To answer my own question:
Switching from tight encoding to hextile encoding resolved the problem with slow redrawing completely.
To add some detail: I have noticed that during slow redrawing of the screen the cpu on the client was spiking to the 100% usage. I was using tight encoding and from the page VNC Tight Encoder - Comparison Results it can be seen that tight encoding is quite cpu intensive when compared to hextile encoding. After switching to hextile max cpu usage is never 100%, almost the whole available bandwidth is utilized and redrawing always takes less than a second. So the client's CPU was the bottleneck.

Or even better alternative (less bandwidth, low cpu usage and seems even faster than hextile) is to compile x11vnc with TurboVNC support and then use TurboVNC client.


Q:

UIDeviceOrientation Notifications

In order to receive UIDeviceOrientation change notifications, one must do two things:

call beginGeneratingDeviceOrientationNotifications on UIDevice
register for the notifications.

Here's my question:
Let's say I have two view controllers who want to receive these notifications and the first calls beginGeneratingDeviceOrientationNotifications and registers, then the second does the same.  Now my first VC unloads and unregisters and calls endGeneratingDeviceOrientationNotifications.  Will the second VC continue to receive these notifications even though the first VC "turned them off"?

A:

Yes. The documentation for the begin… method says so, at least sort-of:

You may nest calls to this method safely, but you should always match
  each call with a corresponding call to the
  endGeneratingDeviceOrientationNotifications method.

This kind of interface is usually implemented using some counter. Each begin… method increments the counter, each end… method decrements it. The notifications are sent as long as the counter is greater than zero.


Q:

Increment int variable every 5 iterations of loop (JAVA)

i want to Increment int variable every 5 iterations of loop. so the current int is 009. I want to change it to an infinite loop wherein the value add + 1 every 5 loops. so after that the value of 009 will change to 010, then after 5 loops. again it will change into 011.
 String itemID = "2014-009";
    for (int i = 0; i <= 5; i++) {
        String sdf = new SimpleDateFormat("yyyy").format(new java.util.Date());
        String[] parts = itemID.split("-");
        String part2 = parts[1];
        int result = Integer.parseInt(part2);
        String second = sdf + "-" + String.format("%03d", result + 1);
        JOptionPane.showMessageDialog(null, second);
        System.out.println(second);
    }

A:

Something like this should work:
int value = 0;
for (int i = 0; ; i++) {
    if (i%5 == 0) {
        value++;
    }
}

Explanation:

The loop has no end, because it doesn't have a condition
The value variable is incremented only every 5 iterations
We enforce that restriction by asking whether i is exactly divided by 5

Be aware that I'm not taking into account the fact that ints are finite and at some point they will overflow. For truly "infinite" values (limited only by the memory available in your machine), we would have to use arbitrary precision values, BigInteger will come in handy for that.


Q:

It doesn't display the data, it only shows never-ending loop

I'm getting a never-ending loop. What did I do wrong in this code? Thank you so much for helping me out.
void viewStudents()
{
    student *current = head;
    do
    {
        if(current == NULL)
            cout<<"Nothing here."<<endl;
        else
        {
        cout<<"Student Name: "<<current->name<<endl;
        cout<<"Student's ID Number: "<<current->studentNum<<endl;
        cout<<"Student Degree: "<<current->studentDeg<<endl;
        cout<<"Student Year Level: "<<current->studentYearLvl<<endl;
        cout<<"Student Contact Number: "<<current->studentCont<<endl;
        cout<<"Student Email: "<<current->studentEmail<<endl;
        cout<<endl;
        current = head->next;
        }
    }
    while(current != NULL);
}

A:

The problem is that you keep setting current to head->next.
What you want is to set current to current->next
current = current->next;


Q:

How to add an 'on-click' background change

I am basically using this - http://jsfiddle.net/navjottomer/8u57u/4/ and also using Bootstrap's panel styles.
I want it to look more like this though - https://support.google.com/mail#topic=
I have no idea where to start in terms of changing the colour of the panel-heading on open / active / expanded. You can see in the example that it starts white, and changes to dark grey on expand.
Any info would be great!
Here's my current mock up:

                 Overview

                content here

                 Utilities

Contents panel 2

                 Organization

Contents panel 3

A:

Here is full code.

var selectIds = $('#panel1,#panel2,#panel3');
  $(function($) {
  selectIds.on('show.bs.collapse hidden.bs.collapse', function() {
  $(this).prev().find('.glyphicon').toggleClass('glyphicon-plus glyphicon-minus');
  });
  $(".panel-heading").find("a[data-toggle=collapse]").on('click', function() {
  if ($(this).hasClass('collapsed')) {
  $(this).closest('.panel-group').find('.panel-default').removeClass('open');
  $(this).closest('.panel-default').addClass('open');
  } else {
  $(this).closest('.panel-default').removeClass('open');
  }
  });
  });
.panel-default.open {
  background-color: red;
  transition: all 1s;
  }
  .custom-panel .panel-default.open >.panel-heading {
  background: transparent;
  }
       .custom-panel .panel-default>.panel-heading {
         background: #fff;
       }
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Title Page</title>

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">

     Panel 1

Contents panel 1

     Panel 2

Contents panel 2

     Panel 3

Contents panel 3


Q:

Computer Feedback in Meditation

Are there any meditation computer  feedback programs out there? Like Biofeedback.
What could they do? Allow a teacher much insight into a student? Allow a meditator to know when wandering is happening,  when subtle thinking is happening or to know when reality is seen directly or with concepts?
Would this be a helpful tool to be used all the time, only  sometimes or never?-(Perhaps because it creates a duality, it creates aversion, it's unnessasary, it's not in the Pali Canon or anything).

A:

Biofeedback programs just take data such as heart rate, blood pressure, etc... and display them on a screen so that the person can see them. The underlying theory is that if a person can directly see what's going on, they would be better able to adjust themselves to slow them down.
Because these devices cannot directly access the mental activity of the meditator, I don't see how they could be of much use. Certainly if one is developing some form of calm abiding it might be useful to an absolute beginner, but once they start making progress, even stopping to check the machine readout would be comparatively distracting and would erode one's concentration.

A:

I've heard of some meditators who use tools like EEGs. Of late these models are becoming pretty cheap, USD 100-500, which was unthinkable even a few years ago. They can't be very accurate at this price but they are there, see for example Neurosky Brainwave.
At least in theory they can reveal whether thoughts stray frequently or stay in one spot, and we can train using the feedback to move brain waves to certain areas and stay there. I don't immediately see how this will add any more than novelty value to my meditation practice, since I already know the familiar zones my brain hits by observing the breath and other bodily signs. If I was more curious I'd probably read up on the possible patterns of breaths and their associated brain states, as far as I know the advanced Buddhist meditation literature is pretty encyclopaedic about such patterns.
Of course, such tools might be very useful - having never tried one I can't be certain.
A lot of reviews I've read claim these don't work very well. They seem to be mostly marketed for kids with ADD, but the geeky meditator is an emerging sub-category.
If someone I knew had one around I'd try it since I am curious, but since I know it'll probably be a useless toy on the shelf after a few weeks, in the spirit of letting go, I've skipped buying one for myself.


Q:

Asking the reason of two related statements in one "why" sentence

Suppose I want to say

Why does your method work?  Why doesn't mine work?

in one sentence.  Shoud I say

Why does your method work but mine doesn't?

or

Why does your method work but doesn't mine?

A:

Why does your method work but mine doesn't?

and

Why does your method work while mine doesn't?

They're both absolutely fine because that's how native speakers typically say it. Though, some might argue that the second way sounds a little bit better.


Q:

Can't upload files with IE11 - does not support binary blobs

I am using the following script to upload files,
function upload_file(id, index)
{
    var input = document.getElementById('FILE_INPUT_' + index);
    var parentId = id;
    var filesToUpload = input.files;

    for(var i = 0, f; f = filesToUpload[i]; i++)
    {
        var reader = new FileReader();

        // Keep a reference to the File in the FileReader so it can be accessed in callbacks
        reader.file = f;

        reader.onerror = function(e)
        {
            switch(e.target.error.code)
            {
                case e.target.error.NOT_FOUND_ERR:
                    alert('File Not Found!');
                    break;
                case e.target.error.NOT_READABLE_ERR:
                    alert('File is not readable');
                    break;
                case e.target.error.ABORT_ERR:
                    break; // noop
                default:
                    alert('An error occurred reading this file.');
            };
        };

        reader.onabort = function(e)
        {
            alert('File read cancelled');
        };

        reader.onload = function(e)
        {
            var att = new sforce.SObject("Attachment");
            att.Name = this.file.name;
            att.ContentType = this.file.type;
            att.ParentId = parentId;

            att.Body = (new sforce.Base64Binary(e.target.result)).toString();

            sforce.connection.create([att],
            {
                onSuccess : function(result, source)
                {
                    if (result[0].getBoolean("success"))
                    {
                        console.log('success');
                        console.log("answer id " + answer_id);
                        console.log("new attachment created with id " + result[0].id);
                        refresh_page();
                        //jQuery('.file_input').val('');

                    }
                    else
                    {
                        console.log('failure');
                        console.log("answer id " + answer_id);
                        console.log("failed to create attachment " + result[0]);
                        //jQuery('.file_input').val('');
                    }
                },
                onFailure : function(error, source)
                {
                    console.log("An error has occurred " + error);
                }
            });
        };

        reader.readAsBinaryString(f);
    }
}

It works perfectly in Chrome and Firefox, but I get the following error in IE 11,
SCRIPT438: Object doesn't support property or method 'readAsBinaryString'

So it looks like IE does not support binary blobs, is there any work around this??
Thanks

A:

You should be able to make it work by switching to readAsArrayBuffer and then using the following in your onload callback to build the binary String.
var binary = "";
var bytes = new Uint8Array(e.target.result);
var length = bytes.byteLength;

for (var i = 0; i < length; i++)
{
    binary += String.fromCharCode(bytes[i]);
}

att.Body = (new sforce.Base64Binary(binary)).toString();


Q:

MPI_ALLGATHER error parallelizing code

I'm trying to parallelize the following code.
subroutine log_likelihood(y, theta, lli, ll)
    doubleprecision, allocatable, intent(in)    :: y(:)
    doubleprecision, intent(in)                 :: theta(2)
    doubleprecision, allocatable, intent(out)   :: lli(:)
    doubleprecision, intent(out)                :: ll
    integer                                     :: i
ALLOCATE (lli(size(y)))
lli = 0.0d0
ll = 0.0d0
do i = 1, size(y)
    lli(i) = -log(sqrt(theta(2))) - 0.5*log(2.0d0*pi) &
           - (1.0d0/(2.0d0*theta(2)))*((y(i)-theta(1))**2)
end do
ll = sum(lli)
end subroutine log_likelihood

To do this, I'm trying to use MPI_ALLGATHER. This is the code I wrote
subroutine log_likelihood(y, theta, lli, ll)
    doubleprecision, allocatable, intent(in)    :: y(:)
    doubleprecision, intent(in)                 :: theta(2)
    doubleprecision, allocatable, intent(out)   :: lli(:)
    doubleprecision, intent(out)                :: ll
    integer                                     :: i, size_y, diff
size_y=size(y)
ALLOCATE (lli(size_y))
!Broadcasting
call MPI_BCAST(theta, 1, MPI_DOUBLE_PRECISION, 0, MPI_COMM_WORLD, ierr)
call MPI_BCAST(y, 1, MPI_DOUBLE_PRECISION, 0, MPI_COMM_WORLD, ierr)

! Determine how many points to handle with each proc
points_per_proc = (size_y + numprocs - 1)/numprocs
! Determine start and end index for this proc's points
istart = proc_num * points_per_proc + 1
iend = min((proc_num + 1)*points_per_proc, size_y)
diff = iend-istart+1
allocate(proc_contrib(istart:iend))
do i = istart, iend
    proc_contrib(i) = -log(sqrt(theta(2))) - 0.5*log(2.0d0*pi) &
                    - (1.0d0/(2.0d0*theta(2)))*((y(i)-theta(1))**2)
end do
call MPI_ALLGATHER(proc_contrib, diff, MPI_DOUBLE_PRECISION, &
                   lli, diff, MPI_DOUBLE_PRECISION, &
                   MPI_COMM_WORLD, ierr)
ll = sum(lli)
end subroutine log_likelihood

When I try to run my program, I get the following error.
$ mpiexec -n 2 ./mle.X
Fatal error in PMPI_Allgather: Internal MPI error!, error stack:
PMPI_Allgather(961)......: MPI_Allgather(sbuf=0x7ff2f251b860, scount=1500000, MPI_DOUBLE_PRECISION, rbuf=0x7ff2f2ad5650, rcount=3000000, MPI_DOUBLE_PRECISION, MPI_COMM_WORLD) failed
MPIR_Allgather_impl(807).:
MPIR_Allgather(766)......:
MPIR_Allgather_intra(560):
MPIR_Localcopy(357)......: memcpy arguments alias each other, dst=0x7ff2f2ad5650 src=0x7ff2f251b860 len=12000000

===================================================================================
=   BAD TERMINATION OF ONE OF YOUR APPLICATION PROCESSES
=   EXIT CODE: 1
=   CLEANING UP REMAINING PROCESSES
=   YOU CAN IGNORE THE BELOW CLEANUP MESSAGES
===================================================================================

Can somebody please explain to me what I'm doing wrong?
Thanks!

A:

I finally was able to solve my problem. The serial and parallel versions of my code are available at https://bitbucket.org/ignacio82/bhhh
subroutine log_likelihood(y, n, theta, lli, ll)
    integer, intent(in)                         :: n
    doubleprecision, intent(in)                 :: y(n)
    doubleprecision, intent(in)                 :: theta(2)
    doubleprecision, intent(out)                :: lli(n)
    doubleprecision, intent(out)                :: ll
    integer                                     :: i

do i = istart, iend
    proc_contrib(i-istart+1) = -log(sqrt(theta(2))) - 0.5*log(2.0d0*pi) &
                    - (1.0d0/(2.0d0*theta(2)))*((y(i)-theta(1))**2)
end do
 if ( mod(n,numprocs)==0 ) then
    call MPI_ALLGATHER(proc_contrib, points_per_proc, MPI_DOUBLE_PRECISION, &
                       lli, points_per_proc, MPI_DOUBLE_PRECISION, &
                       MPI_COMM_WORLD, ierr)
    else if (numprocs-1 == proc_num ) then
    recvcounts(numprocs) = iend-istart+1
    call MPI_ALLGATHERV(proc_contrib, points_per_proc, MPI_DOUBLE_PRECISION, &
                        lli, recvcounts, displs, MPI_DOUBLE_PRECISION, &
                        MPI_COMM_WORLD, ierr)
 end if
 ll = sum(lli)
end subroutine log_likelihood


Q:

Hibernate foreign key as part of primary key

I have to work with hibernate and not very sure how solve this problem, I've 2 table with a 1..n relationship like this:

-------
TABLE_A
-------
first_id (pk)
second_id (pk)
[other fields]

-------
TABLE_B
-------
first_id (pk)(fk TABLE_A.first_id)
second_id (pk)(fk TABLE_A.second_id)
third_id (pk)
[other fields]

How can I manage this with Hibernate???
I don't have idea how to manage the primary key for the second table...

A:

There is an example which is completely similar to your case in the Hibernate reference documentation. Just before this example, you'll find the explanations. Here's the example, which matches your problem (User is table A, and Customer is table B):
@Entity
class Customer {
   @EmbeddedId CustomerId id;
   boolean preferredCustomer;

   @MapsId("userId")
   @JoinColumns({
      @JoinColumn(name="userfirstname_fk", referencedColumnName="firstName"),
      @JoinColumn(name="userlastname_fk", referencedColumnName="lastName")
   })
   @OneToOne User user;
}

@Embeddable
class CustomerId implements Serializable {
   UserId userId;
   String customerNumber;

   //implements equals and hashCode
}

@Entity
class User {
   @EmbeddedId UserId id;
   Integer age;
}

@Embeddable
class UserId implements Serializable {
   String firstName;
   String lastName;

   //implements equals and hashCode
}

Note: it would be much much simpler of you had a surrogate identifier for those two tables. Unless you're forced to deal with a legacy schema, do yourself a favor and use surrogate keys.

A:

Use @PrimaryKeyJoinColumn and @PrimaryKeyJoinColumns annotations. From Hibernate manual:

The @PrimaryKeyJoinColumn annotation does say that the primary key of the entity is used as the foreign key value to the associated entity.


Q:

Matlab GUIDE blurs image?

my plan is implementing an image in a Matlab GUIDE figure. Somehow the output is always blurred (see screenshot). On the left you can see the image in Photoshop on the right in Matlab - notice how the font and other parts become blurred.
I experimented with JPEG and PNG file formats (no compression), I also tried various pixel sizes(resolutions smaller, same and bigger as the actual position of the image) and DPI(values between 30-300) settings, because I expected some scaling issue. Somehow I am stuck - Looking forward to your input!
Thank you,
Florian
Screenshot of the issue: http://s1.bild.me/bilder/260513/6875414Screen_Shot_2014-06-29_at_23.19.34.png

A:

Most probably the reason for the blur is interpolation.
If the axis size you allocated for the image is different from the size of the image MATLAB will resize the image to occupy the whole area.
In order to prevent any interpolation you must set the axis dimension to be the image dimension.


Q:

Php - How to reorder a date

I have a date which is formatted simply as 19830210 (YYYYDDMM).
How would I reorder it to 02101983 (DDMMYYYY) using php?
I simply want to rearrange the digits in the date.

A:

use createFromFormat(), do:
$date = "19830210";
$newFormat = DateTime::createFromFormat('Ydm', $date);
echo $newFormat->format('dmY'); //will give you 02101983


Q:

Integrate $\int\frac{x^3}{(x^3+1)^2}dx$

any ideas on how I could continue this integral
$$\int\frac{x^3}{(x^3+1)^2}dx$$
I am half way done, by entirely using fraction decomposition
$\int\frac{x^3}{(x^3+1)^2}dx=\int\frac{1}{x^3+1}dx-\int\frac{1}{(x^3+1)^2}dx$
$\frac{1}{x^3+1}=\frac{A}{x+1}+\frac{Bx+C}{x^2-x+1}$ from which it follows that $A=\frac{1}{3}, B=-\frac{1}{3}, C=\frac{2}{3}$
$\frac{1}{x^3+1}=\frac{1}{3(x+1)}-\frac{x-2}{3(x^2-x+1)}$
$\int\frac{1}{3(x+1)}dx=\frac{1}{3}\ln|{x+1}|+C$
$\int\frac{x-2}{3(x^2-x+1)}dx=\frac{1}{3}\left(\int\frac{2x-1}{2(x^2-x+1)}dx-\int\frac{3}{2(x^2-x+1)}dx\right)=\frac{1}{3}\left(\frac{1}{2}\ln|{x^2-1+1}|-\frac{3}{2}\frac{2}{\sqrt{3}}\arctan(\frac{2x-1}{\sqrt{3}})\right)+C$
$\int\frac{dx}{(x^3+1)^2}=?$
This is the part where I am stuck currently, using fraction decomposition seems to take a lot of time and effort, could I be missing anything?

A:

Hint:  Try integrating by parts first, with $u=x$ and $dv={x^2\over(x^3+1)^2}dx$.


Q:

"Almost" Hilbert spaces

This question is a bit (very?) vague. Is there some notion of how "close" a Banach space is to being a Hilbert space?
What I have in mind is something like a real or complex valued function on (equivalence classes) of Banach spaces, which gives $0$ for all Hilbert spaces and some non-zero value for other spaces, which tells you how close it is to being a Hilbert space. Of course, one could always put some arbitrary function, but is there something 'natural'?
For instance, is $L^3$ somehow closer to being a Hilbert space than $L^{10}$, or $L^\infty$?

A:

Generally, people tend to think of distances between normed spaces in multiplicative terms, because it fits the way how composition of operators works. That is, the smallest value of the distance is $1$ and the triangle inequality has multiplication instead of addition. If you don't like this, take the logarithm.
The Banach-Mazur distance does not directly answer your question, since it is infinite whenever the Banach space $X$ is not isomorphic to a Hilbert space.  But one can restrict consideration to all $n$-dimensional subspaces of $X$, and take supremum of their BM distances to a Euclidean space. For example, in Banach space projections and Petrov-Galerkin estimates by Ari Stern one finds this supremum for $n=2$, called the Banach-Mazur constant of $X$, denoted $C_{BM}(X)$. The author notes:

There are various other such “geometric constants” for normed vector spaces; see Kato and Takahashi [Some recent results on geometric constants of Banach spaces] for a survey of recent results on several of these constants. Generally, these constants lie between $1$ and $2$, equaling $1$ in the case of an inner product space, and equaling $2$ for the most pathological spaces, such as non-reflexive spaces. One of the oldest and best-known is the von Neumann–Jordan constant, dating to the 1935 paper of Jordan and von Neumann [On inner products in linear, metric spaces] (see also Clarkson [The von Neumann–Jordan constant for the Lebesgue spaces]), which measures the degree to which the norm satisfies (or fails to satisfy) the parallelogram law.

The von Neumann-Jordan constant of $X$ is defined as
$$
C_{NJ}(X) = \sup \left\{\frac{\|x+y\|^2+\|x-y\|^2}{2(\|x\|^2+\|y\|^2)}: \|x\|+\|y\|>0 \right\}
$$
The aforementioned paper of Clarkson has the proof that $C_{NJ}(L^p)=2^{2/\min(p,p')-1}$ where $p'=p/(p-1)$. In particular, $$C_{NJ}(L^2)=1, \quad C_{NJ}(L^3)=2^{1/3}, \quad  C_{NJ}(L^{10})=2^{4/5}$$
Theorem 3.4 of Stern's paper shows that $C_{NJ}(X)\le C_{BM}(X)$ for every $X$.


Q:

Battery Life Estimation - Sanity check

I'm trying to estimate the battery life of my device and just need a sanity check since numbers I'm getting are wildly different depending on the method I use to calculate battery life. For brevity I'm going to write first method that I've tried.
Device will spend 7 seconds in active mode, during which average current is 5mA. After that unit spends 600 seconds in sleep mode, where average current is 70uA.
So total period is 607 seconds, meaning ~0.012% of the time unit is drawing 5mA, while rest of the 99.988% it's drawing 70uA. So assuming this logic is sound (which might not be the case) my unit is drawing
(0.012*5 + 99.988*0.07)mA = ~7.06mA
On 1000mA battery with 0.7 factor (700mAh), that means my unit will run for ~99 hours?
Does this makes sense?
Is there a better way to calculate/estimate battery life if your unit is not drawing constant current like in this case?

A:

"... So total period is 607 seconds, meaning ~0.012% of the time unit is drawing 5mA ...*"

No, it's 0.012 of the time (with no '%' symbol). That's 0.012/1, not 0.012/100 of the time.
That means that the remaining time is 0.988, not 99.988.
$$ 0.012 \times 5 + 99.988 \times 0.07 = ~7.0 \ \text {mA} $$
should have been
$$ 0.012 \times 5 + 0.988 \times 0.07 = ~0.127 \ \text {mA} $$


Q:

Is using Select-Object suitable when you don't have access to -Extension?

In Powershell v6, the split-path has the -Extension parameter to access the extension of a file name, for example:
$pathToResume = "R:\Work\cover.letter_resume_base.odt"
$extension = Split-Path -Extension $pathtoResume
Write-Output $extension # Will print .odt

However, Powershell 3 doesn't provide the -Extension parameter, but I came up with this solution:
# Notice the period between cover and letter
$pathToResume = "R:\Work\cover.letter_resume_base.odt"
$pathToResumeLeaf = Split-Path -Leaf $pathToResume
$pathToResumeLeafArray = $pathToResumeLeaf.Split(".")

$fileExtension = $pathToResumeLeafArray | Select-Object -Last 1
Write-Output $fileExtension # Will print odt

I still get the file extension, but without the period. No matter how many periods are in the filename or the length of the array, I will get the same output.
I can't think of any situation where the period is required. If I wanted to print the period with the extension, I can easily add it when I use Write-Output or [string]::format()
Is Select-Object as I've shown above a viable solution when -Extension is unavailable?

A:

With a path string as the input, a concise and performant - though a bit obscure - PowerShell-native solution is to use the
-replace operator to extract the extension using a regex:
PS> "R:\Work\cover.letter_resume_base.odt" -replace '^.+(\.[^.]+)$', '$1'
.odt

Note: This solution only works reliably if the file path has an extension.
Alternatively, use the .NET framework directly, as Theo suggests:
PS> [IO.Path]::GetExtension("R:\Work\cover.letter_resume_base.odt")
.odt

You can also cast to [System.IO.FileInfo] and access the .Extension property:
PS> ([IO.FileInfo] "R:\Work\cover.letter_resume_base.odt").Extension
.odt

The above is a faster and more flexible alternative to LotPings' Get-Item suggestion, which, as Theo points, requires that the file exist:
# Works, but file must exist.
PS> (Get-Item "R:\Work\cover.letter_resume_base.odt").Extension
.odt

Is Select-Object, as shown above, a viable solution when -Extension is unavailable?

Yes, it is, but it is verbose and slow (though performance may not matter in this case), because using the pipeline and cmdlets invariably introduces overhead compared to using expressions involving operators.
LotPings points out that simply indexing with [-1] into the results of the .Split() call to extract the last token is both more concise and faster.
Also, consider routinely using PowerShell's -split operator instead of the [string] type's .Split() method:
PS> '.' + ("R:\Work\cover.letter_resume_base.odt" -split '\.')[-1]
.odt

As for whether or not to retain the initial . as part of the extension:
Either way, works, as long as you make sure the . is there when you synthesize a filename, but retaining the . has two advantages:

looking at the value makes it obvious that you're dealing with an extension
you can directly append the value to a file's base name (e,g, $baseName + $ext), which also works in the case when there's no extension (if $ext happens to contain the empty string).


Q:

WPF - clear all textboxes in tabcontrol not working

I have an application with a tab control and several textboxes in each tab and when the user says so, I would like every text box in the window (called MainWindow) to be cleared. I used the method described here, but it only seems to work for the textboxes in the tab that it is in focus.

A:

Try this:
void ClearTextBoxes(DependencyObject obj)
{
    TextBox tb = obj as TextBox;
    if (tb != null)
        tb.Text = "";

    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj as DependencyObject); i++)
        ClearTextBoxes(VisualTreeHelper.GetChild(obj, i));
}

private void Button_Click(object sender, RoutedEventArgs e)
{
    ClearTextBoxes(this);
}


Q:

If...Then statement to show results in a new location

I have multiple sheets in a workbook. I am trying to total columns D-G and them apply a variable if..then statement to the results.
Using the below code provide a total but I can't figure out how to get the "if" to work right and display results.
Dim colm As Long, StartRow As Long
Dim EndCell As Range
Dim ws As Worksheet
StartRow = 3
For Each ws In Worksheets
    Set EndCell = ws.Cells(Rows.Count, "c").End(xlUp).Offset(1, 1)
    If EndCell.Row > StartRow Then
    EndCell.Resize(, 4).Formula = "=SUM(R" & StartRow & "C:R[-1]C)"
    End If
    If EndCell.Row >= 0 Then J3 = "6 Free Bottles"
    If EndCell.Row >= 1000 Then
    J2 = Formula = ((EndCell.Row) * (0.05))
    J3 = "5% Discount"
    ElseIf EndCell.Row >= 3000 Then
    Range(J2) = Formula = ((EndCell.Row) * (0.1))
    Range(J3) = "10% Discount"
    End If
Next ws

A:

When you want to change the value of a cell, you aren't able to use J3 = "6 Free Bottles".  Excel thinks that J3 is a variable.  Use Cells(3, "J").Value = "6 Free Bottles".  You could also use Range("J2").Value =.  Range(J2) = tries to set the Range object equal to something, which will not do what you want.
Separate note that will cause problems: You are also missing an End If for one of your If statements.


Q:

Quran ayat of sajdah or sujūd during salat

We know that there are fourteen places in the Holy  Quran (also mentioned fifteen) where we need to perform sajdah or sujūd. Whenever we are reciting the Holy Quran, it is obligatory/recommended upon us to immediately perform the sajdah.
Now, during (mostly tarabih) salat we often see the imam announcing  before start that there is a sajdah in the first or second rakat. This is the most common method where we see on extra sajdah in that rakat in addition to the regular two.
Is it permissible for the imam to make a niyat (mental intention) that the regular sajdah will be sufficient for the extra sajdah needed in that rakat? That means the imam recites an ayat of sajdah, does not perform any extra sajdah, and when asked later on, explains that he made a niyat (mental intention) that the regular sajdah will be sufficient for the ayat of sajdah.
I hope that I have made my question clear. Please answer with sufficient references.

A:

explains that he made a niyat (mental intention) that the regular sajdah will be sufficient for the ayat of sajdah

Yes, that's permissible. See, for example, QIBLA.COM: Sajdah Tilawa, Qada Salat:

If you recite a verse of prostration as the imam or if praying alone, you should prostrate at the end of the verse, come back up, recite a few more verses, and then bow. If the verse of prostration is at the end of the sura, it is nonetheless recommended to add some verses. However, it is also permitted to simply bow, while intending to make one's regular prayer prostration also count for the verse of prostration. One needs to intend this, and to bow shortly after reciting the verse.


Q:

High Speed-High Resolution Image Capture with Raspberry Pi 3 Model B (and Pi Camera)

Is there a way to lessen the time taken by the raspberry pi 3 in capturing at least 1 image while being on the move? It’s like point and shoot setup.
Currently, what I have is that the raspberry pi 3 takes at least 2-3secs to capture 1 image with the 8-megapixel pi-camera (read-write). Since the raspberry pi is attach on a drone, being on the move while taking photo causes a blurry output (the ave. speed of the drone is around 4.5ft/sec), I can still slow it down depending in your advice.
I only need to take 1 image once my object of interest is spotted.
As much as possible I don't want to sacrifice the quality of the image since I'll be using it for another analysis.
I'm hoping that you can give me direction on this one.
Thanks in advance!

A:

This may sound blunt but you are pushing the Raspberry Pi to it's limits, reaching them, and then not wanting to implement the suggestions to work around those limits.
If you want to work with real-time, high quality images, the RPi is not the device. You would be better off working with something that has a GPU, and a lot more processing capability.
Something like this would cut the mustard much better.


Q:

prepend and append a tag at each occurence of a string

Basically I have a simple search feature where you can search anything, my problem at the moment is that I need to highlight the searched word on all my articles. For example if I search "Spain" and I have a article like with the following title: "Spain is the best country, on Spain we have..." I need to highlight both "Spain" words.
I already made some attempts & currently I have a function below where my entry.title is the article title, "Spain is the best country, on Spain we have..." and the search Word is "Spain", this solves my problem but just with 1 occurrence.
    processTitle () {
        let newTitle = this.entry.title
        if(this.entry.title.includes(this.searchWord) && this.searchWord) {
            newTitle = this.entry.title.split(this.searchWord)
            console.log(newTitle)
            return `${newTitle[0]} <b>${this.entry.title}</b> ${newTitle[1]}`
        }

        return newTitle
    },

I Need to have a fresh new title where I have all occurrences of the searched word highlighted. Any help with this?

A:

You can use regex to search entire string globally for all occurences of the phrase and replace it with a new one

const title = "Spain is the best country, on Spain we have...";
const searchWord = "Spain";

function replaceAll(title, searchWord) {
    const replacement = `<b>${searchWord}</b>`
    return title.replace(new RegExp(searchWord, 'g'), replacement);
};

console.log(replaceAll(title, searchWord));


Q:

Efficiently consuming a rate-limited service

So my exact case is that I have ~1400 domains on an ancient, self-hosted bind server and I'm looking to migrate them to a hosted service. The trouble is that the hosted service's API has a rate limit of 150 requests per 300 seconds and each domain will require at least 3 requests to migrate. [Note: This API does not provide any quota information, it simply stops working with a generic error message. :I]
If I were to simply hard-code a 2-second sleep between requests I'd end up with 6+ seconds of API calls, plus an additional ~2 seconds to retrieve/reformat records from the legacy server. This clocks me in at around 3.1 hours for the migration, which is a hefty ask.
Another alternative that I considered was adding a $last_call variable that I could use to calculate a sleep to add up to 2 seconds since the last call, but that still doesn't account for the time spent outside of the API client/calls.
Lastly I've tried keeping a list of millisecond timestamps representing each call, counting how many have occurred in the last 300 seconds, and dividing the window equally among them. However I've found that this tends to result in longer-than necessary sleeps at the beginning of the first window, frantically small sleeps at the end, and a call rate somewhat lower than the configured limit. This repeats in a cycle and does not seem to average itself out very much even over the course of a couple hours.
Is there a particular method or algorithm that would be well-suited to more evenly coordinating these requests within the given rate limit?

A:

So after much floundering I used some math to figure out a function that would sleep for the correct sum of time over the given request, and allow me to ramp it up exponentially towards the end.
If we express the sleep as:
y = e^( (x-A)/B )

where A and B are arbitrary values, then the sum of all sleeps, M, from 0 to N requests would be:
M = 0∫N e^( (x-A)/B ) dx

This is equivalent to:
M = B * e^(-A/B) * ( e^(N/B) - 1 )

and can be solved with respect to A as:
A = B * ln( -1 * (B - B * e^(N/B)) / M )

While solving for B would be far more useful, since specifying A lets you define a what point the graph ramps up aggressively, the solution to that is mathematically complex, and I've not been able to solve it myself or find anyone else that can.
/**
 * @param int $period   M, window size in seconds
 * @param int $limit    N, number of requests permitted in the window
 * @param int $used x, current request number
 * @param int $bias B, "bias" value
 */
protected static function ratelimit($period, $limit, $used, $bias=20) {
    $period = $period * pow(10,6);
    $sleep = pow(M_E, ($used - self::biasCoeff($period, $limit, $bias))/$bias);
    usleep($sleep);
}

protected static function biasCoeff($period, $limit, $bias) {
    $key = sprintf('%s-%s-%s', $period, $limit, $bias);
    if( ! key_exists($key, self::$_bcache) ) {
        self::$_bcache[$key] = $bias * log( -1 * ( ($bias - $bias * pow(M_E, $limit/$bias)) / $period ) );
    }
    return self::$_bcache[$key];
}

With a bit of tinkering I've found that B = 20 seems to be a decent default, though I have no mathematical basis for it. Something something slope mumble mumble exponential bs bs.
Also, if anyone wants to solve that equation for B for me I've got a bounty up on math.stackexchange.


Q:

Convert Array to serialize like string

I have a Array like below:
Array
(
    [0] => Select one
    [1] => FB
    [2] => RM
    [3] => Joey
    [4] => Isaac
    [5] => Christina
    [6] => James
    [7] => Armando
    [8] => Kent
    [9] => Tyler
    [10] => Michael
    [11] => Dylan
    [12] => Ryan
)

I want to convert it to 0:None;1:FB;2:RM;3:Joey;4:Isaac;5:Christina;6:James;7:Armando;8:Kent;9:Tyler;10:Michael;11:Dylan
I can do it using FOR loop and using IF, But I want to know the shortest way or is there any function available.
Any reference will be helpfull.
Thanks in advance.

A:

you can try this
$output = implode(';', array_map(
    function ($v, $k) { return $k.":".$v; },
    $data,
    array_keys($data)
));


Q:

Does ffmpeg always produce the same YUV file when decode a video file?

With the same computer, same OS, and same version of ffmpeg and decoder, does ffmpeg always produce the same YUV file when decode a video file? By same I mean the YUV value is exactly the same.

A:

A search didn't produce any indication of non-deterministic video decoding for a digital --> digital signal flow.

In any case, you can first run :
ffmpeg -i in.mp4 -flags +bitexact out1.y4m

ffmpeg -i in.mp4 -flags +bitexact out2.y4m

And then run
ffmpeg -i out1.y4m -v 0 -f md5 -

ffmpeg -i out2.y4m -v 0 -f md5 -

Compare the MD5 values. Same here for H.264 input.


Q:

OpenGL 3.2 w/ NSOpenGLView

How would I create a core profile in a custom implementation of NSOpenGLView? Which method should I override and what code should I put there?
So far I have this code:
// Header File
#import <Cocoa/Cocoa.h>

@interface TCUOpenGLView : NSOpenGLView

@end

// Source File
#import "TCUOpenGLView.h"
#import <OpenGL/gl.h>

@implementation TCUOpenGLView

- (void)drawRect:(NSRect)dirtyRect {
    glClear(GL_COLOR_BUFFER_BIT);
    glFlush();
}

@end

A:

Apple has a sample code project called GLEssentials that shows exactly how to do this (note that it is a Mac OS X and iOS sample code project).
Essentially you will need to subclass NSOpenGLView (the NSGLView class in the sample code) and implement the awakeFromNib method using the following:
- (void) awakeFromNib
{
    NSOpenGLPixelFormatAttribute attrs[] =
    {
        NSOpenGLPFADoubleBuffer,
        NSOpenGLPFADepthSize, 24,
        // Must specify the 3.2 Core Profile to use OpenGL 3.2
        NSOpenGLPFAOpenGLProfile,
        NSOpenGLProfileVersion3_2Core,
        0
    };

    NSOpenGLPixelFormat *pf = [[[NSOpenGLPixelFormat alloc] initWithAttributes:attrs] autorelease];

    if (!pf)
    {
        NSLog(@"No OpenGL pixel format");
    }

    NSOpenGLContext* context = [[[NSOpenGLContext alloc] initWithFormat:pf shareContext:nil] autorelease];

    [self setPixelFormat:pf];

    [self setOpenGLContext:context];
}

Also remember that if you use any OpenGL API calls that have been removed from the 3.2 API your app will crash.  Here is a PDF document of the 3.2 spec so you can see the changes.


Q:

Point to 3dimensional array in c++

I have searched on google but only found answers for single-dimension arrays.
I have a 3 dimension array storing data to be later processed by a function.
My array looks like this : levelcode[400][20][100]. It stores all the info that the decode level function needs. I get an stack overflow error immediately.
But how can i point to the entire array to get the values of it ( or how do i pass down the entire array? ) ?
I know i can technically call the function for each existing parameter but i think it would be faster and it would look better if the entire array was passed down or being used using a pointer of some sort.
How can i accomplish this?

A:

I suggest you use a std::vector. It is basically a self managed grow-able array. It stores the data dynamically(heap) so you will be using the full system memory instead of the small  bit of memory the program is given for automatic objects(stack).  With your levelcode[400][20][100] you have 800,000 elements.  if the array is of type int then you would more than likely need 3.2MB of space for the array.  typically this is larger than than the space provided to the program and will cause a stack overflow
I would suggest you use single dimension vector and then you can use math to fake the 3 dimensions.  This will make the data more cache friendly as multi-dimensional vectors do not have to have each dimension located right next to each other like a multi-dimensional array does.
So instead of having a
std::vector<std::vector<std::vector<some_type>>> name{DIM1, vector<vector<some_type>>{DIM2, vector<some_type>{DIM3}}};

and using it like
name[x][y][z]

We could have a
std::vector<some_type> name{DIM1 * DIM2 * DIM3};

and then you can access the elements with
name[x*DIM2*DIM3 + y*DIM3 + z]


Q:

How to add on python

I am trying to make a program where I can ask someone's age - then tell them that on their next birthday they will be x many years old.
for example:
python = "How old are you?"
answer = "17"
python = "On your next birthday you will be 18 years old".
that is the program which I am trying to make however I am stuck on how to add 1 to the age of the person

A:

How about this?
age += 1

or
age = age + 1

Make sure you are casting the user's input from a string to an integer.


Q:

Explain the use of full-stop/period/point in a paragraph

I use COBOL in my business and I originally learned at a a site using perform - thru ....
Now I have changed jobs and the local programming standards are different, so I need to get used to PERFORM without THRU.
I also have a doubt about the use of the full-stop/period/point in a paragraph.
You can use the period to end sentences within a paragraph. I say this because I read in places that the paragraph ends with the first point, and elsewhere I see full-stop/period/point used differently to that.
I wrote two structures below which I understand should be equal. Is that so?
Structure A:
       PERFORM 100-WRITING.
       PERFORM 200-FINISH.

100-WRITING.
*-----------
   DISPLAY "HI MY NAME IS FELIPE".
   DISPLAY "THE WORLD IS GREAT".
   DISPLAY "I DONT SPEAK ENGLISH".
200-FINISH.
*----------
   DISPLAY "BYE BYE BABY".
   DISPLAY "ESTO ES TODO".

Structure B:
       PERFORM 100-WRITING.
       PERFORM 200-FINISH.

100-WRITING.
*-----------
   DISPLAY "HI MY NAME IS FELIPE"
   DISPLAY "THE WORLD IS GREAT"
   DISPLAY "I DONT SPEAK ENGLISH".
200-FINISH.
*----------
   DISPLAY "BYE BYE BABY"
   DISPLAY "ESTO ES TODO".

A:

You are correct, the code you show is equivalent.
A paragraph or a SECTION must end with a full-stop/period/point. This means that the last thing (other than a comment or a blank line) in a paragraph or a SECTION must be a full-stop/period/point.
This does not mean that a full-stop/period/point actually ends a paragraph or SECTION. You are correct, a full-stop/period/point in a paragraph ends a sentence. A paragraph or SECTION must contain sentences only. Therefore a paragraph or SECTION must end with a full-stop/period/point because a sentence must end with one.
   PERFORM 100-WRITING
   PERFORM 200-FINISH
   .

100-WRITING.
*-----------
   DISPLAY "HI MY NAME IS FELIPE"
   DISPLAY "THE WORLD IS GREAT"
   DISPLAY "I DONT SPEAK ENGLISH"
   .
200-FINISH.
*----------
   DISPLAY "BYE BYE BABY"
   DISPLAY "ESTO ES TODO"
   .

Since the 1985 COBOL standard, sentences are no longer really important in COBOL in the PROCEDURE DIVISION, so it is only extra work if they are made important by the coder.
I find it much more convenient to re-write like the above. Don't attach the full-stop/period/point to anything. Just have it on in a line of its own. Then it means you can move around any of the lines in a paragraph/SECTION without worrying about whether the full-stop/period/point is in the correct place, because it is not actually attached to anything, so it never gets move around until you need it for the next paragraph/SECTION.
However, your site coding standards may not allow you to do this. You could always attempt to get them changed for the better :-)


Q:

Why is my condition causing my while loop to become infinite?

The question I am asking the user, is to input their total bill as an integer greater than zero and less than or equal to 2000. While the user's entry is not in the specified range I will continue to ask them for input.
After that, I wanted to ask the user to enter the size of their dinner party as an integer greater than zero and less than or equal to 20, following the same rule as mentioned above. If I can have guidance with the first part of my program, I am confident I can finish the rest on my own. This what I have so far:
bill = int(input('What is the bill total: '))
while bill > 0 and bill <= 2000 :
    bill = int(input('What is the bill total: '))

A:

You got your condition reversed.  Negate it:
bill = int(input('What is the bill total: '))
while bill <= 0 or bill > 2000 :
    print "Total must be positive and no more than 2000"
    bill = int(input('What is the bill total: '))

... or, if you prefer the concept "while input is not legal", just stuff not around the whole thing:
bill = int(input('What is the bill total: '))
while not (bill > 0 and bill <= 2000) :
    print "Total must be positive and no more than 2000"
    bill = int(input('What is the bill total: '))


Q:

CSS Navigation Vertical Align

I am unaware of the best practice to get my desired result. I have used tables here which have got me close to what I want.
The result doesn't have vertically centered text and I cannot figure out how. Tried using UL to get this but had no luck:

#hotspotbg table {
  margin-top: 1px;
}
#hotspotbg table tr td {
  border-right: 1px solid #ccc;
  border-left: 1px solid #ccc;
}
#hotspotbg table tr td a {
  text-align: center;
  text-decoration: none;
  display: block;
  font-family: Tahoma, Geneva, sans-serif;
  color: #fff;
  height: 51px;
}
#hotspotbg table tr td a:hover {
  background: #FFF;
  color: #000;
}

    Home

    Products

    Reviews

    Contact

A:

Setting the line-height of the child (a element in your case) to the height of the parent, will vertically align the text of the a element. See below for more information.

.wrapper {
    height: 70px;
    width: 100%;
    background: red;
    overflow: hidden;
}

.wrapper a {
    /*NOT AFFECTING THE VERTICAL ALIGN*/
    display: block;
    float: left;
    height: 70px;
    width: 50%;
    color: #fff;
    text-align: center;
    /*AFFECTING VERTICAL ALIGN*/
    line-height: 70px;
}

    test
    nice


Q:

Is there a way to "recreate" data with scikit-learn?

My question is about scikit-learn in python.
Let's say that a have 3 features A, B and C, with A and B capable of predicting C with:
exampleModel.fit(AandB, C)
exampleModel.predict(C)

Is there a way for me to input some C value, and get the A and B values necessary to achieve that C value? Almost inputing it in reverse. If there is a way, how is it called? (I've searched a lot for this information and until now, i have not found anything about it, sorry if my question already exists)

A:

Yes, it's possible!
But you need to be very clear in what you want: How are A, B and C related - decide what is the appropriate prediction model.
You also need to realize that there can't be a "perfect" reconstruction. A and B are in general a richer representation than C. Unless they are very restricted (for example high correlation between A and B) some information is lost when going from AB to C. This information cannot be recovered.
This will not work for all models, it works differently for every model, and it is not directly implemented in scikit-learn. In other words, you will have to do some manual work and you need to know what you are doing. In particular, you need to understand the model you are working with. There is no drop-it-in-and-go-for-it solution.
Let's assume that A and B are continuous features, and C is discrete 0 or 1. In this case an appropriate model would be a classifier. Let's further assume the A and B cluster nicely in different blobs for different C. In this case a linear classifier could work.
I'll provide an example with Linear Discriminant Analysis. It works by linearly projecting the class centers into the most discriminative direction. In general, we would need to reverse this projection, but we are lucky in that the LDA exposes the original class centers. To get a representation of the original features from a given C we only need to find the correct class center.
import numpy as np
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis as LDA
from sklearn.datasets import make_blobs
import matplotlib.pyplot as plt

np.random.seed(7)

def inverse_lda(lda, C):
    c = np.flatnonzero(model.classes_ == C)
    return model.means_[c]

AB, C = make_blobs(n_samples=333, n_features=2, centers=2)  # toy data
A, B = AB.T

plt.scatter(A, B, c=C, alpha=0.5)
plt.xlabel('A')
plt.ylabel('B')

model = LDA(store_covariance=True).fit(AB, C)

# reconstruct A and B for C=[0, 1]
ABout = inverse_lda(model, C=[0, 1])

plt.plot(ABout[0, 0], ABout[0, 1], 'o', label='C=0')
plt.plot(ABout[1, 0], ABout[1, 1], 'o', label='C=1')
plt.legend()


Q:

Angular2, how to import visjs

I just add visjs to my node modules so now I would like to import visjs like that:
import * as Vis from 'vis';
import { Component, ViewChild, ElementRef } from '@angular/core';

@Component({
  selector: 'center-pane',
  templateUrl: './center-pane.component.html',
  styleUrls: ['./center-pane.component.scss']
})
export class CenterPaneComponent {

  constructor(){}

  ngAfterViewInit(){
     console.log(Vis);
  }
}

But it doesn't work, 'vis' is not found.
How can I do ?
To bypass that I currently use the lib like that :
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/vis/4.18.1/vis.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/vis/4.18.1/vis.min.css" rel="stylesheet" type="text/css" />

But it's not the best way to use it...

A:

Besides installing vis, you also need to install its type definitions.
npm install vis --save
npm install @types/vis --save-dev

After that, you can import and use vis elements:
import { Network, DataSet, Node, Edge, IdType } from 'vis';

A:

remove script link from cdn if you wanna import
run this first npm install vis --save
if you wanna use cdn instead, remove this import * as Vis from 'vis'; then add this line
declare var vis


Q:

mysql returning 0 when should return 1 in BASH script

I am working on a bash script to dump a database to a file to be uploaded via FTP. It will be launched by a cron job and the sql server isn't localhost.
I have the script working but am running into a road block with error checking. If the script cant connect to the sql server (in the unlikely event that it goes down) I want it to stop and output whatever the problem was to an error log. The outputting to error log works fine, but the script still runs and creates a blank file. I am trying to use the $? to check if the mysql connection failed and even when I am using a testing server that is off, a 0 is returned instead of a 1. I'm wearing a hole in the wall that I am bashing my head against, what am I doing wrong?
If this has been asked before, please point me in the right direction but I couldn't find any answers when I searched.
contents of the bash script:
{
mysql -h $HOST -u $USERNAME -p$PASSWORD < dump.sql | sed "s/\t/\",\"/g;s/^/\"/;s/$/\"/" > test.csv
} 2>error.log
if [ $? -ne 0 ]; then { echo "SQL Server connection failed. Aborting" ; exit 1; } fi

A:

$? in this case is returning the result of your sed command, not the mysql command.  Since the sed command is always succeeding (you're passing valid input to it and a valid set of substitutions) you're always going to get 0 in $?.
When using one or more piped commands in a bash script then you want to use the built-in PIPESTATUS variable which will let you examine the return value of each command in a series of piped commands, no matter how many you pipe together.


Q:

Calling back into a native application from Java, via JNI

So I built this C library. It calls Java methods via the JNI, everything works fine. But how can I call back from Java into my C application?
I imagine the following: I do have a function, I take its address, I have a function pointer. I pass the pointer to Java (for example as a callback, an event handler, or anything). How can I call that function from within Java?
Is there maybe a method to dynamically and explicitly bind a native void method(); to a function pointer or something?

A:

Is there maybe a method to dynamically and explicitly bind a native void method(); to a function pointer or something?

Yes there is! You can use RegisterNatives to dynamically bind Java methods with C/C++ functions.
To change implementation you can first call UnregisterNatives followed by a new call to RegisterNatives.


Q:

Does neo4j have something like primary key/object id?

I need an efficient way of getting to a specific node from some type of ID. For example, the website will have a URL like https://website.dev/board/9e88d2717bb64639
Then "9e88d2717bb64639" (just an example) should quickly be able to find the correct node in the neo4j database. How is this done?
I know there is an 'ID' field, however upon further research I found out that it is not as reliable as one would want. It is crucial that this is done as efficiently as possible, since these node look-ups will happen frequently.

A:

You need an indexed property on your node. UUIDs will work. You can use the function randomUUID() to generate a unique random UUID, and set that on a node during its creation. If you have an index on the label/property then lookup should be quick.


Q:

Error on overload for a function that updates an object with properties of different types

I have this function that uploads an array of objects.
These are the types involved:
interface BLOGPOST_IMAGE {
  src:       string,
  alt:       string,
  caption:   string,
  credit:    string,
  creditSrc: string,
  sizeKb:    number,    // THESE TWO ARE number
  maxWidth:  number,    // THESE TWO ARE number
}

// AND THE FUNCTION UPDATES AN ARRAY OF THE FOLLOWING TYPE:

BLOGPOST_IMAGE[]

And I'm creating a function that updates one of the objects in the array:
function updateImage(index: number, propertyName: Extract<keyof PROJECT.BLOGPOST_IMAGE,"sizeKb" | "maxWidth">, newValue: number): void
function updateImage(index: number, propertyName: Exclude<keyof PROJECT.BLOGPOST_IMAGE,"sizeKb" | "maxWidth">, newValue: string): void {
  props.setBlogPost((prevState: PROJECT.BLOGPOST) => {
    const newImages = Array.from(prevState.images);
    newImages[index][propertyName] = newValue;
    return({
      ...prevState,
      images: newImages
    });
  });
}

That function gets an index, a propertyName and the newValue.
But the newValue should be a number for the following properties: "sizeKb" | "maxWidth" and should be a string for the other properties. So I've used Extract and Exclude on keyof PROJECT.BLOGPOST_IMAGE to select those properties and create an overload.
But I'm getting the following error:

QUESTION
What am I doing wrong?

A:

Javascript cannot have actual real overloads, so when you declare like this in typescript you need to provide one method declaration that can handle all the possible overloads. In your case it should look like:
function updateImage(index: number, propertyName: Extract<keyof PROJECT.BLOGPOST_IMAGE,"sizeKb" | "maxWidth">, newValue: number): void
function updateImage(index: number, propertyName: Exclude<keyof PROJECT.BLOGPOST_IMAGE,"sizeKb" | "maxWidth">, newValue: string): void
function updateImage(index: number, propertyName: keyof PROJECT.BLOGPOST_IMAGE, newValue: number | string): void {
...
}

Side note, you can simplify it a bit and get rid of the overloads like this:
function updateImage<K extends keyof PROJECT.BLOGPOST_IMAGE>(
  index: number,
  propertyName: K,
  newValue: PROJECT.BLOGPOST_IMAGE[K]
): void


Q:

How can I set file permissions to prevent anyone else from taking exclusive lock on my file?

I want to open file for append on Windows 7 host using C#/.NET. I want to use usual file output operations for this purpose. I found such solution:
FileStream trace_fd = new FileStream(r"c:\temp\testlog.txt",
                                     FileMode.Append,
                                     FileAccess.Write,
                                     FileShare.ReadWrite)

My tracefile is readable even if my program with line above is up and running. I don't have exception that file is used by another process anymore from proper code like this:
FileStream good_logreader_fd = new FileStream("c:\temp\testlog.txt",
                                              FileMode.Read,
                                              FileAccess.Read,
                                              FileShare.ReadWrite)

Then I have another program (buggy log scanner) with such line:
FileStream bad_logreader_fd = new FileStream("c:\temp\testlog.txt",
                                             FileMode.Read,
                                             FileAccess.Read,
                                             FileShare.None)

Such line is obviously a bug for log scanner. If my program is not running then buggy logscaner will get exclusive lock and subsequent runs of my program will fail to get fd for trace file.
My question is what can I do to prevent such horrific scenario from happening.
E.g. can I set file permissions for the tracefile to prevent anyone from taking exclusive lock? If yes then how? Anything else which can protect my program from buggy log scanner problem? Note that I have to keep the same trace filename between my program runs.

A:

You can not set permissions to allow any access to a file, but somehow restrict FileShare.None as file sharing mode is not related to access permissions.
Permissions give a process (based on account it runs under) access to a file/resource. If access granted process can open file with whatever share mode it desires. If this share mode does not conflict with existing share modes on the file request succeeds and now file will have this share mode (combined with previous one). See CreateFile- dwShareMode section for details.
In your case log reader needs to have permissions to open file, so it will be able to set ShareMode.None if it the first process to open file. As devshorts says there is not much you can do short of changing offending process OR hacking file access methods (search for "hook CreateFile").
Side note: if your log reader runs under the same account as other processes permissions will not help for one additional reason - as there is no "per process" permissions in Windows and all processes will share the same user's permissions.


Q:

Is it possible to make scripts to automatically install programs?

I have some programs that I like in Ubuntu and some that I don't like. Is it possible to make a script to my memory stick such that it removes those programs I don't need and installs those I do need? For example, remove Gnome and Gedit, install Xfce, Kate, Texlive-base, and Okular.

A:

You can write a script in a text editor, adding the sequence of apt-get commands you want to execute:
apt-get update && apt-get upgrade -y
apt-get dist-upgrade
apt-get remove --purge gnome gedit ...
apt-get autoremove -y
apt-get install xfce4 kate texlive-base ...

Then save the file. Now you can run it in a terminal (assuming you've saved it in your home directory):
[username@localhost ~] $ sudo sh my-script.sh


Q:

CSS + jQuery: scale, center and rotate image along its container's rectangle

I'd like to do some tricky transformations with CSS (and jQuery, if necessary).
What I'd like to achieve:

I have a container with width/height either set by fixed pixel values or a percentage (example: blue rectangle, 600px x 1000px)
In this container, an image with known original dimensions (in my case, 1000px x 200px) should be

rotated around its own center (the + in the middle of the image) along the container's diagonal axis, and
placed in the container's center (vertical, horizontal), and
scaled to not exceed the container.

The result would look like this:

Can a CSS/jQuery expert help me out on how to achieve this? Many thanks!

A:

Should the result be static, or animated/responsive, depending on screen/box size?
position: absolute;
top: 50%;
left: 50%;
translate3d(-50%, -50%, 0);
transform: rotate(66deg) translate3d(-50%, -50%, 0);
transform-origin: 0% 0%;

To Rotate:
transform: rotate(66deg);
Centerpoint:
transform-origin: 0% 0%;
Center absolute container:
position: absolute;
top: 50%;
left: 50%;
translate3d(-50%, -50%, 0);

Static example:
http://codepen.io/anon/pen/NGwozM
:)


Q:

java: how do I create an array of tuples

how can I create an array of tuples in jsp (java)
like
(a:1, b:2)
(c:3, d:4)
...
...

A:

Create a tuple class, something like:
class Tuple {
    private Object[] data;
    public Tuple (Object.. members) { this.data = members; }
    public void get(int index) { return data[index]; }
    public int getSize() { ... }
}

Then just create an array of Tuple instances.


Q:

Changing XSD ConnectionString at Runtime for a Multitenant app

I'm changing our application from "one set of code & one database" to "one set of code to multiple databases (one database per customer)".
The original code is VS2005 ASP.NET(VB) & lots of XSD's in a separate DLL. The web.config's ConnectionString would override the one stored in the DLL at runtime.
Now I need to change the ConnectionString every time I declare a Data adapter/Dataset/table, because the call could be going to a different database from the last call.
Has anyone got any hints on this?

A:

After a bit of research, it seems that an XSD has a property called ConnectionModifier.
To find it, on your XSD diagram, click the TableAdapter part of the diagram (where the queries are defined).
In the properties window, change ConnectionModifier to Public and click Save. (This seems to change the property for all the Datasets on that page too.)
Back in the main code of your site you can now do something like this:
'declare the adapter as normal
Dim AdapterTest As New DataSetTestTableAdapters.TestTableAdapter

'pass the new connection object into the now visible property
AdapterTest.Connection = New Data.SqlClient.SqlConnection("Data Source=Myserver;Initial Catalog=TEST;Integrated Security=True;")

It only takes a connection object.
I have yet to give this a proper test! Unfortunatley, a new connection object will have to be passed every time you declare something from an XSD.


Q:

Can't understand how to invoke my own theme() function

i have made formexample.module, from Drupal 7 Pro Development
function formexample_menu() {
    $items['formexample'] = array(
        'title' => 'View the sample form',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('formexample_nameform'),
        'access callback' => TRUE,
        'type' => MENU_NORMAL_ITEM,
    );
    return $items;
}

function formexample_nameform() {
    $form['name'] = array(
        '#title' => t('Your name'),
        '#type' => 'fieldset',
        '#description' => t('what people call you'),
    );

    $form['name']['user_name'] = array(
        '#title' => t('Your name'),
        '#type' => 'textfield',
        '#description' => t('please enter name'),
    );

    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Submit'),
    );
    return $form;
}

and a theme function and preprocess function
function formexample_theme() {
    return array(
        'formexmaple_nameform' => array(
            'render element' => 'form',
            'template' => 'formexample-nameform',
        ),
    );
}

function template_preprocess_formexample_nameform(&$variables) {
    $variables['name'] = $variables['form']['name'];
    $variables['submit'] = $variables['form']['submit'];
}

this is template file for this theme() - formexample-nameform.tpl.php
<div id="formexample_nameform">
<?php
    print render($name);
    print render($submit);
?>
</div>

my question is: how and where to invoke this theme('formexample_nameform') , i thought i should insert function template_preprocess_formexample_nameform to my template.php file(with template rename to my theme name) but its not working for me

A:

You just need to set it on the $form element inside your form function:
function formexample_nameform($form, &$form_state) {
  $form['#theme'] = 'formexmaple_nameform';
  // ...

When you use render element with a theme the variable on which you set #theme is the one that's passed through to the theme/preprocess functions.
Don't forget to add drupal_render_children() at the bottom of your template file or the form won't render correctly:
echo drupal_render_children($form);


Q:

SQL Query - Join the same column twice

I'm having trouble to achieve the result I want trying join a column from a table twice.
My first table is "dbo.Sessions", which contains basic session info like the user ID, the project ID, login/logout date and times, etc.
I need to join to that the user names and project names. However, these are found in another table, but in the same column (dbo.tblObjects.Name).
Example:
+------+---------------+
| k_Id | Name          |
+------+---------------+
|   1  | AgentName1    |
|   2  | ProjectNameX  |
|   3  | ProjectNameY  |
|   4  | AgentName2    |
|   5  | ProjectNameZ  |
|   6  | AgentName3    |
+------+---------------+

To try and achieve my goal, I used two "LEFT JOIN". However, I get duplicate results in both. I'll either get both columns to display either the project names or the user names (depending on which "LEFT JOIN" is first).
This is what I have at this point:
SELECT SysDB.dbo.Sessions.*, SysDB.dbo.tblObjects.Name AS AgentName, SysDB.dbo.tblObjects.Name AS ProjectName
FROM SysDB.dbo.Sessions
LEFT JOIN SysDB.dbo.tblObjects ON SysDB.dbo.Sessions.userId = SysDB.dbo.Objects.k_Id
LEFT JOIN SysDB.dbo.tblObjects ON SysDB.dbo.Sessions.projectId = SysDB.dbo.Objects.k_Id
WHERE (SysDB.dbo.Sessions.loginDate BETWEEN 'm/d/yyyy' AND 'm/d/yyyy')

Note: SysDB is the name of the database that I identify every time because this query is to be run externally. I also don't use "USE SysDB" before my selection because it doesn't work from the VBA macro this will run from.
Note 2: I have found a thread on this site that addresses this exact issue, but I can't understand what is being done, and it dates back in 2012. Something about aliases. The solution offers to add "ls." and "lt." before the table names, but that doesn't work for me. Says the table doesn't exist.
SQL Query Join Same Column Twice
Note 3: I have tried many different things, such as:
LEFT JOIN SysDB.dbo.tblObjects AS AgentName ON SysDB.dbo.Sessions.userId = SysDB.dbo.tblObjects.k_Id
LEFT JOIN SysDB.dbo.tblObjects AS ProjectName ON SysDB.dbo.Sessions.projectId = SysDB.dbo.tblObjects.k_Id

Any insights would be greatly appreciated. Thanks!

A:

You may find it much easier to see what you are doing by giving each table an alias (session, agent, project below)
SELECT session.*, agent.Name AS AgentName, project.Name AS ProjectName
  FROM SysDB.dbo.Sessions session
       LEFT JOIN SysDB.dbo.tblObjects agent
              ON session.userId = agent.k_Id
       LEFT JOIN SysDB.dbo.tblObjects project
              ON project.projectId = session.k_Id
 WHERE (session.loginDate BETWEEN 'm/d/yyyy' AND 'm/d/yyyy')


Q:

How do I know what changed in my Observable class?

So I'm using the Observer pattern in my app in order to get notified of changes in another class without having to look for them.
I have a Singleton class which extends Observable. Inside this class I have two CountDownTimer type variables. Eachs of these contains two methods: onTick() and onFinished().
Let's call those Timers A and B for the sake of simplicity.
Every time A.onTick(), A.onFinished(), B.onTick(), B.onFinished() are called, I must call notifyObservers() to notify my Observer that something has changed.
Until here everything works fine. The problem is that I know something has changed, but I don't know what exactly has changed. Depending on which one notified me, I must execute some code on the Observer side.
How do I know which of these methods notified me?

A:

Use LiveData instead of Observable. LiveData is quite useful because not only it's observable but also it binds to your activity's lifecycle so you don't have to worry about handling it yourself.
Maybe this example will help you:
public class MyTimerWrapper {

    public static MyTimerWrapper getInstance() {
        // Your singleton logic

        createTimers();

        return instance;
    }

    private CountDownTimer timerA;
    private CountDownTimer timerB;

    private MutableLiveData<TimerEvent> timerALiveData = new MutableLiveData<TimerEvent>();
    private MutableLiveData<TimerEvent> timerBLiveData = new MutableLiveData<TimerEvent>();

    public LiveData<TimerEvent> startTimerA() {
        timerA.start();
        return timerALiveData;
    }

    public LiveData<TimerEvent> startTimerB() {
        timerB.start();
        return timerBLiveData;
    }

    private void createTimers() {
        createTimerA();
        createTimerB();
    }

    private void createTimerA() {
        timerA = new CountDownTimer(30000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                // If you're running on another thread
                timerALiveData.postValue(TimerEvent.TICK);

                // Otherwise
                timerALiveData.setValue(TimerEvent.TICK);
            }

            @Override
            public void onFinish() {
                // If you're running on another thread
                timerALiveData.postValue(TimerEvent.FINISH);

                // Otherwise
                timerALiveData.setValue(TimerEvent.FINISH);
            }
        }
    }

    private void createTimerB() {
        // Same as createTimerA, but with timerB
    }
}

public enum TimerEvent {
    TICK,
    FINISH
}

Now to observe that data in your activity:
MyTimerWrapper timerWrapper = MyTimerWrapper.getInstance();
timerWrapper.startTimerA().observe(this, new Observer {
    @Override
    public void onChanged(TimerEvent timerEvent) {
        // Here you'll be able to see whether timerA is ticking or finished
    }
})


Q:

1's complement - Can 1 bit or 2 bit errors go undetected? How? Why?

Within a network packet header, when 1's complement is used with 8 bit bytes (rather than the 16 bits normally used in TCP), can a 1 bit error go undetected?
can a 2 bit error go undetected?
If they can how and why does this happen?

A:

This is the way a 1's complement works with 3 8-bit bytes. (rather than the 16 bits in TCP)
   10011001
+  01010010
___________
   11101011
+  01011001
___________
1  01000100
          1   Wrap Around and add 9th Bit
___________
   01000101  <- Sum
___________
   10111010  <- 1’s Complement

If there are 1 Bit errors they will all be detected, however 2-bit errors can go undetected.
   10011000 <- last bit switched (should be 10011001)
+  01010011 <- last bit switched (should be 01010010)
___________
   11101011
+  01011001
___________
1  01000100
          1 <- Wrap Around and add 9th Bit
___________
   01000101 <- Sum
___________
   10111010 <- 1’s Complement with 2 bit error is the same as previous answer


Q:

Why does stack overflow suggest so many irrelevant questions on the "Ask a Question" screen?

I was just asking a question on Stack Overflow and after entering the title I got a hundred or so related questions, which are absolutely unrelated to anything I care about. Did anyone actually bothered to scroll the down and see more than the first 5 hints? Wouldn't it make more sense to filter it a bit better?

A:

I have actually found the suggested results on the ask a question screen a lot more helpful than those that are returned by the search sometimes, I suppose with more questions the filters should be tightened up a bit.

A:

The stackoverflow search leaves much to be desired, however it is a useful quick check to see if there are any questions already asking the same thing. I think they could improve on it.
However, the site has been setup to help Google index the content as many people have pointed out that Google is really StackOverflow's homepage, and the majority of users will come from there and land on the question which answers their question (ie: google search).
Some ideas for additional search options have been suggested regarding the general search, and I think that the similar question search/filter needs to also be improved.


Q:

Copying data between two remote hosts - how does it works?

I need to copy data from host A to host C. There is no connection between them. Only way is A <-> B and then B <-> C.
To made this in some faster way I use the following command on B (the middle server):
    ania@hostname_B: /home/ania/
    ssh hostname_A 'cd /home/ania/lot_of_files; tar cf - .' | ssh hostname_B 'cd /home/ania/new_place; tar xf -'

It works, but I don't understand something here and really would like to.
Where is hidden in this command is the strictly copying data?
I see normal ssh connection, change the directory and packing/unpacking files only done on two hostnames and after another separated by pipe.
No files after execution are stored on hostname_B, there is no scp here used also.
Done on AIX, but it will work on Linux also.

A:

foo | bar means "take all normal output from foo and pass it as input to bar" ("normal" since there is also "error" output).
It doesn't really matter what foo or bar are as long as the first one writes it output to stdout (a.k.a "file handle 1") and the second one can read from stdin (or file handle 0).
SSH does something similar but involving sockets. So it connects to the SSH server on a different computer (via Unix Sockets) and redirects stdin/out/err of the command running on the remote computer to the stdin/out/err of the ssh command which you executed locally.
So if you do ssh user@host echo Hello, then SSH will send the command echo Hello to the remote SSH server which will execute it "locally" (i.e. on the same computer where the SSH server is running). The result (Hello) will be piped through the SSH server into the socket connection to the computer running the ssh command which has set up its pipes to redirect the data to it's stdout.
So we have:

tar on A collecting data and piping that to the SSH server on A
The SSH server on A sends the output on to the first ssh command via Unix Sockets
The first ssh command pipes (or streams) everything to it's stdout where the | (pipe) command picks it up.
The pipe command passes the output of the first ssh to the second.
The second ssh sends the data to the SSH server on B via Unix Sockets
The remote SSH server on B pipes the data then to the second tar command as stdin

Or as a graphics:
tar cf --pipe>> SSH(A) --socket>> ssh hostA --pipe>> ssh hostB --socket>> SSH(b) --pipe>> tar xf

Where --pipe>> is a pipe between processes on the same computer and --socket>> is a Unix socket connection between two different computers.


Q:

comparing c++ char struct to an ASCII value yields an error

if (sale->taxStatus[i] = "y")  // line 44

yields error:
y.cpp:44:12: error: request for member taxStatus in sale, which is of non-class type Sale*
My struct:
struct Sale {
    int quantity[MAX_SALES];
    float unitPrice[MAX_SALES];
    char taxStatus[MAX_SALES]; // MAX_SALES = 10
};

the full function:
void total(struct Sale sale[], int sales) {

    int i = 0;
    float subTotal, hst, total = 0;

    for (i = 0; i < sales; i++) {
        subTotal = subTotal + (sale->quantity[i] * sale->unitPrice[i]);
        if (sale->taxStatus[i] = "y")
        {
            hst = hst + ((sale->quantity[i] * sale->unitPrice[i]) * 0.13);
        }
    }

    cout << "\n" << "Subtotal  : " << subTotal << endl;
    cout << "HST (13%) : " << hst;
}

A:

if (sale->taxStatus[i] == 'y')

As @jweyrich and @AustinPhillips also pointed out that you need double equal sign ( == )  and chars are compared in single quotes.
single equal sign ( = ) is used to assign value.
e.g. s = 5;
double equal sign ( == ) is used to check equality of two or more than two values.
e.g. if( s == d && d== e && e == f && f == b ) { };
equal sign with exclamation mark ( != ) is used to check inequality of two or more than two values.
e.g. if( s != d && d != e && e != f && f != b ) { };