vendredi 31 juillet 2015

json_decode multidimensional from database

I have this json saved in my database in a column called 'price' with the type of 'text'.

{
  "desks": {
    "Dedicated Desk": "$400 mo"
  },
  "private offices": {
    "1 Person": "$550 mo",
    "2 Person": "$1100 mo",
    "3 Person": "$1600 mo",
    "4 Person": "$2100 mo",
    "6 Person": "$3300 mo"
  },
  "flexible membership": {
    "Starting at": "$45 mo",
    "Every Extra Day": "$50 Day"
  }
}

I then make a call from PHP to return my all the fields in my database and encode them as json.

$json = json_encode($response,JSON_PRETTY_PRINT);
echo $json;

$response is the response from the database. When I var_dump on $response I get

array(22) {
    [0]=>
      object(stdClass)#6 (38) {
        [...]

        ["price"]=>
        string(242) "{"desks":{"Dedicated Desk":"$400 mo"},"private offices":{"1 Person":"$550 mo","2 Person":"$1100 mo","3 Person":"$1600 mo","4 Person":"$2100 mo","6 Person":"$3300 mo"},"flexible membership":{"Starting at":"$45 mo","Every Extra Day":"$50 Day"}}"

        [...]
      }
    [...]
}

When I echo the result from json_encode i get

[
    {
        [...]

        "price": "{\"desks\":{\"Dedicated Desk\":\"$400 mo\"},\"private offices\":{\"1 Person\":\"$550 mo\",\"2 Person\":\"$1100 mo\",\"3 Person\":\"$1600 mo\",\"4 Person\":\"$2100 mo\",\"6 Person\":\"$3300 mo\"},\"flexible membership\":{\"Starting at\":\"$45 mo\",\"Every Extra Day\":\"$50 Day\"}}",

        [...]
    },
    [...]
]

My problem is json_encode is taking the json from the database and formatting it as a string. I am trying to get it to format it as part of a multidimensional json structure. This is what im trying to achieve:

[  
   {  
      "price":[  
         {  
            "desks":{  
               "Dedicated Desk":"$400 mo"
            },
            "private offices":{  
               "1 Person":"$550 mo",
               "2 Person":"$1100 mo",
               "3 Person":"$1600 mo",
               "4 Person":"$2100 mo",
               "6 Person":"$3300 mo"
            },
            "flexible membership":{  
               "Starting at":"$45 mo",
               "Every Extra Day":"$50 Day"
            }
         }
      ]
   }
]

Any help would be appreciated. Running latest version of php.

How to assign array into variable in jquery

The original and working array is this:

 var columns =[{
        name: 'level',
        minWidth: '200px'},
        {
        name: 'subject',
        minWidth: '70px'},
        {
        name: 'catid',
        minWidth: '70px'}],

However, I want to use if else statement to assign different array for different 'target' value. So I tried as below but it doesn't seem to supply the array correctly to the 'columns' variable.

 var useThis=[];
        if(target=="subject")
        {
            useThis = {
            name: 'level',
            minWidth: '200px'},
            {
            name: 'subject',
            minWidth: '70px'},
            {
            name: 'catid',
            minWidth: '70px'};

        }
        else
        {
            useThis = {
            name: 'level',
            minWidth: '200px'};

        }
var columns="["+useThis+"],";

How do I assign array correctly with if else statement?

Modify global variable array through a bash function, passing the function the name of the variable as a string

Dear I need something to help me in this. I'm trying to modify a global array through a function , using an auxiliary variable called "array". I would like to modify the global array "config " using a function that takes a string with the name of the variable " config".

I'm trying the following but I have not gotten results .

declare -A config

function testABC {
    array=${1}[@]
    array["key"]="value1"
    array["key2"]="value2"
}

testABC "config"
echo ${config["key"]}
echo ${config["key2"]}

#desired output:
#value1
#value2

My version of bash is 4.2.45

regards.

PHP Database Incremental Search using Array

I am learning coding, but I am wanting to make an interactive roster for a local youth camp where upon registering a new camper's personal information (in database is 'name', 'birth_year', 'hobbies', 'favorite_subject', 'spirit_animal_explanation' and 'contact_information') the camper can select a "group-me" button that will display the profiles of other campers who have similar hobbies and spirit animals as them as well as being within the same age group (11-13yrs, 14-16yrs,etc).

