mardi 4 août 2015

Extracting elements of a tuple from an array of tuples in swift

I have managed quite easily to extract tuple from an array of tuples however I am stumped as to how to extract the elements of the tuple.

//: Playground - noun: a place where people can play

import UIKit

import Foundation

class ActivityDetailsModel {


    var activityCategory: String! // The choice of major activity


    init(activityCategory: String){
        self.activityCategory = activityCategory
    }

    class func activityForm(activityCategory: String) -> [(Question: String, Answer: String)] {
        var activityProfile: [(Question: String, Answer: String)] = [] //An array of tuples containing the users activity details

        switch activityCategory {
        case "Sport":
            activityProfile = [(Question:  "Home Club", Answer: "a"),(Question: "Other venues", Answer: "b")]// [, ["Activity days – Mon – Sunday": "c"], ["Player strength": "d"], ["Age group to play with": "e"]]
            return activityProfile
        case "Recreation":
            activityProfile = [(Question:  "Home Club2", Answer: "ab"),(Question: "Other venues3", Answer: "bc")]
            return activityProfile

        default:
            var activityProfile = [(Question:  "nixs", Answer: "nie")]
            return activityProfile
        }

    }


}
var actProf:[(Question: String, Answer: String)]
actProf = ActivityDetailsModel.activityForm("Recreation")
println(actProf[1])

This returns the second tuple from the array - all I need now is to extract the elements of the tuple

How to avoid creating a copy of an array of objects in swift

I have a dictionary of arrays that contain one kind of objects : database records. Each array is like a table associated to a key (table name) in the dictionary.

My issue is: How do I update a table (delete a record, add a record, etc) without making any temporary copy of the table, like I would do with an NSDictionary of NSArrays ?

Currently, I do :

func addRecord(theRecord: DatabaseRecord, inTable tableName: String)
{
    if var table = self.database[tableName]
    {
        table.append(theRecord)
        self.database[tableName] = table
    }
    else
    {
        self.database[tableName] = [theRecord];
    }
}

The issue is: a temporary copy of the table is made twice. This is pretty inefficient.

loop through multidimensional array and order sub-array by scores

I am trying to calculate the winning order of golfers when they are tied in a competition.

The rules are to use a "countback". i.e., if scores are tied after 9 holes, the best placed of the ties is the best score from the last 8 holes. then 7 holes, etc.

The best I can come up with is 2 arrays.

  1. An array with all the players who tied in a given round. ($ties)
  2. One which has the full score data in (referencing the database playerid) for all 9 holes. ($tie_perhole)

I loop through array 1, pulling data from array 2 and using the following formula to create a temporary array with the highest score:

$max = array_keys($array,max($array));

If $max only has 1 item, this player is the highest scorer. the loop through the first array is "by reference", so on the next iteration of the loop, his playerid is now longer in the array, thus ignored. this continues until there is only 1 playerid left in the first array.

However, it only works if a single player wins in each iteration. The scenario that doesn't work is if a sub-set of players tie on any iterations / countbacks.

I think my problem is the current structure I have will need the original $ties array to become split, and then to continue to iterate through the split arrays in the same way...

As an example...

The $ties array is as follows:

Array 
( 
    [18] => Array 
        ( 
            [0] => 77 
            [1] => 79 
            [2] => 76 
            [3] => 78 
        ) 
)

The $tie_perhole (score data) array is as follows:

Array 
( 
    [18] => Array 
        ( 
            [77] => Array 
                ( 
                    [9] => 18 
                    [8] => 16 
                    [7] => 14 
                    [6] => 12 
                    [5] => 10 
                    [4] => 8 
                    [3] => 6 
                    [2] => 4 
                    [1] => 2 
                ) 
            [79] => Array 
                ( 
                    [9] => 18 
                    [8] => 17 
                    [7] => 15 
                    [6] => 14 
                    [5] => 11 
                    [4] => 9 
                    [3] => 7 
                    [2] => 5 
                    [1] => 3 
                ) 
            [76] => Array 
                ( 
                    [9] => 18 
                    [8] => 16 
                    [7] => 14 
                    [6] => 12 
                    [5] => 10 
                    [4] => 8 
                    [3] => 6 
                    [2] => 4 
                    [1] => 2 
                ) 
            [78] => Array 
                ( 
                    [9] => 18 
                    [8] => 17 
                    [7] => 15 
                    [6] => 13 
                    [5] => 11 
                    [4] => 9 
                    [3] => 7 
                    [2] => 5 
                    [1] => 3 
                ) 
        ) 
) 

So in this competition, player's 78 and 79 score highest on the 8th hole countback (17pts), so 1st and 2nd should be between them. Player 79 should then be 1st on the 6th hole countback (14pts, compared to 13pts). The same should occur for 3rd and 4th place with the 2 remaining other players.

There are other scenarios that can occur here, in that within a competition, there will likely be many groups of players (of different amounts) on different tied points through the leaderboard.

Also note, there will be some players on the leaderboard who are NOT tied and stay in their current outright position.

The basics of the working code I have is:

foreach ($ties as $comparekey => &$compareval) {
$tie_loop = 0;
for ($m = 9; $m >= 1; $m--) {
    $compare = array();
    foreach ($compareval as $tie) {
        $compare[$tie] = $tie_perhole[$comparekey][$tie][$m];
    }
    $row = array_keys($compare,max($compare));

    if (count($row) == 1) {
        $indexties = array_search($row[0], $ties[$comparekey]);
        unset($ties[$comparekey][$indexties]);
        // Now update this "winners" finishing position in a sorted array
        // This is a multidimensional array too, with custom function...
        $indexresults = searchForId($row[0], $comp_results_arr);
        $comp_results_arr[$indexresults][position] = $tie_loop;
        $tie_loop++;
    }
    // I think I need conditions here to filter if a subset of players tie
    // Other than count($row) == 1
    // And possibly splitting out into multiple $ties arrays for each thread...

    if (empty($ties[$comparekey])) {
        break;
    }
}
}
usort($comp_results_arr, 'compare_posn_asc');
foreach($comp_results_arr as $row) {
    //echo an HTML table...
}

Thanks in advance for any helpful insights, tips, thoughts, etc...

PHP: Adding to array replaces previous value

What I'm trying to do:
Pull data from a database and insert it into an array

The code I'm using:

sql = "SELECT * FROM `products`, categories WHERE category = cat_ID AND pro_ID = " . $_GET['id'];
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        // output data of each row
        while($row = $result->fetch_assoc()) {
            $name = $row['pro_name'];
            $cartContents[$name] = array(
                "id" => $row['pro_ID'],
                "name" => $row['pro_name'],
                "price" => $row['price'],
                "quantity" => $_GET['q']
            );
        }

The problem:
This does indeed take the values from the database and insert them into the array, but it replaces everything dat was in the array before this.

What I've tried:
- Replacing array(...) with [...]
- Using the following code:

$cartContents[$name]["id"] = $row['pro_ID'];
$cartContents[$name]["name"] = $row['pro_name'];
$cartContents[$name]["price"] = $row['price'];
$cartContents[$name]["quantity"] = $_GET['q'];

