jeudi 23 avril 2015

Tracing through a recursive function

For the following code segment, I am having trouble tracing through it (which I need to be able to do for my upcoming test.

public int question(int x, int y)
{
    if (x ==y)
        return 0;
    else
        return question(x-1, y) + 1;
}

I am also confused as to what the + 1 is doing. What is 1 being added on to. I know the result is five, but I need to be able to better understand the concept. Thanks for your help.

Finding a document in RethinkDB that meets multiple criteria

I want to create a wrapper function that accepts an array of requirements. This wrapper function will ask rethinkDB for any documents that meet all criteria. The values will be numerical and I want anything returned which has >= the asked for value.

The syntax supplied in the API is like this:

r.table("name").filter(
r.row("cond1").lt(val1).and(r.row("cond2").gt(val2))
).run(conn, callback);

But that doesn't allow me to query for an arbitrary amount of conditions.

Is there a feature that I am missing, or is the solution to: 1. build a string and eval it - or - 2. pass a function to the RethinkDB server with my array of requirements included ?

An example that might make more sense: I have a database of monster trucks. I want to allow someone to say "show me trucks with a power score of at least 5 and with a speed of at least 10". Here is a failed attempt at passing a function:

r.db('test').table('monstertrucks').filter(
function(item){
var fail = 0, 
    arr = [{attr: "speed", val: 5}, {attr: "power", val: 10}];
for(var i = 0; i < arr.length; i++){
  if(item(arr[i].attr).lt(arr[i].val)){fail++}
}
return fail ? false : true;
})

Calling a func from one class in another class - swift

I have a class viewcontroller. In another class, SigViewController, I have a function which captures an image of a signature. I would like to call the function in the viewcontroller class (specifically in an IBAction).

In viewcontroller I have the following.

@IBAction func sigsave(sender: AnyObject) {
    SigViewController().getSignature()
}

In SigViewController the function is...

func getSignature() ->UIImage {
    UIGraphicsBeginImageContext(CGSizeMake(self.bounds.size.width,
        self.bounds.size.height))
    self.layer.renderInContext(UIGraphicsGetCurrentContext())
    var signature: UIImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    println("saved image")
    return signature
}

The viewcontroller is returning the error `Use of unresolved identifier SigViewController.

Thanks for any help.

How can I create a function in MySQL for add elements in a table?

I would like to add elements in a table like this:

Codigo  Name   Lastname   Date    Sex    Salary
1       name1  lastname1  random  random random
2       name2  lastname2  random  random random
3       name3  lastname3  random  random random
4       name4  lastname4  random  random random

Date is a date random betweem years 2000 - 2015

Sex is random boolean 1 or 0

Salary is a random float between 500.00 and 5000.00

is that possible? How can I do that?

jQuery. Pass a variable from a function to an .each inside

I want to pass a variable, either '1' or '2' and run a function depending on available size. How can i ensure that the var can get pass through another function? Thanks!

$(function() {
    function newFunc(varNum){
        $('.listing__item .item__details').each(function() {
            var ul = $('ul.item__authors', this);
            var authors = $('.item__authors-info', this);
            if(ul.children('li.author').size() <= varNum) return;

            var hiddenElements = ul.children('li:gt(varNum)', this).hide(),
                showCaption = '+ ' + hiddenElements.size() + ' others';

            authors.append($('<span class="other-authors">' + showCaption + '</span>'));
        });
    }       
    newFunc('1');
});

Method 'setChecked' with Objective-C selector 'setChecked:' conflicts with setter for 'checked' with the same Objective-C selector

I have created custom class that inherits from UIButton.

In that class I have created a function defined as:

  func setChecked(checked:Bool){
        self.checked = checked
        if checked {
            buttonImageView.image = UIImage(named: "radioSelected.png")
        } else {
            buttonImageView.image = UIImage(named: "radioUnselected.png")
        }
    }

which was working fine until I updated my xCode to 6.1.3.

Now I keep getting the error message on the function definition line:

Method 'setChecked' with Objective-C selector 'setChecked:' conflicts with setter for 'checked' with the same Objective-C selector

I already tried to make a override it but then I get a error saying that "Method does not override any method from its superclass".

Anyone know how can I correctly solve it?

(I don't want to change the name of my function.)

when code is executed execution won't move inside a excel vba function

For VBA functions and most programming in general i understand general program execution to occur something like this...

Inside a sub procedure if you call a function (it should return a value), in this case it would return a value to variable num.

To expand this means that execution reaches the line where I call the function, and should then skip down to where the function is written, and go through executing each line inside that function.

This is how it has worked for me previously when I use the F8 key to highlight and follow the code execution line by line.

The problem The problem is when execution reaches the line inside the sub procedure where the function is called the function is just skipped over and execution doesn't go inside the function and run each line inside it.

(and I should say when this happened I had 95% of a working program, and i've tried re-writing the function, calling other functions).

But whenever a function is called execution of the code doesn't go into the function itself it just skips over it, and the variable that holds the result of the function therefore is left empty.

I've tried creating breakpoints at the beginning of the function and when the function is called in the sub procedure however this hasn't worked.

At the very least execution should get to the definition of the function (Function FirstRow() etc) and throw and error but it's not doing that.

Sub Main

    Dim num as double

    Dim sheet_name as string

    num = FirstRow(sheet_name)

End Sub

Function FirstRow(sheet as string) as double

    select case sheet '<<----- execution never gets inside the function

    case "sheet"
        FirstRow = 8
    case "sheet2"
        FirstRow = 12

    end select

End Function

for loop with ";" at the end in C

Heyy people, I have one question. I have a big missunderstand. I found one code and I dont understand one thing. The code of function is:

int func_prim (int zahl)

int count;
if(zahl <0)
    return -1;

for(count=2; zahl % count != 0 && zahl >= count; count++); //Wenn der Rest 0 ist, dann haben wir einen Teiler! ist der Teiler gelich der zahl ist es eine Primzahl!
if(count == zahl)//Primzahlen sind nur durch sich selber teilbar
    return 1;
return 0;

The point of function is to check if number prime number is or not. I dont understan : Why the for function has ";" at the end: for(count=2; zahl % count != 0 && zahl >= count; count++);

without that, code doesnt work properly.

Can anybody help me?

C++ Type Check in Functions ignored (required double, provieded int)

I have the following code

#include <iostream>

using namespace std;

int dmult(int a, int b){
    return 2*a*b;
}


int main(void)
{
    double a = 3.3;
    double b = 2;
    int c = dmult(a,b);
    cout << c << endl;
    return 0;
}

It compiles with MinGW without problems. The result is (as I thought) false. Is it a problem of the compiler, that there is now warning, that a function expecting integers, but is feeded with doubles, can compile without waring that the input type is wrong? Does it mean, C++ ignores the input type of a function. Shouldn't it realise, that the function arguments have the wrong type.

Thanks for the answer!

write a function that square entries of a vector( input vectors should be passed as pointer)

How do I write a function that square entries of a vector( input vectors should be passed as pointer). I couldn't define my vector in function as pointer! What should I do? hi guys..totally a a beginner...

#include <stdio.h>

int squareVec(double vec, int n)
{
  int j = 0;
  for(j = 1, j < dim; --j)
  {
    *vec[j] = &vec[j] * &vec[j];
  }
  return vec;
}

main()
{
  double vec[3] = { -1.0, 2.0, 0.0 };
  int j = 0;
  squareVec(vec, 3);
  for(j = 0; j < 3; ++j)
  {
    printf("vec[%d] = %f ", j, vec[j]);
  }
  printf("\n");
}

MySQL Trim only works in certain cases in function definition

I have a function I'm troubleshooting in MySQL where I'm using TRIM. The problem seems to be that TRIM can handle certain "easy" strings, but not others. (The specifics of the rest of the function aren't that important. In other words, running the function with any two valid inputs will give the same output since the output is hard-coded.) For example, when the line "SET amts_sep_by_delim2 = trim(LEADING '1' FROM '12');" uses '12', '2' is returned when the function is called. However, when that line is changed to "SET amts_sep_by_delim2 = trim(LEADING '1' FROM '1000.00?---ase1000.00?5000');", the value returned by the function is "0".

Any ideas?

DROP FUNCTION IF EXISTS SUM_LIST;
DELIMITER //
CREATE FUNCTION SUM_LIST (amts_sep_by_delim VARCHAR(50), delim CHAR(1))
    RETURNS DOUBLE
    DETERMINISTIC
    BEGIN
        DECLARE i INT;
        DECLARE amt DOUBLE;
        DECLARE run_total DOUBLE;
        DECLARE amts_sep_by_delim2 VARCHAR(50);

        SET i = POSITION(delim IN amts_sep_by_delim);
        SET amt = SUBSTRING_INDEX(amts_sep_by_delim, delim, 1);
        SET run_total = amt;

        -- WHILE i > 0 DO
            SET amts_sep_by_delim2 = trim(LEADING '1' FROM '12'); -- TRIM(LEADING CONCAT(amt, delim) FROM amts_sep_by_delim);
            SET amt = SUBSTRING_INDEX(amts_sep_by_delim, delim, 1);
            SET i = POSITION(delim IN amts_sep_by_delim);
            SET run_total = run_total + amt;
        -- END WHILE;
     RETURN amts_sep_by_delim2;
    END;
    //

Python High Order Function IF ELSE check

I've an object with a function as one of its variables that can be kind1 or of kind2. These functions are in an other imported file and are passed to its constructor which is obviously an high order function (a function that takes a function as input). Once that I've created the object I can access the associated function with object.function Now I want to perform some checks on the object and I want to discriminate wheter its function is of kind1 or of kind2.

I've tried with

if object.function == kind1:
    print 'kind1'
elif object.function == kind2:
    print 'kind2'

and with

if object.function == kind1():
    print 'kind1'
elif object.function == kind2():
    print 'kind2'

it doesn't work because kind1, kind2 or kind1(), kind2() are not defined...what's wrong?

Using R to writing a function to export a PDF graph, but PDFs are corrupted

I have written this function to export graphs in R. When I run this function the pdf files are created, but they are corrupted and won't open (or when I made it export png file the files are empty). When I run the individual lines of code, not as part of the function they work.

Help!! I think it must be something to do with making the tables or graphs in the function, (do I have to do something like return the graphs/data frames?) but I don't know what!

    graphFunction <- function(fileName){

pdfTitle <- paste(fileName, "_graph", ".pdf", sep = "")

File <- read.csv(fileName, quote = "")
ByPopAge<- ddply(File, .(age), summarise, # need to discount trials where no feeding obs and eve
        NCols = length(!is.na(colony_ID)),
        TotNumInd = sum(num.indvs)
)

pdf(pdfTitle, width =10, height =10)

ggplot(data = ByPopAge, aes(x = age, y = TotNumInd)) + geom_line() + geom_point()   
ggplot(data = ByPopAge, aes(x = age, y = NCols)) + geom_line() + geom_point()

dev.off() }

Thanks!

Angularjs - $http request does not work from inside a function

In the controller i would like to put the http request of a json file into a function. Only when its outside of a function it works. Why? I would like to display the contents in the view.

Controller:

$http.get('components/json/list.json').success(function (data) {
    main.listNoFunction = data;
});

main.listFunction = function () {
    var result = null;
    $http.get('components/json/list.json').success(function (data) {
        result = data;
    });
    return result;
}

View:

// This works:
{{ main.listNoFunction }}

// This works NOT:
{{ main.listFunction }}

Thanks for your help! Vin

Python read from file and show total max and min population from year 1900-1990

I'm working on this python code where I have to open up this file http://ift.tt/1OLHGBf and read from it so that it finds out the total population with the max and min from the years 1900 - 1990 but I cant quite figure it out I'd appreciate any help .. here is an example of how the finished code should look like http://ift.tt/1HsSiGl

def open_file():
    data = open("urpop0090.txt","r")

def STATES(check_year):
  check_year.extend(input_year2)
  data = open("urpop0090.txt","r")
  check_year.remove("UNITED STATES")
  check_year.remove("%")
  check_year.pop("%")

def check_year(year):
if year >= 1900 and year <= 1990:
      if year % 10 == 0:
#X axis horizontally on x axis
        if year == 1990 or year == 1980 or year == 1970: #1st page
            x= 0
        elif year == 1960 or year == 1950 or year == 1940:#2nd page
            x = 52
        elif year == 1930 or year == 1920 or year == 1910:#3rd page
            x = 154
        elif year == 1900:
            x = 206
#Y axis going vertically by spaces
        if year == 1990 or year == 1960 or year == 1930 or year == 1900:#1st page
            y= 1
        elif year == 1980 or year == 1950 or year == 1920:#2nd page
            y = 7
        elif year == 1970 or year == 1940 or year == 1910:#3rd page
            y = 12
        #elif year == 1900:
              #y = 241

        return (x,y)

def search(myFile, x , y):
data = open ("urpop0090.txt","r")


def print_max_min(census_list):
max = 0
max_tuple = ()
min = 99999999
min_tuple = ()

for tuple in census_list:
    if tuple[1] > max:
        max = tuple[1]
        max_tuple = tuple
    elif tuple[1] < min:
        min = tuple[1]
        min_tuple = tuple

print ("the maximum is : ({} {:>,d)".format(max_tuple[0],max_tuple[1]),
       "\nthe minimum is : ({} {:>,d})".format(min_tuple[0], min_tuple[1]))

import string, sys

while True:
myFile = open_file()

try:
    year = input("Enter a census year 1900 - 1990 (must end with 0): ")
    year = int(year)
except ValueError:
    print("Non-Integer value input:", year)
    print("")
    continue

page_num, block_num = check_year(year)
if page_num != "Error":
    census_list = search (myFile, page_num, block_num)
    print_max_min(census_list)

myFile.close()

Change global 2d array from a function PHP?

$q = $_POST['q'];

$inCart = isset($_COOKIE['cart']) ? unserialize($_COOKIE['cart']) : array();

function alreadyInCart() {

    global $inCart, $good, $q;

    foreach ($inCart as $inCart1) {

        if ($inCart1[0] == $good->id) { // if this good already in cart

            $inCart1[1] = $inCart1[1] + $q; // write sum of q's to existing array

            return true; // and return true

        }

    }

    return false; // return false if not

}


if (alreadyInCart() == false) { // if good added to cart for the first time

    $inCart[] = array($good->id, $q); // add array at the end of array

}

Hello. So my problem is that I'm running a function to find out if $good->id is already inside of 2d $inCart array.

$inCart looks something like this:

Array
(
    [0] => Array
        (
            [0] => 6
            [1] => 1
        )

    [1] => Array
        (
            [0] => 5
            [1] => 1
        )

)

Where [0] is a good ID and [1] is an amount of this good in a cart.

So I tracked that function actually does what I want and returns true/false as expected, but looks like it only does it inside of itself. Cause if I put print_r($inCart1[1]) inside of a function it does add up and outputs the sum, as expected. But when I output the array at the end of the code (outside the function) the amount doesn't add up, just stays how it was before the function run.

Any ideas why that happens?

Splitting and replacing a character variable in a dataframe in R

I have a dataframe with multiple character variables of different lengths, and I would like to convert each variable to a list, with each element containing each word, split by spaces.

Say my data looks like this:

char <- c("This is a string of text", "So is this")
char2 <- c("Text is pretty sweet", "Bet you wish you had text like this")

df <- data.frame(char, char2)

# Convert factors to character
df <- lapply(df, as.character)

> df
$char
[1] "This is a string of text" "So is this"              

$char2
[1] "Text is pretty sweet"                "Bet you wish you had text like this"

Now I can use strsplit() to split each column individually by word:

df <- transform(df, "char" = strsplit(df[, "char"], " "))
> df$char
[[1]]
[1] "This"   "is"     "a"      "string" "of"     "text"  

[[2]]
[1] "So"   "is"   "this"

What I would like to do is create a loop or function which would allow me to do this for both columns at once, something like:

for (i in colnames(df) {
    df <- transform(df, i = strsplit(df[, i], " "))
}

This, however, produces the error:

Error in data.frame(list(char = c("This is a string of text", "So is this",  : 
  arguments imply differing number of rows: 6, 8 

I have also tried:

splitter <- function(colname) {
    df <- transform(df, colname = strsplit(df[, colname], " "))
}

splitter(colnames(df))

Which tells me:

Error in strsplit(df[, colname], " ") : non-character argument

I am confused as to why the call to transform works for an individual column but does not when applied within a loop or function. Any help would be much appreciated!

How to echo function in a link php [duplicate]

This question already has an answer here:

So I have a navigation bar, and based on the session the specific links are displayed and I need the list-item to have a class of active.

I have this, however it doesn't make it active, i.e. when it's active the link is dark.

if ('admin' == $_SESSION['username'] ) {
echo "<li echoActiveClassIfRequestMatches('admin')><a href='admin.php'>Admin</a></li>";

function echoActiveClassIfRequestMatches($requestUri)
{
    $current_file_name = basename($_SERVER['PHP_SELF'], ".php");

    if ($current_file_name == $requestUri)
        echo 'class="active"';
}

For some reason for the links that are not being generated with PHP it works fine, but for that link it doesn't.

How can I store the result of a function as an item in an array?

I have some code that returns the contents of a <div> after you press a button. I need to save the result of this function to an array. So how do I do that?

Here's my code so far:

var numKey = document.getElementsByClassName('num-key');

  for (var i = 0; i < numKey.length; i++) {
  numKey[i].addEventListener("click", function () {
    return this.innerHTML;
  });
};

Using String functions on flattened chararray data

Objective : Using String functions on flattened chararray data

Input : test.txt

file_id     file_name       created_time            accesssed_by
   1          a1                1                       user1
   1          a2                2                       user1
   2          b1                3                       user1
   3          c1                4                       user1

Pig Script :

  A = LOAD 'usertest.txt' USING PigStorage('\t') AS (file_id:long, file_name:chararray, created_time:long,accessed_by:chararray);
  B = GROUP A BY file_id;
  C = FOREACH B {
   sorted = ORDER A BY created_time DESC;
   user = A.accessed_by;
   uniq_user = DISTINCT user;
   last = LIMIT sorted 1;
   GENERATE UPPER(FLATTEN(last.file_name)) AS file_name, COUNT(uniq_user) AS access_count;
};

Trying to use any of the string manipulation functions on top of flattened chararray data type is resulting in the below ERROR.

ERROR org.apache.pig.tools.grunt.Grunt - ERROR 1200: <line 185, column 22>  mismatched input 'FLATTEN' expecting RIGHT_PAREN

Without using the string manipulation function on top of FLATTEN will result in the required data.

(a2,1)
(b1,1)
(c1,1)

Objective is to use some string manipulation functions to convert the file_name to the required format before persisting without going for another iteration of the data.

Going for one more iteration as below we are able to achieve our objective, can we avoid this and do the same earlier.

 D = FOREACH C GENERATE UPPER(file_name) AS file_name, access_count;

Output :

 (A2,1)
 (B1,1)
 (C1,1)

c++ function resolution selects templated version over plain function

Consider the following code:

#include <iostream>

template<typename T>
void f(T t)
{
  (void)t;
  std::cout << "templated f(T)\n";
}

template<typename T>
void entry(T t)
{
  f(t);
}

void f(double d)
{
  (void)d;
  std::cout << "normal f(double)\n";
}

int main()
{
  double d = 0.0;
  entry(d);

  return 0;
}

Output:

templated f(T)

I find this surprising, because I thought that the plain function will be selected over any templated version. Why does this happen?

Another thing I noticed while playing around is that: if I put the normal function void f(double) before the templated void entry(T) function the code will call the normal function, basically outputting:

normal f(double)

Therefore my other question: why does the order matter in this particular example?

Using pointers to access 2D array in a function

I am currently working on a code to access elements of an array using Depth-First Search. If I come across a 'Y', I replace it with a '*' and increment my count. But while using pointers, I am encountering the following error:

In function 'dfs':
5:5: error: invalid type argument of unary '*' (have 'int')


In function 'checkMe':
23:16: error: invalid type argument of unary '*' (have 'int')

Here is my Code:

#include <stdio.h>

void dfs(char* m,int r,int c,int v1,int v2)
{
    *(*(m+r)+c) = '*';
    for(int k=0;k<2;k++)
    {
        if((r<(v1-1))&&(c<(v2-1)))
        {
            dfs(m,r,c,v1,v2);
        }
    }
} 

int checkMe(char* m,int row,int col)
{
    int counter = 0,i=0,j=0;

    for(i=0;i<row;i++)
    {
        for(j=0;j<col;j++)
        {
            if(*(*(m+i)+j) == 'Y')
            {
                dfs(m,i,j,row,col);
                counter++;
            }
        }
    }

    return counter;
}

int main()
{
    int i = 0,count = 0,p = 4,q = 4;
    char input[4][4]={{'Y','Y','Y','N'},{'N','N','N','Y'},{'Y','Y','N','Y'},{'Y','N','N','N'}};

    count = checkMe(input,p,q);
    printf("%d",count);

    return 0;
}

Can anyone help me with this?

jQuery, function is applied x times instead of one

I want to check if all the inputs having the class "toCheck" are not empty, to do so, I'm using code found at: Checking if ALL form inputs are empty with jQuery

function formCheck(){
    var $fields = $(".toCheck");
    $fields.keypress(function() {
        var $emptyFields = $fields.filter(function() {

            // remove the $.trim if whitespace is counted as filled
            return $.trim(this.value) === "";
        });

        if (!$emptyFields.length) {
            alert("form has been filled");
        } else {
            alert("uh-oh, you forgot to fill something out");
        }
    });
}

My issue is, my inputs having "toCheck" class can be dynamically created, so I need to load formCheck() everytime I dynamically create a new "toCheck".

But then function formCheck() is applied 2 times (2 alert messages for one keypress)

use result of variable from one function to another function

I need to use variable generated value from first function (variable url), in second function, here is a code:

var kategorije = ["c1", "c2", "c3", "c4", "c5", "c6"];
var url;

function checkbox_test() {  //first function
// calculating url ...
alert(url); // here everything is ok, something like c1=x&c2=a&c3=5 ...
}

function loadXMLDoc()   {  // second function
   regid = "123456abcdefg";
   var xmlhttp;
   xmlhttp=new XMLHttpRequest()
   xmlhttp.onreadystatechange=function()    {
     if (xmlhttp.readyState==4 && xmlhttp.status==200)  {
        document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
            }
            }
     xmlhttp.open("GET","http://ift.tt/1DTTAWW" + regid + '&' + url, true);
     xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
     xmlhttp.send();
   alert(url); // just checking is value of url is correct! here it say url is undefined!
 }

I need to pass value of url generated in first function in GET as url. Thanks!

R: Return a data frame to the workspace, and name it from a function argument

I want to create a data frame within in a function and return it to the workspace, but additionally to be able to name that data frame each time I call that function (by passing a text string as function argument). Below is my best guess but doesn't do it.

func = function(named.df = "NA"){
  df <- data.frame(c(1,2,3), c('a','b','c'))
  assign(named.df, df)
}

func("my.data.frame")

.js method "undefined" in a jsp

I have this code in a jsMethods.js file:

function openPopup(url, name) {
    var options = 'height=650px, width=1050px, scrollbars=no, resizable=yes, toolbar=no, location=no, directories=no, status=no, menubar=no';
    window.open(url,name,options);
}

and then, I have a .jsp file trying to access this code, but I get an error that says "'openPopup' is undefined". Here is the code in my .jsp file:

<%@ page import="[some imports here]"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="ISO-8859-1"%>
<%@ include file="[some jspf files included here]" %>

<%@ page import="[some more imports here]" %>

<%@ taglib prefix="bean" uri="http://ift.tt/18NLDGF" %>
<%@ taglib prefix="html" uri="http://ift.tt/18NLDGG" %>
<%@ taglib prefix="logic" uri="http://ift.tt/1c9Z5PU" %>
<%@ taglib prefix="i18n" uri="/WEB-INF/tld/i18n.tld" %>
<%@ taglib prefix="display" uri="http://ift.tt/JXB0VM" %>
<%@ taglib prefix="c" uri="http://ift.tt/QfKAz6" %>
<%@ taglib prefix="spring" uri="http://ift.tt/18bwTB1" %>

<bean:define [some code] />     

<style>
.hiddenColumn{
    display: none;
}
</style>

<script type="text/javascript" charset="ISO-8859-1" src="<html:rewrite page='/js/jsMethods.js'/>"></script>  // the path is correct

<script type="text/javascript">        
function myFunction(id, type) { 

    if (type == '3') {
        // PROBLEM - METHOD NOT FOUND ???
        openPopup('<html:rewrite page="/app/tasks/"/>' + id, '');
    }
}
</script>

<%@ include file="[a jspf file included here]"%>

<div id="page">
<html:form action="blabla.do" method="GET">    

    <%@ include file="[a jspf file included here]"%>

    <div id="page-body">
// the page body in which myFunction is called

Why is the function openPopup not accessed? I've checked with other .jsp in the project and this is exactly the way they import .js files in the .jsp files. Please, help...

Passing an array into a function c++

so I'm having an issue passing an entire array of histograms into a function in C++

the arrays are declared like this

TH1F *h_histogram[2];
h_histogram[2] = new TH1F("h1", "h1", 100, 0, 100);

And here is what I'm trying to do in the function:

void overlayhists(TH1 *hists, int numhists) {
    int ymax = 0;
    for (int i=0; i<numhists; i++) {
        if (hist[i].GetMaximum() > ymax) {
            ymax = (hist[i].GetMaximum())*1.05;
        }
     }
}

And I'm passing the function an array like this overlayhists(*h_Energy, 2);

Where h_Energy is an 1D array with 2 elements. The code will run through the first histogram in the loop but as soon as it starts the second loop and tries to access hist[i].GetMaximum() on the second try it segfaults.

What gives?

How to compare two dates in C++

I need to compare two dates. The current date with the user input one in the format dd/mm/yyyy.

So if expiry_date > current_date

display.... I have tried difftime() but that didnt work well since it uses a time parameter

time_t now;
  struct tm newyear;
  double seconds;

  time(&now);  /* get current time; same as: now = time(NULL)  */

  newyear = *localtime(&now);

  newyear.tm_hour = 0; newyear.tm_min = 0; newyear.tm_sec = 0;
  newyear.tm_mon = 0;  newyear.tm_mday = 1;

  seconds = difftime(now,mktime(&newyear));

  printf ("%.f seconds diff", seconds);
  system("pause");

heres a sample code i found

Trigger any Actor by Line Trace

I want to trigger a standard function for all actor who get triggered by the Line Trace Function.

Thats my function to find the Actor, that works.

Blueprint

Now i want to trigger a function like "clicked" or something in the Actor.

On the Unreal Doc is a TickActor() but it like seems i can't access this function.

Is there any predefined function to trigger an actor?

E-goi what is the function name that makes the user 's email validation that will receive the newsletters

im using e-goi and i whant to know if possibel what is the function name that makes the user 's email validation that will receive the newsletters.

tks

How can i open different URLs (in a web browser) under different conditions in C?

For example, I want to have the program get a name/userID from the user and open the corresponding profile, on a particular website.

i.e-

Name: "Steve".

URL: "http://ift.tt/1OhDVIK"

Name: "Bob"

URL: "http://ift.tt/1OhDTRa"

I can open an URL using: system ("start www.website.com");

But how do i make this dynamic, so it can open a URL that depends on user input?

Adding a column with consecutive numbers in R

I apologize if this question is abhorrently simple, but I'm looking for a way to just add a column of consecutive integers to a data frame (if my data frame has 200 observations, for example, starting with 1 for the first observation, and ending with 200 on the last one).

How can I do this?

Function work around Matlab and Octave

I work both in Matlab and GNU Octave.

A problem i have common is that Octave have a slightly different method for creating functions as MatLab have…

Example Matlab:

function [Y1, … , YN] myfunc (x1, …,xm)
    Some things to do
end

and octave do tha same function this way

function [Y1, … , YN] myfunc (x1, …,xm)
    Some things to do
endfunction

Not a big difference but enough that matlab functions won't run at Octave and probably also other way around.

Is there a work around that a scrips starts reading of it is working in matlab or octave and then choose what function it needs?

if matlab == true
then
[]=myfunc()
elseif octave == true
[] =myfuncoct()
else
error(…)
end

Thanks hope for some help

what is the fastest function in RDD spark

I'm implementing GroupBy function and it is "transformations" operation.

I need that the my GroupBy function must be computed immediately, so I've found out a solution that calling another "action" likes first() or count() operation after GroupBy then it will be computed.

The running time of GroupBy is equal its + the action operation, and thus I need a fastest function to minimum total running time!!

thanks!

Apply different functions to columns of a matrix

I have a matrix, for example, "A", with size 5 * n, where "n" is a large number. I want to apply functions to the columns of "A", is for loop the best solution?

To be specific, assume

A = randn(5, 10000);
B = randn(5, 5000);
ix = cell(ix_1, ix_2, ...);

and I want to do the following:

for i = 1:10000
    A(:, i) = B(:, ix_i) * B(:, ix_i)' * A(:,i);
end

The function in this example is just B(:, ix_i) * B(:, ix_i)' and "ix" is a cell of vectors which are indices, for example, "ix_i" could be [1, 3, 11, 20].

How to document overloaded functions in Doxygen?

I am getting a warning message when documenting overloaded functions.

Doxygen version 1.8.7

I have an implementation class and a header class. The header class declares two virtual functions, the second of which overloads the first.

ClassA.h

    virtual void doSomething(int i); 
    virtual void doSomething(int i,int j);`

The implementation class implements each virtual function, as follows

ClassA.cpp

    void doSomething(int i) { 
    printf ("doSomething: %d", i); 
    }

    void doSomething(int i,int j) { 
    printf ("doSomething: %d", i); 
    printf ("doSomething: %d", j); 
    }

I need to document both doSomething functions in doxygen. How do I do it?

I have tried documenting the .h file as follows:

Attempt 1:

ClassA.h

    /*! 
    * \fn void doSomething(int i) 
    * do something with i 
    */ 
    virtual void doSomething(int i); `

    /*! 
    * \fn void doSomething(int i, int j) 
    * do something with i and j 
    */ 
    virtual void doSomething(int i,int j);

Attempt 2:

    /*! 
    * \fn void doSomething(int i) 
    * do something with i 
    */ 
    virtual void doSomething(int i); 

    /*! 
    * \overload void doSomething(int i, int j) 
    * do something with i and j 
    */ 
    virtual void doSomething(int i,int j);

I have also tried to document the .cpp file in the same way, with and without documenting the .h file.

However, whichever way I try, I always get the same warning message, which is:

    ClassA.cpp: warning: no uniquely matching class member found for void doSomething(int i) 
    Possible candidates: 
    virtual void doSomething(int i) at line 123 of file ClassA.h 
    virtual void doSomething(int i, int j) at line 135 of file Class.h

    ClassA.cpp: warning: no uniquely matching class member found for void doSomething(int i,int j) 
    Possible candidates: 
    virtual void doSomething(int i) at line 123 of file ClassA.h 
    virtual void doSomething(int i, int j) at line 135 of file Class.h

Note: Ideally I would prefer to document only the .cpp file and not the .h file in order to resolve this problem.

Putting a PHP script into a HTML web page

so yeah probably a really basic straight forward problem i'm stuck on.

i have been doing PHP for about 2 months now and in that time i have created a script where in the terminal a 'User' can log in and play around with a fake, hard coded ATM and other such small features. This is a small personal project for myself. i do not have any databases for the users i just hard coded some details.

so anyways its all working fine and what i have now done is set up MAMP and what i want to do is create this on a web page, i'm guessing that for a user input i will have to link it to a html text input box? i'm not sure, i may be way off, i was think along the lines of 'include' but that just showed all the echo statements on my file and not any of the actual functionality.

as i said i'm new to most things and i'm trying to learn a lot so i apologise for not knowing the very basic stuff but any help or pointers would be appreciated.

Thanks Calvin :)

Passing class method as parameter in Typescript

I'm searching for a possibility to pass a class-method to a function which then can execute that function on an instance of that class. Something like that pseudocode: (note that this is an abstract example)

class Foo {
    public somefunc() {
        // do some
    }
    public anyfunc() {
        // do any
    }
}

function bar(obj: Foo ,func: "Foo.method") {  // "that's what im looking for"
    obj.func();
}

bar(new foo(), Foo.somefunc);  // do some
bar(new foo(), Foo.anyfunc);  // do any

Is there a possiblity to do this?

I know i could be doing something like that:

class Foo {
    static somefunc(fooObj: Foo) {
        // do some
    }
    static anyfunc(fooObj: Foo) {
        // do any
    }
}

interface func {
    (fooObj: Foo);
}

function bar(obj: Foo, fn: func) {
    fn(obj);
}

bar(new foo(), Foo.somefunc);  // do some
bar(new foo(), Foo.anyfunc);  // do any

but that involves static functions which I don't want.

Prime numbers in an dynamic array

I've a program which inserts all prime numbers up to a specific number in an array. The calculation is correct. My problems are the function parameters and the transfer of my dynamic array to the function. My function doesn't modify my array.

Please take a look at the code:

#include <iostream>

using namespace std;

int primeinlesen(int *i);
int primarrayspeicherung (int *primarray,int *bis);

int main()
{
    int reload=1;
    while(reload==1)
    {
        int bis=0,*primarray,valcounter;
        primeinlesen(&bis);
        valcounter=primarrayspeicherung(primarray,&bis);
        for(int i=0;i<valcounter;i++)
        {
            cout<<i<<". Primzahl: "<<primarray[i]<<"\n";
        }
        delete [] primarray;
        cout<<"Anzahl Primzahlen: "<<valcounter<<endl;
        cout<<"Erneute Berechnung?(Ja(1) oder Nein(0))";
        cin>>reload;
    }
    return 0;
}

int primeinlesen(int *i)
{
    cout<<"Bis zu welchem Wert moechten SiePrimzahlen ausgegeben,haben(max.500)";
    cin>>*i;
    if(*i>500)
    {
        cout<<"Wert zu hoch...";

    }
    return 0;
}
int primarrayspeicherung (int *primarray,int *bis)
{
    int x,y,counter,e,valcounter=0,xcounter=0,xvalcounter=0,xx,xy,xe;
    for(x=2;x<*bis;x++)
    {
        counter=0;
        for(y=2;y<x;y++)
        {
            e=x%y;
            if(e==0)
            {
                counter++;
            }
        }
        if(counter==0)
        {
            valcounter++;
        }
    }
    //ZWEITER DURCHGANG
    primarray=new int[valcounter];
    for(xx=2;xx<*bis;xx++)
    {
        xcounter=0;
        for(xy=2;xy<xx;xy++)
        {
            xe=xx%xy;
            if(xe==0)
            {
                xcounter++;
            }
        }
        if(xcounter==0)
        {
            primarray[xvalcounter]=xx;
            xvalcounter++;
        }

    }
    return valcounter;
}

Best regards

Returning variable outside function

I'm trying to work out how many lines of metadata there are until the real data starts, and the defined function below doesn't return the x value later on.

Why is x not defined outside the function? Is return x placed wrong?

def find(): 
    data=file('file.dat')
    x=0
    for line in data:
        if 'metaend' in line:
            break
            return x
        else:
            x+=1
find()

Pass argument to dplyr

I'd like to pass argument to a function which use dplyr.

The idea is to transform the data of a specific column (my argument) of a data frame.

Here is an illustrative example:

example = function(x){
  df %>%
    mutate( paste(x, '_with_noise', sep = '') = x + rnorm(n(), 0, 0.01))
}

The problem is I obtain this error message:

> Error: unexpected '=' in: "  df %>%
>     mutate( paste(x, '_with_noise', sep = '') ="
> > } Error: unexpected '}' in "}"

I also tried to use these but I have the exact same error.

  • mutate_ instead of mutate
  • quote()

change attributes of css class when javascript function runs

so I have this function below...

<script>          
$('.tile').on('click', function () {

    $(".tile").addClass("flipOutX");
    setTimeout(function(){
        $(".tile-group.six").load("musability-musictherapy-company-overview.html");
    }, 2000);

});
</script>

I basically want to change the css attributes of tile-group.six to have a different margin. Any ideas how I might go about this ?

Excel: Count number of cells based on criteria

I have an excel spreadsheet that contains a "Customer ID" field and a "Check ID" field. I need to count the number of check id's associated with that customer id for a specific date?

## Customer ID ##  ## Check ID##  ## Check Date##

   2554               823488         04/24/2015
   2554               823489         04/24/2015
   4856               823450         04/24/2015

So Customer 2554 would have a count of 2 and Customer 4856 would have a count of 1.

Bourne shell - convert IP range into set of subnets

I'm looking for a function in Bourne shell to convert a given range of IPs in the format "sIP-dIP" into a usable set of subnets that defines the very same range. What I'm looking for precisely it's the very same result of the IP Range function provided at this site: http://ift.tt/1uKLdKm

example:

Given:

10.0.0.6-10.10.1.34:

Result:

10.0.0.6/31
10.0.0.8/29
10.0.0.16/28
10.0.0.32/27
10.0.0.64/26
10.0.0.128/25
10.0.1.0/24
10.0.2.0/23
10.0.4.0/22
10.0.8.0/21
10.0.16.0/20
10.0.32.0/19
10.0.64.0/18
10.0.128.0/17
10.1.0.0/16
10.2.0.0/15
10.4.0.0/14
10.8.0.0/15
10.10.0.0/24
10.10.1.0/27
10.10.1.32/31
10.10.1.34/32 

I have seen many examples around but they are all for bash, C or phyton, but I'm on busybox with Bourne shell.

Can anybody please provide some inputs?

Many thanks!

I'm new to OOP. I dont understand what does this do?

function printLine($line)
{
    return $this->formatter->printLine($line) ;
}

What does this line do? I don't understand at all

return $this->formatter->printLine($line)

Please help me. May be its a stupid doubt. Function returns something and is it something related to variable functions?

Fortran polymorphism, functions and allocation

I am quite a beginner in OOP with Fortran and I am trying to write a program with procedures that deal with polymorphic variables as arguments. Although my original code is much more complicated (many procedures, several derived types etc), I could isolate a simple example of my problem, say: I have a procedure that copies a polymorphic variable and slightly modifies this copy.

I was able to successfully write my test program using a subroutine:

MODULE my_module

type :: my_type
    real :: data
endtype my_type

type, extends(my_type) :: my_derived_type
end type my_derived_type

CONTAINS

subroutine sub_copy(old,new) 
implicit none
class(my_type), intent(in) :: old
class(my_type), allocatable, intent(out) :: new
allocate(new, source = old)
new%data = new%data + 1
end subroutine sub_copy

END MODULE my_module

PROGRAM my_prog
use my_module
implicit none
type(my_derived_type) :: x
class(my_type), allocatable :: y

x%data = 1.0
call sub_copy(x,y)
print*,y%data
deallocate(y)

END PROGRAM my_prog

This performs nicely both regarding the expected result and the memory allocation/deallocation.

However, I have been fighting for days trying to make working a Fortran function that would do the same job.

It seems that a function defined in a similar way to the subroutine (see here after) cannot be used simply as

y = fun_copy(x)

and my gfortran compiler (v5.0.0) complains:

Error: Assignment to an allocatable polymorphic variable at (1) is not yet supported

I have read here and there that indeed such assignment is not supported by my compiler. Waiting for that, I have tried to work that around by defining my own assignment operator (=). The following code works:

MODULE my_module

type :: my_type
    real :: data
endtype my_type

type, extends(my_type) :: my_derived_type
end type my_derived_type

interface assignment(=)
  module procedure myassign
end interface

CONTAINS

function fun_copy(old) result(new) 
implicit none
class(my_type), intent(in) :: old
class(my_type), allocatable :: new
allocate(new, source = old)
new%data = new%data + 1
end function fun_copy

subroutine myassign(new,old)
class(my_type), intent(in)  :: old
class(my_type), allocatable, intent(out) :: new
allocate(new, source=old)
end subroutine

END MODULE my_module

PROGRAM my_prog
use my_module
implicit none
type(my_derived_type) :: x
class(my_type), allocatable :: y

x%data = 1.0
y = fun_copy(x)
print*,y%data
deallocate(y)

END PROGRAM my_prog

It works in the sense that indeed, a copy of x is created as y. However, inspecting the memory budget of this simple test program (I use the Instrument software on OS X), it appears that some memory is not deallocated before the end of it. I suspect that the copy function and the assignment subroutine both allocate memory and that I only free one occurrence, leaving one allocated.

As I intend to use such a routine a large number of times in a much more complicated code, I am really concerned about memory allocation/deallocation. Of course, I can use the subroutine version of the program, but if there is a way, I would prefer the function version.

Is there a way to deal with such a problem?

Is there still a use for inline? [duplicate]

This question already has an answer here:

I believed, inline was obsolete because I read here:

No matter how you designate a function as inline, it is a request that the compiler is allowed to ignore: the compiler might inline-expand some, all, or none of the places where you call a function designated as inline.

However, Angew seems to understand something I don't. In this question he and I go back and forth quite a bit, on whether inline is still useful.

This question is not a question on:

Bearing in mind that the compiler can inline at will, so inline is not helpful there: Where can inline be used to force, not suggest, a change in compiled code?

while loop calling function but only for first line, Serverlist.txt contains multiple server details

I am trying to catch the log, Serverlist.txt contains some servers details like root 10.0.0.1 22 TestServer, while I run the script it only read the first line and exit, its not working for further lines. Below is my script.

newdate1=`date -d "yesterday" '+%b %d' | sed 's/0/ /g'`
newdate2=`date -d "yesterday" '+%d/%b/%Y'`
newdate3=`date -d "yesterday" '+%y%m%d'`
DL=/opt/$newdate3
Serverlist=/opt/Serverlist.txt
serverlog()
{
mkdir -p $DL/$NAME
ssh -p$PORT $USER@$IP "cat /var/log/messages*|grep '$newdate1'"|cat > $DL/$NAME/messages.log
}
while read USER IP PORT NAME
do
    serverlog
    sleep 1;
done <<<"$Serverlist"

how can I pass the output of a command to a function in bash

I'm facing an issue when trying to create a function, I have a code to detect a bluetooth dongle connected to a usb, which is the first part of the code, and it works fine, if the usb is indeed plugged in, then it checks its stats (UP or DOWN) and storages it in the bt_stat variable which is printer after all, so far everything works fine

#!/bin/bash
clear    
echo "Looking for bluetooth USB"
bt_id=`lsusb|grep ASUS|cut -c24-32`
bt_stat="0"
    if [[ -z "$bt_id" ]]; then
        echo "not found"
        exit 1 
    else
        bt_stat=`hciconfig|head -3|tail -1|grep "UP\|DOWN"`
        echo "USB BT found"
    fi
echo $bt_stat

OUTPUT:

USB BT found

UP RUNNING

the problem starts when I try to pass that variable to a function

function disp
{
    eval st1="$1"
    echo "Status: ${st1}"
}

The function it self works as well, I have pass a fixed variable and the output, as expected is "Status: TEST"

var="TEST"
disp "\${var}"

but the moment I place the function at the beginning of the code, even if I don't use it, then the assignation of the command to the variable bt_stat is not even made, what can be causing this? do I have to take something in consideration when making a function in a program that is assigning the output of a command to a variable?

below is how the code looks with the function, I'm sorry for the long question, but I wanted it to be clear

#!/bin/bash
function disp
{
    eval st1="$1"
    echo "Status: ${st1}"
}
clear    
echo "Looking for bluetooth USB"
bt_id=`lsusb|grep ASUS|cut -c24-32`
bt_stat="0"
    if [[ -z "$bt_id" ]]; then
        echo "not found"
        exit 1 
    else
        bt_stat=`hciconfig|head -3|tail -1|grep "UP\|DOWN"`
        echo "USB BT found"
    fi
echo $bt_stat

OUTPUT:

USB BT found

an additional line shows if I call with disp "\${bt_stat}" the function, but the assignation is still not taking place

Status:

Changing cout with return [on hold]

I'm learning object programming in C++ .
Here is mine .h file:

#include <iostream>
#include <string>

using namespace std;

class Hokejist {
private:
    int StDres,StGol,StPodaj;
    string Ime;
public:
    Hokejist(); // default constructor
    Hokejist(const Hokejist& x); //copy constructor
    Hokejist(int xy, string x); // constructor
    Hokejist(string x,int a,int b, int c):Ime(x),StDres(a),StGol(b),StPodaj(c){} // constructor
    ~Hokejist(); // descructor
    void setDres(int x);
    void setGol(int x);
    void setPodaj(int x);
    void setIme(string x);
    int getDres()const;
    int getGol()const;
    int getPodaj()const;
    string getIme()const;
    int getSteviloTock();
    void izpis();
    string boljsi(Hokejist x);


};

here is my .cpp file:

#include <iostream>
#include <string>
#include "Hokej.h"

using namespace std;

Hokejist::Hokejist(){
    StDres=0;
    StGol=0;
    StPodaj=0;
    Ime.clear();
}

Hokejist::Hokejist(const Hokejist& x){
    StDres=x.StDres;
    StGol=x.StGol;
    StPodaj=x.StPodaj;
}

Hokejist::Hokejist(int xy, string x){
    StDres=StGol=StPodaj=xy;
    Ime=x;
}

Hokejist::~Hokejist(){

}

void Hokejist::setDres(int x){
    StDres=x;
}

void Hokejist::setGol(int x){
    StGol=x;
}

void Hokejist::setPodaj(int x){
    StPodaj=x;
}

void Hokejist::setIme(string x){
    Ime=x;
}

int Hokejist::getDres()const{
    return StDres;
}

int Hokejist::getGol()const{
    return StGol;
}

int Hokejist::getPodaj()const{
    return StPodaj;
}

string Hokejist::getIme()const{
    return Ime;
}

int Hokejist::getSteviloTock(){
    return (StGol+StPodaj);
}

void Hokejist::izpis(){
    cout<<"Ime hokejista: "<<Ime<<endl;
    cout<<"Stevilka dresa: "<<StDres<<endl;
    cout<<"Stevilo golov: "<<StGol<<endl;
    cout<<"Stevilo podaj: "<<StPodaj<<endl;

}

string Hokejist::boljsi(Hokejist x){
    if(this->getSteviloTock()>x.getSteviloTock()){
        return this->getIme();
    }
    else{
        return x.getIme();
    }
}

and here is my main program:

#include <iostream>
#include <cstdlib>
#include <string>
#include "Hokej.h"

using namespace std;

template<typename T>
void izpisNaj(T a, T b) {
    if (a > b) {
        cout<<a;
    } else {
        cout<<b;
    }
}

void izpisNaj(string x, string y) {
    if(x.size()>y.size()){
        cout<<x;
    }
    else {
        cout<<y;
    }
}

void izpisNaj(Hokejist x,Hokejist y){
    if(x.getSteviloTock()>y.getSteviloTock()){
        cout<<x.getIme()<<" "<<x.getDres();
    }
    else
    {
        cout<<y.getIme()<<" "<<y.getDres();
    }
}


int main() {

    string a= "aba"; string b= "a";

    Hokejist c("Kopitar",11,7,7); Hokejist d("Mursak",39,5,1);

    izpisNaj(12,35);  // writes 35
    cout<<endl;
    izpisNaj(13.5,3.5);  // writes 13.5
    cout<<endl;
    izpisNaj(b,a);    // writes aba
    cout<<endl;
    izpisNaj(c,d);    // writes Kopitar 11
    return 0;
}


Now I need to change cout in functions with return and this is where I get problems, I don't know how to change cout to return and make it work with this function:

void izpisNaj(Hokejist x,Hokejist y){
    if(x.getSteviloTock()>y.getSteviloTock()){
        cout<<x.getIme()<<" "<<x.getDres();
    }
    else
    {
        cout<<y.getIme()<<" "<<y.getDres();
    }
}
**NOW I NEED TO CHANGE THIS FUNCTION TO:**
template<>
    Hokejist izpisNaj(Hokejist x,Hokejist y){
        if(x.getSteviloTock()>y.getSteviloTock()){
           // needs to be return
        }
        else
        {
        // needs to be return
        }
    }


mercredi 22 avril 2015

Why does wp_insert_post take longer than media_handle_upload?

I've got a page on my Wordpress site where users can submit posts or documents through the front end. I use wp_insert_post for the posts, and media_handle_upload for documents.

wp_insert_post takes around 10 seconds to run, whereas media_handle_upload is almost instant.

Why is this? I would have thought that as the former only has to insert a post, whereas the latter inserts a post and uploads an image, media_handle_upload would take longer to run.

What gives?

When I call a function, it returns null if the argument is not set

When I call a function, if the argument is not set it doesn't work. This issue happens only for this DATE type argument. How come?!!!

set @date = '2015-01-01';

select stock_date(shop, description, 5, @date) from packaging where shop = 'xxx';

Result:

stock_date(shop, description, 5, @date)

3130.00

3093.00

2157.00

2463.00
...

Then if i put a date directly in the function, it doesn't work!

select stock_date(shop, description, 5, '2015-01-01') from packaging where shop = 'xxx';

stock_date(shop, description, 5, '2015-01-01')

NULL

NULL

...

This issue make me crazy. I need this function for calculate other things and because of this it gives me wrong results.

Learning to implement a C++ BubbleSort using function pointers

My compare function is a simple return true or false. My BubbleSort works by going through the vector once, sorting it once, but not going back to continue to sort. So if the numbers are 1, 5, 2, 4, 3, 6, I will get 5, 1, 4, 2, 6, 3. Instead of 1, 2, 3, 4, 5, 6. If I use my bool swapped, there is an error. Here is the code:

void bSort(vector<int> &vector1, bool (*compare) (int a, int b))
{
    bool swapped = true; //using swapped in following code causes crash
    while(swapped)
    {
        swapped = false;
            for (int i = 0; i < vector1.size(); ++i)
            {
                for (int j = 1; j < vector1.size(); ++j)
                {
                    if ((*compare)(vector1[i], vector1[j]) == true)
                    {
                        swap(vector1[i], vector1[j]);
                        swapped = true;
                    }
                }
            }
    }
}

I have seen a function like this before, and now I am trying to implement it because I want to learn. Please help.

EDIT: Here is the fixed and working function! :)

void bSort(vector<int> &vector1, bool (*compare) (int a, int b))
    {
        bool swapped = true;
        while(swapped)
        {
            swapped = false;
                for (int i = 0; i < vector1.size(); ++i)
                {
                        if ((*compare)(vector1[i], vector1[i+1]) == true)
                        {
                            swap(vector1[i], vector1[i+1]);
                            swapped = true;
                        }
                }
        }
    }

Can anyone tell me what's wrong with my function?

I'm working on this project and I keep getting this problem when the code tries to return the "guess" variable, instead of returning the value of "guess" it goes to line 9 which converts the value into a string for some reason, and then returns that. when I go to use the returned value in something, Python says that the value is "NoneType".

def ask_question(max_length, rowOrCol, guessNumber):
    guess = raw_input("What is the "+rowOrCol+" number of your "+guessNumber+" guess? ")
    try:
        guess = int(guess)
        if guess <= max_length:
            return guess
        else:
            print "That number was too big, it must be no larger then " +str(max_length)
            ask_question(max_length, rowOrCol, guessNumber)
    except(TypeError):
        print "Only numbers are accepted, please try again!"
        ask_question(max_length, rowOrCol, guessNumber)

I call the function with this line:

first_guess_row = ask_question(4, "row", "first")

Is there anything that I'm missing?

Syntax for adding function to jQuery UI Accordion Event

I'm fixing up some jQuery functions that I wrote eons ago, and I can't seem to get the syntax right for inserting a simple function that should be called when the event is triggered.

It was nice and easy to insert the show() to the mouseleave function, but I've run into a wall on how to insert a simple hide() function into the event: "click hoverintent".

 $(".accordion_closed").accordion({
    event: "click hoverintent",
    collapsible: true,
    active: false,
    autoHeight: false,
    Height: 20,
}).mouseleave(function () {
    $(this).accordion({ active: false });
    $("#HideThis").show();
});

Javascript + HTML: Button Not Calling on Function Onclick

I have made a button:

<input type="button" value="a" onclick="searchLetter(this)"></input>

When clicked, it is supposed to call on a function which checks if the letter is in the word and if it is, add it to the spaces array in the corresponding spot:

    function searchLetter(obj)
    {
        var letter = obj.value;
        obj.disable;
        for (i = 0; i <= word.length; i++){
            if (word[i] == letter) {
                wordSpaces[i] = letter;
                document.getElementById('spaces').innerHTML = wordSpaces.join('');
                break;
            }
        }
    }

However, the button is not calling on it and I am not sure why.

Here is the JSFiddle (Hangman)

Defining a function with exec from inside a function in global environment

I have a function that, when called, should define another function with use of exec and make this new function available for the main program. The mwe is the following.

Main program:

#!/usr/bin/python
from ext import makeF

makeF()
sayA()

External module:

def makeF():
    script="def sayA():\n\tprint 'Aah'"
    exec(script)
    sayA()
    return

What I want is to be able to call the inner function sayA() from the main program, so in this example the output should be

Aah
Aah

but instead it returns

Aah
Traceback (most recent call last):
  File "mwe.py", line 5, in <module>
    sayA()
NameError: name 'sayA' is not defined

which I kind of expected, so I replace the exec(script) line with exec(script,globals), according to the docs, but instead I get

Traceback (most recent call last):
  File "mwe.py", line 4, in <module>
    makeF()
  File "/home/tomas/tests/ext.py", line 3, in makeF
    exec(script,globals,locals)
TypeError: exec: arg 2 must be a dictionary or None

I have the feeling I'm missing something pretty obvious here but I can't figure out. Any help is appreciated.

Thank you.

Calling a func from one class in another class - swift

I have a class viewcontroller. In another class, SigViewController, I have a function which captures an image of a signature. I would like to call the function in the viewcontroller class (specifically in an IBAction).

In viewcontroller I have the following.

@IBAction func sigsave(sender: AnyObject) {
    SigViewController().getSignature()
}

In SigViewController the function is...

func getSignature() ->UIImage {
    UIGraphicsBeginImageContext(CGSizeMake(self.bounds.size.width,
        self.bounds.size.height))
    self.layer.renderInContext(UIGraphicsGetCurrentContext())
    var signature: UIImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    println("saved image")
    return signature
}

The viewcontroller is returning the error `Use of unresolved identifier SigViewController.

Thanks for any help.

Swift how to make my ViewController label display information corresponding to the information of a clicked tableView cell

I have a function that uses swifty JSON and calls a web service using my DataManager swift file. I'm using my AppModel.swift as a model to populate my array with information I need from that JSON string. I'm using that array to call back pieces of information I need to update my DetailsViewController's labels. Here is my function:

class EarthTableViewController: UITableViewController {
    var info = [AppModel]()



    func getEarthquakeInfo(completion: (results : NSArray?) ->Void ){

        DataManager.getEarthquakeDataFromFileWithSuccess {
            (data) -> Void in

                let json = JSON(data: data)


                if let JsonArray =  json.array {

                    for appDict in JsonArray {
                        var ids: String? = appDict["id"].stringValue
                        var title: String? = appDict["title"].stringValue
                        var time: String? = appDict["time"].stringValue
                        var information = AppModel(idEarth: ids, title: title, time: time)

                        self.info.append(information)
                        completion(results: self.info)
                    }


            }

        }



    }

One person on here helped me populate my tableView with title. When I segue from my EarthTableViewController's cell to my DetailsViewController, I want one of the labels to display the time of that corresponding cell. For example if my cell says California, when I click on it, it'll show the time corresponding to California's Earthquake. Is there anyone who can help me with what syntax I should use for this? Here is my prepareforsegue method:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {

        if segue.identifier == "SEGUE" {
            let vc = segue.destinationViewController as DetailsViewController
            let cell = (sender as UITableViewCell)
             let title = cell.textLabel!.text
            vc.titleData = title
            let timeArray = self.info.time //error [{AppModl}] does not have a member named 'time'

        }
            }

And finally here's my AppModel.swift:

class AppModel: NSObject, Printable {
    let idEarth: String
    let title: String
    let time: String


    override var description: String {
        return "ID: \(idEarth), TITLE: \(title), TIME: \(time), \n"
    }

    init(idEarth: String?, title: String?, time: String?) {
        self.idEarth = idEarth ?? ""
        self.title = title ?? ""
        self.time = time ?? ""
    }

}

DetailsViewController:

class DetailsViewController: UIViewController {


    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var idLabel: UILabel!

    @IBOutlet weak var timeLabel: UILabel!
    var titleData: String!
    var idData: String!
    var timeData: String!

    override func viewDidLoad() {
        super.viewDidLoad()
        var earthInfo = EarthTableViewController()
        var getEarthInfo: () = earthInfo.getEarthquakeInfo { (info) in
            println("\(info)")



        }


        titleLabel.text = titleData
        idLabel.text = idData
       timeLabel.text = timeData
    }

Any help would be appreciated. If I should add more of my code, please let me know.

Can somebody help me write and understand this callback?

I'm trying to write a function utilizing callback that will mimic this behavior:

var fullName = function (firstName, lastName) {
  return firstName + ' ' + lastName;
};

var michaelName = partial(fullName, 'Michael');
michaelName('Moore'); // 'Michael Moore'
michaelName('Jackson'); // 'Michael Jackson'

I was stuck for a while trying to write a function named partial that will call back the function fullName but finally got it to work but am not sure if it's a) correct and b) exactly what is happening.

var partial = function(callback, firstName) {
    var innerFunction = function(lastName) { //I declared an inner function in order to create a closure of the variable lastName
      return callback(firstName, lastName); //The closure is completed (or is it only then created?) by returning the function argument named callback taking firstName and lastName as arguments
    };
    return innerFunction; //the function partial will finally return the closure, function innerFunction
}

var michaelName = partial(fullName, 'Michael');
console.log(michaelName('Moore')); //Michael Moore

Is what I've written in defining the function partial the general pattern for writing a callback? If not, can someone show/point me to where I can study this pattern? Is there any other way to refactor this callback so that it's cleaner? I wasn't sure if I needed to create a new innerFunction but when I did I finally got the behavior to work as intended. Is my reasoning in the comments to the code accurate? Would somebody mind stepping through my code and further explaining what is happening, why callback is returned from innerFunction and why partial returns innerFunction instead of callback? Much obliged.

Can't pass nil to two optional parameters

I'm in the process of converting an Objective-C category to a Swift extension to provide simplified methods for adding constraints. One method for equally spacing views has the following signature,

func addAndEquallySpaceViews(views: [UIView], leftOrTopSpace: CGFloat?, rightOrBottomSpace: CGFloat?, options: NSLayoutFormatOptions?)

I call it like this,

self.view.addAndEquallySpaceViews([view1, view2], leftOrTopSpace: nil, rightOrBottomSpace: nil, options: .AlignAllBottom)

I want to be able to pass nil to the leftOrTopSpace and rightOrBottomSpace parameters, but when I pass nil for both of them, I get a series of compile time errors. I can pass nil for either of them alone, but not for both. Why can't I pass nil for both optional parameters?

The errors I'm getting seem to be non-specific, and not related to the line in question,

enter image description here

Fill Color Python Graphic (India Flag)

I'm working now on creating the Indian flag in the Graphwin graphics system in python. I'm just missing something with my code right now. When I run this code below, the dark green covers up the white. But when I remove the setFill('darkgreen') from the bottom, the white shows up just fine, and doesn't cover anything else out. What am I missing?

from graphics import *

def main():
  win = GraphWin("India Flag", 500, 500)

  pt = Point(50,50)
  pt.draw(win)

  top = Rectangle(Point(260,100), pt)
  top.setFill('orange')
  top.draw(win)

  pt2 = Point(50, 150)
  middle = Rectangle(Point(260,100), pt2)
  middle.setFill('white')
  middle.draw(win)

  pt3 = Point(50, 200)
  bottom = Rectangle(Point(260,100), pt3)
  bottom.setFill('darkgreen')
  bottom.draw(win)

main ()

any help is appreciated!

C++ : What is the usage of int('0') in this code?

This code Find the sum of all digits that occur in a string.

Example

sumUpNumbers("2 apples, 12 oranges") = 5 //2+1+2

Can anyone explain the need for use int('0') in this code!?

int sumUpDigits(std::string inputString) {

  int answer = 0;

  for (int i = 0; i < inputString.size(); i++) {  
    if ('1' <= inputString[i] && inputString[i] <= '9') {
      answer += int(inputString[i]) - int('0');
    }
  }

  return answer;
}

wp_insert_post not working correctly with custom_post_type

This is the code I use to register my custom post-type:

// Register Projects custom post-type
add_action('init', 'projects_register');
function projects_register() {
    $labels = array(
        'name' => _x('Projects', 'post type general name'),
        'singular_name' => _x('Project', 'post type singular name'),
        'add_new' => _x('Add New', 'project'),
        'add_new_item' => __('Add New Project'),
        'edit_item' => __('Edit Project'),
        'new_item' => __('New Project'),
        'view_item' => __('View Project'),
        'search_items' => __('Search Projects'),
        'not_found' =>  __('No projects found'),
        'not_found_in_trash' => __('No projects found in Trash'),
        'parent_item_colon' => ''
    );
    $args = array(
        'labels' => $labels,
        'public' => true,
        'publicly_queryable' => true,
        'exclude_from_search' => false,
        'show_ui' => true,
        'query_var' => true,
        'menu_icon' => 'dashicons-plus-alt',
        'rewrite' => true,
        'capability_type' => 'post',
        'hierarchical' => false,
        'menu_position' => 20,
        'can_export' => true,
        'supports' => array('title','editor','custom-fields','thumbnail')
    );
    register_post_type( 'projects' , $args );
}

And this is the function where I (supposedly) add new posts to my custom post-type:

// Create new post from form data
function save_project_submission($cfdata) {

    $formtitle = $cfdata->title;
    $formdata = $cfdata->posted_data;   

    if ( $formtitle == 'Form Title') {

        $the_title = $formdata['post_title'];
        $the_content = $formdata['post_content'];

        // Create new post
        $newpostid = wp_insert_post(array(
            'post_type' => 'projects',
            'post_title' => $the_title,
            'post_content' => $the_content,
            'post_status' => 'pending',
            'comment_status' => 'closed'
        ), true);

        // Add meta data for the new post
        add_post_meta($newpostid, 'sample_meta_data1', $formdata['name']);
        add_post_meta($newpostid, 'sample_meta_data2', $formdata['address']);
    }

}
add_action('wpcf7_before_send_mail', 'save_project_submission', 1);

Expected behaviour:

  1. Form is submitted

  2. New PENDING post is created under custom post-type "projects" (with data from the form)

Current behavior:

  1. Form is submitted

  2. New PUBLISHED post is created under "posts" (with data from the form, but with empty custom fields)

  3. New PENDING post is created under "projects" (without data from the form, e.g. "no title", no "post content", no custom fields)

Everything looks correct code-wise to me, and I can't figure out why I am not achieving the expected behaviour. Thanks for your help.

Function/Procedure to add values in non-1NF format separated by delimiter

I need a function written in MySQL to add numbers together (positive and negative) that are in a single column and separated by a delimiter. The delimiter in this case is "?". The function also needs to ignore extraneous characters that are not numeric, not a minus sign ("-"), not a period ("."), and not a delimiter (e.g., "?").

An example is a column named "BalAdjAmt" whose values could be:

500.00?500.00?-1000.00
500.00
500.00?500.00
500.00?500.00?-1000.00 B

The result of the function when run on this dataset should be:

0
500.00
1000.00
0

Any pointers would be helpful. Thanks in advance.

when code is executed execution won't move inside a excel vba function

For VBA functions and most programming in general i understand general program execution to occur something like this...

Inside a sub procedure if you call a function (it should return a value), in this case it would return a value to variable num.

To expand this means that execution reaches the line where I call the function, and should then skip down to where the function is written, and go through executing each line inside that function.

This is how it has worked for me previously when I use the F8 key to highlight and follow the code execution line by line.

The problem The problem is when execution reaches the line inside the sub procedure where the function is called the function is just skipped over and execution doesn't go inside the function and run each line inside it.

(and I should say when this happened I had 95% of a working program, and i've tried re-writing the function, calling other functions).

But whenever a function is called execution of the code doesn't go into the function itself it just skips over it, and the variable that holds the result of the function therefore is left empty.

I've tried creating breakpoints at the beginning of the function and when the function is called in the sub procedure however this hasn't worked.

At the very least execution should get to the definition of the function (Function FirstRow() etc) and throw and error but it's not doing that.

Sub Main

    Dim num as double

    Dim sheet_name as string

    num = FirstRow(sheet_name)

End Sub

Function FirstRow(sheet as string) as double

    select case sheet '<<----- execution never gets inside the function

    case "sheet"
        FirstRow = 8
    case "sheet2"
        FirstRow = 12

    end select

End Function

Implementing pure virtual functions in twice derived classes?

Basically

class C inherits from class B which inherits from class A

So class A is the base class. Let's say the function is

virtual display const () = 0;

And I implement the pure virtual function in class C with say...

virtual display const(){std::cout << "chocolate" << std::endl};

Why do I get a gcc error telling me that I haven't defined all pure virtual functions in my code?

Set variables in a PostgreSQL Funtion/Trigger

I 'am trying to create partitions in PostgreSQL database with respect to time. While the below function/trigger that I came across servers the most of purposes I still need to figure out a way to set the table name and schema name a parameter. As we are planning on running the same trigger for different tables and schema's by changes the parameter values. Any help is much appreciated as I hardly have any experience working with functions/triggers.

CREATE OR REPLACE FUNCTION
myschema.server_partition_function()
RETURNS TRIGGER AS 
$BODY$
DECLARE
_new_time int;
_tablename text;
_startdate text;
_enddate text;
_result record;
BEGIN
--Takes the current inbound "time" value and determines when midnight is for the given date
_new_time := ((NEW."time"/86400)::int)*86400;
_startdate := to_char(to_timestamp(_new_time), 'YYYY-MM-DD');
_tablename := 'server_'||_startdate;

-- Check if the partition needed for the current record exists
PERFORM 1
FROM   pg_catalog.pg_class c
JOIN   pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE  c.relkind = 'r'
AND    c.relname = _tablename
AND    n.nspname = 'myschema';

-- If the partition needed does not yet exist, then we create it:
-- Note that || is string concatenation (joining two strings to make one)
IF NOT FOUND THEN
_enddate:=_startdate::timestamp + INTERVAL '1 day';
EXECUTE 'CREATE TABLE myschema.' || quote_ident(_tablename) || ' (
CHECK ( "time" >= EXTRACT(EPOCH FROM DATE ' || quote_literal(_startdate) || ')
AND "time" < EXTRACT(EPOCH FROM DATE ' || quote_literal(_enddate) || ')
)
) INHERITS (myschema.server_master)';

-- Table permissions are not inherited from the parent.
-- If permissions change on the master be sure to change them on the child also.
EXECUTE 'ALTER TABLE myschema.' || quote_ident(_tablename) || ' OWNER TO postgres';
EXECUTE 'GRANT ALL ON TABLE myschema.' || quote_ident(_tablename) || ' TO my_role';

-- Indexes are defined per child, so we assign a default index that uses the partition columns
EXECUTE 'CREATE INDEX ' || quote_ident(_tablename||'_indx1') || ' ON myschema.' || quote_ident(_tablename) || ' (time, id)';
END IF;

-- Insert the current record into the correct partition, which we are sure will now exist.
EXECUTE 'INSERT INTO myschema.' || quote_ident(_tablename) || ' VALUES ($1.*)' USING NEW;
RETURN NULL;
END;
$BODY$
LANGUAGE plpgsql;

Passing values to char array in a function

I am trying to use a function to sort through a char array full of words. The current issue I am having is that in my sortNames function I am getting the error, "expression must be a modifiable lvalue" at the part below

hold = nameArr[ii];
nameArr[ii] = nameArr[jj];
nameArr[jj] = hold;

I am guessing that its because I am trying to pass values through an array for some reason. I am struggling with understanding references and pointers and the such, and I imagine that is hurting me here as well. Any help with this would be fantastic, thank you in advance.

Here is my current code...

#include <iostream>
#include <string>

using namespace std;

char nameArr[20][15];           // array to store the 20 values
int val = 0;                    // variable to pass values to the array
int x = 0;                      // loop counter outside functions

//Function prototypes
void getNames(char (&nameArr)[20][15], int &val);
void sortNames( char(&nameArr)[20][15]);

//getNames Function
void getNames(char (&nameArr)[20][15], int &val)
{
    int i = 0;                  // loop counter

    cout << "Awesome, now lets input those names...\n" << endl; 

    for (i = 0; i < val; i++)
    {
        cout << "\nNAME " << i+1 << ": " << ' ';
        cin >> nameArr[i];
    }

    cout << "\n\n\nThese are the names that you inserted:\n" << endl;

    for (i = 0; i < val; i++)
    {
         cout << nameArr[i] << "\n" << endl;
    }
}

// sortNames function
void sortNames( char(&nameArr)[20][15])
{
    int n = 15;             // max length of word
    int ii = 0;             // loop counter
    int jj = 0;             // other counter
    string hold;            // holding array

    for (int ii = 0 ; ii < n ; ii++) 
    {   
         for (int jj = ii + 1; jj < n; jj++) 
        {
             if (nameArr[ii] > nameArr[jj])
            {
                hold = nameArr[ii];
                nameArr[ii] = nameArr[jj];
                nameArr[jj] = hold;
            }
        }
    }
}


int main()
{
    cout << "NAME SORTER!\n\nPlease enter in the amount of names you wish to enter: " << ' ';
    cin >> val;

    getNames(nameArr, val);

    cout << "\n\n\nAlright, lets sort now..." << endl;

    sortNames(nameArr);

    cout << "\nHere are the results:\n" << endl;

    for (x = 0; x < val; x++)
    {
         cout << nameArr[x] << "\n" << endl;
    }

    system("pause");
 }

Python: why does it not use the created variable?

Why is this not working?

example:

x = 0
def print_x():
    x += 5
    print x

it does not know that the variable x exists why is this and how can i resolve this?

Thank you so much if you know this answer!

What does this program do? (Self calling main function + getchar)

Can anybody help me explain this question from a past exam paper? When I compile it, it is never satisfied with any input. Also, what is the reason for the self calling main function?

What does the following program do? Justify your answer.

#include <stdio.h>
int main ( void ) {
    int c;
    if (( c = getchar() ) != EOF) {
        main();
        printf("%c", c);
    }
    return 0; 
}

Using String functions on flattened chararray data

Objective : Using String functions on flattened chararray data

Input : test.txt

file_id     file_name       created_time            accesssed_by
   1          a1                1                       user1
   1          a2                2                       user1
   2          b1                3                       user1
   3          c1                4                       user1

Pig Script :

  A = LOAD '/Users/muralirao/Desktop/usertest.txt' USING PigStorage('\t') AS (file_id:long, file_name:chararray, created_time:long,accessed_by:chararray);
  B = GROUP A BY file_id;
  C = FOREACH B {
   sorted = ORDER A BY created_time DESC;
   user = A.accessed_by;
   uniq_user = DISTINCT user;
   last = LIMIT sorted 1;
   GENERATE UPPER(FLATTEN(last.file_name)) AS file_name, COUNT(uniq_user) AS access_count;
};

Trying to use any of the string manipulation functions on top of flattened chararray data type is resulting in the below ERROR.

ERROR org.apache.pig.tools.grunt.Grunt - ERROR 1200: <line 185, column 22>  mismatched input 'FLATTEN' expecting RIGHT_PAREN

Without using the string manipulation function on top of FLATTEN will result in the required data.

(a2,1)
(b1,1)
(c1,1)

Objective is to use some string manipulation functions to convert the file_name to the required format before persisting without going for another iteration of the data.

Going for one more iteration as below we are able to achieve our objective, can we avoid this and do the same earlier.

 D = FOREACH C GENERATE UPPER(file_name) AS file_name, access_count;

Output :

 (A2,1)
 (B1,1)
 (C1,1)

How to get the least and most common value in postgresql?

So the postgres wiki has a mode function we can add to our query and use. So, I modified it to get a lmode function, for least common value. The functions, on a single postgresql instance works great, until its part of a greenplum cluster. It goes from rapidfire, to dog slow.

I was curious to how I would be able to combine them so the query can run once to return both the most common and least common. It's okay if they aren't separate fields, I'm fine with a result like most,least.

Here is sql aggregate functions I've been using.

-- The unnest function is required for postgresql ^8.4 and lower, our green plum instance uses postgresql ~8.2
CREATE OR REPLACE FUNCTION public_work_tbls.unnest(anyarray)
  RETURNS SETOF anyelement AS
$BODY$
SELECT $1[i]
FROM   generate_series(array_lower($1,1), array_upper($1,1)) i
$BODY$
LANGUAGE sql IMMUTABLE;

-- Start: Function for Least common value --
CREATE OR REPLACE FUNCTION public_work_tbls._final_lmode(anyarray)
  RETURNS anyelement AS
$BODY$
    SELECT a
    FROM public_work_tbls.unnest($1) a
    GROUP BY 1
    ORDER BY COUNT(1) ASC, 1
    LIMIT 1;
$BODY$
LANGUAGE 'sql' IMMUTABLE;

-- Tell Postgres how to use our aggregate
CREATE AGGREGATE public_work_tbls.lmode(anyelement) (
  SFUNC=array_append, --Function to call for each row. Just builds the array
  STYPE=anyarray,
  FINALFUNC=public_work_tbls._final_lmode, --Function to call after everything has been added to array
  INITCOND='{}' --Initialize an empty array when starting
);
-- End: Function for least common value --

-- Start: Function for most common value --
CREATE OR REPLACE FUNCTION public_work_tbls._final_mode(anyarray)
  RETURNS anyelement AS
$BODY$
    SELECT a
    FROM public_work_tbls.unnest($1) a
    GROUP BY 1
    ORDER BY COUNT(1) DESC, 1
    LIMIT 1;
$BODY$
LANGUAGE 'sql' IMMUTABLE;

-- Tell Postgres how to use our aggregate
CREATE AGGREGATE public_work_tbls.mode(anyelement) (
  SFUNC=array_append, --Function to call for each row. Just builds the array
  STYPE=anyarray,
  FINALFUNC=public_work_tbls._final_mode, --Function to call after everything has been added to array
  INITCOND='{}' --Initialize an empty array when starting
);
-- End: Function for most common value --

Notes: The greenplum server I am using is on Postgresql 8.2

Thanks postgresql wizards

Custom Sorting Function

I am trying to sort the contents of a textbox (Which contains the names of people) alphabetically. When the user presses the button, the contents of the textbox is supposed to sort. This is what I have so far:

btn_alpha.addEventListener(MouseEvent.CLICK, alphabeticalSort);


function alphabeticalSort(Sort:Array):Array
{
for (var i:int = 0; i < Sort.length; i++)
{
    var sortArray:int = i;
    for (var ii = i+1; ii < Sort.length; ii++)
    {
        if (Sort[ii]["Name"] < Sort[sortArray]["Name"])
        {
            sortArray = ii;
        }
    }
    var temp:Object;
    temp = Sort[i];
    Sort[i] = Sort[sortArray];
    Sort[sortArray] = temp;
}

return Sort;
}

The program runs, but the textbox isn't sorted when the button is pressed. The only error that comes up is when you try and press the button, it says "TypeError: Error #1034: Type Coercion failed: cannot convert flash.events::MouseEvent@8686881 to Array."

Any suggestions on how to make this work would be appreciated!

My template code in C++ is generating odd errors I can't seem to resolve.

I am having some errors appear in my code and i can't figure them out. I reduced my code down to the very basic simple functions/class calls but still have issues with this.

#include <iostream>
using namespace std;

template <class T> 

class FC
{
private: 
    double netprofit, costofinvest;
    double curras, invent, curliab;
public: 

    void ROI(double np, double ci)
    {
     netprofit = np; costofinvest = ci;
    }

    double getROI()
    {
     return (netprofit - costofinvest) / costofinvest;
    }

    void ATR(double ca, double inv, double cl)
    {
     curras = ca; invent = inv; curliab = cl;
    }

    double getATR()
    {
    return (curras - invent) / curliab;
    }

};


int main()
{
 FC ROI, AcidTestRatio; 

 ROI.ROI(27, 288);
 cout << ROI.getROI() << endl;

 AcidTestRatio.ATR(77, 2l, 344);
 cout << AcidTestRatio.getATR() << endl;


return 0;
}

The errors I get look like this:

In function 'int main()':
39:22: error: missing template arguments before 'ROI'
41:2: error: 'ROI' was not declared in this scope
44:2: error: 'AcidTestRatio' was not declared in this scope

How to get arglist from a function handle?

I have the following function handle

 fun = @(x,y,z)[x.^3+y.^2+z.^2,x.^2-y.^3+sin(z)]

And now I am using the function

jacobian(fun, [x,y,z])

which returns the jacobian of the function. To use this function I first need to define

syms x y z. 

If the function changes to

@(x,y,z,w)[x.^3+y.^2+z.^2+w,x.^2-y.^3+sin(z)+w] 

the jacobian is returned by

jacobian(fun, [x,y,z,w]). 

Now I don't want to change the second input argument of the jacobian manually. Is there a function in Matlab, that looks at the function handles and returns them, or returns how many there are?

Many thanks!

R Debugger doesn't stop at breakpoints

I'm running a script in R (using R Studio) which calls several nested functions (the script calls a function, which has some code, and then calls another function, etc). I need to debug a function which is several levels down. I can get into the first function called by the script by placing a breakpoint on the line with the function call, and then stepping into the function. However, when I try to repeat this step to get into the next function (by having a breakpoint at the line for the next function call), R just keeps running the code until it's done. Even using the 'continue' command which claims "continue execution until the next breakpoint is encountered."

I can get to the other functions by stepping through line by line, and then stepping into each function once I reach it, but it would take a very long time to get where I need to this way.

Any thoughts are appreciated

JavaScript - Outputting a line with Document Write

I am trying to output a line with the javascript Document.Write function, however, on Submitting the form, the line just flashes and disappears

any thoughts?

<!DOCTYPE html>

<html>
    <head>
        <title>Form Validation</title>
    </head>
    <body>

        <script type="text/javascript">
            function checkAge() {

                var x = document.forms['myForm']['age'].value;

                if(x < 18) {
                    document.write("<p>You are too Young. Form NOT submitted</p>");
                } else {
                    document.write("Form sent successfully");
                }
            }

            function tips() {
                alert("Please enter your Name in the name Box, \nand Your age in the Age box.\nYou have to be Over 18 to submit the form");
            }
        </script>

        <form id="myForm" action="formvalidation.html" onsubmit="checkAge();">    
            Name: <input type="text" name="text" id="name">
            Age: <input type="text" name="age" id="age">
            <input type="submit" value="Submit">
            <input type="button" value="Help" id="hBtn" onclick="tips();">
        </form>
    </body>

</html>

Using function integer arguments with my C++ program

I have a little project to do, I've created a program that when the user types a number, it will say if it's even or odd. I even used a function. Here's my question:

How do I use integer arguments in a function for the program? (My program does work, it just doesn't use integer arguments.)

Instructions

Write a C++ function that accepts an integer argument, determines whether the passed integer is even or odd, and displays the result of this determination. (Hint: Use the % operator.)

Make sure your function is called from main(). Test the function by passing various data to it.

My code

#include <iostream>

using namespace std;

void oddEven() //My Function

{

int num;

cout<<"Please enter a number "<<endl;
cin>>num;

if (num % 2)

    {
    cout<<"It's odd"<<endl;
    }
else
    {
    cout<<"It's even"<<endl;
    }


}
int main() //Main program

{

oddEven(); //Calling my Function
    return 0;
}

How do i delay this function [duplicate]

This question already has an answer here:

i have this code

$('a[href*=#]').click(function(){
$('html, body').animate({
    scrollTop: $( $.attr(this, 'href') ).offset().top
}, 500);
return false;
});

But I need a 600ms delay after click the link so my page have chance to perform other actions that I set to 500ms, thank you in advance

Prevent loss of context for 'this' variable in a function passed as a parameter

Question

How can I prevent the loss of context for this variable inside a function passed as a parameter?

Simple Example, also in JSFiddle

var a = {
    start: function() {
        b.start( this.process );
    },

    process: function( justAParameter ) {
        justAParameter += ' of multiple contexts!'

        this.finish( justAParameter );
    },

    finish: function( finishParameter ) {
        console.log( finishParameter );
    }
}

var b = {
    start: function( justAFunction ) {
        justAFunction( 'Hello world' )
    }
}

a.start();

Expected Output

Hello world of multiple contexts!

Received Output

TypeError: this.finish is not a function

Function to search for string in array of strings

I am trying to write a function that searches for the unique part(maximum two characters) of a string in an array of strings. Although strstr and strchr are not working and crash my program for some reason. So I have resorted to trying to create something that resembles their function.

My question is this:
Why is strstr not working (something like strstr(lex[j],word)) and what am I doing wrong here?

Here is the code for the function that searches for two unique characters within an array of strings :

void convert(char word[]){
int i;

for(i=0;i<=strlen(word);i++){
    if(word[i]>=65 && word[i]<=90){
    word[i]=word[i]+32;
    }
}
}


int  twochar(char lex[50][50],char word[], int size,char temp[3]){
int i,j,k,count,totlen;
convert(word);

for(i=0;i<strlen(word)-1;i++){
    count=0;
    totlen=0;
    for(j=0;j<size;j++){
        convert(lex[j]);
        totlen+=strlen(lex[j])-1;
        for(k=0;k<strlen(lex[j])-1;k++){
            if(word[i]!=lex[j][k] || word[i+1]!=lex[j][k+1]){
                count++;
            }   
        }
    }
    if(count==totlen){
        temp[0]=word[i];
        temp[1]=word[i+1];
    }
}
}



int main(int argc, char *argv[]) {
char lex[50][50]={"","word2","word3","word4"}, word[]="test";
char p[3];

twochar(lex,word,4,p);
printf("%c%c\n",p[0],p[1]);
return 0;
}

Javascript - change paragraph Text on Each Button Click

I am trying to create 3 buttons, and using javascript, If button 1 is clicked then it changes the "Click a button" text to "You pressed Button 1"

Same for Button 2 and 3!

However, I can't seem to get it to work! Any help would be appreciated

Here is my Current Code:

<!DOCTYPE html>

<html>
    <head>
        <title>Button</title>
    </head>
    <body>

        <script type="text/javascript">
            function changeText() {

                var b1 = document.getElementById('b1');
                var b2 = document.getElementById('b2');
                var b3 = document.getElementById('b3');

                if(b1.onclick="changeText();") {
                    document.getElementById('pText').innerHTML = "You pressed button 1";
                }

                if(b2.onlick="changeText();") {
                    document.getElementById('pText').innerHTML = "You pressed Button 2";
                }

            }


        </script>

        <input type="button" value="Button 1" id="b1" onclick="changeText();"/>
        <input type="button" value="Button 2" id="b2" onclick="changeText();"/>
        <input type="button" value="Button 3" id="b3" onclick="changeText();"/>

        <p id="pText">Click on a Button</p>
    </body>
</html>

what is the fastest function in RDD spark

I'm implementing GroupBy function and it is "transformations" operation. I need that the my GroupBy function must be computed immediately, so I've found out a solution that calling another "action" operation after GroupBy then it will be computed. The running time of GroupBy is equal its + the "action" operation called and thus I need a fastest function to minimum total running time!!

thanks!

Get WooCommerce product gallery image caption

Quick Question for someone who knows their wordpress.

I'm using the following code to show the WC product gallery on the product page (in the right order).

Someone can quickly point me in the direction of including the image caption between the <p>'s?

global $product;
$attachment_ids = $product->get_gallery_attachment_ids();

echo '<div class="flexslider"><ul class="slides">';
foreach( $attachment_ids as $attachment_id ) 
{
echo '<li>';
  echo "<img src=".$image_link = wp_get_attachment_url( $attachment_id, 'large').">";
  echo '<p>';
  echo '</p>';
  echo '</li>';
}
echo '</ul></div>';

python - calling up function not working

def td():

choice = input("\nwhich trainning event would you like to access?\n1.swimming\n2.cycling\n3.running\n4.comare data\n5.final eight\nplease type in the number before the event of which you want to choose\n")
if choice == "1": ################################################
    swim()        # will call up a function depending on which option the user choices, the function will take the user to that menu

elif choice == "2":
    cyc()

elif choice == "3":
    run()

elif choice == "4":
    comp()

elif choice == "5":
    eight()

    ######################################################   

def swim():

  Swimming_file_exists = exists("Swimming_file.txt") # this will create a will for swimming as it has 'txt' in it or will get the swimming file that already exsits 
  if  Swimming_file_exists  == False:  # if the file doesnt exsit this will then create it

    Swimming_file = open("Swimming_file","w") # allows user to write to the file 
    Swimming_file.close
    Swimming_file = open("Swimming_file","a")  # open with the "a"  mode the write position will be at the end of the file


  else:
    Swimming_file = open("Swimming_file","a")

    totaldistance = input("what was the total distance you swam in meters?")
    totaltime = input("how long did you swim for in minutes?")
    speed = totaldistance/totaltime # formula for speed so the user doesnt have to work out the speed
    swimtype = input("\nwhich style did you swim\n1.slow freestyle\n2.fast freestyle\n3.backstroke\n4.breaststroke\n5.butterfly\n\nplease type in the number before the swimming style\n") 
    print ("Make sure these are the right values. If not pres ctrl z to undo any mistakes")
    time_hours = totaltime / 60 # this turns the minutes they swam into hours so i am able to calculate the calouries that they have burnt 

    if swimtype == "1":
        calb1 = time_hours * 236 # this is a formula to work out how many calouries the user has burnt for swimming  
    if swimtype == "2":
        calb1 = time_hours * 590
    if swimtype == "3":
        calb1 = time_hours * 413
    if swimtype == "4":
        calb1 = time_hours * 590
    if swimtype == "5":
        calb1 = time_hours * 649


    print ("on average you where swimming at a speed of", speed, "mps\nand you have burnt", clab1,"calories") # spped and calb1 are numbers which the program calculated so 
    score = totaldistance - totaltime # this will make the users score which will show the final 8 
    score_file.write(str(score)) #this will make the score a string and add the score in what thye got to the score file so it can get the final 8 later
    score_file.close()
    total = (totaldistance, totaltime, speed)
    Swimming_file.write(str(total)) # this adds all the swimming details to the file and saves it as a string 
    Swimming_file.close()
    score_file = open("score_file","w") # file for the score will be added and score will be calculated so users are able to see the final 8
    score_file = open("score_file","a")


def run():########################
score_file = open("score_file","w")
score_file = open("score_file","a")

Running_file_e = exists("Running_file.txt") # if the running file already exsits it will open that file
if  Running_file_e  ==False: # if it doesnt exsit this will create a new running file for the user

    Running_file = open("Running_file","w")
    Running_file.close
    Running_file = open("Running_file","a")
else:
    Running_file = open("Running_file","a")


    totaldistanceR = int(input("what was the total distance you ran in KM?"))
    totaltimeR = int(input("how long did you run for in minutes?"))
    print ("Make sure these are the right values.")
    totaltimeR1 = 60/totaltimeR  # this will but the inputed minuted into hours so the program can accuratly calculate the average speed of the runner 
    speedR1 = totaldistanceR/totaltimeR1
    calburn = (speedR1 * 95)/(60/totaltimeR1) # this is an easy formula so the amount of calouries the runner has burnt can be calculated
    score = totaldistance - totaltime
    score_file.write(str(score))
    score_file.close()



    print ("The records have been saved")
    print ("on average you where running at a speed of", speedR1, "KMph\nyou burnt",calburn," calouries")

    totalR = (totaldistanceR, totaltimeR, speedR1, calburn)
    Running_file.write(str(totalR))
    Running_file.close()



 def cyc():####################################
  score_file = open("score_file","w")
  score_file = open("score_file","a")
  Cycling_file_file_e = exists("Cycling_.txt")
  if  Cycling_file_file_e  ==False:

    Cycling_file_file = open("Cycling_file","w")
    Cycling_file_file.close
    Cycling_file_file = open("Cycling_file","a")

  else:
    Cycling_file = open("Cycling_file","a")

    totaldistancec = int(input("what was the total distance you cycled in KM?"))
    totaltimec = int(input("how long did you cycle for in minutes?"))
    print ("Make sure these are the right values. If not pres ctrl z to undo any mistakes")
    speedc = totaldistancec/totaltimec

    if speedc <10:
        caloriesb= 236 * totaltimec # this works out the calouries for the us4er depending on his input for the distance and time
    if speedc >=10 and speedc <=11.9:
        caloriesb= 354 * totaltimec
    if speedc >=12 and speedc <=13.9:
        caloriesb= 472 * totaltimec
    if speedc >=14 and speedc <=15.9:
        caloriesb= 590 * totaltimec 
    if speedc >=16 and speedc <=20:
        caloriesb= 708 * totaltimec
    if speedc >20:
        caloriesb= 944 * totaltimec

    print ("on average you where running at a speed of", speedc, "KMph\nyou burnt", caloriesb, " calories")
    score = totaldistance - totaltime
    score_file.write(str(score))
    score_file.close()
    totalc = (totaldistancec, totaltimec, speedc)
    Cycling_file.write(str(totalc))
    Cycling_file.close()
    Personaldetails_file.close()



def comp():####################################
Username_file = open ("Username.txt", "r")


Username_file.close()


which_event = input("Which event will you like to compare\n1.swimming\n2.cycling\n3.running\n")
if which_event == "3":
    competitor3 = input("who would you like to compare your data with")
    for n in range (len(ausers)): # this finds the user which the first user is looking for
        x = n + 1
        print (x, ausers[n]) # displays the other usres running details 
        person = ausers[(competitor3 - 1)] #calculates the actual name of the selected user by inputted integer
        run1 = open("Running_file","r") # the "r" is so that the file will only be read 
        line1 = Username_file.readlines()# this reads whole file content into memory 
        run1.close()



if which_event == "2":
    competitor2 = input("who would you like to compare your data with")
    for n in range (len(ausers)): # "(len" is the nembered length of the users 
       x = n + 1 # as python starts counting from 0 this makes it start counting from 1 
       print (x, ausers[n])
       person = ausers[(competitor2 - 1)]
       cyc1 = open("Cycling_file","r")
       line2 = Username_file.readlines()
       cyc1.close()


if which_event == "1":
    competitor1 = input("who would you like to compare your data with")
    for n in range (len(ausers)):
        x = n + 1
        print (x, ausers[n])
        person = ausers[(competitor1 - 1)]
        swim1 = open("Swimming_file","r")
        line1 = Username_file.readlines()
        swim1.close()

for some reason when I type a 1, 2 or 3 the program skips to option 4. I don't know why. it use to work a while ago but I cant remember what I did to make it skip the other functions does anyone know why? thank you