To achieve this, when a camper enters in his/her information, it is first saved into the database. I then query a SELECT syntax that takes the info from the 'hobbies' and 'spirit_animal_explanation' columns of the camper and filter it of unwanted words and put them in an array (so for 'hobbies' if the camper says "I like Running and Jumping" the the filter will array will only print_r Array([0]=>running[1]=>jumping).

I then array_merge the two filtered arrays into one so I easily manage the search (some campers like mixing up the hobbies into the spirit_animal_explanation so by having a single reference array for both columns the search can be easier) leaving me with a $compiled variable containing the two merged arrays.

Now the part(s) I am Struggling with: I am able to prepare the reference array for the search, but I don't know the query syntax to begin the search or scanning the 'hobbies' and 'spirit_animal_explanation' columns of every user using the reference array. From previous suggestions I've read up on JOIN queries but I don't see a point in making two tables because the elements of the reference array are not fixed/constant for every camper that executes the search. Also, I have no idea how/when I should add in the age conditional. Finally, the improve latency I want the system to look for the first 10 matching users on the first search session, then the next ten users on the second, etc. How can I go about doing this?

Python "numpy.dtype" structure for reading binary to "list" with "numpy.fromfile"

+++ WARNING, THE FOLLOWING CONTAINS VERY UGLY PROGRAMMING +++

+++ PLEASE HELP!!! +++

Hey, I am playing around quit a long time with my read in routines and I still not have figured out a good and fast way!

I have something like this: A huge binary file, which I want to slice down to a numpy-array!

I created this structure to read in fromfile a certain amount of bytes:

    mydt = numpy.dtype([
                       ('col1', np.uint64),
                       ('col2', np.int32),
                       ('cols3_56', np.float32, (53,))
                       ])

reading that like this:

data_block = numpy.fromfile(openfile, dtype=mydt, count=ntimes)

What I am getting out is something like this:

[(88000031189210L, 1, [-1000.0, -1000.0, -1000.0, -2.0, -2.0, -2.0, 65004000.0, 0.0, 760680000.0, 0.0, 0.12124349921941757, 0.04971266910433769, 2328.39990234375, 0.00013795999984722584, 0.0, 0.0, -1.0, -1.0, -1.0, 65004000.0, -1.0, 760680000.0, 0.0, 0.0, -1.0, 825680000.0, 0.0, -1.0, -1.0, -1.0, 157630.0, 0.0, 756310.0, 0.0, -1.0, -1.0, 0.0, 5.250500202178955, 0.0, 5.250500202178955, -13.602999687194824, -16.760000228881836, -17.283000946044922, -16.95800018310547, -17.513999938964844, -17.57200050354004, -13.657999992370605, -16.77199935913086, -17.291000366210938, -16.9689998626709, -17.520999908447266, -17.57200050354004, 1.0]), [(88......1L, 1, [-1000.0, ....]), ....

then I extend this datablock to my array

data_block_array.extend(data_block)

... and this million of times ....

I want now to access two things:

  • the 2th element in the above structure (in this example "1") for the entire data array which is a couple of millions times the above mentioned array
  • the 8th (in total the 12th) element in the 53-column data block for the entire array, again millions of substructures!

I figured that out with doing some loops over a count:

 i=0           
 while i<count:
     self.data_array[i,element1] = data_block_array[i][1]
     self.data_array[i,element8] = data_block_array[i][2][13]  

which is incredible slow ... I would like to develop a very fast and easy way to filter my data that way and extract the columns I am interested in. Appreciate some advise and insights!

Sending a dynamic range to a function

Newbie here, so please bear with me. I'm just not getting something about properly putting a dynamic column of values into an array.

The following lines of code work properly for me:

Set RangeD = Sheets("Data").Range("D2:D15")
unique2chan = UniqueItems(RangeD, False)

RangeD is the range I will pass to the function, called "UniqueItems". "unique2chan" is the array of values that will be returned by UniqueItems.

The assumption above is that the values always run from D2 to D15. But for these data, the range's length can vary on each run. (All values will be consecutive in the column, no spaces.)

Here's my question: How do I put a changing number of values into an array that I can pass to my function? I added a counter that tells me how many rows are filled in the column, so if there are 12 values in the column (plus the header), I have a counter that will read 13. How can I use that number to define a range of all the values (minus the header) that I can put into an array to pass to my function?

Any help is appreciated. I've tried a bunch of things I've found on the net, but everyone seems to have a different approach, and I haven't found one that worked for me.

XML parsing in a function and return data in an array list - java [on hold]

I need to read an xml in a method and use that data to drive selenium webdriver script. I am able to read the xml data in to a Arraylist and print the contents in the console. I am also returning ArrayList in the method. I am just struggling to use that returned data in my selenium method for different browser actions(type, click etc). This is my read method which is main method of my class

public static ArrayList main(String[] args) {

    ArrayList<String> testData = null;
    try {
        testData = new ArrayList<>();

        File fXmlFile = new File("C://Javaseleniumworld/Book.xml");
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(fXmlFile);

        //optional, but recommended
        //read this - http://ift.tt/IJO9S6
        doc.getDocumentElement().normalize();

        System.out.println("Root element :" + doc.getDocumentElement().getNodeName());

        NodeList nList = doc.getElementsByTagName("staff");

        System.out.println("----------------------------");

        for (int temp = 0; temp < nList.getLength(); temp++) {

            Node nNode = nList.item(temp);

            System.out.println("\nCurrent Element :" + nNode.getNodeName());

            if (nNode.getNodeType() == Node.ELEMENT_NODE) {

                Element eElement = (Element) nNode;

                System.out.println("firstname : " + eElement.getAttribute("id"));
                System.out.println("server : " + eElement.getElementsByTagName("firstname").item(0).getTextContent());
                String FirstName = eElement.getElementsByTagName("firstname").item(0).getTextContent();
                testData.add(FirstName);
                System.out.println("server : " + eElement.getElementsByTagName("lastname").item(0).getTextContent());
                String LastName = eElement.getElementsByTagName("lastname").item(0).getTextContent();
                testData.add(LastName);
                System.out.println("Array List" + testData);
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    return testData;
}

Knockoutjs "foreach" equivalent for non array objects

I've been using Knockoutjs for a while, but there is something I haven't been able to solve and I'm sure there must be an easy way to do it.

I really like nesting objects, using "foreach" on the html and then accessing each of these object's property directly. That way it keeps the code simple and clear.

The problem is that sometimes I use an observableArray to hold only one element in order to use the "foreach way" that I mention.

Is there other way of saying "I'm now within this scope", same behaviour as "foreach".

Example: here

<body>
    <!-- ko foreach: people -->
        <div data-bind="text: name">name</div>
    <!-- /ko -->
    <br />

    <!-- here I would like to say I'm inside 'importantPerson' and therefore name is a property of importantPerson -->
    <!-- <div data-bind="text: name">name (important)</div> -->
    <br />
</body>

Array element checking in swift

Currently implementing a favourite function to my application which is based on quotes. I would like to perform a check for if the user has already saved an element to an array. If they have, I would change a favour button to unfavour button.

   var favouriteQuotesArray: [String]? = NSUserDefaults.standardUserDefaults().objectForKey("thekey") as? [String]

    func makeQuoteFavourite() {
        if favouriteQuotesArray == nil {
            favouriteQuotesArray = []
        }
        let currentQuote = dreamFact.dreamArray[factIndex]
        favouriteQuotesArray!.append(currentQuote)
        NSUserDefaults.standardUserDefaults().setObject(favouriteQuotesArray!, forKey: "thekey")
    }

    @IBAction func favour(sender: AnyObject) {

        if liketext.currentTitle == "Like"{

            liketext.setTitle("Unlike", forState: UIControlState.Normal)

     makeQuoteFavourite()


        } else if liketext.currentTitle == "Unlike" {

            liketext.setTitle("Like", forState: UIControlState.Normal)


        }

See the issue at currenttitle, the dependency on upon the text which is unreliable because if the user reopens the app, the element would still be saved instead of starting out with the default unlike. If the element is found in the array. How would I perform a search inside my favouriteQuotesArray if the element exists like:

if elementfound statement {

button.settitle(unlike)
removearrayatindex statement.

} else {
button.settitle(like)
makeQuoteFavourite()
}

How would the array checking statement look like? P.S If you can please give tips on building the delete class?

Copying and Referencing of NSObjects iOS

So for a while I have been working on this app - in which contains a folder-like structure of objects which have properties of arrays that can contain the same type of object, which in turn can contain more of this object, etc. These objects are called groups. In a shared data class I have a mater group object called mainGroup, and a property of my data class called selectedGroup to facilitate the display of data. These group objects can be modified, so for a considerable chunk of time I tried to develop a solution for getting the path through all of the arrays to the desired object, all the while having no clue about copying and that assigning one array equal to the other does not create a deep copy, just some kind of reference. The code was logically sound, but in it after a while I noticed that deleting things in the selectedGroup’s array property had the same effect on the actual master copy, which did some wonky things to my app.

I did some googling and figured out that I was not actually creating a whole new array, just referencing it some how. I’m still confused on this next part though. I thought that setting one array equal to the other would have the same effect as calling copy on it - and when I replace or delete objects in one array the other is affected. So what exactly is the compiler doing when you set two arrays equal to each other? Shouldn’t it just populate the new array with the pointers to the objects in the old array, not just reference the array itself? And how come that when doing this same operation with objects such as NSStrings you do not see the same effect? Lastly, what other objects have this same behavior as the NSArrays?

Creating multiple arrays within a for loop (Python)

I'm currently having an issue with numpy arrays. If this question has already been asked elsewhere, I apologize, but I feel that I have looked everywhere.

My initial issue was that I was attempting to create an array and fill it with multiple sets of station data of different sizes. Since I cannot fill the same array with data sets that vary in size, I decided I need to create a new array for each station data set by defining the array inside the for loop I'm using to iterate through each station data set. The problem with this is that, while looping through, each data set will overwrite the previous data set, returning only the final instance of the for loop.

Then, I tried using the + and then the join operations to concatenate a new title for each array, but turns out that is illegal when defining arrays. This is the instance of the program where each data array overwrites the previous one. Note that not all the code is included and that this is part of a definition.

for k in range(len(stat_id)):

    ## NOTE - more code precedes this final portion of the for loop, but was
    ## not included as it is unrelated to the issue at hand.

    # Bring all the data into one big array.
    metar_dat = np.zeros((len(stat_id),len(temp),7), dtype='object')
    for i in range(len(temp)):
        metar_dat[k,i] = np.dstack((stat_id[k], yr[i], month[i], day[i], time[i], temp[i], dwp[i]))
    #print np.shape(metar_dat[k])
    #print metar_dat[k]

#print np.shape(metar_dat) # Confirm success with shape read.
return metar_dat

Upon running and printing the array from this definition, I get this (two empty arrays and a final filled array):

[[[0 0 0 ..., 0 0 0]
[0 0 0 ..., 0 0 0]
[0 0 0 ..., 0 0 0]
..., 
[0 0 0 ..., 0 0 0]
[0 0 0 ..., 0 0 0]
[0 0 0 ..., 0 0 0]]

[[0 0 0 ..., 0 0 0]
[0 0 0 ..., 0 0 0]
[0 0 0 ..., 0 0 0]
..., 
[0 0 0 ..., 0 0 0]
[0 0 0 ..., 0 0 0]
[0 0 0 ..., 0 0 0]]

[[\TZR 2015 7 ..., 2342 58 48]
[\TZR 2015 7 ..., 2300 59 47]
[\TZR 2015 7 ..., 2200 60 48]
..., 
[\TZR 2015 7 ..., 0042 56 56]
[\TZR 2015 7 ..., 0022 56 56]
[\TZR 2015 7 ..., 0000 56 56]]]

My question is this: how can I create an array for each set of station data such that I do not overwrite any previous data? Or how can I create a single array that contains data sets with varying numbers of rows? I am still new to Python (and new to posting here) and any ideas would be much appreciated.

Find() for embed document in mongodb

I have a mongodb for a photo albums. Some photos could be 'special'. So here is part of my db, a album:

{
        "_id" : ObjectId("55bc30befd401b12108b45a8"),
        "name" : "Vacation",
        "criate_at" : "2015-07-31",
        "photos" : [
                {
                        "uri" : "portfolio/h2171874c6e31bab44bed7df8c8ae91a.jpg",
                        "special" : true,
                        "criate_at" : "2015-07-31"
                },
                {
                        "uri" : "portfolio/o2171874c6e31bab44bed7df8c8ae91a.jpg",
                        "special" : false,
                        "criate_at" : "2015-07-31"
                },
                {
                        "uri" : "portfolio/o2171874c6e35bab44bed7df8c8aeq1a.jpg",
                        "special" : false,
                        "criate_at" : "2015-07-31"
                },
                {
                        "uri" : "portfolio/o2171874c6e31bab44bed7df8c8ae23a.jpg",
                        "special" : true,
                        "criate_at" : "2015-07-31"
                }
        ]
}
{
        "_id" : ObjectId("55bc30befd401b12108b4599"),
        "name" : "Zoo",
        "criate_at" : "2015-07-31",
        "photos" : [
                {
                        "uri" : "portfolio/h2171874c6e31bab44bed7df8c8ae933.jpg",
                        "special" : true,
                        "criate_at" : "2015-07-31"
                },
                {
                        "uri" : "portfolio/o2171874c6e31bab44bed7df8c8ae93f.jpg",
                        "special" : false,
                        "criate_at" : "2015-07-31"
                }
        ]
}

I want get only all special photos. I want this result:

{
        "_id" : ObjectId("55bc30befd401b12108b45a8"),
        "photos" : [
                {
                        "uri" : "portfolio/h2171874c6e31bab44bed7df8c8ae91a.jpg",
                        "special" : true,
                        "criate_at" : "2015-07-31"
                },
                {
                        "uri" : "portfolio/o2171874c6e31bab44bed7df8c8ae23a.jpg",
                        "special" : true,
                        "criate_at" : "2015-07-31"
                }
        ]
}
{
        "_id" : ObjectId("55bc30befd401b12108b4599"),
        "photos" : [
                {
                        "uri" : "portfolio/h2171874c6e31bab44bed7df8c8ae933.jpg",
                        "special" : true,
                        "criate_at" : "2015-07-31"
                }
        ]
}

I tried various queries, but nothing... This query give me the first special photos of each album.

db.albuns.find({'photos.special':true},{'photos':{$elemMatch:{'special':true}}}).pretty()

There is any way to get only all specials photos ?

Select rows where jsonb array contains any string in array

This is my SQL so far:

select * from table where table.json_info @> '{"search_tags":["hello", "world"]}'

And this works if the row has BOTH hello and world in the search_tags

I'm wondering if there is a way to include rows that have EITHER hello OR world and of course those that have both.

Thanks to all ahead of time!

Lodash search by startswith in an array

I'm creating a simple search that searches an array of objects that starts with a string passed from an input.

So I have this:

var items = [
    {id: 1, tags: ['foo']},
    {id: 2, tags: ['fish', 'ball']},
    {id: 3, tags: ['bar', 'goo']},
];

input.on(function(e) {
    var test = _.filter(items, function(item) {
         return _.includes(_.pluck(items, 'tags'), input.val());
    });
    console.log(test);
});

This always returns an empty array, I think i'm missing startsWith, how do I use it here in my implementation, or is there a better way of doing search like this?

Store entire line of text file in array line by line (not word by word; include spaces)

I am writing a program where the contents of a text file will be stored in an array line by line. I have it working, but it's only storing one word at a time.

  try ( Scanner fin = new Scanner ( new File("toDoItems.txt") ); ) 
    {
    for (int i = 0; i < listCount && fin.hasNext(); i++) 
          {
          textItem[i] = fin.next();
          }
    }

The listCount variable stores how many lines to read from the file, from the top. Instead it is telling it how many words to read. What can I do to read the entire line into the Array, without knowing how long each line may be?

I set the array size to much larger than I need and I am using the following to display the items one line at a time and only displaying the items in use (so to avoid a long list of nulls)

    for (int i = 0; i < listCount; i++) 
          {
              String temp = textItem[i];
              System.out.println(temp);
          }

(For this I am restricted to arrays only. No Arraylists or lists)

Note: Most similar questions I could find are only attempting to store lines that contain a single word.

PHP function returning NULL instead of array

I call a function that does some recursion and is supposed to return an array. In fact, a var_dump immediately before the return statement in the called function evinces the array; however, a var_dump of the results from the calling function reveals NULL instead of the array.

Here's the calling function.

<?php  

// configuration
require_once("../includes/config.php");
require_once("../includes/getParentNodes.php");  

$bottomNode = 17389;
$chain = [];
$chain[] = $bottomNode;
$results = getParentNodes($bottomNode,$chain);

var_dump($results); ?>

Here's the called function.

<?php

function getParentNodes($node, $results)
{
    $select = query("SELECT parent_id FROM classifications WHERE node_id = ?", $node);
    $parent = implode("",$select[0]);
    if (!empty($parent))
    {
        $results[] = $parent;
        getParentNodes($parent,$results);   
    }
    else
    {
        return $results;
    }
}
?>

If I place a var_dump immediately preceding the return call, I get the following.

Array
(
    [0] => 17389
    [1] => 17386
    [2] => 17334
    [3] => 16788
    [4] => 15157
    [5] => 10648
    [6] => 3962
    [7] => 665
    [8] => 39
    [9] => 1
)

However, the var_dump in the calling function produces a NULL.

I've read the manual and the related posts, but none shed light on this problem. Any help would be much appreciated.

Add items to an empty array [duplicate]

This question already has an answer here:

I have learned that to declare an empty array you do:

int myArray = new int[0]

But how do I add items to this array. For example, how would I add the integers 31, 35, 37?

Sorting grouped multi-dimensional array by value

$data = array(
    'apple' => array(
        0 => array('sort'=>4, 'name'=>'apple_4'),
        1 => array('sort'=>10, 'name'=>'apple_10'),
        2 => array('sort'=>5, 'name'=>'apple_5'),
        3 => array('sort'=>1, 'name'=>'apple_1')
        ),

    'orange' => array(
        0 => array('sort'=>4, 'name'=>'orange_4'),
        1 => array('sort'=>10, 'name'=>'orange_10')
        )
    );

Need assistance sorting multi-dimensional array. For the array above, I would like to sort the contents of each group in descending order by the 'sort' value. The group's keys should remain in tact (apple, orange) but content's keys are not important.

Data should be ordered:

  • apple
    • apple_10
    • apple_5
    • apple_4
    • apple_1
  • orange
    • orange_10
    • orange_4

How to i add a custom style_formats with using data from the database on tinymce? (For ASP.NET MVC)

I use TinyMCE editor. And i want to create a custom inline styles for a span tag. But style datas should come from the database. In this way the data can be obtained.

    $(document).ready(function () {

        $.ajax({
            type: "POST",
            url: '@Url.Action("GetFormats", "Editor")',
            dataType: "json",
            success: function (formats) {
                $.each(formats, function (index, format) {
                    // Datas from database
                });
            }
        });
    });

and define tinymce

    tinymce.init({           
    selector: "textarea",
        theme: "modern",
        plugins: [
            "advlist autolink lists link image charmap print preview hr anchor pagebreak",
            "searchreplace wordcount visualblocks visualchars code fullscreen",
            "insertdatetime media nonbreaking save table contextmenu directionality",
            "emoticons template paste textcolor colorpicker textpattern imagetools"
        ],
        toolbar1: "insertfile undo redo | styleselect formatselect fontselect fontsizeselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image media",
        toolbar2: "cut copy paste | searchreplace | print preview removeformat | forecolor backcolor emoticons",

        image_advtab: true,

        style_formats: [
        {
            title: 'My_Style_Combo', inline: 'span', styles: { color: 'rgb(0, 0, 255)', fontFamily: 'comic sans ms,cursive', fontSize:'12px',textDecoration:'underline' } 
        }
       //------> How can I integrate my each data here like this format type?
        ]

    });

I'm sorry for my bad English if you have difficulty in understanding.

I hope it has been a true expression. Thank you in advance for your answers.

Recursive Fortran function return array?

I am relatively new to Fortran (using 90), and haven't been able to find any literature answering this question, so I thought I would ask here on SO: I am trying to write a recursive function that will return an array.

My end goal was to write my own FFT in Fortran without going through the C fftw and using the "C to Fortran" package; I understand there are ways of doing this without using a recursive function, but I would still like to know if a recursive function is able to return an array.

As an exercise, I tried to write a program that takes in a natural number, recursively computes the Fibonacci sequence and returns a list of the Fibonacci numbers indexed up to the argument integer. Using the same algorithm, I wrote this function in Matlab and it works, but there is a semantic error when writing in Fortran 90:

recursive function Fibbo(l)
    integer, INTENT(IN) :: l
    integer, dimension(l)  :: x

    integer, dimension(l) :: Fibbo

    if ( l == 1 ) then
        x = 1
    else if ( l == 2 ) then
        x(1) = 1
        x(2) = 1
    else
        x(1:l-1) = Fibbo(l-1)
        x(n) = x(l-1) + x(l-2)
    end if

Fibbo = x  
end function

It will compile just fine, and no problems except for the output: (when trying to call ell = 3)

Enter an integer:
3
 -1610612736
  1342177280
           0

There is a different output each time, and with an out like that I am guessing there is an issue with memory allocation, or something like that, but like I said I cannot find any literature online addressing recursive functions returning arrays. Perhaps it cannot be done?

Any help would be great, thank you so much for your time!

P.S. It will output the correct list--i.e., 1, [1 1]--when calling Fibbo(1), Fibbo(2), rest.

EDIT: P.P.S. If it matters, I am compiling with gfortran, in Yosemite

Why we have used pointer in this C program?

Why we have used pointer in this C code? Basically, I am just searching a string in the array, but without pointer, it is unable to run. But why is that?

int main() {

    char *x[] = {"ab", "bc", "cd", 0};

    char *s = "ab";

    int i = 0;

    while(x[i]) {

            if(strcmp(x[i], s) == 0) {
                    printf("Gotcha!\n");
                    break;
            }

            i++;
    }
}

numpy - meshgrid for multiple dimensions

numpy has a beautiful function which generate multidimensional grid. It is easy to work with it when number of dimension is low and is known in advance, but what to do when number of dimension is only known at time of execution or simply big and it takes too long to type. I guess I am looking for something like

 import numpy as np

 x = np.meshgrid(y)

where y is an array of arrays of evaluation points, for example

y = [array([-3.,  0.,  3.]) array([-3.,  0.,  3.]) array([-3.,  0.,  3.])]

Suggestions?

MongoDB find by ids array on params order

I have a dataset, such as:

   {
      "_id" : ObjectId("559a9b9c9d9e9f9g1"),
      "title": "First"
    },
    {
      "_id" : ObjectId("559a9b9c9d9e9f9g2"),
      "title": "Second" 
    },
    {
      "_id" : ObjectId("559a9b9c9d9e9f9g3"),
      "title": "Third"
    },
    {
      "_id" : ObjectId("559a9b9c9d9e9f9g4"),
      "title": "Fourth"
    }  

When I try to find with an array of items, like:

db.snippets.find( { _id: { $in: [ObjectId("559a9b9c9d9e9f9g4"), 
                                 ObjectId("559a9b9c9d9e9f9g1"), 
                                 ObjectId("559a9b9c9d9e9f9g3") ] } } )

Instead of returning the query result in the given array of ids order, it returns based on the persisted data order.

Expected:

    { "_id" : "559a9b9c9d9e9f9g4", ...}, (item 4)
    { "_id" : "559a9b9c9d9e9f9g1", ...}, (item 1)
    { "_id" : "559a9b9c9d9e9f9g3", ...}  (item 3)

Result:

    { "_id" : "559a9b9c9d9e9f9g1", ...}, (item 1)
    { "_id" : "559a9b9c9d9e9f9g3", ...}, (item 3)
    { "_id" : "559a9b9c9d9e9f9g4", ...}  (item 4)

Is there a way to force the returned query to follow the same given array order?

Printing after typecasting with %d or %i gives unexpected outputs

I am rounding off some values and then printing them. When I use %f option, they are printed correctly, but using the %d or %i option (even after casting the rounded values to int) is giving a weird output, and I am not able to figure the why of it out.

Any help is much appreciated!

When I use %f:

i = 0;

while(i < n_shapes)
{
    ll_x[i] = (int)round((ll_x[i] - min_x)/pitch_x);
    ll_y[i] = (int)round((ll_y[i] - min_y)/pitch_y);
    ur_x[i] = (int)round((ur_x[i] - min_x)/pitch_x);
    ur_y[i] = (int)round((ur_y[i] - min_y)/pitch_y);
    printf("%f,%f,%f,%f\n", ll_x[i], ll_y[i], ur_x[i], ur_y[i]);
    i++;
}

Output:

115.000000,94.000000,115.000000,101.000000
116.000000,51.000000,117.000000,58.000000
116.000000,60.000000,117.000000,67.000000
116.000000,69.000000,117.000000,75.000000
116.000000,77.000000,117.000000,84.000000
116.000000,86.000000,117.000000,93.000000
116.000000,94.000000,117.000000,101.000000

Now, with %d (or %i):

i = 0;

while(i < n_shapes)
{
    ll_x[i] = (int)round((ll_x[i] - min_x)/pitch_x);
    ll_y[i] = (int)round((ll_y[i] - min_y)/pitch_y);
    ur_x[i] = (int)round((ur_x[i] - min_x)/pitch_x);
    ur_y[i] = (int)round((ur_y[i] - min_y)/pitch_y);
    printf("%d,%d,%d,%d\n", ll_x[i], ll_y[i], ur_x[i], ur_y[i]);
    i++;
}

Output:

1079590912,0,6,-1
1078788096,0,5,-1
1079033856,0,6,-1
1079164928,0,6,-1
1079312384,0,6,-1
1079459840,0,6,-1
1079590912,0,6,-1

Thank you!

Edit: Yes, I realize that using (int) in the printf gives me the right output. I was curious about the values I got when I didn't do so. What does my output when I use %d without casting inside the printf mean?

Solving a simple matrix in row-reduced form in C++

Okay, I am pulling out all my hair on this one, though, as a noob, I am sure there are several problems. I want to take a matrix and, by sing elementary row operations, reduced it to row-reduced echelon form. We assume (1) it is solvable and (2) a unique solution. There is no checking for zeros or anything; it just does row operations. Here is the code:

#include <iostream>
#include <cstdlib>

using namespace std;

void printmatrix(float A[][4]);
void RowReduce (float A[][4]);


int main()
{


     float A[3][4] = {{5, -6, -7, 7}, {3, -2, 5, -17}, {2, 4, -3, 29}}; //answer should be {2, 4, -3}

    printmatrix(A);
    RowReduce(A);
 }

 void printmatrix(float A[][4]){ // Outputs the matrix

int p=3;
int q=4;

 for (int i=0; i<p; i++)
    {
        for (int j=0; j<q; j++)
        {
            cout << A[i][j] << " ";
        }
        cout << endl;
    } 
}

void RowReduce (float A[][4]){
  int p=3;  //rows
  int q=4;  //columns

  int lead = 0; //the determines the column we are at which holds the diagonal, the basis for all elimination above and below

    cout << endl;
    while (lead<q-1)
    {
        for (int i=0; i<p; i++) //for each row . . .
        {
           if (i!=lead) // ignore the diagonal, and we will not have a tree rref as the diagonal will not be divided by itself. I can fix that.
                {
                    cout << A[lead][lead] << "  " << A[i][lead];
                    for (int j=0; j<q; j++)
                    {
                        A[i][j]=A[lead][lead]*A[i][j]; //here is the math . . . . probably where the problem is?
                        A[i][lead]=A[i][lead]*A[lead][j];
                        A[i][j]=A[i][j]-A[i][lead];
                    }
                cout << endl;
                }
    }
lead++;  // now go to the next pivot
cout << endl;

}

}

I tried doing it by hand, but what I get is, of course, the right answer, but this gets a diagonal matrix--which is great--but the wrong answer!

Accessing Public 2D Array Variables via Script in Unity

So I figured out how to make a 2D array that is viewable in the inspector via the code below.

[System.Serializable]
 public class QuestPhase {
     [HideInInspector]
     public string name;
     public int[] Phase = new int[5];
 }
 public QuestPhase[] questPhase    = new QuestPhase[5];

That works just fine, but I'm trying to figure out how to access that information via script and I can't figure it out.

 questVariable = questPhase[1,1];

That returns an error of "Expected 1 index, got 2", and just using one index gives me "Cannot convert type QuestPhase into type int." I'm sure the answer is obvious, but if anyone could answer it for me I would be most appreciative.

how are arrays actually created under the hood ? so if I I'm creating my own implementation?

I would actually like to understand the implementation of them if I was writing a raw class to emulate the behavior. I understand there is a reference variable that points to multiple objects, but not sure how to model that in code. Any language appreciated: please do not answer the question like you make an array as such : int []i. Thanks in adance

Rectangle intersection in Ruby

So I'm trying to understand this program but I'm having some difficulty. What I don't get in particular is the part with x_min, y_min, x_max, y_max. I get the the program passes through 2 rectangles with the bottom left and top right coordinate points. But where do the array indices come from? [0][0] , [1][1], etc? I'm confused about what's happening here exactly so if someone could break this down for me like I'm 5 that'd be awesome. I saw this particular question was answered before on here but I didn't get the explanation. Thanks.

    # Write a function, `rec_intersection(rect1, rect2)` and returns the
# intersection of the two.
#
# Rectangles are represented as a pair of coordinate-pairs: the
# bottom-left and top-right coordinates (given in `[x, y]` notation).
#
# Hint: You can calculate the left-most x coordinate of the
# intersection by taking the maximum of the left-most x coordinate of
# each rectangle. Likewise, you can calculate the top-most y
# coordinate of the intersection by taking the minimum of the top most
# y coordinate of each rectangle.
#
# Difficulty: 4/5
def rec_intersection(rect1, rect2)

x_min = [rect1[0][0], rect2[0][0]].max
x_max = [rect1[1][0], rect2[1][0]].min

y_min = [rect1[0][1], rect2[0][1]].max
y_max = [rect1[1][1], rect2[1][1]].min

return nil if ((x_max < x_min) || (y_max < y_min))
return [[x_min, y_min], [x_max, y_max]]
end

puts rec_intersection(
      [[0, 0], [2, 1]],
      [[1, 0], [3, 1]]
    ) == [[1, 0], [2, 1]]

puts rec_intersection(
      [[1, 1], [2, 2]],
      [[0, 0], [5, 5]]
    ) == [[1, 1], [2, 2]]


puts rec_intersection(
      [[1, 1], [2, 2]],
      [[4, 4], [5, 5]]
    ) == nil

puts rec_intersection(
      [[1, 1], [5, 4]],
      [[2, 2], [3, 5]]
    ) == [[2, 2], [3, 4]]

Why do I get an error just because I have a large array in swift?

I'm writing something in Swift and I have an array with some pre-calculated values which you can see below:

let pointArray = [[[185,350],8],[[248.142766340927,337.440122864078],5],[[301.67261889578,301.67261889578],5],[[337.440122864078,248.142766340927],5],[[350,185],8],[[327.371274561396,101.60083825503],5],[[301.67261889578,68.3273811042197],5],[[248.142766340927,32.5598771359224],5],[[185,20],8],[[101.60083825503,42.6287254386042],5],[[68.3273811042197,68.3273811042197],5],[[42.6287254386042,101.60083825503],5],[[20,185],8],[[32.5598771359224,248.142766340927],5],[[68.3273811042197,301.67261889578],8],[[101.60083825503,327.371274561396],5]]

My problem is that when compelling, I'm getting the following error:

Expression was too complex to be solved in reasonable time; consider breaking up the expression into distinct sub-expressions

I can't quite see why I'm getting this error because this is just an array with data - surely there isn't a maximum size for an array?

So my question is why am I getting the error? Is it just because the array is too large or maybe because there are many decimal points in the array?

Array of classes 'undefined' C++

So, I have a array of monsters and a function to display their names. The problem is the debugger says Mons(the array) is undefined. I'd like to know what I'm doing wrong. Please help! The errors are mostly Mons is undefined.

#include <iostream> 
#include <fstream>
#include <windows.h>
#include <time.h>

/**
RPG v0.1.6
-
**/

//-- WinAPI stuff
void ClearScreen()
  {
  HANDLE                     hStdOut;
  CONSOLE_SCREEN_BUFFER_INFO csbi;
  DWORD                      count;
  DWORD                      cellCount;
  COORD                      homeCoords = { 0, 0 };

  hStdOut = GetStdHandle( STD_OUTPUT_HANDLE );
  if (hStdOut == INVALID_HANDLE_VALUE) return;

  /* Get the number of cells in the current buffer */
  if (!GetConsoleScreenBufferInfo( hStdOut, &csbi )) return;
  cellCount = csbi.dwSize.X *csbi.dwSize.Y;

  /* Fill the entire buffer with spaces */
  if (!FillConsoleOutputCharacter(
    hStdOut,
    (TCHAR) ' ',
    cellCount,
    homeCoords,
    &count
    )) return;

  /* Fill the entire buffer with the current colors and attributes */
  if (!FillConsoleOutputAttribute(
    hStdOut,
    csbi.wAttributes,
    cellCount,
    homeCoords,
    &count
    )) return;

  /* Move the cursor home */
  SetConsoleCursorPosition( hStdOut, homeCoords );
  }



class Player {
    public:
    int HP;
    int MHP;
    int STR;
    int AGI;
    int RES;
    int XP;
    int LVL;
    Player() { HP = 8; MHP = 8; STR = 4; AGI = 3; RES = 2; XP = 0; LVL = 1; };
private:
};

struct DT {

void save_to_file(std::string filename, const Player& P)
{
    std::ofstream f( filename.c_str() );
    f << P.HP << std::endl;
    f << P.MHP << std::endl;
    f << P.STR << std::endl;
    f << P.AGI << std::endl;
    f << P.RES << std::endl;
    f << P.XP << std::endl;
    f << P.LVL << std::endl;
}

bool load_from_file(std::string filename, Player& P) {
  std::ifstream f( filename.c_str() );
  f >> P.HP;
  f >> P.MHP;
  f >> P.STR;
  f >> P.AGI;
  f >> P.RES;
  f >> P.XP;
  f >> P.LVL;
  if(f.good()){
    std::cout << "Success!" << std::endl;
  }
  else {
    std::cout << "Failure" << std::endl;
  }
  return f.good();
}

};

class Monster {
public:
    int HP;
    int MHP;
    int STR;
    int AGI;
    int RES;
    int XP;
    std::string name;
    ///For Calling
    Monster() { };
    ///Set variables for new battle
    Monster(int A, int B, int C, int D, int E, int F, std::string G){
    this->HP = A;
    this->MHP = B;
    this->STR = C;
    this->AGI = D;
    this->RES = E;
    this->XP = F;
    this->name = G;
    };
    void setStats(int A, int B, int C, int D, int E, int F, std::string G){
    this->HP = A;
    this->MHP = B;
    this->STR = C;
    this->AGI = D;
    this->RES = E;
    this->XP = F;
    this->name = G;
    };
};

int monstersalive = 3;




// -- Call Functions
void BtlDisplay(Player& P, Mons M[]);
void Battle(Player& P, Mons M[]);

int main()
{
    // -- Call Classes
    Player p;
    DT d;

    Monster Mons[3];
    for(int j = 0; j < 3; j++){
        Mons[j].setStats(9,9,9,9 + j,9,9,"Noob");
    }

    BtlDisplay(p,Mons);


    //Battle(p,m);


    d.save_to_file("GameData1.txt", p);
    d.save_to_file("GameData2.txt", p);
    d.save_to_file("GameData3.txt", p);



    return 0;
}

void BtlDisplay(Player& P, Mons M[]) //-- Displays battle stats
{
    ClearScreen();
    std::cout << "---------" << std::endl;
    std::cout << "L " << P.LVL << std::endl;
    std::cout << "HP " << P.HP << "/" << P.MHP << std::endl;
    std::cout << "---------\n\n" << std::endl;
    std::cout << "Monsters\n--------" << std::endl;
    for(int i = 0; i < 3; i++){
        if(M[i].HP > 0){

        }
    }
}

void Battle(Player& P, Mons M[])
{
    while(monstersalive > 0 && P.HP > 0){
        srand(time(NULL));
    }
}

IndexError: Too many indices when indexing array with another array

I realize a lot of people have asked about this error, but I have yet to find anything that will help me. I'm new to Python and working on some pretty high-level simulations, so up until now this website has been my best friend - now I could really use some help figuring out how to fix this error.

This is my code:

def nanalyze(pupil, pw_sim):
    import numpy as np

    temp_s = abs(pw_sim)**2 * pupil

    vals_x, vals_y = np.where(pupil > 0)
    mask = pupil[vals_x[0]:vals_x[len(vals_x)-1], vals_y[0]:vals_y[len(vals_y)-1]]

    s_i = (np.mean(temp_s[tuple(mask)]**2) / (np.mean(temp_s[tuple(mask)])**2)) - 1
    return s_i

The second-to -last line,s_i = (np.mean(temp_s[tuple(mask)]**2) / (np.mean(temp_s[tuple(mask)])**2)) - 1, is what returns the index error: too many indices.

pupil and pw_sim are each arrays of shape (1024,1024). temp_s is therefore also a (1024,1024) array and mask ends up being a (1023,1023) array. I've tried making mask a (1024,1024) to check and see if I'm getting the index error just because of the difference in shapes, but that doesn't seem to change anything. I cannot figure out what the problem is!

Reading A File and Storing It In An Object

I am trying to read from a file and store the contents into an object called ToDoList(from what I assume is under the GetItem method). Then I am supposed to allow the user to add on to the list. But I am lost on how to create the object and print it.

public class ToDoList {

private ToDoItem[] items;

ToDoItem td = new ToDoItem();
String inputline;
Scanner keyboard = new Scanner(System.in);

int i = 0;

String[] stringArray = new String[100];



private void setItems(ToDoItem[] items) throws FileNotFoundException {
    File file = new File("ToDoItems.txt");
    Scanner ReadFile = new Scanner(file);

    while (ReadFile.hasNext()) {
        String ListString = ReadFile.nextLine();
        stringArray[100] = (ListString);
    }
}

private ToDoItem[] getItems() {

    return items;
}

public void addItem(int id, String description) {
    stringArray[100] = (td.getId() + td.getDescription());

}

public String[] getAddItem() throws FileNotFoundException {

    try (PrintWriter fout = new PrintWriter(new File("ToDoItems.txt"))) {
        do {
            System.out.println("add to the list? [y/n]");
            inputline = keyboard.nextLine();

            if ("y".equals(inputline)) {
                i++;
                stringArray[i] = (td.getId() + ". " + td.getDescription() + "\n");
                fout.print(stringArray[i]);
            } else {

                System.out.println("Here is the list so far:");

            }
        } while ("y".equals(inputline));
        return stringArray;
    }
}

@Override
public String toString() {
    return "ToDoList{" + "items=" + getItems()
            + '}';
}

I am supposed to use the "getAddItem" method to allow the user to add to the list. But I can't figure out how to add an array to an object. let alone make the object.

PHP from string to multiple arrays at the hand of placeholders

Good day,

I have an I think rather odd question and I also do not really know how to ask this question.

I want to create a string variable that looks like this:

[car]Ford[/car]
[car]Dodge[/car]
[car]Chevrolet[/car]
[car]Corvette[/car]
[motorcycle]Yamaha[/motorcycle]
[motorcycle]Ducati[/motorcycle]
[motorcycle]Gilera[/motorcycle]
[motorcycle]Kawasaki[/motorcycle]

This should be processed and look like:

$variable = array(
                   'car'            =>           array(
                                                        'Ford',
                                                        'Dodge',
                                                        'Chevrolet',
                                                        'Corvette'
                                                      ),
                   'motorcycle'     =>           array(
                                                        'Yamaha',
                                                        'Ducati',
                                                        'Gilera',
                                                        'Kawasaki'
                                                      )
                  );

Does anyone know how to do this? And what is it called what I am trying to do?

How to check arrays for equality between multiple values?

So I'm trying to build a tic-tac-toe game that involves the user playing against a the computer. I would like these arrays to check for a winning sequence of blocks that will indicate someone has won the game. I'm wondering if this method of checking different parts of an array and comparing them for equality is valid?

function winner() {
    var blocks = document.getElementsByClassName('block');
    for (var i = 0; i < blocks.length; i++) {
        if (blocks[0, 1, 2].value == 'X' || blocks[0, 3, 6].value == 'X' || blocks[2, 5, 8].value == 'X' || blocks[6, 7, 8].value == 'X' || blocks[2, 4, 6].value == 'X' || blocks[0, 4, 8].value == 'X') {
            alert('Player X Wins!!');
            blocks.classList.toggle('block');
            player === 1;
        }
    };

    var blocks = document.getElementsByClassName('block');
    for (var i = 0; i < blocks.length; i++) {
        if (blocks[0, 1, 2].value == 'O' || blocks[0, 3, 6].value == 'O' || blocks[2, 5, 8].value == 'O' || blocks[6, 7, 8].value == 'O' || blocks[2, 4, 6].value == 'O' || blocks[0, 4, 8].value == 'O') {
            alert('Player O Wins!!');
            blocks.classList.toggle('block');
            player === 1;
        }

    }
}

Also, is this a viable way to dictate whose turn it is? I had a little success with this class switching mechanism to determine which blocks have been chosen in the beginning but can't seem to make it work now.

This is the code for changing turns and class switching so far but I'm sure there's a better way:

var player === 1

var blocks = document.getElementsByClassName('block');

function turn() {
    if (player === 1) {
        player -= 1;
        winner();
        var buttons = document.getElementsByTagName("button");
        console.log(buttons.length);
        for (var i = 0; i < buttons.length; i++) {
            buttons[i].addEventListener("click", function(e) {
                var number = (this.getAttribute('name'));
                var chosenblock = document.getElementsByName(number)[0];
                chosenblock.classList.toggle('chosen');
                chosenblock.value = 'X';
                // console.log('click!');
            });
        }
    } else {
        player += 1;
        winner();
        var computer;
        computer = function() {
                var computerchoice = Math.floor(Math.random() * (9) + 1);

                function compselected(number) {
                    //How to make number equal to the id of the selected block?
                    var chosenblock = document.getElementsByName(number)[0];
                    chosenblock.classlist.toggle('picked');
                }

Any advice is appreciated thanks guys! Here's the fiddle if that helps.

DataTables Javascript AJAX with plain data array

I have an ajax call that returns:

[{"fields": 
    {"account_to": ["Bank Account - SECU", "11000"],
     "posted_by": 1, 
     "amount": "1000", 
     "created_date": "2015-07-31T14:53:03.766Z", 
     "posting_date": "2015-07-31T14:53:03.763Z", 
     "account_from": ["Consulting Income - ABC", "41000"], 
     "company": "S&S Co"},

     "model": "base.glentry", "pk": 8},
  {"fields": ...
]

Note that there is no: {'data': [ data array ]} which all the examples have. I can find how to change the name so that 'data' can be something else, but how do I make it render like this with AJAX without manually processing the return value and wrapping the data?

Here is my javascript:

$('#dt').dataTable( {
    "processing": true,
    "ajax": "http://localhost:8000/gl/",
"columns": [
    {"": "fields.amount"}
]
} );

I've tried all sorts of things, but get the same result. What can I do?

R: Fill multidimensional array by row

Before presenting the question, I will point out that something similar was asked here but that this thread doesn't really answer my question.

Consider the following dimensional arrays:

 1D: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
 2D: [[1,2,3,4,5,6,7,8], [9,10,11,12,13,14,15,16]]
 3D: [[[1,2,3,4],[5,6,7,8]], [[9,10,11,12],[13,14,15,16]]]
 4D: [[[[1,2],[3,4]], [[5,6],[7,8]], [[[9,10],[11,12]], [[13,14],[15,16]]]]
 ...

  • The 1D array is length 16
  • The 2D array is 2x8
  • The 3D array is 2x2x4
  • The 4D array is 2x2x2x2

Suppose I want to create the arrays. For the first two, I could do something like this in R

oneD <- array(1:16, dim=16) # class(oneD) = array
twoD <- array(1:16, dim=8) # class(twoD) = matrix

However, the twoD array is now represented as

[[1,3,5,7,9,11,13,15], [2,4,6,8,10,12,14,16]]

I am aware of two ways around this.

twoD <- aperm(array(1:16, dim=8))
twoD <- matrix(1:16, nrow=2, byrow=TRUE)

However, these methods won't work for filling the 3D and 4D arrays. I fill them below, but I would like them to match my definitions above.

threeD <- array(1:16, dim=c(2,2,4)) # class(threeD) = array
fourD <- array(1:16, dim=c(2,2,4)) # class(fourD) = array

Conditionally instantiate a new Perl array

I've got the following code:

my @departments;
if( $opts->{'d'} )
{
    @departments = @{$opts->{'d'} };
}

$opts is just a hash reference that could possibly have an array ref as the value of a key.

I'd like to do something like the following:

my @departments = $opts->{'d'} ? @{$opts->{'d'}} : undef;

But obviously that will just put one element into @departments with value undef.

The reason I'm performing this action is because I later want to be able to check

if( @departments )
{
    my $department_string = join( q{,}, @departments );
    $big_string . $department_string;
}

to dynamically add to a string.

Assign variables value through array in Haxe?

How to assign variables a, b, c and d values to 1, 2, 3 and 4 through an array?

    var a:Int = 0, b:Int = 0, c:Int = 0, d:Int = 0;
    var array1:Array<Int> = [a, b, c, d];
    var array2:Array<Int> = [1, 2, 3, 4];

    for (i in 0...4)
        array1[i] = array2[i]; //this does not work, it assigns array1's elements instead

    trace(a); // this prints 0 instead of 1
    trace(b); // 0 instead of 2
    trace(c); // 0 instead of 3
    trace(d); // 0 instead of 4

Fortran output large array to netCDF nf90_enddef

Hi first question on stackoverflow.

I've been stuck on this for 5 days. I want to write a netcdf file in Fortran.

I'm using netcdf/3.6.3 I am trying to output a large 43000x 18000 array named frech and some smaller ones (1d arrays).

a sample of my code is below it is a really large file and the problem is not in putting in values for the variables the problem is ending the definition of variables:

  print*,"nunks is",nunks
  print*,"neqns is",neqns


  ok=nf90_create('michalek.nc', NF90_CLOBBER, ncid)
  print *,"create ok=",ok

  ok=   nf90_def_dim(ncid,"nunks", nunks, nunks_dimid)
  print *,"def nunks dimension ",ok
  ok=   nf90_def_dim(ncid,"neqns", neqns, neqns_dimid)
  print *,"def neqns dimension ",ok
  dimids=(/neqns_dimid, nunks_dimid/)
  print *,dimids
  ok=   nf90_def_var(ncid,"frech", NF90_REAL, dimids, frech_varid)
  print *,"def frech",ok
  ok=   nf90_def_var(ncid,"src", NF90_REAL, nunks_dimid, src_varid)
  print *,"def src",ok
  ok=   nf90_def_var(ncid,"csrc", NF90_REAL, nunks_dimid, csrc_varid)
  print *,"define csrc",ok
  ok=   nf90_def_var(ncid,"dat", NF90_REAL, neqns_dimid, dat_varid)
  print *,"define dat",ok
  ok=   nf90_def_var(ncid,"cdat", NF90_REAL, neqns_dimid, cdat_varid)
  print *,"define cdat",ok
  ok=   nf90_enddef(ncid)
  print *,"end dif ", ok
  ok=   nf90_put_var(ncid, frech_varid, frech)
  print *, 'frech put in ok=',ok
  ok=   nf90_put_var(ncid, src_varid, src)
  print *, 'src put in ok=',ok
  ok=   nf90_put_var(ncid, csrc_varid, csrc)
  print *, 'csrc put in ok=',ok
  ok=   nf90_put_var(ncid, dat_varid, dat)
  print *, 'dat put in ok=',ok
  ok=   nf90_put_var(ncid, cdat_varid, cdat)
  print *, 'cdat put in ok=',ok
  ok=   nf90_close(ncid)
  print *, 'close?',ok

I understand that ok=0 when the file is correctly read However when I get to the stage of ending the defintions of the file (nf90_enddif) ok is returned as =-62 and the netcdf file is not created. I imagine its a problem with a too large array but I can't fix this problem

the relevant output for the above code is:

nunks is       43894
neqns is       18144
create ok=           0
def nunks dimension            0
def neqns dimension            0
     2           1
def frech           0
def src           0
define csrc           0
define dat           0
define cdat           0
end dif          -62
frech put in ok=         -39
src put in ok=         -39
csrc put in ok=         -39
dat put in ok=         -39
cdat put in ok=         -39
close?         -62

Thanks for any help!

Regards Peter :)

remove a part in array value without foreach

for example i have this array

my @a = ("http://aze.com/azfaz","http://acc.com/azfssz");

i want to romove this part in sites in the array (azfaz,azfssz) without foreach i made this sub to romove the last after the 3 /

sub cheat {
my @o = split(/\//,$_[0],3);
my @r = split (/\//,$o[2],0);
return $r[0];

}

when i make cheat(@array); it just remove the azfaz from the first site in array and not working from the other

Fortran array Index

I am migrating the Fortran code to C. I would like to know what will be the c equivalent for the following statements T is 2d array dim T (D,D) and T_indices is array of indices in T , T_indices(E) where E< D.

T(T_indices(:),:) = 1/(A/B)*T(T_indices(:),:)

T(:,T_indices(:)) = 1/(A/B)*T(:,T_indices(:))  

C interpretation

for (i=0 ; i < E ; i++){
 for (j=0 ; j< B ; j++){
  T[T_indices[i] * B + j] = 1/(A/B)* T[T_indices[i] * B + j];
  T[J * B + T_indices[i]] = 1/(A/B)* T[J * B + T_indices[i]];
 }
}

Is this valid interpretation ?

How to access string object in array of JSON-array via PHP?

I have searched for almost 30 minutes and still can't find the answer for my problem. So, here is it: I have an JSON-file called "localeDE.l", now I'm trying to print the objects to the website, "locale_name"(type: string) works, but "translations"(type: array) won't work.

My JSON file:

"locale_name": "DE",
"translations": [
    {"Welcome": "Willkommen",
     "Goodbye": "Auf Wiedersehen"}
]

Here my PHP file:

$file = file_get_contents('localeDE.l');
$locale = json_decode($file);
print_r($locale);
echo "Locale=" . $locale->{'locale_name'};
echo "Translations:";
echo "  Welcome:" . $locale->{'translations'}->{'Welcome'};
echo "  Goodbye:" . $locale->{'translations'}->{'Goodbye'};

I also tried something like (...) $locale->{'translations.Welcome'}; etc. Can You help me?

- Felipe Kaiser

Having trouble with PHP and JSON

I have to create a JSON request in PHP based on this encoded JSON layout and I'm having difficulty preparing the request in the pre-encoded PHP. Any help would be greatly appreciated as what I am trying to put together does not see to be working:

{   
    "skin":"weborder",  
    "establishmentId":1,    
    "items":[{  
        "modifier_amount":0,    
        "modifieritems":[   

        ],  
        "initial_price":0.1,    
        "special_request":"",   
        "price":0.1,    
        "product":null, 
        "product_name_override":"Bag Charge",   
        "quantity":1,   
        "tax_amount":0, 
        "tax_rate":0,   
        "is_cold":false 
    },
    {   
        "modifier_amount":0.5,  
        "modifieritems":[{  
            "modifier":106, 
            "modifier_cost":0,  
            "modifier_price":0.5,   
            "qty":1,    
            "qty_type":0    
        }], 
        "initial_price":1.95,   
        "special_request":"",   
        "price":1.95,   
        "product":1,    
        "product_name_override":"Regular Coffee",   
        "quantity":1,   
        "tax_amount":0.197, 
        "tax_rate":8.75,    
        "is_cold":false 
    }], 
    "orderInfo":{   
        "created_date":"2014-­‐06-­‐11T18:52:44",   
        "pickup_time":"2014-­‐06-­‐11T19:22:44",    
        "tax":0.2,  
        "subtotal":2.55,    
        "final_total":2.55, 
        "surcharge":0,  
        "dining_option":0,  
        "call_name":"Joe Smith / Jun 11, 7:22pm / 1234567890"   
    },  
    "paymentInfo":{ 
        "type":3,   
        "phone":"1234567890",   
        "email":"joe@mail.com", 
        "first_name":"Joe", 
        "last_name":"Smith" 
    },  
    "notifications":[{  
        "skin":"weborder",  
        "type":"email",
        "destination":"joe@mail.com"    
    }]  
}

Here is the PHP I put together that is breaking:

$order_data = array(
            'skin' => 'weborder',   
            'establishmentId' => $establishment,
            'items' => array(
                'modifier_amount':0,    
                'modifieritems' => array(   
                    'modifier' => '106',    
                    'modifier_cost' => '0', 
                    'modifier_price' => '0.5',  
                    'qty' => '1',   
                    'qty_type' => '0'   
                ),  
                'initial_price' => '0.1',   
                'special_request' => '',    
                'price' => '0.1',   
                'product' => null,  
                'product_name_override' => 'Bag Charge',    
                'quantity' => '1',
                'tax_amount' => '0',    
                'tax_rate' => '0',  
                'is_cold"' => 'false'   
             ),
             'orderInfo' => array(
                'created_date' => '2014-­‐06-­‐11T18:52:44',    
                'pickup_time' => '2014-­‐06-­‐11T19:22:44', 
                'tax' => '0.2', 
                'subtotal' => '2.55',   
                'final_total' => '2.55',    
                'surcharge' => '0', 
                'dining_option' => '0', 
                'call_name' => 'Joe Smith / Jun 11, 7:22pm  / 1234567890'
             ),
             'paymentInfo' => array(
                'type' => 3,    
                'phone' => '1234567890',    
                'email' => 'joe@mail.com',  
                'first_name' => 'Joe',  
                'last_name' => 'Smith'  
             ),
             'notifications' => array(
                'skin:' => 'weborder',  
                'type' => 'email',
                'destination' => 'joe@mail.com'
             )
        );

        // Then use json_encode
        $json = json_encode($order_data);

Thanks in advance. :)  

Why json_encode() doesn't work if the number of elements in the array more then 3

I have an array that contains the following elements:

array(4) {
[0]=> array(2) { ["home"]=> string(5) "Niort" ["away"]=> string(12) "Valenciennes" } 
[1]=> array(2) { ["home"]=> string(15) "Kuban Krasnodar" ["away"]=> string(3) "Ufa" } 
[2]=> array(2) { ["home"]=> string(17) "Fratangelo, Bjorn" ["away"]=> string(13) "Bhambri, Yuki" } 
[3]=> array(2) { ["home"]=> string(13) "VfL Wolfsburg" ["away"]=> string(15) "Bayern Mnchen" } } 

and i'm trying to convert it to json array with:

while ($row = $result->fetch_assoc()) {
        array_push($events, $row);
    }
echo json_encode($events);

but it does not work, however, when i reduce the number of elements to 3 or less, it's work perfectly. Please, help me to understand why is this so, and if it is possible, let me know how i can convert more then 3 elements of my array.

Get every combination of multiple arrays that can have multiple options

I know a similar question has been asked in the past but this one is a bit different. I'm looking to get every variation possible including multiple options from a single array so. I'm really struggling with this and I greatly appreciate any help in it.

$arrayA = array("1","2","3"); $arrayB = array("A","B");

Results should be

1 2 3 12 13 121 123 1A 1B 1C 1A 12A etc..

so the same value can't be repeated twice but can include others from the same array. The desired output is in the form of an array where it's easy to see what the pulled elements are.

Appending to an array vs writing to file

I'm writing a program which takes in a byte array of potentially millions of bytes, reads each one from a BinaryArrayInputStream, and if the byte is not "printable" (ascii 32-126), that byte is encoded in a certain way and written to a BinaryArrayOutputStream instance; if the byte is "printable" it is directly written to that same BinaryArrayOutputStream instance. So from a broader view I am taking in a byte array, and getting back a similar byte array except certain characters have been encoded.

My question is: would it be faster to write my data out to a file or to continuously be writing to this OutputStream?

convert variable string into char array c++

I found so incredibly many question posts of this sort - i'm speaking of "convert string to char array" - but none of those solutions actually work for me, trying to convert cin >> text into some char array textArray[1024] which I could then convert into a list cause I think it's easier to work with. It's for some encryptor (code down below).

If there's any easier way of doing this then let me know.

#include <iostream>
#include <string>
#include <fstream>
#include <list>
#include "encryptor.h"

using namespace std;

void encrypt()
{
    string text;
    char textArray[1024];
    list<char> listText;
    list<char>::iterator it;
    int textSize;
    string code;
    bool fail = false;
    string segment;
    string fileName;

    cout << "Now enter your text. (max 1024 chars)" << endl;
    cin >> text;

    textSize = text.size();

    //string to char[]
    //none of these work
    strncpy(textArray, text.c_str(), sizeof(textArray));
    textArray[sizeof(text) - 1] = 0;

    strcpy_s(aText, text.c_str());

    for (int i = 0; i < text.length(); i++)
    {
        aText[i] = text[i];
    }

    aText[text.length()] = '\0';

    text.copy(aText, text.length()+1);



    //char[] to list
    for(int i = 0; i < textSize; i++)
    {
        char *c = new char(textArray[i]);
        listText.push_back(*c);
    }

    //Going through list
    //for every char there's a special segment added to the string
    for(it = listText.begin(); it != listText.end(); it++)
    {
        if(fail == true) break;

        switch (*it)
        {
        case 'a':
        case 'A':
            {
                segment = "XQ7";
            } break;
        {/*---*/}               //I just let everything from b - z and 0 - 9 out for this post
        case ' ':
            {
                segment = "Z 7";
            } break;
        case '.':
            {
                segment = "Z 8";
            } break;
        case ',':
            {
                segment = "Z 4";
            } break;
        default:
            {
                cout << "There's a special char this program doesn't understand. It is "
                cout << *it << endl;
                cout << "Do it again" << endl;
                fail = true;
            } break;
        }

        code = code + segment;
    }

    do
    {
        cout << "\n\nname of the file: ";
        cin >> fileName;

        if(fileName != "")
        {
            ofstream write;
            write.open(fileName + ".txt");
            write << code;
            write.close();
        } else {
            cout << "Name shouldn't be empty!" << endl;
        }
    } while(fileName == "");
}

PHP - Checking up on string with regex and push to array

I have two variables as follows:

$string1 = '/test/10/25';
$string2 = '/test/[0-9]+/[0-9]+

Is it possible to make PHP compare these two strings and push the actual ID's (10 and 25) into an array like so by using the regex as some sort of guidance?

Array
(
    [0] => 10
    [1] => 25
)

I tried playing around with preg_match() but this just puts everything into the same array key.

Return matching values in other sheet according to multiple criteria

Warning: Complex situation requires wall of text

What I have as data

In sheet A, I have alphanumerical numbers In column A and sometimes, suppliers in columns B, C, D.

 colA      colB   colC   colD

H-19328    SupA   SupB   SupA
H-12801    SupC   SupD
H-32829    
H-23123    SupB   SupC
.......    ....   ....   ....

In sheet B, I have alphanumerical numbers in column A, and 1 supplier in column B. I also have a bunch of other information in the next columns.

 colA      colB    colC   colD

H-19328    SupA   stuffs stuffs 
H-52601    SupA   stuffs stuffs
H-3279     SupA   stuffs stuffs
H-4987123  SupB   stuffs stuffs
.......    ....   ...... ......

In sheet A, the alphanumerical number is unique in the list. The numbers in sheet A may or may not have a matching number in sheet B and vice versa. Even when the number matches, the suppliers may or may not match.

What I want to do

For each number in sheet A, I want to check if sheet B holds that number with the associated supplier. For example, for the first number H-19328, I will check if sheet B has:

 colA      colB    colC   colD

H-19328    SupA   stuffs stuffs   < This could match twice as it was twice in A
H-19328    SupB   stuffs stuffs

I don't know if the number/supplier combo will match, and if it does, I don't know how many times it will match. I want to retrieve the values from sheet B in the other columns, C and D.

What I have as code

I put the values in column A of sheet A in a dictionnary. The keys are the numbers, and the Supplier information is in an array tied to each key. The dictionnary works well. The issue is not about the dictionnary, if you are not good with them you can still help me.

Right now I have a loop that matches every key + supplier to the sheet b list and returns how many times it matched. To dispel confusion, Dict_Sup is the dictionnary. Dict_sup.items(1) is an array containing suppliers. Dict_sup.items(1)(0) is the first entry of that array. Dict_sup.items(1)(supcount) is the last entry of that array.

For i = 0 To Dict_Sup.Count - 1
    For j = 0 To supcount 'supcount is the size of the array containing the suppliers
        nb_of_matches = TimesExtracted(Dict_Sup.Keys(i), Dict_Sup.Items(i)(j))   
    Next j
Next

The function TimesExtracted looks into sheet B (which is an extract, sheet name is SupDocs) and matches what I mentioned to look at the number of matches. Here it is:

Function TimesExtracted(Key As String, Sup As String) As Integer()
    Dim lastline As Integer
    Dim AllSupDocs As Range
    Dim SupDoc As Range

    lastline = SupDocs.Range("A" & Rows.Count).End(xlUp).Row
    Set AllSupDocs = SupDocs.Range("E1:E" & lastline)

    For Each SupDoc In AllSupDocs
        If SupDoc.Value = Key And SupDoc(, 61).Value = Sup Then
              Timesextracted = TimesExtracted + 1
        End If
    Next
End Function

I would like to transform this function so that it would send the 'stuffs' on which it found matches, instead of sending the amount of matches. There are 3 'stuffs' values I want. I tried making it an Array function, but I was not successful in redimensioning the array to send back an appropriate amount of results;

Function TimesExtracted(Key As String, Sup As String) As String()
    Dim lastline As Integer
    Dim AllSupDocs As Range
    Dim SupDoc As Range
    Dim tmpArray(0) As String
    Dim j As Integer

    lastline = SupDocs.Range("A" & Rows.Count).End(xlUp).Row
    Set AllSupDocs = SupDocs.Range("E1:E" & lastline)

    For Each SupDoc In AllSupDocs
        If SupDoc.Value = Key And SupDoc(, 61).Value = Sup Then
            ReDim Preserve tmpArray(UBound(tmpArray) To UBound(tmpArray) + 2) 'adds 2 places in the array
            tmpArray(j) = SupDoc(, 3).Value
            tmpArray(j + 1) = SupDoc(, 4)Value
            j = j + 2
        End If
    Next
    Timesextracted = tmpArray 'Doing this so I can redim 
End Function

Is there a better way to return the values I want? Am i making this way too complex? If both answers are no, then what do i need to modify in this last block for it to send an array with the following information

If only SupA matched in column A100:
    (C100.Value, D100.Value)

If supA matched in A100 and matched again in A110:
    (C100.Value, D100.Value, C110.Value, D110.Value)

Spring RestTemplate and JSON how to ignore empty Arrays deserialization?

I am currently using Spring 4.1.6 with a RestTemplate to consume a third party webservice with JSON which I cannot change its behavior.I am using Jackson databind v2.6.0.

Problem: Sometimes the service returns for a member a hashmap {member:{"key":"value",...}} sometimes the same member is just an empty array {member:[]}. So I can not ignore the property by default.

Is there a way to configure the deserialization to ignore empty arrays? I saw a jackson property "WRITE_EMPTY_JSON_ARRAYS" but I am not quite sure how I can use it with my restTemplate and spring configuration.

Are there other possiblities e.g. use some combination of @JsonXXX Annotations? I saw @JsonSerialize which can be used on class level, but I don't like to write a deserializer for all my classes just to handle this situation (However if there is no other way of course I will do)

Example responses to llustrate the behavior of the service:

  • response with a hashmap {"id":170,"categories":{"13":"caro"}}

  • response with empty array of the same member {"id":170,"categories":[]}

Example of my RestTemplate usage:

    BasicAuthRequestFactory requestFactory = new BasicAuthRequestFactory(httpClient);        
    restTemplate = new RestTemplate(requestFactory);
    Article a = restTemplate.getForObject(new URI("http://..."), Article.class);

Error:

 caused by: com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.LinkedHashMap out of START_ARRAY token
 at [Source: java.io.PushbackInputStream@4aa21f9d; line: 1, column: 1456] (through reference chain: ResponseArticleWrapper["data"]->Article["categories"])
 at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:148)

Example of my current annotated class:

@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(Include.NON_NULL)
public class Article {  
    @JsonProperty("id")
    private Integer id;
    @JsonProperty("categories")  
    private Map<Integer,Category> categories = new HashMap<Integer,Category>();
}

Thank you in advance for any hints and examples.