Any help would be greatly appreciated, thank you!

Using Hashmap contains to check for a duplicate key

So i have an interface.

    public interface ARecord {
        public BigInteger getAutoID();
        public String getACompId();
}

and

    public class APPPRecord extends AbstratAPRecord implements ARecord{
    private BigInteger autoID;
    private String ACompId = null;
   //setter and getter}

In service,

    List<APPPRecord> PFRecord = null;
    while(scroll.next()){
    APPPRecord item = (APPPRecord) scroll.get(0);
    List<ARecord> recs = new ArrayList<ARecord>();
    recs.addAll(PFRecord);

My PFRecord list has results that are being duplicated. I have to use hash maps that can check for ACompId contains key. If the key already exists don't pass it to recs.addAll. How can I go about doing this? Any help appreciated

Facebook Ads API message '(#17) User request limit reached'

Good Day All,

I'm working on retrieving facebook ad stats through the Facebook Ads php sdk. I'm able to retrieve the stats the way I want, but I keep running into a rate limit problem. I don't think I'm making an absurd amount of calls to the api and I don't intend to other than to retrieve daily stats for a list of clients. I'm wondering anyone here sees a way I can make the calls, without receiving {message '(#17) User request limit reached} to get the stats and insights every day for all of our ad sets. Ultimately, we have about 10-20 campaigns running at any time and I need to report on these stats daily for clients. The example below returns only 4 ads within this adset. Anything higher than this, I typically receive the error message.

<?php

include 'vendor/vendor/autoload.php';
$ACCESS_TOKEN = '****';
$APP_ID = '****';
$APP_SECRET = '****';
$appsecret_proof= hash_hmac('sha256', $ACCESS_TOKEN, $APP_SECRET);  

use FacebookAds\Api;
Api::init($APP_ID, $APP_SECRET, $ACCESS_TOKEN, $appsecret_proof);

use FacebookAds\Object\AdUser;

//$user = (new AdUser('me'))->read(array('id'));
//echo $user->id ."\n";

use FacebookAds\Object\AdAccount;
use FacebookAds\Object\AdAccountFields;
use FacebookAds\Object\AdCampaign;
use FacebookAds\Object\AdCreative;
use FacebookAds\Object\Fields\AdCreativeFields;
use FacebookAds\Object\AdGroup;
use FacebookAds\Object\AdSet;
use FacebookAds\Object\Values\InsightsPresets;
use FacebookAds\Object\Values\AdObjectives;

$insightsFields = array(
    'actions',
    'cpm',
    'ctr',
    'frequency',
    'impressions',
    'reach',
    'social_clicks',
    'social_impressions',
    'social_reach',
    'spend',
    'website_clicks',
    'video_p25_watched_actions',
    'video_p50_watched_actions',
    'video_p75_watched_actions',
    'video_p95_watched_actions',
    'video_p100_watched_actions',
    'video_avg_sec_watched_actions'
);
$statsFields = array(
    'actions',
);
$impressionCheck = array(
    'impressions',
);
$imageFields = array(
    'creative',
);
$adSetFields = array(
    'id',
    'name',
    'campaign_status'
);
$adGroupFields = array(
    'creative',
    'id',
    'name',
    'adgroup_status'
);  
$campaignFields = array(
    'id',
    'name',
    'campaign_group_status'
);
$campaignParams = array(        
    'date_preset' => InsightsPresets::LAST_MONTH,
);
$params = array(
    'date_preset' => InsightsPresets::LAST_MONTH,
);
$statsParams = array(
    'date_preset' => 'last_month',
);


/* Global Insights Variables */
$responseArray = '';
$facebook_cpm = '';
$facebook_ctr = '';
$facebook_frequency = '';
$facebook_impressions = '';
$facebook_reach = '';
$facebook_spend = '';
$facebook_website_clicks = '';
$video25Watched = '';
$video50Watched = '';
$video75Watched = '';
$video100Watched = '';
$videoAverageWatched = '';

/* Global Stats Variables */    
$facebookComment = '';
$facebookLike = '';
$facebookLinkClick = '';
$facebookMention = '';
$facebookOffsiteConversion = '';
$facebookPhotoView = '';
$facebookPost = '';
$facebookPostLike = '';
$facebookUnlike = '';
$facebookVideoPlay = '';
$facebookVideoView = '';
$facebookPageEngagement = '';
$facebookPostEngagement = '';
$facebookCheckin = '';

$account = new AdAccount('****');
$campaigns = $account->getAdCampaigns($campaignFields, $campaignParams);    

    $campaign = new AdCampaign('****');
    $adSets = $campaign->getAdSets($adSetFields, $params);

    foreach($adSets as $adSetKey => $adSetValue){                   
        $adSetID = $adSetValue->id;
        $adSetName = $adSetValue->name;         

        $adSet = new AdSet($adSetID);

        $adSetImpressionCheck = $adSet->getInsights($impressionCheck, $params); 
        $impressionsTrue = '';
        foreach($adSetImpressionCheck as $i => $c){
            $impressionsTrue = $c->impressions;
        }

        if ($impressionsTrue > 0){
            $adGroups = $adSet->getAdGroups($adGroupFields, $params);           
            foreach($adGroups as $k => $v){
                $adGroupID = $v->id;
                $adGroupName = $v->name;
                $adGroupCreative = $v->creative;                    

                $adGroup = new AdGroup($adGroupID);

                $insights = $adGroup->getInsights($insightsFields, $params);    
                $stats = $adGroup->getStats($statsFields, $params);

                foreach($insights as $key => $response){                        
                    $facebook_cpm = $response->cpm;
                    $facebook_ctr = $response->ctr;
                    $facebook_frequency = $response->frequency;
                    $facebook_impressions = $response->impressions;
                    $facebook_reach = $response->reach;
                    $facebook_spend = $response->spend;
                    $facebook_website_clicks = $response->website_clicks;
                    $facebook_date = $response->date_start;
                    $responseArray = $response->actions;
                    $adSetNameLowerCase = strtolower($adSetName);
                    if (strpos($adSetNameLowerCase, 'video') !== false){
                        $video25Watched = $response->video_p25_watched_actions[0]['value'];     
                        $video50Watched = $response->video_p50_watched_actions[0]['value'];
                        $video75Watched = $response->video_p75_watched_actions[0]['value'];
                        $video95Watched = $response->video_p95_watched_actions[0]['value'];
                        $video100Watched = $response->video_p100_watched_actions[0]['value'];
                        $videoAverageWatched = $response->video_avg_sec_watched_actions[0]['value'];
                        $videoActions = '
                            <li>25% Watched: '. $video25Watched .'</li>
                            <li>50% Watched: '. $video50Watched .'</li>
                            <li>75% Watched: '. $video75Watched .'</li>
                            <li>95% Watched: '. $video95Watched .'</li>
                            <li>100% Watched: '. $video100Watched .'</li>
                            <li>Average Video Watched: '. $videoAverageWatched .'</li>
                        ';
                    }                       
                    $returnInsights .= '                        
                        <strong style="display:block">'. $adSetName .'</strong>
                        <ul style="margin-left:40px">               
                            <li><strong>'. $adGroupName .'</strong></li>
                            <li><a href="'. $adGroupCreative .'">Ad Preview</a></li>
                            <li>CPM: '. $facebook_cpm .'</li>
                            <li>CTR: '. $facebook_ctr .'</li>
                            <li>Frequency: '. $facebook_frequency .'</li>
                            <li>Impressions: '. $facebook_impressions .'</li>
                            <li>Reach: '. $facebook_reach .'</li>
                            <li>Total Spend: '. $facebook_spend .'</li>
                            <li>Website Clicks: '. $facebook_website_clicks .'</li>
                            '. $videoActions .'
                        </ul>
                    ';
                }                   
                foreach($stats as $keyStats => $responseStats){                             
                    $responseStatsArray = $responseStats->actions;      
                    $facebookComment = $responseStatsArray['comment'];
                    $facebookLike = $responseStatsArray['like'];
                    $facebookLinkClick = $responseStatsArray['link_click'];
                    $facebookMention = $responseStatsArray['mention'];
                    $facebookOffsiteConversion = $responseStatsArray['offsite_conversion'];
                    $facebookPhotoView = $responseStatsArray['photo_view'];
                    $facebookPost = $responseStatsArray['post'];
                    $facebookPostLike = $responseStatsArray['post_like'];
                    $facebookUnlike = $responseStatsArray['unlike'];
                    $facebookVideoPlay = $responseStatsArray['video_play'];
                    $facebookVideoView = $responseStatsArray['video_view'];
                    $facebookPageEngagement = $responseStatsArray['page_engagement'];
                    $facebookPostEngagement = $responseStatsArray['post_engagement'];
                    $facebookCheckin = $responseStatsArray['checkin'];
                    $returnStats .= '
                        <strong style="display:block">'. $adSetName .'</strong>
                        <ul style="margin-left:40px">   
                            <li>Comments: '. $facebookComment .'</li>
                            <li>Likes: '. $facebookLike .'</li>
                            <li>Link Click: '. $facebookLinkClick .'</li>
                            <li>Facebook Mention: '. $facebookMention .'</li>
                            <li>Facebook Offsite Conversion: '. $facebookOffsiteConversion .'</li>
                            <li>Facebook Photo View: '. $facebookPhotoView .'</li>
                            <li>Facebook Posts: '. $facebookPost .'</li>
                            <li>Facebook Post Like: '. $facebookPostLike .'</li>
                            <li>Facebook Post Unlike: '. $facebookUnlike .'</li>
                            <li>Facebook Video Play: '. $facebookVideoPlay .'</li>
                            <li>Facebook Video View: '. $facebookVideoView .'</li>
                            <li>Facebook Page Engagement: '. $facebookPageEngagement .'</li>
                            <li>Facebook Post Engagement: '. $facebookPostEngagement .'</li>
                            <li>Facebook Checkin: '. $facebookCheckin .'</li>
                        </ul>
                    ';
                }
            }
        }
    }

    echo $returnInsights;
    echo $returnStats;

?>

P.S. I'm only using LAST_MONTH date preset temporarily as all accounts are currently paused...

Any and all recommendations are helpful. Thank you Stack community.

VBA- How to search date in array of dates coming from excel

I am trying to write a simple function in VBA which takes as input a date and an array of dates both coming from Excel. It then returns true if the given date is part of the array or false otherwise.

My problem is that arrays coming from excel are 2 dimensional but I always pass in a 1 dimensional array. In other words, a column and a row value so I can check values in my array but I pass in a 1 dimensional array.

Here is my code:

Function IsInArray(ByVal MyDate As Date, ByRef Holiday_Calendar As Range) As Boolean
Dim length As Integer
length = WorksheetFunction.Count(Holiday_Calendar)
Dim counter As Integer
'counter = 0

For counter = 0 To length
If Holiday_Calendar(counter) = MyDate Then
IsInArray = True
End If
Next counter

IsInArray = False
End Function

List vs Linked List vs Array vs Array List

What are the differences between these data types? Whenever I try to find the answer, I just get Java-specific questions about the difference between LinkedLists and Array Lists, but what are the differences between all four.

Also I would prefer if the answer was not too language specific, but could maybe use some examples from different languages.

Everything I know about linked lists and arrays comes from Lisp, but is there a difference between all four or just naming conventions?

How to save nil into serialized attribute in Rails 4.2

I am upgrading an app to Rails 4.2 and am running into an issue where nil values in a field that is serialized as an Array are getting interpreted as an empty array. Is there a way to get Rails 4.2 to differentiate between nil and an empty array for a serialized-as-Array attribute?

Top level problem demonstration:

#[old_app]
 > Rails.version
 => "3.0.3"
 > a = AsrProperty.new; a.save; a.keeps
 => nil

#[new_app]
 > Rails.version
 => "4.2.3"
 > a = AsrProperty.new; a.save; a.keeps
 => []

But it is important for my code to distinguish between nil and [], so this is a problem.

The model:

class AsrProperty < ActiveRecord::Base
  serialize :keeps, Array
  #[...]
end

I think the issue lies with Rails deciding to take a shortcut for attribute that are serialized as a specific type (e.g. Array) by storing the empty instance of that type as nil in the database. This can be seen by looking at the SQL statement executed in each app:

[old_app]: INSERT INTO asr_properties (lock_version, keeps) VALUES (0, NULL)

Note that the above log line has been edited for clarity; there are other serialized attributes that were being written due to old Rails' behavior.

[new_app]: INSERT INTO asr_properties (lock_version) VALUES (0)

There is a workaround: by removing the "Array" declaration on the serialization, Rails is forced to save [] and {} differently:

class AsrProperty < ActiveRecord::Base
  serialize :keeps #NOT ARRAY
  #[...]
end

Allows:

 > a = AsrProperty.new; a.save; a.keeps
 => []

I'll use this workaround for now, but: (1) I feel like declaring a type might allow more efficiency, and also prevents bugs by explicitly prohibiting the wrong data type being stored (2) I'd really like to figure out the "right" way to do it, if Rails does allow it.

So: can Rails 4.2 be told to store [] as its own thing in a serialized-as-Array attribute?

SQL "Update" Query occurring happens once in PHP "Foreach" loop but loop still runs

I am trying to have a foreach loop run through an array and update my database for each entry.

My code looks like this:

$basketID = mysqli_insert_id($conn);
$basket = $_SESSION['basket'];
$x = array_count_values($basket);
foreach($x as $prodID => $Quant){
    $sql = "
    UPDATE products SET stock = (stock - '$Quant') 
    WHERE productID = '$prodID'; 

    INSERT INTO basketitems(basketID, productID, quantity)
    VALUES ('$basketID','$prodID','$Quant'); ";

    mysqli_multi_query($conn, $sql);
}

The result at the moment is that the loop occurs say 5 times (if I have 5 items in the array) but the query only happens once [I placed a counter in to find out if it was breaking the loop and it counted 5 times]. If I remove the "Update" query then 5 items are inserted into the basketitems table.

Error converting object array to hashtable

Quick Overview: Script has two functions, one gets a two lists of roles and puts them in a hash table, then returns that hash table. Process-Roles then accepts a hash table, and does some comparisons on it.

$RoleTable is supposed to be a hash table, but I think after my Get-Roles function, Powershell makes the $RoleTable an object array. I then get a conversion error:

Cannot convert the "System.Object[]" value of type "System.Object[]" to type 
"System.Collections.Hashtable".

Here's the "main" of my script

$creds = Get-Credential
$MasterServer = Read-Host "`n Master Server"
$SlaveServer  = Read-Host "`n Slave Server"

$RoleTable = Get-Roles -MasterServer $MasterServer -SlaveServer $SlaveServer -Credential $creds

Process-Roles -RoleTable $RoleTable

Here's the function I make a hashtable in, and pass that to $RoleTable

function Get-Roles {
    Param(
        [Parameter(Mandatory=$True,Position=0)]
        [string]$MasterServer,

        [Parameter(Mandatory=$True,Position=1)]
        [string]$SlaveServer,

        [Parameter(Mandatory=$True,Position=2)]
        [pscredential]$Credential
    )

    $DiscoveredRoles = @{}

    # Get Master Roles
    Connect-VIServer $MasterServer -Credential $Credential
    $DiscoveredRoles["MasterRoles"] = Get-VIRole
    Disconnect-VIServer $MasterServer -Confirm:$false

    #Get Slave Roles
    Connect-VIServer $SlaveServer -Credential $Credential
    $DiscoveredRoles["SlaveRoles"] = Get-VIrole
    Disconnect-VIServer $SlaveServer -Confirm:$false

    Write-Verbose "`n + Retrieved Roles Successfully"

    return $DiscoveredRoles

}    

Here's where the error occurs. Process-Roles requires a hashtable, but I believe powershell converted $RoleTable to an array? (that's at least what my google-fu told me)

function Process-Roles { 
    param(
        [Parameter(Mandatory=$true)]
        [ValidateScript({ $_.ContainsKey("MasterRoles") -and $_.ContainsKey("SlaveRoles") })]
        [hashtable]$RoleTable
    )

    $MasterRoleNames = $RoleTable["MasterRoles"] |Select-Object -ExpandProperty Name

    $SlaveRoleNames = $RoleTable["SlaveRoles"] |Select-Object -ExpandProperty Name

    $MasterRoleNames |Where-Object { $SlaveRoleNames -notcontains $_ } |ForEach-Object {
        Write-Verbose "$_ doesn't exist on slave"    
    }

    $SlaveRoleNames |Where-Object { $MasterRoleNames -notcontains $_ } |ForEach-Object {
        Write-Verbose "$_ doesn't exist on Master"    
    }

    Write-Verbose "`n + Processed Roles Successfully"
}

display highest value

I have written a function which is used to pick the highest value and display everything from sql based on the ID. If aa[0] is highest it will display everything in ID 0, if not, it will display either 1 or 2. But the problem now is it only displays value in ID 0 although ID 1 is the highest! Anyone can help me to figuring out what;s wrong with my coding ? Thanks

  private void pick_highest_value_here_and_display(ArrayList<Double> value) throws Exception {
                 // TODO Auto-generated method stub
                 double aa[]=value.stream().mapToDouble(v -> v.doubleValue()).toArray(); 
                 double highest=aa[0]; 
                 if(highest==aa[0])
                 {
                     String sql ="Select * from placeseen where ID =0";
                     DatabaseConnection db = new DatabaseConnection();
                     Connection  conn =db.getConnection();
                     PreparedStatement  ps = conn.prepareStatement(sql);
                     ResultSet rs = ps.executeQuery();
                     if (rs.next()) 
                     {  
                      String aaa=rs.getString("place1");  
                      String bbb=rs.getString("place2");
                      String cc=rs.getString("place3");
                      Tourism to =new Tourism();
                      to.setPlace1(aaa);
                      to.setPlace2(bbb);
                      to.setPlace3(cc);
                      DispDay dc=new DispDay();
                      dc.setVisible(true);
                     }
                     ps.close();
                     rs.close();
                     conn.close();
             }   else
             {
                  for(int i=0;i<aa.length;i++)
                 {
                     if(aa[i]>highest)
                     {
                         highest=aa[i];
                         System.out.println(highest);
                         String sql ="Select * from placeseen where ID =?";
                         DatabaseConnection db = new DatabaseConnection();
                         Connection  conn =db.getConnection();
                         PreparedStatement  ps = conn.prepareStatement(sql);
                         ps.setDouble(1, i); 
                         ResultSet rs = ps.executeQuery();
                         if (rs.next()) 
                         {  
                          String aaa=rs.getString("place1");  
                          String bbb=rs.getString("place2");
                          String cc=rs.getString("place3");
                          Tourism to =new Tourism();
                          to.setPlace1(aaa);
                          to.setPlace2(bbb);
                          to.setPlace3(cc);
                          DispDay dc=new DispDay();
                          dc.setVisible(true);
                         }
                         ps.close();
                         rs.close();
                         conn.close();
                 }   

                 }

             }

How to store 3 different types of data in one array

I need to store 3 linked bits of data in c. My original thought was a 3 dimensional array but that won't work as all 3 data types are different. The top level needs to be a char array. The second level needs to be a date/time so a integer. The third level is a temperature reading so needs to be a float.

Is the correct way to do this an array of pointers pointing to an array of pointers pointing to a array of floats? If so how would that be written in C?

Javascript: Make new array out of nested json object

I am getting data back which includes nested json objects and would like to make a new array containing those json objects. So if I am getting

[
   {
        "number": 1,
        "products": [
            {
                "fruit": "apple",
                "meat": "chicken"
            },
            {
                "fruit": "orange",
                "meat": "pork"
            }
        ]
    }
]

I would like the new array to be

[
    {
        "fruit": "apple",
        "meat": "chicken"
    },
    {
        "fruit": "orange",
        "meat": "pork"
    }
]

efficient way to create JavaScript object from array of properties and array of matching property values

Is it possible to create the the data1 array without using nested for loops?

// My starting Normalized data
var fields = ["name","age"];
var data2 = [["John",20],["Tom",25]]; 


// What I want the result to look like Denormalized
var data1 = [{"name":"John", "age":20},{"name":"Tom", "age":25}];


// My solution
var data1 = [];
for(var i = 0; i < data2.length; i++){
   var temp = {};
   for(var y = 0; y < fields.length; y++){
      temp[fields[y]] = data2[i][y];
   }
   data1.push(temp);
}

Modify if-counter inside a loop

I'm trying to modify a counter in if loop because one array index number needs to be corresponded by the other in order for me to change the place of it's text, but the space between the strings add 1 to the counter.

for(int i = 0, n = strlen(p); i < n; i++){

    if(isspace(p[i])){
        c1 = x[i-1];
        printf("%c", p[i]);
    }
    if(isalpha(p[i])){
        c1 = x[i];
        c2 = c1-96;
        printf("%c --- %c ---%d\n",p[i],c1, c2);
    }

This is one of the attempts but it made an infinite loop, I've tried different approach like:

    if(isspace(p[i))){
        printf("%c", p[i]);
        i -= 1;
    }

Why does my program display the Array address instead of its contents?

My C program consists of an array called 'test_var'. It has another integer array 'arr_int' that consists of a set of integer numbers. My code looks something like this:

 #include <stdlib.h>
 #include <stddef.h>
 #include <stdio.h>

 int State(var);
 int main()
       {
         int arr_int[3] ={1000, 1001, 1002, 1003};
         int var;
         int *test_var[4]={0};

         State(var)
         {
            int i;
            for(i=0; i<4; i++){
               test_var[i] = arr_int[i];
               i++;
                }
          return test_var[var];
          }

          printf("Enter a number between 0 and 3\n");
          scanf("%d",&var);   
          State(var);
          printf ("The array structure is %d", test_var[var]);

          return 0;
          }

However now when I try to print the returned value array test_var for the user input var=0 instead of the whole array(1000) I just get 0. What am I doing wrong here ? COuld somebody please tell me? Am I dereferencing the array in a wrong way?

prev() next() array element on PHP

I have problem,

$text = "My little brother give me a snack";

I sign that if the word = give it sign as verb and then it'll be current position

how to show my all previous position and my all next position.

output :

verb = give

current = give

subject = My little brother

object = a snack

I know that it can be applicate with prev() and next()

but how to use it ?

Thank's

Error when saving 3D array

I'm trying to save a 3D array of data to a file using the following code:

print "Writing results to a file..."
format = "GTiff"
driver = gdal.GetDriverByName(format)

fileName = 'path_to_folder/FLENAME.tif'
NumberOfBands = 46

new_dataset = driver.Create( fileName, 2400, 2400, NumberOfBands,6)
new_dataset = None

for band in range( NumberOfBands ):
    new_dataset.GetRasterBand(band + 1).WriteArray(DATA[band,:,:])

With this I get the error: 'NoneType' object has no attribute 'GetRasterBand'

I tried it without GetRasterband and got 'NoneType' object is not attainable.

Originally tried np.save as an alternative but it was not implemented and was advised to try this method instead. Any help would be appreciated. Thanks.

Swig Templates: How to check if value exists in array?

I'm using Swig on a new project. One of my variables is an array of values (strings). Is there a built-in operator in Swig to check if a value exists in an array? Per the docs, it would seem "in" should do it but no further detail is provided. Also, what's the proper way to negate it? I'm trying the following, but no luck. Would I need to write a custom tag?

{% if 'isTime' in dtSettings %}checked{% endif %}

{% if 'isTime' not in dtSettings %}hide{% endif %}
{% if !'isTime' in dtSettings %}hide{% endif %}
{% if !('isTime' in dtSettings) %}hide{% endif %}

PyFITS: hdulist.writeto()

I'm extracting extensions from a multi-extension FITS file, manipulate the data, and save the data (with the extension's header information) to a new FITS file.

To my knowledge pyfits.writeto() does the task. However, when I give it a data parameter in the form of an array, it gives me the error:

    'AttributeError: 'numpy.ndarray' object has no attribute 'lower''

Here is a sample of my code:

    'file = 'hst_11166_54_wfc3_ir_f110w_drz.fits'
     hdulist = pyfits.open(dir + file)'
     sci = hdulist[1].data # science image data
     exp = hdulist[5].data # exposure time data
     sci = sci*exp # converts electrons/second to electrons
     file = 'test_counts.fits'

     hdulist.writeto(file,sci,clobber=True)

     hdulist.close()

I appreciate any help with this. Thanks in advance.

Build an array from a MySQL query?

Could someone please let me know how I can create an array from the MySQL query?

The array should look like this:

<?php
$testLocs = array(
    '1' => array( 'info' => '1. New Random info and new position', 'lat' => 45345345, 'lng' => 44.9634 ),
    '2' => array( 'ino'  => '1. New Random info and new position', 'lat' => 686788787, 'lng' => 188.9634),
    '3' => array( 'info' => '1. New Random info and new position', 'lat' => 88888, 'lng' => 144.9634),
    '4' => array( 'info' => '1. New Random info and new position', 'lat' => 666666, 'lng' => 144.964 )
);
echo json_encode($testLocs);
exit();
?>

Where the text for info and numbers for lat and lng are MySQL $rows.

Any help would be appreciated.

PHP sort an associative array

I have an array like this. I need to sort countries (array key) by [0][amount] value.

Array
(
    [Germany] => Array
        (
            [0] => Array
                (
                    [amount] => 50
                    [count] => 1
                )

        )

    [Poland] => Array
        (

            [0] => Array
                (
                    [amount] => 80
                    [count] => 2
                )

        )

)

Result should be Poland first and Germany. Any idea in PHP?

Javascript: Brackets after an array in braces [duplicate]

This question already has an answer here:

I've just run into a piece of code I've never seen before, and can't find an explanation anywhere online:

function segColor(c) {
    return {
        red: "#FF0000",
        green: "#00ff00",
        blue: "#0000ff"
    }[c];
}

What operation is being done to the function parameter c? What does {array}[val] do in javascript? Searching for "brackets after braces" doesn't really reveal a lot.

Export Random Cell of Array

My worksheet contains a list of items with different characteristics. Column A contains the name, B & C the colors, D the size, E the cost, etc.

I want to create a userform where I can select specific characteristics (ie. red, $10+, etc) and have it randomly output a value from column that meets the selected criteria.

Any guidance?

How do i use delimiter?

Is there any idea how do i use delimiter in this case so as to extract ", " out ? Much help will be appreciated!

selectedProducts = selectedProducts + "," + cb.Value;

Product.Add(selectedProducts);

LblText.Text = selectedProducts;
string url = "CompareProducts.aspx?prodId=" + selectedProducts.Substring(selectedProducts.LastIndexOf(',') + 1);

Response.Redirect(url);

foreach every 3 put inside a new ul

Actually I have this foreach loop:

<ul>
    <?php foreach ( $tasks as $task ) { ?>
        <li>
            ...
        </li>
    <?php } ?>
</ul>

It returns:

<ul>
    <li>...</li>
    <li>...</li>
    <li>...</li>
    <li>...</li>
    ...
</ul>

Now I need to change the loop to put every 3 <li> into a new <ul>, so I can have:

<div>
    <ul>
        <li>...</li>
        <li>...</li>
        <li>...</li>
    </ul>
    <ul>
        <li>...</li>
        <li>...</li>
        <li>...</li>
    </ul>
    ...
</div>

How I have to modify the foreach loop to achieve that result?

is it possible to store ResultSet from a query into an array and use the array as search parameters for an SQL query

i have two tables WorkSkillsPlanning(WSP) and TrainingAchieved(TA). WSP hold a list of planed training and targeted number of people to be trained e.g. ISOO:90001 10 people while TA holds the actual number of people trained as well as the actual course done. Since WSP and TA are dynamic in the sense that the data they hold is not static neither is known as training plans can change is it possible to run an intersect query on these table to find similarities i.e a course in WSP which has actually be done and recorded in TA. Store the results of the intersect query in an array e.g. MyArrayList{ISO,COMMUNICATION) these being values present in both table and use MyArrayList values to run count queries on TA to establish the number of people who would have done the course i.e ISO and COMMUNICATION and use the resultant to subtract from WSP (ISO,COMMUNICATION).

here is an example, first part

"Select QUALIFICATIONGROUP from  APP.WSP intersect select COURSEBOOKED from APP.BOOKCOURSE"

which results in ISO and COMMUNICATION which i want to store in an ARRAY or variable.

second part

select count(COURSEBOOKED) from APP.BOOKCOURSE where COURSEBOOKED = Variable1
 rs.getString(Count(COURSEBOOKED))
 value returned == 5

re do the process again for COMMUNICATION and any other course in the array, of which after use the values returned from the count query to subtract to subtract WSP total minus TA total.

I hope this makes sense

Prime calculation formula does not shows prime number till 100000 it show till 9973

long i = 0;
int primeNumberCounter = 1;
long upperLimit = 100000;
PrintWriter writer = resp.getWriter();
while (++i <= upperLimit) {
    long i1 = (long) Math.ceil(Math.sqrt(i));
    boolean isPrimeNumber = false;
    while (i1 > 1) {
        if ((i != i1) && (i % i1 == 0)) {
            isPrimeNumber = false;
            break;
        } else if (!isPrimeNumber) {
            isPrimeNumber = true;
        }
        --i1;
    }

    if (isPrimeNumber) {
        writer.write(String.valueOf(i));
        writer.write("\n");
        ++primeNumberCounter;
    }
}

I deployed above code on google app engine.I am getting value till 9973 not 99991 which must be last prime number.Thanx any help appreciated

Add elements to existing array

I have an array that looks like this

array(3) {
      [0]=>
      array(4) {
        ["sort"]=>
        string(0) ""
        ["day"]=>
        string(2) "2"
        ["month"]=>
        string(1) "8"
        ["year"]=>
        string(4) "2015"
      }
      [1]=>
      array(4) {
        ["sort"]=>
        string(0) ""
        ["day"]=>
        string(1) "5"
        ["month"]=>
        string(1) "8"
        ["year"]=>
        string(4) "2015"
      }
      [2]=>
      array(4) {
        ["sort"]=>
        string(0) ""
        ["day"]=>
        string(1) "9"
        ["month"]=>
        string(1) "8"
        ["year"]=>
        string(4) "2015"
      }
    }

As you can see it consists of sort, date, month and year. I want to add new element into the same array with value "day" +1.

If the 8th of august 2015 is in array the it should also include 9th of august 2015. I need a way to extract values, calculate new date and put back in all dates. The result should look like this:

array(3) {
          [0]=>
          array(4) {
            ["sort"]=>
            string(0) ""
            ["day"]=>
            string(2) "2"
            ["month"]=>
            string(1) "8"
            ["year"]=>
            string(4) "2015"
          }
          [1]=>
          array(4) {
            ["sort"]=>
            string(0) ""
            ["day"]=>
            string(1) "5"
            ["month"]=>
            string(1) "8"
            ["year"]=>
            string(4) "2015"
          }
          [2]=>
          array(4) {
            ["sort"]=>
            string(0) ""
            ["day"]=>
            string(1) "9"
            ["month"]=>
            string(1) "8"
            ["year"]=>
            string(4) "2015"
          }
          [3]=>
          array(4) {
            ["sort"]=>
            string(0) ""
            ["day"]=>
            string(2) "3"
            ["month"]=>
            string(1) "8"
            ["year"]=>
            string(4) "2015"
          }
          [4]=>
          array(4) {
            ["sort"]=>
            string(0) ""
            ["day"]=>
            string(1) "6"
            ["month"]=>
            string(1) "8"
            ["year"]=>
            string(4) "2015"
          }
          [5]=>
          array(4) {
            ["sort"]=>
            string(0) ""
            ["day"]=>
            string(1) "10"
            ["month"]=>
            string(1) "8"
            ["year"]=>
            string(4) "2015"
          }
        }

Ideally it should also exclude new dates, if allready identical date is in the array.

Twig json encode and comma's

I have a Twig array like this:

var settings = JSON.parse('{{ theme | json_encode | raw }}');  

For example as a result I get this:

var settings = JSON.parse('{"text_color":"#444444","company_info":"my company profile with a comma's"}');

What happens now is that when somebody write at company profile something with a comma or any other character the complete script breaks.

Example's: - 'something' - thing's - awesome;

Is there a way to "accept" these special characters? I thought encode would read past those characters?!

How to write scietific notation in perl?

I have been working on a program for awhile, and the next goal I have to say basically "In column [27] if the value is more than 10^-8 delete the file" How does one write "10^-8" in a program? I can post the code if that would be helpful in anyway. Thank you very much

Convert JSON to list of arrays

How can I convert my JSON to list of arrays My JSON is Serie :
[{"Value":10,"ValuePourcent":2},{"Value":20,"ValuePourcent":3},{"Value":51,"ValuePourcent":1}]

I Would like this : [[10,2],[20,3],[:51,1]]

var linq = Enumerable.From(rows);

var Serie = linq
                .GroupBy("$.Year", null,
                    function(key, g) {
                        var result = {
                            Value: g.Sum("$.Car"),
                            ValuePourcent: g.Sum("$.CarPourcent")/Total*100,
                        };
                        return result;
                    })
                .ToJSON()

Sending Python array to django template by AJAX

Im trying to send a random Python array to a template in Django by using AJAX:

JS:

    $("button").click(function() {
        $.ajax({
            url: "/hello",
            type: "get",
            success: function(data) { 
                printData(data);                    
            },
            error: function(data) { 
                alert("Error!");
            }
        });
    })

Django view:

from django.http import HttpResponse
from django.views.generic import View
from django.shortcuts import render, render_to_response

import numpy as np

def hello(request):
    rand_arr = np.random.randint(100, size=10)
    return HttpResponse(rand_arr)

I receive the array as a string like: 3133352430290167691. Is it possible to receive it as an array, and access the individual values?

Make 2D Numpy array from coordinates

I have data points that represent a coordinates for a 2D array (matrix). The points are regularly gridded, except that data points are missing from some grid positions.

For example, consider some XYZ data that fits on a regular 0.1 grid with shape (3, 4). There are gaps and missing points, so there are 5 points, and not 12:

import numpy as np
X = np.array([0.4, 0.5, 0.4, 0.4, 0.7])
Y = np.array([1.0, 1.0, 1.1, 1.2, 1.2])
Z = np.array([3.3, 2.5, 3.6, 3.8, 1.8])
# Evaluate the regular grid dimension values
Xr = np.linspace(X.min(), X.max(), np.round((X.max() - X.min()) / np.diff(np.unique(X)).min()) + 1)
Yr = np.linspace(Y.min(), Y.max(), np.round((Y.max() - Y.min()) / np.diff(np.unique(Y)).min()) + 1)
print('Xr={0}; Yr={1}'.format(Xr, Yr))
# Xr=[ 0.4  0.5  0.6  0.7]; Yr=[ 1.   1.1  1.2]

What I would like to see is shown in this image (backgrounds: black=base-0 index; grey=coordinate value; colour=matrix value; white=missing).

matrix

Here's what I have, which is intuitive with a for loop:

ar = np.ma.array(np.zeros((len(Yr), len(Xr)), dtype=Z.dtype), mask=True)
for x, y, z in zip(X, Y, Z):
    j = (np.abs(Xr -  x)).argmin()
    i = (np.abs(Yr -  y)).argmin()
    ar[i, j] = z
print(ar)
# [[3.3 2.5 -- --]
#  [3.6 -- -- --]
#  [3.8 -- -- 1.8]]    

Is there a more NumPythonic way of vectorising the approach to return a 2D array ar? Or is the for loop necessary?

Storing integer arrays in a MySQL database

I have a lot of spectra that I want to store in a database. A spectrum is basically an array of integers with in my case a variable length of typically 512 or 1024. How best to store these spectra? Along with the spectra I want to store some additional data like time and a label, which will be simple fields in my database. The spectra will not be retrieved often and if I need them, I need them as a whole.

For storing the spectra I can think of 2 possible solutions:

  • Storing them as a string, like "1,7,9,3,..."
  • Storing the spectra in a separate table, with each value in a separate row, containing fields like spectrum_id, index and value

Any suggestions on which one to use? Other solutions are much appreciated of course!

Find out multiple nonintersecting increasing sequences in an array of maximal combined length

There is a known problem "Longest increasing subsequence", which is: Given an array of integers, find out the longest increasing sequence in that array. I now face a similar but apparently more complicated problem: Given an array of integers and a given number N, find N sequences in that array so that each of them is increasing, they do not intersect by indexes and their combined sum of lengths is maximal.

So far I have tried "greedy" algorithms in the line of:

  1. Use the longest increasing subsequence algorithm, throw that sequence away from the array, repeat N times, provide found sequences as result. This works if N=1 by design, works in several odd cases but returns incorrect results for shuffled arrays such as an array constructed of N increasing subsequences.
  2. Construct a number of sequences, adding each element to the now-longest possible subsequence. Obviously flawed, as it finds "substrings" more often than prolonged sequences.
  3. Construct a number of sequences, adding each element to the sequence that has the largest last element. This works better, at least if an array is known to contain N increasing subsequences, this algorithm correctly returns full array as the result, but it does not work properly in general, as it does not consume N as is.

Any other ideas?

Difference between JavaScript Array every and some

I see both return true or false upon given tests.

http://ift.tt/16HuOcN

http://ift.tt/YHNWr1

What should be the right case to use them both together ?

Test code:

function checkUsersValid(goodUsers) {
  return function allUsersValid(submittedUsers) {
    //Im testing arrays here
    return submittedUsers.every(function isBigEnough(element, index, array) {
          return goodUsers.some(function (el, i, arr) {
                return element.id == el.id;
          });
        });
  };
}

var goodUsers = [
      { id: 1 },
      { id: 2 },
      { id: 3 }
    ];
    
var testAllValid = checkUsersValid(goodUsers);

testAllValid([
      { id: 2 },
      { id: 1 }
    ]);

How do I set an Enviromental Variable in Postman, from an array, within an array?

I am struggling to extract the data from an array within an array to set as a variable. How would I set the variable from the ID, listed within address

{
"user profile":{
"email_address" : "test@test.com",
"addresses" : [
{
"id": 1
},
{
"id": 2
},
]

For a single array I use

var data = JSON.parse(responseBody); 
postman.setEnvironmentVariable("AddressID",data.user_address[data.addresses.length-1].id);

I'm not quite sure how to use the console log as advised yesterday, if that is the answer to this issue.

Many thanks

Filter a 2D numpy array from an array of values

Let's say I have a numpy array with the following shape :

nonSortedNonFiltered=np.array([[9,8,5,4,6,7,1,2,3],[1,3,2,6,4,5,7,9,8]])

I want to :

- Sort the array according to nonSortedNonFiltered[1] - Filter the array according to nonSortedNonFiltered[0] and an array of values

I currently do the sorting with :

sortedNonFiltered=nonSortedNonFiltered[:,nonSortedNonFiltered[1].argsort()]

Which gives : np.array([[9 5 8 6 7 4 1 3 2],[1 2 3 4 5 6 7 8 9]])

Now I want to filter sortedNonFiltered from an array of values, for example :

sortedNonFiltered=np.array([[9 5 8 6 7 4 1 3 2],[1 2 3 4 5 6 7 8 9]])
listOfValues=np.array([8 6 5 2 1])
...Something here...

> np.array([5 8 6 1 2],[2 3 4 7 9]) #What I want to get in the end

Note : Each value in a column of my 2D array is exclusive.

PHP diff array value and not key diff

I have a problem and i hope i can be helped to fix this problem.

my problem is i got this two arrays

$array1 = ["test1" => "red", "test2" => "blue", "test3" => "green"];
$array2 = ["test1" => "red", "test2" => "blue", "test3" => "blue"];

as you can see the diffiend is the array key test3's value there are a diff, my problem is i need to know the key test3 have a diff and from $array1 to $array2

i have tryed array_diff and array_intersect but its not what i want, i have a product and i need to know what there are changes from last run, and if i use on of this to command its not telling my where the diff are but what the diff is.

can sombardy help here and explain what i can do or about there are a function to handle this problem?

What does this code actually do?

I have recently been employed at an office where they use a lot of php in their work, most of my development background is HTML, CSS, Jquery, Wordpress and Angularjs, I have an idea behind the logic of some of php but was just wondering if anyone can enlighten me as to what this code below actually means/does?

return (isset($rs[0][0]) ? $rs[0][0] : "");

It is located within this function that calls the database and returns values.

function get_temp($table, $field){
global $db;
$sql="select $field from $table";
$rs=$db->select($sql);
return (isset($rs[0][0]) ? $rs[0][0] : "");}

I feel that is selecting one value from an array within an array but I cannot find any sources to confirm this so was hoping someone on here could help me out or at least point me in the right direction if I am wrong. The reason I believe this is the case is because if I pass the $field variable more than one result it will always only return the first one, if this is the case it would also be helpful to me if someone could suggest a way to get all of the results, whenever I simply try:

return $rs

It simply returns "Array".

MATLAB: create a string array with a list of variable names with a given prefix

I would like to store the names of some variables in my workspace into a string array given a prefix. In particular, I have 'Xaws1', 'Xaws2', 'Xaws3' variables other than others in my workspace, and I want their names to populate an array which would look something like {'Xaws1', 'Xaws2', 'Xaws3'}. In my case all the variable names have the same length (5 characters), and I'd like to find them using a prefix like "Xaws*". I tried with who('Xaws*), but the output seems not usable in this sense. I also looked into this post, but could not find a solution so far. Any idea would be very appreciated, thanks in advance.

PHP - Access an array using another array as the key

I'm creating a class that assists in building settings pages for WordPress plugins. The developer instantiates the class by passing in an array of settings. A basic example looks like:

Array
(
    [textbox1] => Array
        (
            [title] => Textbox
            [type] => text
            [section] => general
            [desc] => The text description
        )

    [a_nice_dropdown] => Array
        (
            [title] => Select me
            [type] => select
            [section] => general
            [desc] => The select description
            [choices] => Array
                (
                    [red]   => Red
                    [blue]  => Blue
                    [green] => Green
                )
        )
)

This works fine. My class builds the options page and the inputs have HTML that looks like:

<input id="textbox1" type="text" name="options_slug[textbox1]" value="">

When "Save Changes" is clicked, my class grabs all the options tied to "options_slug" and stores them in a single wp_options entry as a nice serialized array, making it easy to grab later.

The New Challenge

I have a new project which requires multiple nested "repeater" fields, similar to the way Advanced Custom Fields handles it. I've created a new field type, to handle this, which can support "subfields". An example config output (from error_log) looks like:

Array
(
    [subfields_container] => Array
        (
            [title] => Subfields
            [type] => subfields
            [section] => general
            [desc] => This is the subfields description text
            [subfields] => Array
                (
                    [textbox2] => Array
                        (
                            [title] => Textbox
                            [type] => text
                            [section] => general
                            [desc] => The text description
                        )

                    [select1deep] => Array
                        (
                            [title] => Subfield Select
                            [type] => select
                            [choices] => Array
                                (
                                    [1] => 1
                                    [2] => 2
                                    [3] => 3
                                )

                            [std] => 1
                        )
                )
        )
)

I've configured the HTML output so an input inside a "subfields" container now looks like:

<input id="textbox1" type="text" name="options_slug[subfields_container][textbox2]" value="">

The idea being that the end user can easily group fields: i.e.,

$options = get_option('options_slug');

foreach($options['subfield_container'] as $subfield) {

    // etc...

}

The Problem

As I iterate through these multidimensional arrays, I need to continually update a $options variable at the current index so it can be saved to the DB. So where previously I was able to do:

$id = 'textbox1';
$options[$id] = $_POST['textbox1'];

Now I'm doing something like:

$id = array('subfields_container' => 'textbox2');
$options[$id] = $_POST['textbox2'];

But I get "illegal offset type" errors. Because I can't set an array property using another array.

I've considered just putting dashes in the ID's instead of creating a hierarchical array, something like:

<input id="textbox1" type="text" name="options_slug[subfields_container-textbox2]" value="">

But then I'll lose the ability to foreach over a specific part of the stored options.

The Question

What's the best way to dynamically set a value inside of a multidimensional array when the array is not fixed in structure?

Thank you

Use Javascript to objectify csv file

I'm currently working with CSV files that I whould like to objectify.

The csv format is like: "Property, Value1, Value2, ..." Example:

"Recipe_Product_Name, Knife, Fork, Spoon".

I use the split('_') function to get a JSON looking structure, for the example above: "Recepie - Product -Name: Knife" gives me a nice,

var name = Recepie.Product.Fork.Name

To the problem...

The csv file includes arrays like:

  • "Recipe_Product_Connector{0}_Pins, 11, 47, 4"
  • "Recipe_Product_Connector{0}_Brand, Sourai, Harting, Amphenol"
  • "Recipe_Product_Connector{1}_Pins, 5, 64, 18"
  • "Recipe_Product_Connector{1}_Brand, Sourai, Harting, Amphenol"

So far, I use this code for the objectification:

    var nest = function (obj, keys, v) {
    var Arr = [];
    if (keys.length === 1) {
        obj[keys[0]] = v;
    } else {
        var key = keys.shift();
        if (key.split('}').length > 1) {
            Arr.push(nest(typeof obj[key] === 'undefined' ? {} : obj[key], keys, v));
            obj[key] = Arr;
            console.log(Arr);
        } else {
            obj[key] = nest(typeof obj[key] === 'undefined' ? {} : obj[key], keys, v);
        }
    }
    return obj;
};

It works kind of good, except that I get multiple array structures:

var HartingPins = Recipe.Products.Connector[0][0].Pins

I do not like that, probably something wrong with the recursion. Any Ideas on how to continue?

PHP: Why should we use array_udiff()?

I am trying to understand array_udiff() function. But Its confusing that both functions array_diff() and array_udiff() produces same results then why will we use array_udiff() ?

Code:

 echo "<h1>array_udiff()</h1>";
 $a = array('a'=>'apple', 'c'=>'cat', 'b'=>'book');
 $b = array('d'=>'dog');
 echo "<pre>";

 print_r(array_udiff($a,$b,function($a,$b){
  if ($a < $b) {
        return -1;
    } elseif ($a > $b) {
        return 1;
    } else {
        return 0;
    };
 }));


 echo "<h1>array_diff()</h1>";

 print_r(array_diff($a, $b));

Output:

Output

As you can see in above example that output of both functions are same then why should we use array_udiff() ?

Merge multiple arrays of similar type in PHP

I have one dynamic array with me like this:

$final_array1 = array( 
     '0' => array('title' => 'Title 1','price' => 50,'price_type' => 'fixed'),
     '1' => array('title' => 'Title 2', 'price' => 100, 'price_type' => 'fixed'),
     '2' => array('title' => 'Title 3','price' => 150,'price_type' => 'fixed'),
     '3' => array('title' => 'Title 4', 'price' => 200, 'price_type' => 'fixed')
);

I would like to combine all these array like this:

$final_array = array( 
    array('title' => 'Title 1','price' => 50,'price_type' => 'fixed'),
    array('title' => 'Title 2', 'price' => 100, 'price_type' => 'fixed'),
    array('title' => 'Title 3','price' => 150,'price_type' => 'fixed'),
    array('title' => 'Title 4', 'price' => 200, 'price_type' => 'fixed')
);

How can I do this ?

Can I declare an array first and give its value later?

I tried doing this but got an error. Why can't I do this?

int main()
{
char sweet[5];
sweet = "kova";
printf("My favorite sweet is %s\n", sweet);

return 0;
}

java script how to convert a string to number array

I have a string named :

graph_data =[16.665,0,16.665,19.23,35.79,16.665,31.71,16.665,0,16.665,0,16.665,16.665,41.615]

I wanted to covert it to array of number. I am using the following code:

var graph_data1=new Array();
var graph_data = graph_data.split(",");
for (var i=0; i<graph_data.length; i++)
{
graph_data1[i] = parseFloat(graph_data[i]);
}

the output of graph_data1 is showing following NaN,0,16.665,19.23,35.79,16.665,31.71,16.665,0,16.665,0,16.665,16.665,41.615

can any one tell me why it is adding Nan and 0

thanks in advance .

Most efficient way to restructure complex array of objects in javascript?

I have a large set of data that looks similar to this:

var original = [
  { country : 'us', date : '2014-10-29', cost : 45.3 },
  { country : 'africa', date : '2014-10-29', cost : 60.5 },
  { country : 'south_america', date : '2014-10-30', cost : 10 },
  { country : 'us', date : '2014-10-30', cost : 30 }
];

I need to rearrange this data so that it looks more like this:

var newData = [
  { date : '2014-10-29', us : 45.3, africa : 60.5, south_america : 0 },
  { date : '2014-10-30', us : 30, africa : 0, south_america : 10 }
]

I'm new to dealing with datasets like this and I'm struggling to find any efficient way to handle this... The only thing I can come up with uses multiple for loops and just looks gross. Does anyone have any ideas or suggestions?