Using model data and FormCollection in a HttpPost

Question: I have model data in a VIEW, and 'other' data as well, which is not part of a model.
When the user clicks on submit, from the VIEW, i am expecting the model data to also go through?
My HttpPost in the controller looks as such:
    [HttpPost]
    public ActionResult RegisterSP(RegisterModel model, FormCollection collection)
    {
        System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();

        // Create Bytes using userName and Email to calculate CRC32
        String s_user_id = SessionBag.Current.UserName + SessionBag.Current.Email;
        Byte[] bytes_user_id = encoding.GetBytes(s_user_id);
        UInt32 user_Id = Crc32.Compute(bytes_user_id);

However, i also have other data in the VIEW which i would like to POST as well to the controller, hence i have added FormCollection.
When in debug, i see the the RegisterModel, is null, but the FormCollection has ALL the data, both from the model and the 'other' data as well. I can just use the FormCollection, however there are quite alot of 'other' data which i need to get, and loop through (using for statements) the formCollection, and get the number of records for a particular type of field. Basically, i have checkBoxes, which i need to loop through, and they are all called, code1, code2,code3 ... code24  ... I need to get all the ones with "code*" and insert these into the Database. If i just have the FormCollection having the checkboxes i will be fine, but i cant. Is there a way for me to get the FormCollection["code*"] for example, so using a wildcard to get all the ones (checkboxes) that i  need ? Or am i doing all this the wrong way
Here is my VIEW(),
@model mvc1.Models.RegisterModel

@{
    ViewBag.Title = "RegisterSP";
}

@section LoginSignupLink {
    @Html.Partial("_LogOnPartial")
    @Html.Partial("_SignUpPartial")
}

@{
    Layout = "~/Views/Shared/_InitLayout.cshtml";
}

@using (Html.BeginForm())
{

Create a New Account (Page 2)

    Use the form below to continue creating a new account.

    <fieldset style = "width: 840px; margin:  0px auto;">
    <legend>Account Information</legend>

        Address Details

          Company
          @Html.TextBoxFor(m => m.userNameCompany, new { style = "font-family:Verdana;font-size:13px;color:#000000" })
                              @Html.ValidationMessageFor(m => m.userNameCompany)

          Address-Building Name
          @Html.TextBoxFor(m => m.buildingName, new { style = "font-family:Verdana;font-size:13px;color:#000000" })
                              @Html.ValidationMessageFor(m => m.buildingName)

          Address-Building Number
          @Html.TextBoxFor(m => m.buildingNumber, new { style = "font-family:Verdana;font-size:13px;color:#000000" })
                              @Html.ValidationMessageFor(m => m.buildingNumber)

          Address-Street Number
          @Html.TextBoxFor(m => m.streetNumber, new { style = "font-family:Verdana;font-size:13px;color:#000000" })
                              @Html.ValidationMessageFor(m => m.streetNumber)

          Address-Street Name
          @Html.TextBoxFor(m => m.streetName, new { style = "font-family:Verdana;font-size:13px;color:#000000" })
                              @Html.ValidationMessageFor(m => m.streetName)

          Address-Area
           @Html.TextBoxFor(m => m.area, new { style = "font-family:Verdana;font-size:13px;color:#000000" })
                               @Html.ValidationMessageFor(m => m.area)

          Address-City
          @Html.TextBoxFor(m => m.city, new { style = "font-family:Verdana;font-size:13px;color:#000000" })
                              @Html.ValidationMessageFor(m => m.city)

          Address-Country
          @Html.TextBoxFor(m => m.country, new { style = "font-family:Verdana;font-size:13px;color:#000000" })
                              @Html.ValidationMessageFor(m => m.country)

          Postal Code
          @Html.TextBoxFor(m => m.postalCode, new { style = "font-family:Verdana;font-size:13px;color:#000000" })
                              @Html.ValidationMessageFor(m => m.postalCode)

        @{ int l_count = 0;
           int l_code = 0;
           string l_otherExpertise;
         }

        Expertise

        @foreach (var item in ViewBag.Expertise)
        {
               l_count = l_count + 1;
               l_code = l_code + 1;

               if (l_count == 1)
               {

                        <input type="checkbox" name="code@(l_code)" value="@item.expertiseDesc" />
                        @item.expertiseDesc

               }
               else if (l_count < 3)
               {

                        <input type="checkbox" name="code@(l_code)" value="@item.expertiseDesc" />
                        @item.expertiseDesc

               }
               else if (l_count == 3)
               {

                        <input type="checkbox" name="code@(l_code)" value="@item.expertiseDesc" />
                        @item.expertiseDesc

               }
               else if (l_count % 2 == 0 && l_count == 4)
               {

                        <input type="checkbox" name="code@(l_code)" value="@item.expertiseDesc" />
                        @item.expertiseDesc

                    @if (@item.expertiseDesc == "Other")
                    {
                        @Html.TextBox("l_otherExpertise","")

Comma separate specific expertise
                    }

                    @:

                    l_count = 0;
               }
        }

        Skills

        @Html.TextAreaFor(m => m.skills, new { style = "font-family:Verdana;font-size:13px; height: 50px; width:680px; overflow: scroll" })

        About

        @Html.TextAreaFor(m => m.about, new { style = "font-family:Verdana;font-size:13px; height: 50px; width:680px; overflow: scroll" })

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

    </fieldset>

}

And here is my controller, the HTTPPOST part, where i need to access the CheckBox values that were clicked by the user
    public ActionResult RegisterSP(RegisterModel model, FormCollection collection)
    {
        System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();

        // Create Bytes using userName and Email to calculate CRC32
        String s_user_id = SessionBag.Current.UserName + SessionBag.Current.Email;
        Byte[] bytes_user_id = encoding.GetBytes(s_user_id);
        UInt32 user_Id = Crc32.Compute(bytes_user_id);

        DBController dbcontroller = new DBController();

Comment: What does your originating controller method look like, and your view. Could you provide a simplified version of your problem?
Comment: Well, now, i just need to access FormCollection. At the moment, FormCollection contains about 50 different fields, and out of this 50,i need to access the (24) following fields : code1, code2, code3 .. code24. I need to loop through this list and get the values. Can i use a wildcard for accessing data from FormCollection? what is the best way to do this ?
Comment: I think you need to read up on model binding. If you provide your current view and the originating controller action it is much easier to help
Comment: solution can be found here .. http://stackoverflow.com/q/4893147/1278124
Answer: you can access to your FormCollection via
[HttpPost]
public ActionResult RegisterSP(RegisterModel model)
{
  var myForm = Request.Form;
  ....
}

different classes but same base class NameValueCollection


Erro acessando vetor de strings

Question: Tenho o seguinte código:
#include <stdio.h>
#include<stdlib.h>
#include<string.h>

int main() {
    char v[]= {'Brasil', 'Alemanha', Japão'};

    int i = 0;
    for (i=0; i<4; i++){
    printf("%s", v[i]);
    }
}

Porém, quando vou compilar abre o terminal e aparece a mensagem:

paises.exe parou de funcionar

O que está errado?
Answer: O código tem vários erros.
Strings devem ser delimitadas por aspas duplas e e não simples que são reservadas apenas para delimitar um caractere.
Está criando um array de strings, mas está declarando um array de caracteres. Com a modificação que eu fiz está criando um array de ponteiros para char que é exatamente o que produz uma string. No caso o compilador vai alocar as três sequências de caracteres em uma área estática e vai colocar um ponteiro para esses textos no array.
O laço está lendo um item a mais do que existe, se existem 3, tem que ir até o 2, já que o primeiro começa em 0.
#include <stdio.h>

int main(void) {
    char *v[] = { "Brasil", "Alemanha", "Japão" };
    for (int i = 0; i < 3; i++) printf("%s\n", v[i]);
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Comment: @GuilhermeDuarte Olá Guilherme! Marque a resposta como aceita, clicando na marca de verificação do lado esquerdo do texto, please! :)
Comment: Obrigado amigo. Deu certo :) Guardei sua resposta. Bem completa

Erro acessando vetor de strings


Undefined while sending post nodejs

Question: I try to send a form with data in my nodejs app but I get "undefined" I am not sure does it matter but in console first I see "undefined", then POST. I have tried some "fixes" from the Internet like adding "type:'application/*+json', inflate: false" to app.use(bodyParser.json...) but nothing worked for me...
Undefined
POST /users/register 200 32.777 ms - 2346

this is my routes/users.js file:
var express = require('express');
var router = express.Router();

router.get('/register', function(req, res, next) {
  res.render('register', {
    'title': 'Register'
  });
});

router.post('/register', function(req, res, next) {
  console.log(req.body.name);
});

module.exports = router;

heres my jade file
form(method='post', action='/users/register', role='form')
        .form-group
            label Name
            input.form-control(type='text', name='name', placeholder='Enter Name')
        input.btn.btn-default(name='submit', type='submit', value='Register')

and app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var expressValidator = require('express-validator');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var bodyParser = require('body-parser');
var flash = require('connect-flash');
var mongo = require('mongodb');
var mongoose = require('mongoose');
var db = mongoose.connection;

var routes = require('./routes/index');
var users = require('./routes/users');

var app = express();

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(bodyParser.json({ type: 'application/*+json' }));

app.use(session({
  secret: 'secret',
  saveUninitialized: true,
  resave: true
}));

app.use(passport.initialize());
app.use(passport.session());

app.use(expressValidator({
  errorFormatter: function(param, msg, value) {
    var namespace = param.split('.'),
        root = namespace.shift(),
        formParam = root;
    while(namespace.length) {
      formParam += '[' + namespace.shift() + ']';
    }
    return {
      param: formParam,
      msg: msg,
      value: value
    };
  }
}));

app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use(flash());
app.use(function(req, res, next) {
  res.locals.messages = require('express-messages')(req, res);
  next();
});

app.use('/', routes);
app.use('/users', users);

app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

module.exports = app;

Routing works fine what show setting up a title to "Register", but I have problems with sending post :/
Answer: You're configuring body-parser to only accept JSON request bodies, but your form is submitted in URL-encoded format (application/x-www-form-urlencoded).
For that, you need to add the correct parser:
app.use(bodyParser.urlencoded({ extended : true }));

More information, also on the meaning of extended : true, here.

Undefined while sending post nodejs


Correct way to use memset() on multi dimensional array of type enum

Question: I have been struggling to get memset to work for me.
I have the following array type:
typedef enum cell game_board[BOARDHEIGHT][BOARDWIDTH];

Cell enum:
enum cell
{
   C_EMPTY,
   ...
}

But when I call memset() to initialize all values in the board to C_EMPTY. Nothing seems to happen:
void init(game_board board)
{
   memset(board, C_EMPTY, sizeof(board) * BOARDHEIGHT * BOARDHEIGHT);
}

I have tried many different ways of calling memset() but I think the problem is in my understanding.
Comment: Post a minimal self-contained example please.
Comment: Define Nothing seems to happen?
Comment: after I call my init method and check against a position in the array `board[0][0] == C_EMPTY ` it is never true
Comment: @iharob has clarified it for me. Thanks.
Answer: You can't set an integer value that way, memset() sets a byte at a time, an integer is usually 4 bytes. In the particular case you posted it will set all to 0 since it's 0 it works. But with non-zero values it will not work correctly.
Comment: So because C_EMPTY is the first value in my enum it should work but trying to set it to another enum value it will not work? Sorry, very new to C.
Comment: Yes, exactly. Because `C_EMPTY` will be `0` in that case.
Comment: So the best way to init the array to another value would be to loop over the 2D array setting each value to whatever value I need? Another Question: What if the enum was a char enum? So `C_EMPTY = ' ', C_CROSS = 'X'`. Memset would then not work at all, correct?
Comment: *So the best way* -> NO, it's the ONLY way.


C pointer with char[], const keyword ignored?

Question: I made a little function in C which copies a char array. I didn't want source to be changed, so I put const into the function declaration and body, but it changed.
main.c
#include "copy_char.h"
#include <stdio.h>

int main(void)
{
  char source[] = { 'h', 'e', 'l', 'l', 'o', 0 };
  char dest[] = { 'a', 'b', 'c', 0 };

  printf("%s\n", source); // hello
  printf("%s\n", dest); // abc

  copy_char(source, dest);

  printf("%s\n", source); // o (?) - why did this change?
  printf("%s\n", dest); // hello
}

copy_char.c
#include "copy_char.h"

void copy_char(const char* source, char* dest)
{
  while(*source != 0)
  {
    *dest++ = *source++;
  }

  *dest = 0;
}

copy_char.h
#ifndef COPYCHAR_H
#define COPYCHAR_H

void copy_char(const char* source, char* dest);

#endif /* COPYCHAR_H */

Can anyone explain to me, why did my source char array change from hello to o?
Comment: You have Undefined Behaviour because you overflow the `dest` buffer.
Answer: Buffer overrun. The string source is longer than the memory allocated for dest, so when you copy source to dest you are tromping over memory you didn't intend to. Weird things then happen (undefined behavior).
You can make dest big enough by declaring its size to be big enough for "hello":
char dest[6] = { 'a', 'b', 'c', 0 };

Answer:
I didn't want source to be changed, so I put const into function declaration and body. but, it changed

The const qualifier does not magically protect you from writing where you should not. It's merely a contract between you and the compiler that says "trust me, I am not going to modify the memory pointed to by this pointer".
In your function you are writing data past the end of dest, which is undefined behavior. You should either:

Pass a maximum length to the function:
void copy_char(const char* source, char* dest, size_t maxlen)
{
  size_t i;

  for (i = 0; i < maxlen && source[i]; i++)
  {
    dest[i] = source[i];
  }

  dest[i] = 0;
}

Stop at either *source == 0 or *dest == 0:
void copy_char(const char* source, char* dest)
{
  while(*source != 0 && *dest != 0)
  {
    *dest++ = *source++;
  }

  *dest = 0;
}

Create a big enough dest array and leave the function unchanged.

The semantics of the function change depending on which option you choose, which one is the right one is up to you.
What most likely is happening in your case is that it just so happens that source is right past the end of dest, so you overwrite the contents of dest with 'h','e','l','l', then the first character of source with 'o' and then the second one with '\0'. Luckily enough, your program does not crash, and you end up with a valid string in source that is "o". Nonetheless, you should never rely on undefined behavior, whether your program seems to magically work or not.
Comment: @JinLim the order of declaration doesn't matter, the compiler can re-arrange variables on the stack however it wants. Indeed, it's most common to see them in reverse order of declaration.
Comment: @Marco Maybe because it will be on `stack` memory? Last In First Out.
Comment: @JinLim yes, I would argue that's the reason for them being usually reversed, but as I said you should not assume that they always are, it's up to the compiler to decide how to order variables on the stack.
Comment: Yes indeed. I'll just note that one should never *depend* on the behavior described in the last paragraph. I think it is absolutely correct in describing what is causing the observed behavior, but it could change with a different compiler, compiler version, compiler options (such as optimization), etc. Undefined behavior is, after all, undefined.
Comment: @FredLarson indeed. Let me just state it for clarity.
Comment: Ooh, I think there's an off-by-one bug in your example with the maximum size. It may write the null terminator one byte past the end of the buffer.
Comment: @FredLarson depends on the semantics you assign to `n`... in my case I use it as a max length (so you write at most `n + 1`), let me rename the variable to make it clearer.
Comment: I can see that. I was thinking of if you passed `sizeof(dest)` to the function. If you passed in `strlen(dest)` instead, it would work. I would favor going by the size of the buffer rather than the length of the string that's already in it. Whatever works.
Comment: Thanks for the detailed answer. It helps me a lot. One question, why did you guess that ` is right past the end of ` ? I declared  first and then  @Fred


AppDelegate declaration in a second view

Question: I have an issue with my App and maybe the way off managing AppDelegate.
I have 2 views one is the main view and the second is for the setting.
My first view will access to my core data (7 IP Address in string). When going to the second view, I'd like to modify IP Address into my CoreData.
I have of course access to my data in my first view and I'm sending (segue) to my second view.
My question is, I'd like to change my IP Address from my second view and save it into my core data.
I know how to save, .... but, I need to create a ManagedObject, but, for that I need a AppDelegate.
But, it seems that my AppDelegate declaration doesn't works. I mean, Xcode is telling me that AppDelegate is undeclared.
Can I segue my AppDelegate from 1st View to the Second ?
Or
How to create an AppDelegate into my SecondView ?
thanks in advance for your help and support.
Comment: The context shouldn't be owned by the app delegate anyway (research why), but pass the context between view controllers anyway, don't go direct to the app delegate.
Answer: If I understand correctly you want to access your app delegate from another ViewController?
Just do like this:
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate

Comment: Yes, I already tried this into my second controller, but, Xcode is saying that AppDelegate is unknown
Comment: Mmm... But you can access it like that from the first controller just fine? That's definitely weird...
Answer: As Wain recommended, the best practice is to have the main view controller pass the managed object context to the settings view controller.
This is called dependency injection, and here's how you'd do it via a segue:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "showSettings" {
        if let destinationVC = segue.destinationViewController as? SettingsViewController{
            // Pass our managed object context to the settings controller
            destinationVC.managedObjectContext = managedObjectContext
        }
    }
}

You would add a managedObjectContext property to your Settings view controller, like so:
import CoreData

class SettingsViewController: UIViewController {

    var managedObjectContext : NSManagedObjectContext?

The benefit of dependency injection is that each view controller simply uses the context it was given, instead of looking to a "known" place (such as the AppDelegate) for a global managed object context.
This removes the tight coupling between view controllers and the AppDelegate, and also gives you the flexibility to use more than one NSManagedObjectContext throughout your app, which often becomes important as projects grow in size and complexity.
Apple recommends this practice in their Accessing the Core Data Stack documentation:

When you create a view controller, you pass it the context it should
  use. You pass an existing context, or (in a situation where you want
  the new controller to manage a discrete set of edits) a new context
  that you create for it. It's typically the responsibility of the
  application delegate to create a context to pass to the first view
  controller that's displayed.
A view controller typically shouldn't retrieve the context from a
  global object such as the application delegate—this makes the
  application architecture rigid.

Update:
In answer your comment about how to create an NSManagedObject, you only need an NSManagedObjectContext, which your second view controller now has.
let employee = NSEntityDescription.insertNewObjectForEntityForName("Employee", inManagedObjectContext: self.managedObjectContext) as! Employee

See Creating and Saving Managed Objects in Apple's Core Data Programming Guide for more details.
None of your view controllers should need to access the AppDelegate at all, since you're now passing around a context for them to use.
Comment: Thank you, got one more question. I succeeded to segue ManagedObjectContext, but, in my second view, for my value update into my entity, how can I create the ManagedContext without AppDelegate ?
Comment: You don't need the AppDelegate.  If you're following a tutorial that uses the AppDelegate to access the context or create managed objects, you should find a different tutorial :) I've updated the answer with an example and link.
Comment: Thank you, in your example you're using Employee when I'm using Adresses. Honestly I'm bit lost as, it seems not accessible. Do I need to create this class in my second view ?     class Adresses: NSManagedObject
Comment: Thanks PetahChristian, sorry, for that.
Comment: @fred No problem.  Posting code makes a big difference.  It shows people what you've tried, and it makes it easier to understand the problem and provide a solution.  You should show your segue code, so we can see what you're passing to the Settings view controller, the Settings code where you're trying to create a managed object, and the specific error(s) provided by Xcode.


glusterfs configuration files and chef

Question: Seems impossible to find any info on configuration files for Gluster's most recent version (3.2.x).  I'd like to use configuration files as opposed to the CLI because I'd like to automate configuration with chef.
Is this possible? When I googled this, all I found was this, which was pretty useless:
http://community.gluster.org/q/does-glusterfs-support-configuration-files/
How does one do this?
Answer: Incidentally, I'm involved in doing the exact same thing now and have come up with some working solution.
Assumption: Using EL6 platform.
The Gluster package for 3.2.x is available from EPEL repo. apart from Gluster.org. There are quite a  lot of differences from how the package from EPEL works. The package from Gluster.org is purely command-line driven. The package from EPEL has a server and client package and honors the config files. Note that, you will have to ask it to load a config file by modifying the relevant glusterfs config file under /etc/sysconfig.
Apparently, there is a cookbook by mschueler, which sets up AFR (Automatic File Replication) across 2 storage servers. I haven't tested it though as it was completely ubuntu specific but still should work here.
I was testing AFR using client side replication and was able to make it work purely by config files.
I'm skeptical to use the package from EPEL as I read that Gluster is moving away from config file based configuration to completely command-line based confgiuration. ( I could be wrong on this and need confirmation ).
Comment: I set up the glusterfs using puppet manifest.
Comment: I'm pretty sure mscueler's cookbook is for Ubuntu 10.04 and an older version of Gluster that still relied heavily on config files.  It won't work with 3.2.x as far as I understand.

I'm on ubuntu, and probably will use a remote_file to get the deb package from Gluster and install 3.2.6 which is what they currently recommend for production projects.  Still not sure on how to do the configuration though
Answer: Any API/CLI/whatever for any package can ensure the consistency/validity of the generated configuration as changes are made, migrate configs across software updates, etc.  All of that gets thrown away when you generate the configuration files directly from external automation tools, so that should be a last resort generally and GlusterFS is no exception.  I had to do that for HekaFS but, even as someone in a position to influence GlusterFS changes that might break HekaFS-generated configurations, I still consider it an unfortunate necessity.
The configuration-file format itself is very simple.  I wrote a Python parser/generator for it in an hour or so.  Generating a correct set of configuration files, in terms of satisfying dependencies or layering constraints between translators, or setting all the necessary options, is a bit harder.  We also support live configuration changes without restarting daemons, and generating the RPC messages involved to notify them of config changes is all but impossible (not to mention insecure) outside of the current management infrastructure, so a chef-based approach based on rewriting config files would be demonstrably inferior to what's there already.
If there are things that need to be done to make chef integration with the CLI easier, by all means let me know via Bugzilla, email, IRC, whatever.  I'll be glad to help with that, but not with an approach that has been tried before and always caused massive breakage.
Comment: I'm sorry, not sure I understand your answer.  Are you saying that I should essentially write a cookbook that executes the CLI commands necessary to set up a distributed replicated volume every time chef is run, and that Gluster knows how to handle that correctly? (i.e. executing these commands multiple times is idempotent)
Comment: I don't know what kind of software you're used to dealing with, but I know of very few where **defining a new resource** is idempotent, and that's what "the CLI commands necessary to set up a distributed replicated volume" do.  Yes, your chef recipe will run on every node, and will have to detect/negotiate whether to create a new resource or attach to an existing one - just like any other distributed system that does its own coordination instead of **forcing** the user to distribute configs themselves (or automate themselves).
Comment: Ok, for now I'll guess I'll have to go down that road.  But it seems like there should be a better way.  It would be much better if Gluster either did that detection itself when running the CLI commands, or if you could declare in a configuration file how the volumes should be setup.  The old gluster only had 1 file required to do this on the server, and it was pretty self explanatory (see http://www.howtoforge.com/high-availability-storage-with-glusterfs-on-ubuntu-10.04-automatic-file-replication-mirror-across-two-storage-servers)

glusterfs configuration files and chef


Adicionar and e or em Where() de lista

Question: Tenho uma lista em C# e atualmente o código de busca está assim:
filter = lst.Where(s => s.Contains(num.Text) ).Take(3).ToList();

A lista lst se baseia em uma lista com números de telefones e nomes de contatos, exemplo:
123456789$nome1

987654321$nome2

Atualmente estou buscando pelo número, queria fazer um OR para poder buscar tambem pelo nome exemplo:
num.Text = 9;
nome.Text = "l";

Queria pegar os 3 primeiros itens da lista que tem o valor de nome.Text OU de num.Text
Comment: Alguma dificuldade específica? É igual a um ´if`` .
Comment: A `lst` possui campos do tipo Numérico ou Texto?
Comment: Tem muito tempo que não mexo com C#, hoje fui adicionar essa funcionalidade e não lembro de nada do método `Where`, a condição dele seria se `s` contem `num.Tex`t ou `nome.Text`
Comment: lst é uma lista de `string`
Answer: Pode fazer igual a um if:
filter = lst.Where(s => s.Contains(num.Text) || s.Contains(nome.Text)).Take(3).ToList();

Veja funcionando no ideone. E no .NET Fiddle. Também coloquei no GitHub para referência futura.
Isso fará para todos os itens da lista. Item por item, um de cada vez. Primeiro procurá por um critério, se achar, ótimo, se não achar, ele faz a busca no segundo critério, se achar ele retornará true e avançará pra o Take(3). Quando ele chegar no terceiro item que deu true ele não procurá mais nada. E esta é uma das belezas do LINQ, ele não perde tempo com o que não precisa mais (ajudado neste caso pelo mecanismo de short-circuit dos operadores relacionais.
Eventualmente pode ser feita otimizações, mas duvido que seja necessário na maioria dos casos
Answer: Use o operador or || dentro de seu where.
filter = lst.Where(s => s.Contains(num.Text) || s.Contains(nome.Text) ).Take(3).ToList();

Eis um exemplo que fiz no DotNet Fiddle https://dotnetfiddle.net/EYC2gF

Adicionar and e or em Where() de lista


A particular exercise on convergence of recursive sequence

Question: I am given a sequence defined by
$$
x_1=2 \ \text{and} \ x_{n+1}=x_n + \dfrac{1}{x_n} \ \text{for} \ n=1,2,\dots
$$
I want to show that it is strictly increasing and that $x_n \to +\infty$.
Attempt at a solution:
That it is strictly increasing, I sense I need to use induction. Namely, I want to show that for all $n$, $x_n <x_{n+1}$. This statement is true for $n=1$ and I assume it is true for $n=k$ and I need to show that this implies it is true for $k+1$. Having hit a brickwall with this attempt I need some guidance.
As far as $x_n\to +\infty$ is concerned,I need to show that it is not bounded. For if it is increasing and not bounded this would imply it diverges to infinity. Therefore I have to show that for all $M>0$ there exists a $\tilde{n}=\tilde{n}(M)$ such that $x_{\tilde{n}}>M$.
Is my understanding correct? Any hints on the proof would be welcome.
Answer: $x_{n+1}=x_n + \dfrac{1}{x_n}$ implies $x^2_{n+1}=x^2_n +2+ \dfrac{1}{x^2_n}>x^2_n +2$, so we can easily prove $x^2_n\ge2n+2$ by induction: it is true for $n=1$, because $x^2_1=4=2\cdot1+2$. If we know that it's true for $n$, i.e. $x^2_n\ge2n+2$, then $x^2_{n+1}>x^2_n+2\ge2n+2+2=2(n+1)+2$ (induction step).
 This means $x_n\ge\sqrt{2n+2}$, since $x_n>0$ (by induction, too). The inequality is strict, except for $n=1$, naturally.
Comment: @EEEB That was a typo, I've corrected it.
Comment: The last inequality $x_n \geq \sqrt{2n}$ should be strict, right?
Comment: How did you get $x_n^2 \geq 2n+2$? from the previous givens? I mean what was the thought process that lead you there?
Answer: The sequence is increasing. If it is bounded, it has a finite limit $\ell$. What can be the value of this $\ell$?


Garbage appears in vector after inserting result of operator

Question: I have an object with an operator defined like this:
P& operator +(const P &rhs) {
    return P(x + rhs.x, y + rhs.y, z + rhs.z);
}

It does not have custom copy or assignment operators.
After I assign directly the result of an addition inside the vector, garbage appears inside it.
P p1(1.0, 0.0, 0.0);
P p2(0.0, 0.0, 0.0);

vector
 v(1);
v[0] = p1 + p2; // v[0] now contains garbage.

If I do it through a variable, everything is as expected.
vector
 u(1);
P q = p1 + p2;
u[0] = q; // u[0] contains correct value.

What can be the reason for such behavior? What is the difference between the two cases?
Comment: "*It does not have copy or assignment operators.*" Do you mean that you didn't specifically define them (in which case the compiler is likely defining them implicitly)? Or that you went out of your way to disable them?
Comment: @ildjarn I meant to say that I did not specifically define them. Edited my question to make it clearer.
Comment: The difference is the second example read from the invalid/deleted temporary _before_ it was overwritten.  (Both are against the rules, the temporary is dead)
Answer: You return a reference to a temporary. This is a bad idea, since the temporary goes out of scope at the end of the function (in this case, the operator+ function). Declare your operator as:
P operator +(const P &rhs) const

instead.
Comment: @Artium : That's the nature of [undefined behavior](http://en.wikipedia.org/wiki/Undefined_behavior) -- sometimes it may _appear_ to work, but it's never correct.
Comment: That should be `P operator +(const P &rhs) const` -- as you have it, move semantics are inhibited.
Comment: I suspected that this is the issue, but why there is an problem only when I assign the result into a vector?
Comment: @Artium: Because the P is a local member of the `operator +` function, and was "deleted" as soon as the function ended.  If you then call another function, say, `insert`, then it will be erased with random data.
Answer: As you would see
P& operator +(const P &rhs)
{
    return P(x + rhs.x, y + rhs.y, z + rhs.z);
}

returns the reference to a local variable which is destroyed once out of scope of the function operator +.
You can return Pointer to the data created in heap but that would leave enough scope for Memory Leak if the caller fails to delete the object.
You can also return the object as a copy but that at times can be a real overhead
In recent C++11 use the move construct to transfer the ownership which should be the ideal and preferred approach going forward.
Comment: "*You can also return the object as a copy but that at times can be a real overhead*" Every modern compiler implements [RVO](http://en.wikipedia.org/wiki/Return_value_optimization).
Comment: @ildjarn: Seems I am bit outdated. :-)


Dagger 2 - Null Pointer in Field Injection

Question: I am using dagger 2 for dependency injection and got stuck with field injection. Below is the complete scenario with code sample:
Let's say we have a class A which depends on a library B
class A {
    @Inject
    B b;
}

Module for B:
@Module
public class BModule {

    @Provides
    @Singleton
    public B provideB() {
        return new C.methodA();
        // C - static class; C.methodA returns B

    }
}

But when I try to use b in class A then I get null pointer exception but if I do the same using constructor injection then it works perfectly.
I can assure that component and other dependencies are fine as the constructor part works correctly.
A is a dependency of some other class (let's call X) and A is being initialized using constructor injection (tested). Also, X is being injected as void inject(X x);
I have 2 questions:

Is there anything I am missing out for field injection due to which it is not being injected?
I am able to successfully compile the code and get runtime exception, but dagger2 is compile-time DI then why is it unable to catch this while compiling?

P.S.: I have just shared a part of the code as there are multiple dependencies, so just trying to explain the scenario. Let me know if the question/scenario is still unclear or needs more info.
Thanks.
Answer: Field injection in dagger is a bit more complicated than constructor injection. When you use constructor injection like this
class A {
    @Inject
    public A(B b) {}
}

and you have provider for class B
@Module
class DaggerModule {
    @Provides
    B provideB() {}
}

now dagger will know how to create instance of A and pass it required constructor parameter. So everything is fine, compile successfully and works perfect.
But if we speak about field injection
class A {
    @Inject
    B b;
}

and have somewhere provider for B, dagger can't know how to create A instance and when inject b property (in case of manually creating instance of A by hand). To make it work you need write special method in component
@Component(DaggetModule.class)
interface DaggerComponent {
    void inject(A a);
}

and somewhere in code
A a = new A();
DaggerComponent component = //TODO getDaggerComponent()
component.inject(a);

After that b property will be initialized and available for later usage. Hope, it's clear now how to make field injection work.
Comment: Thanks @ConstOrVar, I forgot to mention here that A is a dependency of some other class (let's call X) and A is being initialized correctly. Also, X is being initialized as you have suggested i.e. void inject(X x); I will update in the question as well.


Location errada com Chrome e Firefox

Question: Estou capturando o location de um elemento imagem. Quando busco pelo Phantom, traz as coordenadas X/Y corretas, porém se faço pelo Chrome ou pelo Firefox, ele dá outro location e aí não consigo pegar o conteúdo do elemento.
Veja abaixo as coordenadas do mesmo elemento, capturada com o Phantom e com o Chrome:
Coordenadas pelo Phantom:
X = 0x00000375
Y = 0x00000180
Coordenadas pelo Chrome:
X = 0x000003c1
Y = 0x00000184
Comment: nesses casos cada navegador vai ter a sua particularidade de posicionamento. Não sei a tua finalidade mas teria de capturar esse location diferente para cada navegador que estiver usando.
Comment: Não deveria ser. O element.location deve ser o mesmo, independente do browser, não é?
Todas as pesquisas que faço para obter o printscreen do elemento, a função é sempre a mesma. Então concluo que deveria ser igual.
Minha desconfiança é que a minha máquina tenha algum problema com relação ao posicionamento, pois quando rodo pelo Phantom, ele não tem GUI
Comment: Resolvi (parcialmente) rodando o Chrome e o Firefox em HEADLESS mode. Sendo assim não tem GUI e aí funciona perfeitamente.
Comment: Phantom é headless, por isso vai dar diferença.
Answer: Encontrei o problema: no computador que estou usando, o ajuste de escala e layout do vídeo estava em 125%, conforme recomendado.

Esta alteração fazia com que o driver capturasse as coordenadas desposicionadas e por isso funcionava em headless, já que não usava a GUI.
Voltei para 100% de exibição e funcionou perfeitamente.

Location errada com Chrome e Firefox


PCA and diagonalization of the covariance matrix

Question: I am preparing for an upcoming exam and having looked at older exams I found one PCA related question I am having trouble understanding:

You have a dataset of $N$ two-dimensional points $\ y^t $. You want to
  perform PCA on the dataset. You have already estimated that the data
  is zero-mean and has the covariance matrix
$$ S = \begin{bmatrix}10 & 6 \\ 6 & 10 \\\end{bmatrix}  $$
and you know that covariance matrix can be diagonalized as $\ C^TSC = D $, where
$$ C = \begin{bmatrix} 1/\sqrt{2} & -1/\sqrt{2} \\1/\sqrt{2} & 1/\sqrt{2} \end{bmatrix}  $$ $$ D = \begin{bmatrix}16 & 0 \\0 & 4\end{bmatrix}  $$

A) Explain how the matrices $C$ and $D$ are related to PCA?
B) In
  2-dimensional space, plot the PCA coordinates (direction of the largest
  and second largest variance of the data)
C) Define the principal
  components of the data by $z^t=C^Ty^t$. What is the covariance matrix
  of $z^t$?

I am having trouble understanding how to begin. Matrix $D$ seems to be a diagonalized $S$ (as the diagonal adds up to $20$) but how to perform any calculations on given data I have no clue. What computations should I perform in order to be able to plot the PCA coordinates?
Comment: This is a basic question on the mathematics of PCA. Have you studied any textbooks or tutorials on PCA? Do you know what an eigenvector and an eigenvalue is? Do you know how eigendecomposition is used in PCA?
Comment: @amoeba Basic questions are fine.  If you must question the motivation or background of people who ask them, then please make it clear you are not challenging them but only probing to learn how best to frame a good answer. The issue raised by basic questions, though, is that likely they already are answered here.  I recommend searching our site for related keywords such as "calculate" and "PCA".
Comment: @whuber: Thanks for your comment. I certainly did not mean to say that this question is inappropriate here, and I am sorry if my wording might have suggested it. My point was precisely to find out how much the OP already knows in order to try to give an adequate hint.
Comment: Sorry, you did not ping me (type `@amoeba` in your comment to ping), and I haven't noticed your reply before. Anyway, yes, I believe you are quite confused. Here is one [PCA tutorial](http://www.cs.otago.ac.nz/cosc453/student_tutorials/principal_components.pdf). It covers math that is really necessary to understand PCA on the first 11 pages; eigenvectors/values are explained on pages 9-11. I will try to make an answer with some hints later on, but in the meantime I would suggest you start reading this (or any other) tutorial...
Comment: @amoeba thank you for your views. My background is not in mathematics. All the examples I could find assume the knowledge of the subject on deeper level. Especially the study material I have at hand seems more like a course in Greek language.
Comment: :-) I, or somebody else here, would be happy to try to give you a hint, but please tell us if you know what an eigenvector/eigenvalue is.
Comment: Yes I believe I do. Eigenvector is a vector with length of one. It holds the direction of the vector it has been derived from. Am I completely lost?
Answer: This comes a bit late, but for any other people looking for a simple intuitive (non-mathematical) idea about PCA: one way to took at it is as follows:
if you have a straight line in 2D, let's say the line y = x. In order to figure out what's happening, you need to keep track of these two directions. However, if you draw it, you can see that actually, there isn't much happening in the direction 45 degrees pointing 'northwest' to 'southeast', and all the change happens in the direction perpendicular to that. This means you actually only need to keep track of one direction: along the line.
This is done by rotating your axes, so that you don't measure along x-direction and y-direction, but along combinations of them, call them x' and y'.
That is exactly encoded in the matrix transformation above: you can see it as a matrix transformation, but equivalently as a rotation of the direction in which you measure. Now I will refer you to maths literature, but do try to think of it as directions in which you measure.


How to display rows based on similar cell values but different specific value in Excel?

Question: I have a spreadsheet in excel populated with a column for direction (from and to), a column with train names, and another column for the destination the are coming from and going to. What I would like to do is figure out how to print specific rows on Sheet 2 that have the same train name but are going to and from different places. The following is an example of the spreadsheets I have:

Sheet 1
Direction         Train Name       Destination Name

From               Acadian          Miami
To                 Acadian          Miami
From               Baynes           Miami
To                 Baynes           Orlando
From               Burns            Atlanta
To                 Burns            Atlanta
From               QCRoads          Atlanta
To                 QCRoads          Atlanta
From               Jones            Jackson
To                 Jones            Jackson
From               Cardinal         Nashville
To                 Cardinal         Cleveland
From               Chase            Cleveland
To                 Chase            Cleveland
From               Daniels          Cinncinati
To                 Daniels          Pittsburgh
From               Gathers          Los Angeles
To                 Gathers          San Diego

Sheet 2 (Example of Expected Result)
Direction         Train Name       Destination Name
From              Baynes           Miami
To                Baynes           Orlando
From               Cardinal         Nashville
To                 Cardinal         Cleveland
From               Daniels          Cinncinati
To                 Daniels          Pittsburgh
From               Gathers          Los Angeles
To                 Gathers          San Diego

Comment: Your requirements are not clear...
Comment: There are about 10,000 lines more than what it shown here, but I would like to display on Sheet 2 the rows that have the same train name but different destinations. So I was hoping for an example of a for loop to do this
Comment: @user3870159 could you extend your expected result columns (more examples) please
Comment: @pnuts The spreadsheet has too many lines (13,000) to do copy and paste
Comment: @MaciejLos I've edited the question. Please let me know if its still not clear
Comment: So, if a specific Train/Destination pair (ignoring Direction) exists on more than one row, then do not include that row in the results, but include everything else. Is that what you're aiming for?
Comment: @Joe yes, on Sheet 2 I want to only have the ones with the same train name but different destination names
Answer: So you can do this very simply in several steps:
in a helper column, i.e. column D, put down this formula to see if the row is duplicate or not:
=COUNTIFS($B:$B,$B1,$C:$C,$C1)>1

 then copy and drag and fill down until the end (the last row that contains your data);
then you will see TRUE and FALSE in front of each row: TRUE means the row is duplicate (according to your own rules) and FALSE means the row is not a duplicate.

Then, press ctrl+F to find all TRUE values in your sheet; then click on FIND ALL and it will list the cells found below the find window. Then click on the first row of the results and then hold the shift and click on the last row of the results. It will highlight the TRUE cells in your sheet.
 Then, click on DELETE CELLS... and then in the delete pop-up window select Entire row. Bingo!


Initialize Java CDI Without Weld?

Question: If I understand it correctly, Java CDI should be independent of Weld. But all examples I see use Weld to initialize the container.
I am trying to use CDI without Weld because while I'd like to use DI, I'm very limited on memory.
Here is an example of my LoggerFactory-
@ApplicationScoped
public class LoggerFactory {

    @Produces
    @Singleton
    public Logger getLogger() {
        return LogManager.getLogger("com.myapp");
    }

}

And my trying to fetch it in Main-
Logger logger = CDI.current().select(Logger.class).get();

When I do this I get Unable to locate CDIProvider.
Is it possible to use CDI without additional libraries? How can I get my Logger in this instance?
Answer: CDI is a Java EE specification. It specifies how things should be done but itself provides not functionality.
Weld is the reference implementation of the CDI spec. An alternative implementation of the CDI is for example Apache OpenWebBeans. Either of these implementations will be able to give you the features of CDI.
Weld provides an extension which will boot a CDI bean manager in Java SE:
https://docs.jboss.org/weld/reference/latest/en-US/html/environments.html#weld-se
But be careful because due to my experience Weld SE consumes a lot of memory and needs some time to scan the class-path for (bigger) SE-Applications.
Comment: That makes sense. Thank you
Answer: Actually, CDI from version 2.0 onwards has a standard way to start a CDI container without requiring an application server.
final SeContainerInitializer initializer = SeContainerInitializer.newInstance();
// You can call various configuration methods on the initializer, including
// disableDiscovery(), which turns off all scanning behavior if that's a problem.
// You can programmatically add beans, extensions, etc.
try (final SeContainer container = initializer.initialize()) {
  assert container != null;
  // container is also an Instance<Object> so you can select() with it
}

Initialize Java CDI Without Weld?


CISCO PAT 2 different outside ports, on one ip-address, to 1 inside port on one ip-address

Question: I have a problem with our new corporate CISCO ASA5510 firewall. With our old firewall it was possible to do the following PAT:

outside     -> inside
18.104.22.168:22  -> 192.168.1.2:22
188.8.131.52:443 -> 192.168.1.2:22

How can I do the same on the CISCO box? I need this because of another firewall (not under my control) that don't allow anything out on port 22.
Yours
Rune Henssel
Answer: Unless I am missing something, you should just be able to use static nat rules:
<code>
static (inside,outside) tcp 188.8.131.52 22 192.168.1.2 22 netmask 255.255.255.255
static (inside,outside) tcp 22.214.171.124 443 192.168.1.2 22 netmask 255.255.255.255
</code>
Comment: That just gives me an this: static (inside,outside) tcp 126.96.36.199 22 192.168.1.2 22 netmask 255.255.25 ^5.255
ERROR: % Invalid input detected at '^' marker.


VS2017 Unable to start debugging. Could not load file or assembly

Question: Working with xamarin forms, I have recently updated my android version from 7.1 to 8.1 (even though I don't understand why this might have messed up anything) but I can't run the app anymore in debug mode (it compiles and runs perfectly in release).
Here is the error that I am getting:

Unable to start debugging. Could not load file or assembly 'libadb,
  Version=18.104.22.168, Culture=neutral, PublicKeyToken=___' or one of its
  dependencies. The system cannot find the file specified.

Any idea why this might be happening? I have tried looking for online solutions but couldn't find any that fits my problem. Any help would be greatly appreciated!
Comment: Looks like libabd is a dependency that is missing.  Something might have went wrong in the upgrade process.

Can you search your computer for libabd.dll?  If its only in debug mode, I would guess that libabd opens some kind of debug tunnel.
Comment: It seems that one of the dependencies (libabd) was not referenced properly in your project. At some point VS was able to find it and copy it to the bin folders, but it can no longer find it. It seems that the release bin folder still has it, so it run properly there, but perhaps somebody cleaned the debug bin folder so it no longer has it. As a temporary measure, you can copy the libadb file(s) from the release bin folder to the debug bin folder. But you need to find the library and reference it correctly.
Comment: Right now I'm feeling it is because Xamarin is a bad platform and we should never use it. But I have to make it work so I will let you know if I find anything.
Answer: In my case, after also upgrading from 7.1 to 8.1 my settings were changed, apparently. So the fix was easy. Go to the android project, make sure your debugger is set to Xamarin, not C++ in debug mode. I am not sure why it was changed.

Hope it helps.


Projection in OpenGl (bug with z-axis)

Question: I don't know why but it seems my z-axis is bugged (it seems it is doubling the value or something)
This is supposed to be a cube
https://scontent-mad1-1.xx.fbcdn.net/hphotos-xtp1/v/t34.0-12/11998230_879538255460372_61658668_n.jpg?oh=dd08fee0a66e37bf8f3aae2fba107fa1&oe=55F6170C
However it seems like it is "bigger in depth" what seems wrong
My pr_Matrix:
    mat4 mat4::prespective(float fov, float aspectRatio, float near, float far){
        mat4 result;

        float yScale = 1.0f / tan(toRadians(fov/2.0f));
        float xScale = yScale / aspectRatio;

        float frustumLength = far - near;

        result.elements[0 + 0 * 4] = xScale;
        result.elements[1 + 1 * 4] = yScale;
        result.elements[2 + 2 * 4] = -(far + near) / frustumLength;
        result.elements[3 + 2 * 4] = -1.0f;
        result.elements[2 + 3 * 4] = -(2.0f * far * near) / frustumLength;

        return result;
    }

My ml_Matrix:
        maths::mat4 &ProjectionMatrix(){

            maths::mat4 m_ProjM = maths::mat4::identity();

            m_ProjM *= maths::mat4::translation(m_Position);

            m_ProjM *= maths::mat4::rotation(m_Rotation.x, maths::vec3(1, 0, 0));
            m_ProjM *= maths::mat4::rotation(m_Rotation.y, maths::vec3(0, 1, 0));
            m_ProjM *= maths::mat4::rotation(m_Rotation.z, maths::vec3(0, 0, 1));

            maths::mat4 scale_matrix = maths::mat4(m_Scale);
            scale_matrix.elements[3 + 3 * 4] = 1.0f;

            m_ProjM *= scale_matrix;
            return m_ProjM;
        }

My vw_matrix (camera)
        void update(){
            maths::mat4 newMatrix = maths::mat4::identity();
            newMatrix *= maths::mat4::rotation(m_Pitch, maths::vec3(1, 0, 0));
            newMatrix *= maths::mat4::rotation(m_Yaw, maths::vec3(0, 1, 0));
            newMatrix *= maths::mat4::translation(maths::vec3(-m_Pos.x, -m_Pos.y, -m_Pos.z));
            m_ViewMatrix = newMatrix;
        }

My Matrix Multiplication in the glsl code:
vec4 worldPosition = ml_matrix * vec4(position, 1.0);
vec4 positionRelativeToCamera = vw_matrix * worldPosition;
gl_Position = pr_matrix * positionRelativeToCamera;

Edit: I think I got it! (Will double check maths once I get time) Most tutorials(so, the source of my code) use a mat4::prespective(float fov, float aspectRatio, float near, float far), the thing they don't say is that "fov" means "fovy" (so "vertical field of view"), the results seem to replicate the "usual fov in games" now with this simple change:
        float xScale = 1.0f / tan(toRadians(fov/2.0f));
        float yScale = xScale * aspectRatio;

Thanks for pointing it out as a fov problem Henk De Boer
Comment: What do you pass as "fov" in the prespective function.
Comment: This is my function call "mat4 proj = mat4::prespective(80.0f, 16.0f/9.0f, 0.1f, 100.0f);" so 80.0f
Comment: Try putting that to something lower, should help. Say 45-60.
Comment: That seems very good, thanks. But is this the same "fov slider" we see in games? Because 45-60 seems pretty low if it is
Comment: Yes it is, but you will find that once you have an actual scene, the results of 80 fov may not be as drastic as it looks with just the cube. Also, to add to the confusion, some games advertise the fov as 2*therealfov, so when they say that the fov is 90, it's really 45. I've posted this as an answer.
Comment: Check my edit, I think I found the "real problem" (it wasn't really a problem since you pointed me to fov, but it "explains the numbers)
Comment: To be honest I never even thought about swapping the two to be able to use horizontal FOV. I've always just tinkered with the values till it looked good :) GJ
Answer: This is simply a result of FOV, the FOV you supply greatly alters the way an image looks. It's a matter of personal taste what you choose. To get a natural feeling scene anything between 45-60 is good, but you can enhance this to make the scene feel more immediate or the action more fast paced. Observe how the following image has twice the exact same geometry, but the dock to the right is protruding much further in to the viewport with a 90 degree FOV.
Comment: Thanks a lot for the example and for giving me a solution!
Comment: Oh, I tried to mark it as useful but still can't, didn't even notice that, thanks again :)
Answer: My guess would be that in declaring:
mat4 result;

You're invoking a default constructor that's initialising the matrix to identity.
Then in the subsequent code that sets up the matrix, you need a call to:
result.elements[3 + 3 * 4] = 0.0f;

Also, for what it's worth, in my code the lines:
result.elements[3 + 2 * 4] = -1.0f;
result.elements[2 + 3 * 4] = -(2.0f * far * near) / frustumLength;

Are not negated. TBH, I'm not sure if that's anything to worry about.
Comment: My mat4 constructor puts every element to 0 (unless i put a float as parameter, then everything is 0 except every element of the diagonal that becomes that float) so I don't need to call "result.elements[3 + 3 * 4] = 0.0f;".  I trying to play with those "-" but It only worked this way

Projection in OpenGl (bug with z-axis)


How to populate google map with multiple markers from JPA database

Question: I have a JPA data object from a table that includes longitude, latitude, location name among other data. I need to display multiple google map markers on a JSF webpage. I will be very grateful for a solution, a working sample will be very nice. Alternatively, a JSF managed bean method sample to help me solve this will be good.
Comment: 1) What have you tried? What is the **concrete** issue you are having?
Comment: 2) Do not mix questions: It is a question about JPA? About JSF? About Google Maps?
Answer: YOu could read them into in a array and then use the answer here. But there is a better demo here (JSF) and here
this blog deals with jpa https://blogs.oracle.com/alexismp/entry/mashup_explanation_part_i
also i found a very good code sample for jsf


