mardi 5 mai 2015

How would I make a program that meets these requirements? I need to

Your instructor is in a bind. His place of work has instituted a new technology project that will require remote access verification. In addition to his username and password, he will have a “challenge” to each sign-on. That challenge will require that he input a number or letter depending on what the security application asks him.

But your instructor is lazy. He wants an application that will tell him what those appropriate numbers are without him having to look them up each time. He understands that this will help foil remote hackers, but he does not want to be stuck carrying around a piece of paper all the time.

Write your instructor a program that gives him the three characters asked for. The matrix to use is:

A B C D E F G H I J 1 3 N 1 M 4 R X 5 F N 2 N V T 5 K Q F M 3 P 3 9 K 1 Y R 4 V T F 3 4 3 3 9 V 4 Y R T N N 5 3 1 1 3 2 9 X P N P

A challenge of A1:B2:C3 would yield 3 V 1.

A challenge of G4:D2:J3 would yield R 5 3.

Algorithm

Use a 5x10 matrix to load each the matrix above.

After you get the input, separate the two characters

First character is the column. Translate the letter to the appropriate array number (A = 0, B = 1, etc.)

Second character is the row. Subtract one from the number given to get the proper array number (arrays start counting at zero!).

You now have the row and column for each challenge.

Search the 5x10 array you have created using the row, column you just found

Display the proper number/character to the user (under the appropriate challenge).

This is what I have so far... In the Driver class:

public class Driver { public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);
    System.out.println("Please enter the challenge sepereated by colons:");
    String challenge = scan.nextLine();


    //static call to method that separates the challenge
    String challegeresult =  null;

    // sysprint to print out the contents of the array

    System.out.println("The three characters you need are " + challegeresult + "."); //add the challenge result
    System.out.println(challengevalue); //add the challenge result

}

In the util class:

public class Util {

// put in my matrix
                    //A    B    C    D    E    F    G    H    I     J
String[][] tom = {  {"3", "N", "1", "M", "4", "R", "X", "5", "F", "N"},
                    {"N", "V", "T", "5", "K", "Q", "F", "M", "3", "P"},
                    {"9", "K", "1", "Y", "R", "4", "V", "T", "F", "3"},
                    {"3","3", "9", "V", "4", "Y", "R", "T", "N", "N"},
                    {"3", "1", "1", "3", "2", "9", "X", "P","N", "P"} };

//method to separate the challenge

public static void seperate () {
}

//method to turn the letter into the number

public static void lettertonum(){

}

//method to subtract 1 from the number

public static void subonefromnum (){

}

//method to look up the answer

public static void answerlookup () {

}

Convert value from specific multidimensional array key into key in new array with original arrays as value

Basically I just would like to know if there is a built-in way of doing this, that might be faster, like maybe with an array_map callback or something:

function array_rekey($a, $column)
{
    $array = array();
    foreach($a as $keys) $array[$keys[$column]] = $keys;
    return $array;
}

Multidimensional Arrays in Ruby like C++

I had previously created a struct and an array of the same in C++ , now i want to implement the same in Ruby.

/ Number of Elements (Which can be increased) :D
#define ELM_NO 110

struct elem
{
  char name[18];
  char elm_symbol[5];

  double atm_weight;

  int elm_melting;
  int elm_boiling;
  int elm_yearofdis;
  int elm_group;

  double elm_ionis_e;
};

elem element[ELM_NO] = { {" Hydrogen"  ,"H"  ,1.0079 ,-259 ,-253 ,1776 ,1  ,13.5984 },
                      {" Hydrogen"  ,"H"  ,1.0079 ,-259 ,-253 ,1776 ,1  ,13.5984  } ,
                      {" Helium"  ,"He" ,4.0026 ,-272 ,-269 ,1895 ,18 ,24.5874  } ,
                      {" Lithium" ,"Li" ,6.941  ,180  ,1347 ,1817 ,1  ,5.3917 } ,
                      {" Beryllium" ,"Be" ,9.0122 ,1278 ,2970 ,1797 ,2  ,9.3227 } ,
                      {" Boron" ,"B"  ,10.811 ,2300 ,2550 ,1808 ,13 ,8.298  } ,
                      {" Carbon"  ,"C"  ,12.0107  ,3500 ,4827 ,0  ,14 ,11.2603  } ,
                      {" Nitrogen" ,"N"  ,14.0067  ,-210 ,-196 ,1772 ,15 ,14.5341  } ,
                      {" Oxygen" ,"O"  ,15.9994  ,-218 ,-183 ,1774 ,16 ,13.6181  } ,
                      {" Fluorine" ,"F"  ,18.9984  ,-220 ,188  ,1886 ,17 ,17.4228  } ,
                      {" Neon" ,"Ne" ,20.1797  ,-249 ,-246 ,1898 ,18 ,21.5645  } ,
                      {" Sodium" ,"Na" ,22.9897  ,98 ,883  ,1807 ,1  ,5.1391 } ,
                      {" Magnesium"  ,"Mg" ,24.305 ,639  ,1090 ,1755 ,2  ,7.6462 } ,
                      {" Aluminum" ,"Al" ,26.9815  ,660  ,2467 ,1825 ,13 ,5.9858 } };

Omitted some parts.

Now , I want to implement in Ruby . The problem is I don't know how to implement 2D arrays from which we can access an Individual Element from the Inner Array.

I have checked on previous Questions , and found that the answers were not either clear or were concerned with Narrays.

Can anybody show me how it's done ?

How to showing the date_part all

I have a data array's like this. and I want to make this data into grafik. and the problem is when i put the script

if (isset($b['admin'])) {
      echo $b['admin'];
      $series = $this->HighCharts->addChartSeries();
      $series->addName($user)->addData([(int)$b['admin']]);
      $mychart->addSeries($series);
}

in the foreach($datas as $a){. why the date_part 3 couldn't be show?

QUERY RESULT ARRAY

$array = array(
        (int) 0 => array( 
                        'B' => array(
                                    'company' => 'ABC' 
                        ), 
                        'User' => array( 
                                    'company' => 'abc' 
                        ), 
                        (int) 0 => array(
                                    'date_part' => '3',
                                    'jumlah' => null, 
                                    'jumbuy' => '50990', 
                                    'admin' => '50010' 
                        )
        ),
        (int) 1 => array(
                        'B' => array( 
                                    'company' => 'BCD'
                        ), 
                        'User' => array( 
                                    'company' => 'bcd' 
                        ), 
                        (int) 0 => array( 
                                    'date_part' => '3',
                                    'jumlah' => null, 
                                    'jumbuy' => '65000', 
                                    'admin' => '5000' )
        ),
        (int) 2 => array(
                        'B' => array(
                                    'company' => 'ABC' 
                        ), 
                        'User' => array( 
                                    'company' => 'abc' 
                        ), 
                        (int) 0 => array(
                                    'date_part' => '4',
                                    'jumlah' => null, 
                                    'jumbuy' => '98990', 
                                    'admin' => '2010' )
        ),
        (int) 3 => array(
                        'B' => array(
                                    'company' => 'CDE'
                        ), 'User' => array( 
                                    'company' => 'cde' 
                        ), 
                        (int) 0 => array(
                                    'date_part' => '4',
                                    'jumlah' => null, 
                                    'jumbuy' => '34566', 
                                    'admin' => '2010' )
        ),
        (int) 4 => array(
                        'B' => array( 
                                    'company' => 'BCD'
                        ), 
                        'User' => array( 
                                    'company' => 'bcd' 
                        ), 
                        (int) 0 => array( 
                                    'date_part' => '4',
                                    'jumlah' => null, 
                                    'jumbuy' => '9000', 
                                    'admin' => '5000' )
        ),
);

IN CONTROLLERS

$chartName = 'Line Chart with Data Labels';
$tooltipFormatFunction = <<<EOF
function() { return '<b>'+ this.series.name +'</b><br/>'+ this.x +': '+ this.y +'°C';}
EOF;

    $mychart = $this->HighCharts->create($chartName, 'line');

    $data = array();
    foreach($report_posts as $values) {
        if (!isset($data[$values['User']['company']])) {
            $data[$values['User']['company']] = $values;
        } else {
            $last_element = array_pop($values);
            $data[$values['User']['company']][] = $last_element;
        }
    }
    $datas = array_values($data);

    foreach ($datas as $a) {
            $user = [$a['User']['company']];
            foreach ($a as $b) {
                if (isset($b['date_part'])) {
                    $this->HighCharts->setChartParams($chartName, array(
                            'renderTo' => 'linewrapper', // div to display chart inside
                            'chartWidth' => 1000,
                            'chartHeight' => 750,
                            'chartMarginTop' => 60,
                            'chartMarginLeft' => 90,
                            'chartMarginRight' => 30,
                            'chartMarginBottom' => 110,
                            'chartSpacingRight' => 10,
                            'chartSpacingBottom' => 15,
                            'chartSpacingLeft' => 0,
                            'chartAlignTicks' => FALSE,
                            'chartTheme' => 'dark-green',
                            'title' => 'Monthly Average Temperature',
                            'subtitle' => 'Source: WorldClimate.com',
                            'titleAlign' => 'center',
                            'titleFloating' => TRUE,
                            'titleStyleFont' => '18px Metrophobic, Arial, sans-serif',
                            'titleStyleColor' => '#0099ff',
                            'titleX' => 20,
                            'titleY' => 10,
                            'legendEnabled' => TRUE,
                            'legendLayout' => 'horizontal',
                            'legendAlign' => 'center',
                            'legendVerticalAlign ' => 'bottom',
                            'legendItemStyle' => array('color' => '#222'),
                            'legendBackgroundColorLinearGradient' => array(0, 0, 0, 25),
                            'legendBackgroundColorStops' => array(array(0, 'rgb(217, 217, 217)'), array(1, 'rgb(255, 255, 255)')),
                            'tooltipEnabled' => TRUE,
                            'tooltipFormatter' => $tooltipFormatFunction,
                            'xAxisLabelsEnabled' => TRUE,
                            'xAxisLabelsAlign' => 'right',
                            'xAxisLabelsStep' => 1,
                            'xAxislabelsX' => 5,
                            'xAxisLabelsY' => 20,
                            'xAxisCategories' => [$b['date_part']],
                            'yAxisTitleText' => 'Admin',
                            'plotOptionsLineDataLabelsEnabled' => TRUE,
                            'plotOptionsLineEnableMouseTracking' => TRUE,
                            'enableAutoStep' => FALSE
                        )
                    );
                }//end if

            }//end foreach

        if (isset($b['admin'])) {
            echo $b['admin'];
            $series = $this->HighCharts->addChartSeries();
            $series->addName($user)->addData([(int)$b['admin']]);
            $mychart->addSeries($series);
        }

    }

Array sent from Android to PHP via $_POST getting mucked up in transit

This problem is driving me crazy and I have no idea how to fix it. I have an Android program to gather all names and phone numbers into an array (basic key-value pairs) and then send that array over to a PHP script. The PHP script then parses the values received in a $_POST and inserts them into a MySQL table. Everything works fine except that the data doesn't always come as posted. For instance, some numbers get paired with names they don't belong to. Here's a snippet of my PHP:

$ar = 0;
foreach($_POST as $entry){
    echo $ar.". ".$_POST[$ar]."\n";
    $namenum = explode(',', $entry);
    $names[$ar] = $namenum[1];
    $numbers[$ar] = $namenum[0];
    echo $ar.". ".$numbers[$ar]."--->".$names[$ar]."\n"; 
    $ar += 1;
}
$namenum = NULL;
//$ar = NULL;

The above snippet is right at the beginning of the script and there's nothing to tamper with $_POST. The echo within the loop is to test this exact thing and that's how I discovered the problem. The weirdest part is that most of the time, the data received is exactly as sent. But then at times I suddenly notice a couple of numbers getting either mixed up with wrong names or disappearing altogether. I must also add that each time I have tested the program, I've done it on the same device, using the same contact list. Everything remains the same between test runs and yet results vary at random. The gremlins seem to be appearing in transit! Is this a known issue with $_POST or sending arrays in general? If so, what alternatives do I have? I can think of JSON or text files but would that ensure better data fidelity?

jQuery autocomplete - assigning one JSON PHP array to multiple HTML ID tags

I have successfully setup a jQuery autocomplete call from a PHP file using JSON encode. I am successfully sending a KVP (Key Value Pair) array back to my HTML.

The issue I have, is that I wish to send part of the array items to one id="sometag1" and the other array items to id="sometag2" and id="sometag3".

Here is my javascript jquery code:

jQuery(document).ready(function(data) {
    $('#edit-ad-location').autocomplete({
        source: '/postcodes-latlong.php',
        minLength: 2
    });
});

The file "postcodes-latlong.php" contains the following code:

$rs = mysql_query('select p.ID, p.post_title, m.* FROM wp_posts p, wp_postmeta m WHERE p.ID = m.post_id AND p.post_title like "' . mysql_real_escape_string($_REQUEST['term']) . '%" AND meta_value is NOT NULL AND meta_value !="" AND (meta_key = "_aphs_FYN_latitude" OR meta_key = "_aphs_FYN_longitude") order by post_title limit 0,25', $dblink);
$this_row = "";
// loop through each postcode returned and format the response for jQuery
$data = array();
if ($rs && mysql_num_rows($rs)) {
    while ($row = mysql_fetch_array($rs, MYSQL_ASSOC)) {
        $new_row = $row['post_title'];
        if ($new_row != $this_row) {
            $data[] = array(
                'id' => $row['meta_id'],
                'label' => $row['post_title'],
                'value' => $row['post_title']
            );
        }
        if ($row['meta_key'] == "_aphs_FYN_latitude") {
            $data[] = array_push($data, array(
                'id' => 'geo-search-lat',
                'value' => $row['meta_value']
            ));
        }
        if ($row['meta_key'] == "_aphs_FYN_longitude") {
            $data[] = array_push($data, array(
                'id' => 'geo-search-lng',
                'value' => $row['meta_value']
            ));
        }
        $this_row = $row['post_title'];
    }
}
// jQuery wants JSON data
echo json_encode($data);
flush();

And if the term 4503 is passed, we get the following returning array:

[{
    "id": "384047",
    "label": "4503, DAKABIN",
    "value": "4503, DAKABIN"
}, {
    "id": "geo-search-lat",
    "value": "-27.226474"
}, 2, {
    "id": "geo-search-lng",
    "value": "152.980732"
}, 4, {
    "id": "384062",
    "label": "4503, GRIFFIN",
    "value": "4503, GRIFFIN"
}, {
    "id": "geo-search-lat",
    "value": "-27.272654"
}, 7, {
    "id": "geo-search-lng",
    "value": "153.025911"
}, 9, {
    "id": "384077",
    "label": "4503, KALLANGUR",
    "value": "4503, KALLANGUR"
}, {
    "id": "geo-search-lat",
    "value": "-27.25075"
}, 12, {
    "id": "geo-search-lng",
    "value": "152.992606"
}, 14, {
    "id": "384092",
    "label": "4503, KURWONGBAH",
    "value": "4503, KURWONGBAH"
}, {
    "id": "geo-search-lat",
    "value": "-27.225828"
}, 17, {
    "id": "geo-search-lng",
    "value": "152.947552"
}, 19, {
    "id": "384107",
    "label": "4503, MURRUMBA DOWNS",
    "value": "4503, MURRUMBA DOWNS"
}, {
    "id": "geo-search-lat",
    "value": "-27.258672"
}, 22, {
    "id": "geo-search-lng",
    "value": "153.006916"
}, 24, {
    "id": "384122",
    "label": "4503, WHITESIDE",
    "value": "4503, WHITESIDE"
}, {
    "id": "geo-search-lat",
    "value": "-27.255364"
}, 27, {
    "id": "geo-search-lng",
    "value": "152.929729"
}, 29]

What I am trying to achieve, is send the ID, label and value (i.e. post_id, postcode, and suburb name) to the autocomplete field with id: "#edit-ad-location" and this works fine. But, I wish to send the latitude and longitude values to two other id tags #geo-search-lat and #geo-search-lng as shown below:

<div .... id="geo-search-lat" value=""> </div>

and

<div .... id="geo-search-lng" value=""> </div>

I have tried a number of approaches including converting the PHP JSON array to a Javascript array also trying to pass the JSON array as PHP array rather than JSON...

But I am struggling to glue all this together.

Is there a simple way to parse the array so that part of the KVP's go to one ID tag, and the rest goes to two other ID tags?

Something along the lines of:

jQuery(document).ready(function(data){
    $('#edit-ad-location', '#geo-search-lat', '#geo-search-lng').autocomplete({source:'/postcodes-latlong.php', minLength:2});
});

But if I try this approach returns an error.

You can try sending australian postcodes to the following URL and test it for yourslef:

http://ift.tt/1ckqpn9

Where XXXX is any integer from 0 to 9999.

Any help is appreciated.

Cheers, Henry

Need help accessing JSON array object

Objective: This code collects an array JSONAPIS and passes the APIS into a $.each() loop. Then JSON data field are evaluated in if statements and used to calculate precip. How do I access the JSONAPIS from the obj. Main issue: obj.daily.data.length is undefined on the daily array member. The obj should contain one of the API calls and the JSON dataset to use. Instead it contains keyword like abort, always, promise which I am not familiar how to use. What would access the result JSON object property?

var listAPIs = "";
    var darkForecastAPI = [];
    var result = [];
    var JSONAPIS = [];
$.each(numDaysAPITimes, function(a, time) {
    var darkForecastAPI = /*"http://ift.tt/1eU3pXU" + currentAPIKey + "/history_" + time + "/q/" + state + "/" + city +".json?callback=?"; */
        "http://ift.tt/1JmMFqC" + currentAPIKey + "/" + city + time + "?callback=?";
    //http://ift.tt/1iYC1hI
    JSONAPIS.push($.getJSON(darkForecastAPI, {
        tags: "WxAPI[" + i + "]", //Is this tag the name of each JSON page? I tried to index it incase this is how to refer to the JSON formatted code from the APIs.
        tagmode: "any",
        format: "json"
    }));
});
$.when(JSONAPIS).then(function(result) { /*no log simply an array */
    var eachPrecipSum = 0.0;
    var totalPrecipSinceDate = 0.0;
    alert(result);

    $.each(result, function(d, obj) {
        for (var c = 0; c <= obj.daily.data.length - 1; c++) {
            if (obj.daily.data[c].precipIntensity >= 0.0000 && obj.daily.data[c].precipType == "rain") /*Number(result.history.dailysummary.precipm, result.history.dailysummary.rain*/ {
                eachPrecipSum = result[d].daily.data[c].precipIntensity;
                totalPrecipSinceDate = eachPrecipSum + totalPrecipSinceDate; ///Write mean precip
                alert(Math.round(eachPrecipSum * 10000) / 10000);
                $("body").append("p").text("There has been as least a total of " + Math.round(totalPrecipSinceDate * 10000) / 10000 + " inches per hour of rain at the location in the last " + userDataDatePick + " days")

            } else if (obj.daily.data[c].precipIntensity >= 0.0000 && obj.daily.data[c].precipType != "rain") {
                alert("There is was no rain on ____" /*+ result.history.dailysummary.mon + "/" + result.history.dailysummary.mday + "/" + result.history.dailysummary.year*/ );
            }
        }
    });
});
numDaysAPITimes = 0;

}