CakePHP how validate radio buttons?

Question: How to validate CakePHP radio buttons?
Doesn't work inList rule and notEmpty...
$this->data return good content
Comment: You need to show more code, at least the validation rule and preferably the part of the form where you create the radio buttons.
Answer: As @Juhana mentioned in the comments, it's helpful if you're more specific.
Typically, however, something like this should work:
In your model:
var $validate = array(
    'radioField' => array(
        'rule' => 'notEmpty'
     )
);

In your view:
echo $this->Form->input('radioField', array(
    'type' => 'radio',
    'options' => array('foo', 'bar')
    )
);

Alternatively you can use the radio-specific method in your view:
echo $this->Form->radio('radioField', array('foo', 'bar'));

But then you must include the following line in order to display the error:
echo $this->Form->error('radioField');

CakePHP how validate radio buttons?


sudden peak in cpu usage

Question: We are running a 4 node/machine elastic search cluster on 12 core, 96gb RAM, 4 spinning disk machines. under normal operation most cpu usage is user and around 5-10%. Every few days, one of the machine's cpu usage gets pegged at 80-100% and is all user and system -- io wait actually decreases. We first thought it was an elasticsearch specific issue, but after extensive debugging it doesn't seem to be so:

the high cpu utilization survives an elasticsearch node process restart
the elasticsearch threads are all behaving normally, things just take 10x longer.
non elasticsearch operations (gc collection) also take 10x longer, but heap activity is normal

If we stop the process for about an hour and then restart the process only (not the machine) the problem goes away and things work fine for a few days.
We have also noticed that during the problem, disk copy tests are very slow. With the process up but idle (not indexing/searching data) or soon after the process has stopped, copying a 1GB file via dd happens at about 18MB/s on the problematic machine but at 490MB/s when healthy. Interestingly, we noticed using dstat that the slow copy took about 25 seconds before doing any i/o and then took an additional 30 seconds to complete. The strace output didn't seem to be significantly different.
Any idea what further tests we could run?
Comment: are you sure it is CPU? not say disk i/O ? do you have enough memory?
Comment: our monitoring tools show predominately user cpu usage. i/o actually decreases a bit, probably because the machine becomes so loaded. the machines have plenty of memory, 96GB of physical memory with elasticsearch using 32GB max. we set the mlockall option in elasticsearch so it won't swap.
Comment: You never explicitly said that it is the elasticsearch processes using the CPU when usage spikes. Is it them?
Comment: sorry, yes it's the elasticsearch process taking the cpu, however after a lot of analysis, the operations it's doing are quite normal -- they just seem to take a lot of resources to complete. The hot threads output shows no discernible pattern, which meshes with our thinking that it's not an elasticsearch issue.
Answer: There are lot of issues going around with Elastic Search and by quick googling you can find some. But major problem in high cpu usage might be caused due to lack of control on cache usage. Please below for references :
https://github.com/elasticsearch/elasticsearch/issues/4288
http://elasticsearch-users.115913.n3.nabble.com/Very-high-sys-cpu-usage-with-HTTP-KeepAlive-td4049998.html
http://blog.sematext.com/2012/05/17/elasticsearch-cache-usage/
Comment: it's not an elasticsearch related issue. we have even disabled queries so the cache is not a factor.
Answer: Processes using a lot of CPU should show up in atop as suggested by Ian Macintosh, but because it's based on sampling the process table on a regular cycle, that visibility can be dependent on how long those processes run for.
The GNU accounting utilities can also be very useful for this sort of thing.  (package = 'acct' on debian based systems, or 'psacct' on redhat based ones).  I routinely run atop and the have the accounting package on (accton on) for most servers.
After you enable the accounting data collection, stats are kept about the CPU usage of every process that runs, along wqith when it started and finished its run.  This can be very useful when a bunch of short lived processes are consuming your cpu, which is hard to see with atop, strace, etc, (though strace may be more helpful with the -f or -ff flag).  It's less useful when you have processes with a lifetime much longer than the CPU spike, but in those cases atop should give you what you want.  lastcomm is probably the tool you want for accessing the collected statistics.
while very useful, strace only tells you about system calls.  If you have something using cpu intensively, but not calling the system, it won't show up.  Sometimes ltrace can be useful for this, but again, only if the relevant activity occurs within a library call, and that's not always the case.
Tools like strace and ltrace, and perhaps even a debugger like gdb only come into play once you've identified the process that's consuming the CPU, and it doesn't sound like you've got that yet.  At this point, atop and lastcomm are probably the way to go.
Answer: What further tests could you run?
(Missing some info like what system CPU % is when pegged vs user CPU %) but check what percentage of CPU is IRQ, just in case that leads somewhere.
Assuming the system CPU % is fairly high and it's not IRQ's, you might want to check memory. A handy tool for an overview is atop, it should tell you if something like page scans or page steals is causing it because you're under heavy memory pressure.
I'm going to assume you've excluded swapping as being an issue.
Because atop gives you quite a comprehensive overview of the machine state it's very handy in getting a handle on the overall state. It would help comparing atop on a properly operating system vs one that's misbehaving as well.
If the only abnormality is user CPU % and the system itself is operating correctly otherwise then you're likely dealing with a software bug and will have to revert to the authors for help - or change the way you're using it to avoid triggering whatever bug you've found. Just check that you're not dealing with your own bug - ie, you're calling it badly or in a loop or something of that nature. I've seen that a few times.
In summary, dig into memory, irq, swap etc and see if you can exclude those - I suggest atop for a quick comparison between normal behaviour & aberant behaviour and to highlight critical items.

sudden peak in cpu usage


How to get the content of a node with Devel Path?

Question: I am quite new to Drupal an would like to get the Data of a Node. With the Devel module I read out the Path to the information I like get with PHP.
$var->location['postal_code']

How can I access this path? I would like to get this info an pass to Javascript. So I think I have to access this path with PHP and then use drupal_add_js to pass it to JS. But I don`t even know where to put the PHP code.
Any suggestion?
Comment: sorry, Drupal 7.
Answer: If your main goal is to expose a piece of data to JavaScript, you can use drupal_add_js() to add a "setting". Here is the example from api.drupal.org:
drupal_add_js(array('myModule' => array('key' => 'value')), 'setting');

(https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_add_js/7.x)
That then becomes available in the frontend in the Javascript variable: Drupal.settings.myModule.key.
Now, the question is WHERE do you put that call to drupal_add_js? That depends on exactly what data you want to expose, and when you want to expose it, but in general you would create a custom module and implement a Drupal hook that runs drupal_add_js at a specific point in the Drupal pageload life cycle.
If, as it sounds from your question, you want to add node information to a node's "view" page (ie: on the /node/1 path), one option is to implement hook_node_view() in a module called mymodule like so:
/**
 * Implements hook_node_view().
 */
function mymodule_node_view($node, $view_mode, $langcode) {

  // If the node contains the field we want, add it to a JS setting.
  if (!empty($node->location['postal_code'])) {
    drupal_add_js(array('mymodule' => array('postal_code' => $node->location['postal_code'])), 'setting');
  }
}

Here is the documentation for that hook: https://api.drupal.org/api/drupal/modules%21node%21node.api.php/function/hook_node_view/7.x
That's just one way to do it. There are lots of other hooks where this could be done, again: depending on when and where you want it to.
Comment: Thanks a lot. I managed to get my data in template.php with
function mytheme_preprocess_node(&$variables) {
 $node = $variables['node'];
 $x = $variables['location']['postal_code'];
}
but in JS a get a ReferenceError that myvar is not defined.
If I am building a custom module, is it possible that its only active for special content types?
My site has a clean URL, no /node/.  On that site, I have the actual node content from which I get the postal code. and a view block, where I filter the content with postal_code. there is another block with js content, where the postal_code is used


Why (and when) does one have to learn the reward function from samples in reinforcement learning?

Question: In reinforcement learning we have a reward function that informs the agent how well its current actions and states are doing. In a some what general setting the reward function is a function of three variables:

Current state $S$
Current action at current state $\pi(s) = a$
Next state $S'$

So it looks something like:
$$R(S, a, S')$$
What my question is (which is probably my misunderstanding), normally the person using reinforcement learning decides what is the reward. For example, it assigns 1000 points for reaching the goal, or assings -1000 points for crashing the autonomous robot. In these scenarios, its not clear to me why we would need samples to learn R. R is a priori specified and then we use our agent. Right? However, I know I am wrong because in Andrew Ng's notes he says:

Where he says that we don't know the reward function explicitly. That seems bizarre to me. I know I am wrong and I'd love if someone could clarify to me in what scenarios do we actually have to learn R from samples?
(obviously, the transition probabilities have to be learned because one does not know how the environment will make our agent move a priori).
Answer: In his notes, when you must "estimate them from data", he does not mean the reward function.  You rarely estimate the reward function.  You typically learn the value function, which estimates the immediate reward plus the temporally-discounted future reward  (if the temporal discount is zero, then you are estimating the rewards).  Or, you can learn Q values, which are values associated with state-action pairs.
In summary, the reward function and the true transition function is defined by the environment.  The agent learns things like the transition function,  Q values, and the value function.
Comment: Note also that sometimes we do want to learn the reward function (Inverse Reinforcement Learning)
Answer: I agree with the other answers that usually, the reward function is not learned directly.
The transition probabilities also don't have to be learned. The agent can learn directly the action values, or even directly the policy, with policy gradien method for instance.
There are, however techniques for which the reward and the transition probabilities have to be learned. For example, the dyna-Q algorithm (described in Sutton & Barto) maintains a model of the environment. At each time step, the agent uses the reward and state information received from the environment to update the action-values, just like in Q-learning for instance.
But it also update its own model of the environment, and then performs N other action-values updates based on that model. The supposition is that the acting->sensing loop takes some non-null time, time that we can put to good use by improving the action-values with simulated samples.
Answer: This is a good question which is deeper than any imprecise wording in Andrew's notes. It is true that in RL you generally do not need to learn a reward function R(S,A,S'); you need to specify it as part of the problem setup. BUT, there are algorithms (in my experience associated with the afterstate or post-decision state value function) which require the expected reward r(S,A) = E[R(S,A,S')|S,A]. Generally the texts I've seen make little comment on this and assume that r(s,a) is known just as R(S,A,S') is known. But in some cases the reward is dependent on the future state so, without a model, you need to learn this expectation. I am currently working on such a problem where the expected reward function as well as the value function need to be learned. Note that most RL algorithms do NOT require the expected reward function, but some do. See for example the discussion on pg 58 in Algorithms for Reinforcement Learning by Szepesvari.
In summary you do not need to learn the reward function, but when working with post-decision state variables, you may need to learn the expected reward function. This is the only case that I am aware of where you need to learn an expected reward function, but I'd be interested to hear of other cases.
Answer: In reinforcement learning, the agent learns the value function, not the reward function. The value of an action is it's overall utility; for example, an action may bring a high reward, but lead to low-value states, making it low-value.
What the quote says is that sometimes the world is complicated: some problems have state-action spaces that are too large to enumerate, so we don't have explicit transition probability and reward functions. In such a case the agent would have to learn some generalization of the true value function.
Answer: I think those notes are slightly confusing. The rewards should be designed by you to encourage your RL agent to optimise the behaviour you want to see. The transitions between states are given by the enviroment and will often be estimated from data. I think what Andrew is refering to is a situation where from state A you could transition to state B which you give reward x or state C which you give reward y. If states B and C are identical except for the differences in reward, you would often eliminate states B and C and give state A a reward estimated from data which shows how often you transition to B or C from A.


Looking for good introductory treatment of meta-analysis

Question: A (non-statistician) colleague has been encountering meta-analyses in papers he reviews for medical journals and is looking for a good introductory level treatment so he can educate himself.  Any recommendations?  Favorites?  Books, monographs, nontechnical survey articles would all be fine.
(Yes, he's familiar with the Wikipedia entry and other stuff readily accessible by a Google search, such as Jerry Dallal's nice little article.)
Comment: @Nick Thanks for jumping in. However, you--and all other readers who chance across these comments--might like to know ilhan is not really concerned about this issue but is only using it to widen a personal attack being carried out at http://meta.stats.stackexchange.com/q/2064 and in comments at http://stats.stackexchange.com/q/99376. Because it has become evident that I--as the moderator who voted to close his question--lack any power of persuasion in this matter, I am standing aside and trusting that time and gentle advice from this community will soothe whatever feelings may have been hurt.
Comment: http://stats.stackexchange.com/questions/how-to-ask "avoid asking for opinions or open-ended discussion" see, I can find you are doing similar thing or not following the rules.
Comment: @ilhan: therefore you (and presumably everyone else, in the name of "fairness") should be allowed to break them?
Comment: Thank you @shane for creating the meta-analysis tag: I wanted to but couldn't.
Comment: Thank you @propofol and @Jeromy Anglim for your excellent contributions: after skimming DeCoster and looking over the Amazon reviews of the books, I have passed them all along to my colleague.  It is a real shame one cannot checkmark multiple answers; in this case I literally flipped a coin: tails, it went to propofol.
Comment: @NickStauner, no, but he can go back and close his question. Or you can close. Since this an "opinion question".
Comment: "Answers to this question will tend to be almost entirely based on opinions, rather than facts, references, or specific expertise," is false, so it is not off-topic, and I have voted to invalidate your flag.
Answer: I have two suggestions:

Systematic Reviews in Health Care: Meta-Analysis in Context (Amazon link)
Introduction to Meta-Analysis (Statistics in Practice) (Amazon link)

Both books are very good, including introductory information as well as detailed information about how to actually perform meta-analyses.
Comment: I liked Systematic Reviews in Health Care, though I found it - as I often do with books with a clinical focus, that it was both needlessly critical of observational studies, and a bit blind to the weaknesses of poorly run clinical trials. It was helpful, but it requires some adaptation to be useful outside the RCT world.
Answer: I'll add an independent recommendation for Jeromy's blog post, and second the suggestions of James DeCoster's notes and the Borenstein textbook (propofols' no. 2).
At risk of indulging in self-promotion, I recently published a methods paper entitled Getting Started with Meta-analysis.  It's aimed at ecologists and evolutionary biologists, so the examples are taken from these fields, but I hope it will be useful for those working in other areas.
Answer: I wrote a post a while back on getting started with meta analysis with:
(a) tips on getting started,
(b) links to online introductory texts,
and (c) links to free software for meta analysis.
Specifically, you might want to read James DeCoster's notes.
Answer: Fredric M. Wolf's little green Sage book is worth the $18 or so.  "Pleasantly mathematical" but not too technical, not too dogmatic either (it's a fiercely contested field, you probably know), good for a person with what I'd call intermediate-level stats/research experience.


Agrupar repetições continuas com MySQL

Question: Queria saber se há alguma forma de agrupar repetições usando somente MySQL.
Se fizer um SELECT * from tabela WHERE id_usuario = 1 ORDER BY id ASC retornará:
id | id_usuario | Data       | Texto
0  | 1          | 2016-10-16 | Sua senha foi alterada
1  | 1          | 2016-10-17 | Sua senha foi alterada
2  | 1          | 2016-10-18 | Sua senha foi alterada
3  | 1          | 2016-10-19 | Sua chave de 2FA foi alterada
4  | 1          | 2016-10-19 | Sua chave de 2FA foi alterada
5  | 1          | 2016-10-20 | Seu acesso foi revogado
6  | 1          | 2016-10-20 | Sua senha foi alterada
7  | 1          | 2016-10-20 | Sua chave de 2FA foi alterada

Gostaria que houvesse alguma função que retornasse exatamente:
id | id_usuario | Data       | Repetição | Texto
2  | 1          | 2016-10-18 | 3         | Sua senha foi alterada
4  | 1          | 2016-10-19 | 2         | Sua chave de 2FA foi alterada
5  | 1          | 2016-10-20 | 1         | Seu acesso foi revogado
6  | 1          | 2016-10-20 | 1         | Sua senha foi alterada
7  | 1          | 2016-10-20 | 1         | Sua chave de 2FA foi alterada

Desta forma removendo as repetições e retornando o número de repetições em "Repetição", que poderia ser gerado como num count(id) as Repetição, isso iria permitir informar que houve mais uma notificação do mesmo tipo e teria como expandir para ver as notificações duplicadas, fazendo uma nova requisição.
Answer: Use COUNT(), DISTINCT e GROUP BY.
Exemplo:

SELECT id, id_usuario, Data, COUNT(DISTINCT Texto) AS Repeticao, Texto from tabela WHERE id_usuario = 1 GROUP BY id ASC
Comment: Isso irá agrupar tudo e não apenas por repetição. Imagine isto: 1 1 2 1, que cada número seja uma linha. No seu caso resultaria em 3 e 1. Logo, 3 x "1" e 1 x "2"O que eu desejaria seria: 2 x "1", 1 x "2", 1 x "1", sendo então a contagem de 2 1 1. Porque possui 2 vezes o "1" e então é interrompido por um "2" e depois existe um novo "1".
Comment: Troquei o ORDER BY por GROUP BY, assim vai agrupar pelos ids que você quer.

Agrupar repetições continuas com MySQL


Universal add to bookmarks script?

Question: Does anyone know of a script that I can use to automatically add a site to favourites upon clicking of a link for multiple browsers? Atleast Firefox, IE, Chrome would be good.
If not, is there a way I can simulate ctrl+D through Javascript as I know that keystroke adds a site to bookmark in most browsers?
Answer: A universal script for adding to bookmarks doesn't exists, because not all browsers expose an API for creating bookmarks. Generally, only IE exposes a direct API for this. Both Opera and Firefox offer a possibility to add a site to bookmarks that will be opened in the sidebar and that is a huge difference. Safari and Chrome also don't expose any API for this task.
Some more info on this topic
Answer: I use a small script to attempt adding a bookmark using the most popular window methods, until all have failed. Then it just prompts the user to manually add their bookmark...
Like others have said (above) some browsers prohibit script-activated bookmarking, and because of security they want only users to add bookmarks.
It is not perfect, but it is simple and works well.
function addBookmark()
{
    var success=false;

    // try each until all fail...
    try {
        window.external.AddFavorite(window.location, document.title);
        success=true;
   } catch(e) {}

    try {
        window.sidebar.addPanel(document.title,location.href,'');
        success=true;
    } catch(e) {}

    if(!success)
    {
        alert("AUTO BOOKMKARING not supported\r\nIn your current browser.\r\n\r\nPress CTRL+D, or CMD+D\r\nto manually bookmark this page.");
    }
}

Answer: You can check out this jquery plugin if you are using that or just look at their source if you want to use your own. Though he mentions on his compatibility that Safari and Chrome do not expose this functionality in their API.
http://www.dummwiam.com/jFav
Answer: See digitalinspiration.
1st Google result for javascript bookmark.
Answer: In internet explorer it works with:
window.external.AddFavorite(document.location,document.title);
in firefox and in opera with:
Some link name

I haven't found a solution for safari / chrome yet.

Universal add to bookmarks script?


Eclipse PDE: Programmatically detect opened dialog and close it

Question: On Eclipse Luna, I select a server and click the Start button on Servers view, then the server (for example Tomcat8) will get started. If something is wrong during the start-up process, a dialog will be populated to display the error messages (for example time-out). The dialog is modeless in this test case.
Now I need to start the server programmatically from a plugin. In case that errors occur, how could I programmatically detect that a dialog has been opened and how to close it?
Answer: You could use the Display.addFilter method to listen for all SWT.Activate events which will tell you about all Shells (and other things) being activated. You can then detect the shells you want to close.
Something like:
Display.getDefault().addFilter(SWT.Activate, new Listener()
  {
    @Override
    public void handleEvent(final Event event)
    {
      // Is this a Shell being activated?

      if (event.widget instanceof Shell)
       {
         final Shell shell = (Shell)event.widget;

         // Look at the shell title to see if it is the one we want

         if ("About".equals(shell.getText()))
          {
            // Close the shell after it has finished initializing

            Display.getDefault().asyncExec(new Runnable()
             {
               @Override
               public void run()
               {
                 shell.close();
               }
             });
          }
       }
    }
  });

which closes a dialog called 'About'.
In more recent versions of Java the above can be simplified to:
Display.getDefault().addFilter(SWT.Activate, event ->
  {
    // Is this a Shell being activated?

    if (event.widget instanceof Shell shell)
     {
       // Look at the shell title to see if it is the one we want

       if ("About".equals(shell.getText()))
        {
          // Close the shell after it has finished initializing

          Display.getDefault().asyncExec(shell::close);
        }
     }
  });

This uses Java 8 lambdas and method references and Java 16 instanceof type patterns.


How to evaluate the series $\sum_{n=1}^\infty \frac{1}{F_{4n}}$? Where $F_1=1$, $F_2=1$ and $F_n=F_{n-1}+F_{n-2}$

Question: How would I go about evaluating the following series: $$\sum_{n=1}^\infty \frac{1}{F_{4n}}$$
Where $F_1=1$, $F_2=1$ and $F_n=F_{n-1}+F_{n-2}$ for $n \ge 3$
Not sure how to go about this except maybe by using the close form for the nth fibonacci number, but that seems like way too much arithmetic. Any ideas?
Comment: Is there a reason to believe it has a closed form?
Comment: It is hard to explain in comment, but I think [this paper of Melham and Shannon](https://pdfs.semanticscholar.org/a7df/685ac585881cfca7ba9176ddbe080490a6c5.pdf) may be helpful for you. See the formula 2.9
Comment: Tough question could we know the source, or inspiration?
Comment: Mathematica says $0.389083$.
Comment: @runway44 Yes, there is a closed form, if you allow some special functions. See my answer.
Answer: If you allow what Mathworld calls $q$-polygamma functions, there is a closed form for the series. We start by writing the closed form of $F_{4n}$:
$$F_{4n}=\frac{(7+3\sqrt5)^n-(7-3\sqrt5)^n}{2^n\sqrt5}$$
Thus the series becomes
$$S=\sum_{n=1}^\infty\frac{2^n\sqrt5}{(7+3\sqrt5)^n-(7-3\sqrt5)^n}$$
$$=\sqrt5\sum_{n=1}^\infty\frac{\left(\frac2{7-3\sqrt5}\right)^n}{\left(\frac{7+3\sqrt5}{7-3\sqrt5}\right)^n-1}$$
Define $\alpha=\frac2{7-3\sqrt5}$, then notice that
$$\alpha^2=\frac{7+3\sqrt5}{7-3\sqrt5}$$
Thus we can write
$$S=\sqrt5\sum_{n=1}^\infty\frac{\alpha^n}{\alpha^{2n}-1}$$
$$=\sqrt5\sum_{n=1}^\infty\left(\frac1{\alpha^n-1}-\frac1{\alpha^{2n}-1}\right)$$
Now define $\beta=\frac1\alpha=\frac{7-3\sqrt5}2$, and use the $q$-polygamma relation
$$\sum_{n=1}^\infty\frac1{x^{-n}-1}=\frac{\psi_x(1)+\ln(1-x)}{\ln x}$$
to derive
$$S=\sqrt5\sum_{n=1}^\infty\left(\frac1{\beta^{-n}-1}-\frac1{(\beta^2)^{-n}-1}\right)$$
$$=\sqrt5\left(\frac{\psi_\beta(1)+\ln(1-\beta)}{\ln\beta}-\frac{\psi_{\beta^2}(1)+\ln(1-\beta^2)}{2\ln\beta}\right)$$
$$=\frac{\sqrt5}{2\ln\beta}\left(2\psi_\beta(1)-\psi_{\beta^2}(1)+\ln\frac{1-\beta}{1+\beta}\right)$$
Answer: I do not know if there is a closed form formula but you can have a good approximation of it writing
$$S=\sum_{n=1}^\infty \frac{1}{F_{4n}}=\sum_{n=1}^p \frac{1}{F_{4n}}+\sum_{n=p+1}^\infty \frac{1}{F_{4n}}$$ and use, after some $p$, $F_k\sim \frac{\phi^k}{\sqrt 5}$ (Binet formula). This means
$$S_p=\sum_{n=1}^p \frac{1}{F_{4n}}+\sqrt{5}\frac{ \phi ^{-4 p}}{\phi ^4-1}$$ which converges very fast as shown below
$$\left(
\begin{array}{cc}
 1 & 0.389061423334175 \\
 2 & 0.389082999708164 \\
 3 & 0.389083066686468 \\
 4 & 0.389083066894475 \\
 5 & 0.389083066895121 \\
 6 & 0.389083066895123
\end{array}
\right)$$
Comment: What does $S_p$ mean?
Comment: @MarianG.. Compute exactly the sum for the first $p$ terms and, for $n>p$, use Binet formula with the approximation.
Comment: I was confused since $S_p$ could also denote the $p$-th partial sum. Thanks.


How do I create a "platform" and "site" from CLI, using the drush extension provision

Question: I'm trying to figure out how to use Provision to create new sites from the CLI.
I tried looking at what commands Aegir normally passes to Provision when setting up a new platform and then a new site on that platform, but I haven't succesfully made it work from CLI.
Comment: Hopefully you are using drush 4.x; I happen to know that provision does not work with drush 5 yet.  Unfortunately, though, I do not know enough about provision to answer your question.
Comment: I noticed that as well, so that's not part of the problem.
Answer: There is a good article on this question in Aegir official documentation here:
http://community.aegirproject.org/content/manage-your-aegir-system-command-line


Regular expression (regex) help: Need to delete everything on several lines after an IP address

Question: I have several lines that are
192.168.86.3     0x1  0x2 3cbbaxrad  * br-lan
    192.168.86.213   0x1  0x2 3cccfargarad  * br-lan
    192.168.86.51    0x1  0x2 3cccfcvrad  * br-lan
    192.168.86.11    0x1  0x2 3cccfxxrad  * br-lan
I need to extract only the ip addresses so it's
192.168.86.3
192.168.86.213
192.168.86.51
192.168.86.11
Can anyone help? Thanks
Answer: This works for your test case:
<code>\d*\.\d*\.\d*\.\d*
</code>
Answer: This is a good fit. It only picks up numeric sequences up to three digits and with periods in between. The ()'s make it a selection sequence. So that you can use a replacement string like $1 to only deposit IP addresses.
<code>(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})
</code>
Try out this link for more help: https://regex101.com/r/p3NdGL/1


colour is not getting set to workbook

Question: I am using java workbook xls but i am unable to set the color.I am using the following code.
CellStyle cellStyle = sheet.getWorkbook().createCellStyle();
cellStyle.setFillBackgroundColor(HSSFColor.DARK_RED.index);

Cell celli = row0.createCell((short) i);
celli.setCellValue(list.get(i).toString());
celli.setCellStyle(cellStyle);

I am using the cellstyle but color is not being set.
Answer: You should use
cellStyle.setFillForegroundColor(HSSFColor.DARK_RED.index);
cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

instead of
cellStyle.setFillBackgroundColor(HSSFColor.DARK_RED.index);

colour is not getting set to workbook


Intuitive explanation of covariant, contravariant and Lie derivatives

Question: I would be glad if someone could explain in intuitive terms what these different derivatives are, and possibly give some practical, understandable examples of how they would produce different results.
To be clear, I would like to understand the geometrical or physical meaning of these operators more than the mathematical or topological subtleties that lead to them!
Thanks!
Comment: Of course, and this question "sort of" stems from that reading :-)
Comment: Have you read the relevant wikipedia articles?
Comment: related: http://mathoverflow.net/questions/75220/physicists-request-for-intuition-on-covariant-derivatives-and-lie-derivatives
Answer: The Lie derivative is a derivative of a vector field V along another vector field W.  It is defined at a point p as follows: flow the point p along W for some time t and look at the value of V at this point.  Then push this forward along the flow of W to a vector at p.  Subtract $V_p$ from this, divide by t, and take the limit as $t \to 0$.  So this is a measure of how V changes as it gets pushed around by the flow of W.
The covariant derivative is a derivative of a vector field V along a vector W.  Unlike the Lie derivative, this does not come for free: we need a connection, which is a way of identifying tangent spaces.  The reason we need this extra data is because if we wanted to take the directional derivative of V along the vector W how we do in Euclidean space, we would be taking something like $V_{p+tW} - V_p$, which is the difference of vectors living in different tangent spaces.  If we have a metric, then we can impose reasonable conditions that give us a unique connection (the Levi-Civita connection).
I have no idea what a contravariant derivative is.  I'd guess it has to do with applying a covariant derivative and lowering indices.
Comment: Although the Lie derivative of a vector field is the most intuitive one can use the Lie derivative for arbitrary tensor fields.


JSON.Net Deserialization error, My Class definition is wrong?

Question: In VB.Net program I'm getting the "Cannot deserialize the current JSON array" when using JsonConvert.DeserializeObject(Of MCMusicElements)(sRB).
The JSON array I'm working with is:
[{"Key":465419,"MIK_Energy":3,"MIK_Camelot":"9B","MIK_BPM":118}]
If I delete the "[ ]" in the JSON string my program works. So, I'm assuming my Class definition for MCMusicElements is wrong in some way. I'd like to understand how to make it work without deleting the brackets from the JSON string.
Public Class MCMusicElements
  Public Property Key As Integer
  Public Property MIK_Energy As Integer
  Public Property MIK_Camelot As String
  Public Property MIK_BPM As Integer
End Class

Dim oResult = JsonConvert.DeserializeObject(Of MCMusicElements)(sRB)
dtDataTable.Rows(index).Item(1) = oResult.MIK_Energy
dtDataTable.Rows(index).Item(2) = oResult.MIK_Camelot
dtDataTable.Rows(index).Item(3) = oResult.MIK_BPM

Answer: you have to use list of objects, not an object
Dim oResult = JsonConvert.DeserializeObject(Of List(Of MCMusicElements))(sRB)

dtDataTable.Rows(index).Item(1) = oResult(0).MIK_Energy

Comment: tried; JsonConvert.DeserializeObject(List(Of MCMusicElements))(sRB) but getting this; 'List(Of MCMusicElements)' is a class type and cannot be used as an expression.
Comment: this worked!!  Dim oResult = JsonConvert.DeserializeObject(Of List(Of MCMusicElements))(sRB)      THANKS!!


Bootstrap CDN still being referenced in subtheme, turned off

Question: These are the setting in my .info for my subtheme:
<code>;;;;;;;;;;;;;;;;;;;;;
;; Stylesheets
;;;;;;;;;;;;;;;;;;;;;

stylesheets[all][] = css/style.css

; For information on choosing the desired method, please read the Drupal
; Bootstrap sub-theme "how-to" documentation:
; https://drupal.org/node/1978010

;----------------------------------
; METHOD 1: Bootstrap Source Files
;----------------------------------

;;;;;;;;;;;;;;;;;;;;;
;; Scripts
;;;;;;;;;;;;;;;;;;;;;

; scripts[] = 'bootstrap/dist/js/bootstrap.min.js'
scripts[] = 'bootstrap/js/affix.js'
scripts[] = 'bootstrap/js/alert.js'
scripts[] = 'bootstrap/js/button.js'
scripts[] = 'bootstrap/js/carousel.js'
scripts[] = 'bootstrap/js/collapse.js'
scripts[] = 'bootstrap/js/dropdown.js'
scripts[] = 'bootstrap/js/modal.js'
scripts[] = 'bootstrap/js/tooltip.js'
scripts[] = 'bootstrap/js/popover.js'
scripts[] = 'bootstrap/js/scrollspy.js'
scripts[] = 'bootstrap/js/tab.js'
scripts[] = 'bootstrap/js/transition.js'

; Disable BootstrapCDN if using Bootstrap source files in your sub-theme.
settings[bootstrap_cdn] = ''
</code>
When I view source I'm seeing this:
<code><link type="text/css" rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css" media="all" />
</code>
Where is that coming from? Unless I've misread the settings above should have removed that. Several cache clears and it's still there.
Answer: If you haven't downloaded the bootstrap source files then the CDN will still load I believe. Once you download and place bootstrap inside of your subtheme then the bootstrap source files should load then. The docs mention this but I don't think it's very obvious but you have to download bootstrap and compile the styles.css file from styles.less and that should include your bootstrap styles. So if that file doesn't exist that may be the issue. Or bootstrap just not being there all together. It's been a while since I setup from scratch, I use the dev version and have drush setup everything now.
Comment: I do have the bootstrap source files downloaded to my subtheme, I have been using less to compile the source to *css/style.css*. Which is exactly why I was asking this question.
Comment: So all of the JS files are loading? The ones listed in your info file from above? Also, do you have the Bootstrap base theme turned off in Drupal, only your subtheme should be turned on when doing that. What version of Bootstrap are you using (the Drupal theme)?
Comment: The JS files are loading. The Bootstrap theme is turned off. I am using the 7.x-3.0 version of the Drupal Bootstrap Theme.
Comment: I would recommend upgrading to [beta2](https://www.drupal.org/node/2312697) or the [dev](https://www.drupal.org/node/1840986) version. I know that the recommended version says use 7.x-3.0 but the release date on that version was 2013-Nov-17 and beta2 is 2014-Jul-30. I've used beta2 and dev and I have never had this issue. You can also try uninstalling the themes just incase the variables table has been corrupted by updating procedures. Besides that I would probably need to see your site or chat with you a little more to see exactly what is happening.


PixelGetColor (called with wrong number of args)

Question: I'm trying to create a simple script for getting the hex color value of a position on the screen from a variable given by an input box.
The script is not starting because of that error, I don't really understand why it's not working this way, would really appreciate if anyone can explain this to me.
<code>#include <MsgBoxConstants.au3>
$position = InputBox("", "position:", "", "", 200, 150,  @DesktopWidth / 2-125, @DesktopHeight / 2-100, 0)
$color = PixelGetColor($position)
MsgBox($MB_SYSTEMMODAL,"","Hex Color: " & Hex($color, 6))
</code>
Answer: Your <code>$position</code> is just one parameter (a single string containing a comma), not two parameters delimited with a comma. You need to split it:
<code>#include <MsgBoxConstants.au3>
$aPosition = StringSplit(InputBox("", "position:", "", "", 200, 150, @DesktopWidth / 2 - 125, @DesktopHeight / 2 - 100, 0), ",")
$color = PixelGetColor($aPosition[1], $aPosition[2])
MsgBox($MB_SYSTEMMODAL, "", "Hex Color: " & Hex($color, 6))
</code>


Is the sum of predicted y values equal to the sum of actual y values?

Question: Say I have a set of points Y and I want to accuratly predict the values of Y by using three variables X1,X2,X3. Hence my equation is
Y=intercept + C1*X1 + C2*X2 + C3*X3
After performing linear regression I get my values of C1,C2,C3 and the intercept. For every value of X1,X2,X3 I have a new point Y' that is supposed to be as close as possible to Y.
Now my question is, are the sum of values in Y and Y' supposed to be equal?
Answer: When the analysis is performed using ordinary least regression,  the sum of predicted Y values and that of observed Y values are equal in all models that include an intercept. However, this is  not necessarily true for models that do not include an intercept.
To show it, first we have to note that the difference between the sum of predicted Y and that of observed Y is equal to the sum of the absolute differences or residuals. Considering for simplicity univariable regression (but the following considerations can also be applied to multivariable models such as that cited in the question), the regression parameters A (slope) and B (intercept) in OLS are estimated so that the sum of squared residuals is minimized. Since the regression model is $Y_i = aX_i +  b+\epsilon_i$, where $\epsilon_i$ represents the residual in the estimation of $Y_i$, we get that the sum of squared residuals is
$$\sum_{i=1}^n(Y_i - aX_i -  b)^2$$
To minimize this function, it is necessary that the first partial derivatives with respect to $a$ and $b$ are equal to zero when assessed in $A$ and $ B$.  Calculating the first partial derivative with respect to $a$ and equalizing its value in $A$ and $B$ to zero, we get
$$ -2\sum_{i=1}^n(Y_i - AX_i - B) = 0 $$
Since  $(Y_i - AX_i - B) $ is the residual, it follows that
$$ \sum_{i=1}^n\epsilon_i = 0 $$
Therefore, because the sum of residuals is zero,
 the sum of predicted $Y$ values has to be equal
to that of observed $Y$ values. It is also evident
that this is not necessarily true in models where the constant term is lacking.
Just an example to better illustrate the issue. Suppose that in a sample of three measurements of a single independent variable $X$ we get that the target variable $Y$ assumes the following $(X,Y)$ values: $(1,2), (2,4), (3,8)$. OLS regression yields the regression line $Y=3X-4/3$, which provides a sum of squared errors of $2/3$. The predicted values of $Y$ for $X$ equal to 1, 2, and 3 are $5/3$, $14/3$, and $23/3$. Their sum is $42/3=14$, which is exactly the sum of the three observed $Y$ values $2+4+8=14$.
Now let us build another linear model with no intercept using the same data. The OLS procedure leads to the regression line $17/7\,X$. The predicted values of $Y$ for $X$ equal to 1, 2, and 3 are $17/7$, $34/7$, and $51/7$. Their sum is $102/7=14.6$, which is higher than the sum of the three observed $Y$ values $2+4+8=14$.
Comment: thanks for the detailed answer