mardi 4 août 2015

Append/delete items from array in php/html file

I am a PHP beginner and need some help.

I have a config.data file that has the $logins array serialized in it. (thanks @Barmar!) I have signin.php (below) which I would like to modify in the following way:

  1. Add a 'add project' button which would append the info to the $logins array
  2. Add a 'delete project' button which would delete the info to the $logins array.

Any help to accomplish these two goals would be appreciated!

config.data:

$logins = array(
'project1' =>
        array(
        'password' => 'mypassword',
        'title' => 'Capacitors Project Planner',
        'emails' => array('myweb@mywebsite.com')
         ),
'project2' =>
    array(
        'password' => 'mypassword2',
        'title' => 'My second project',
        'emails' => array('manager@youwebsite.com',
                        'worker@youwebsite.com')
        )
);

signin.php:

require_once( 'config.php' );
//displays arrays
<table class="table" border='1'>
<thead>
    <tr>
    <th> Project name</th>
    <th> Project Login</th>
    </tr>
    </thead>
<tbody>
<?php foreach( $logins as $projname => $projinfos ): ?>
    <tr>
        <td><?= $projname ?></td>
        <td><?= $projinfos["title"]?>
        </td>
        </tr>

<?php endforeach; ?>
</tbody>
</table>



via Chebli Mohamed

CI update_batch; Concatenate and increment variable and string as array value

Using CI update_batch(), I am unable to set a value where I increment an integer db value. This works successfully with CI set(); update(), but batch is the better option as there are multiple updates.

I have columns that all have the same characters at the end of the name, with different characters at the beginning (different years): 2014x , 2015x , 2016x , etc. So I have created a $var that identifies the year, then I add the string 'x' and 'y' via concatenation. Finally, the value setting in the array is to increment by 1 so I add +1 . This concatenation works fine in the keys - that is to say I am updating the correct column and fields.

$data = array(
    array('name' => $name1,
            $var.'x' => $var.'x+1'),
    array('name' => $name2,
            $var.'y' => $var.'y+1')
            );          
$this->db->update_batch('my_table', $data, 'tname');

In the above case, the fields are updated with the value of only $var - the year that has been defined.

I have also tried the following:

=> '{"$var.x+1"}'  // places a '0' value in the field
=> $var.'x' +1       // places the value of $var
=> '$var.x+1'        // places a '0' value in the field

How can I use update_batch() to increment my field by 1?



via Chebli Mohamed

swift: "for" loop and "if" statement return four arrays with one element instead of one array with four elements

I have an array of NSDate. I am filtering this array with a timeIntervalSinceDate to only keep specific ones. After looping through the array, and submitting an "if" statement to compare the elements in the array with others, I intend to append the desired ones into a new array.

However, after the whole process, it returns an array of one element every time, returning all the right elements, but in separate arrays every time. Instead of having one array of four elements, I end up with four arrays of one.

Here are the codes:

  var query = PFUser.query()

query!.whereKey("username", equalTo: PFUser.currentUser()!.username!)

query!.findObjectsInBackgroundWithBlock { (objects, NSError) -> Void in

if let objects = objects as? [PFObject] {

        for member in objects {

          if member["Network"] != nil {

                var acceptedMembers: [String] = member["Network"] as! [String]

               self.usernames = acceptedMembers


  var query = PFUser.query()

  query.findObjectsInBackgroundWithBlock({ (objects2, error2) -> Void in

  if let objects2 = objects2 as? [PFUser] {

                        for otherUser in objects2 {

   if contains(self.usernames, otherUser.username!) {

                           self.nameMember = otherUser.username!

                            self.setName()


                            var otherUserElement: AnyObject? = otherUser["myElement"]

                                    if otherUserElement != nil {

                                var OUEL = otherUserElement as! NSArray


                                var currentUserElement: AnyObject? = PFUser.currentUser()!["myElement"]

                                         if currentUserElement != nil {

                                var CUEL = currentUserElement as! NSArray

                                 var count = CUEL.count




                                   for point1 in OUEL {

                                        var arrayPoint1 = point1 as! NSArray

                                        var elem1: AnyObject = arrayPoint1[0]

                                        var elem11: AnyObject = arrayPoint1[1]

                                        var time1: AnyObject = arrayPoint1[2]


                                        self.element11 = elem1 as! Double
                                        self.element111 = elem11 as! Double
                                        self.date1 = time1 as! NSDate



                                        for point2 in CUEL {

                                            var arrayPoint2 = point2 as! NSArray

                                            var elem2: AnyObject = arrayPoint2[0]

                                            var elem22: AnyObject = arrayPoint2[1]

                                            var time2: AnyObject = arrayPoint2[2]


                                            self.element22 = lat2 as! Double
                                            self.element222 = long2 as! Double
                                            self.date2 = time2 as! NSDate

                                            self.tryPoint = point2 as! [AnyObject]




                                          self.Y.append(self.tryPoint)


                                            let compo = self.cal.components(.CalendarUnitSecond | .CalendarUnitMinute | .CalendarUnitHour | .CalendarUnitDay | .CalendarUnitMonth, fromDate: self.date2)


                                            self.second = compo.second

                     let unit2:NSCalendarUnit = .CalendarUnitSecond

                                            let components = self.cal.components(unit2, fromDate: self.date1, toDate: self.date2, options: nil)

      var range = -15...15

      if (self.element11 == self.element22) && (self.element111 == self.element222) && contains(range, components.second) {

      self.dateX.append(self.date2)

      var countArray = [NSDate]()

     if NSDate().timeIntervalSinceDate(self.date2) <= 86400 {

                                                for n in self.dateX {

                                                    if n == self.date2 {

                                                     countArray.append(n)

                                                    } } }



} } }}}}}}   })
}}}}

Do you have any idea of what might cause this issue ? Why would it return different arrays for each element every time instead of one array with all ?

Thank you very much,



via Chebli Mohamed

compute the wight of each tag for each item in matlab

I have an array like below:

<table style="width:10%">
  <tr>
    <td>Item</td>
    <td>Tag</td> 
  </tr>
  <tr>
    <td>1</td>
    <td>2</td> 
  </tr>
  <tr>
    <td>1</td>
    <td>3</td> 
  </tr>
  <tr>
    <td>2</td>
    <td>1</td> 
  </tr>
  <tr>
    <td>3</td>
    <td>2</td> 
  </tr>
  <tr>
    <td>3</td>
    <td>2</td> 
  </tr>
  <tr>
    <td>3</td>
    <td>4</td> 
  </tr>
</table>

I want to compute the weight of each tag for each item in array. for example the wight of tag 2 for item 3 is 0.66, while the wight of tag 2 for item 1 is 0.5. Is there a simple way in matlab to do this?



via Chebli Mohamed

Accessing an ArrayList method, when the ArrayList is inside an object

I am trying to design a text based game.

The game will have a feature in which, if the user inputs get all, all the objects in the room must be added to the player's inventory.

The inventory of the player is an ArrayList of objects and so is the room's object "sack"

The code that i have written is as follows:

public void getAll(Room room, Player player)
  {
      for(int i = 0; i < room.objectNames.size(); i ++)
      {
          player.inventoryObjects.add(room.objects.get(i));
      }
  }

This method is inside the main class, i.e , the class which has the main method.

The arraylists are declared as:

public ArrayList<Objects> inventoryObjects = new ArrayList<Objects>();
//this is in the Player Class

public ArrayList<Objects> objects = new ArrayList<Objects>();
//this is in the Room Class

Can you tell me an alternative to line: 3 in the first piece of code that i have typed(the one with the loop) ?

-Thanks in advance



via Chebli Mohamed

JSON to Array react, jquery

I have json data obtained form my server and i want to put in a list, i already read Convert JSON To Array Javascript and Converting data from JSON to JavaScript array but i can't figure out what of all the options can i use in my code my json is like this:

{"response": {"user": [{"username": "", "description": "", "picture_url": "", "name": "", "phone": ""}]}, "success": true}

and i want to put it on an array like this:

[{username: "",description: "", picture_url: "", name: "", phone: ""}]

what can i do for this? i already try the answers of this: Converting JSON Object into Javascript array

i also try some functions like this:

$.each(data, function(i,obj){
                $(arr).append(obj.username+'</br>');
                $(arr).append(obj.description+'</br>');
                $(arr).append(obj.name+'</br>');
            });

and this:

var results = data;
            var arr = [], item;
            for (var i = 0, len = results.length; i < len; i++) {
                item = results[i];
                arr.push({username: item.username, description: item.description, name: item.name});
            }

but with the second one dont show anything and dont show any error, with the first one, showme an unespecthed error arr is not defined.



via Chebli Mohamed

Need to Display the Results of MySQLi num_rows in Separate Table from Array Results

I have a page that displays a MySQLi query result array. On this page the data comes to the page correctly but for my $result['rows'] which is the result of num_rows of the array results are showing up for each record and then the array results are being displayed. For example if there are 100 records to the query there is '100' displayed 100 times before the array results. I know it's because I'm using 'foreach' but I can't get it work with anything else. I've tried 'while', 'for', and 'continue' but nothing works but 'foreach' to retrieve the data correctly. What am I missing?

Here is the code:

<?php
            if($results) {
    echo "<table id='test' class='tablesorter' border='2'>";
    echo "<thead>";
    echo "<tr>";
    echo "<th class='header'># of Records</th>";
    echo "</tr>";
    echo "</thead>";
    echo "<tbody>";

        foreach($_SESSION['results'] as $result) {

                echo "<tr>";
                echo "<td>{$result['rows']}</td>";
                echo "</tr>";

            }
            echo "</tbody>";
            echo "</table>";
            }
            ?>

            <?php
            if($results) {
    echo "<table id='test' class='tablesorter' border='2'>";
    echo "<thead>";
    echo "<tr>";
    echo "<th class='header'>Date Set</th>";
    echo "<th class='header'>Branch</th>";
    echo "<th class='header'>Appointment Date</th>";
    echo "<th class='header'>Employee</th>";
    echo "<th class='header'>First Name</th>";
    echo "<th class='header'>Last Name</th>";
    echo "<th class='header'>Last Four</th>";
    echo "<th class='header'>Phone</th>";
    echo "<th class='header'>City</th>";
    echo "<th class='header'>State</th>";
    echo "<th class='header'>Zip</th>";
    echo "</tr>";
    echo "</thead>";
    echo "<tbody>";


            foreach($_SESSION['results'] as $result) {

                echo "<tr>";
                echo "<td>{$result['set_date']}</td>";
                echo "<td>{$result['branch']}</td>";
                echo "<td>{$result['appt_date']}</td>";
                echo "<td>{$result['employee']}</td>";
                echo "<td>{$result['fname']}</td>";
                echo "<td>{$result['lname']}</td>";
                echo "<td>{$result['last_four']}</td>";
                echo "<td>{$result['phone']}</td>";
                echo "<td>{$result['city']}</td>";
                echo "<td>{$result['state']}</td>";
                echo "<td>{$result['zip']}</td>";
                echo "</tr>";

            }
            echo "</tbody>";
            echo "</table>";            

}else{

    echo "No Records Found";
}
?>



via Chebli Mohamed

Is there an easy way to transform a tensor (3D array) to a 2D array of the tensor slices as the vectors in MATLAB?

Consider a 3D matrix t of size d1 x d2 x d3. Is there a an easy way of making the matrix (2D array) of size d1d2 x d3?

so the naive implementation/pseudo-code would be something like:

T % d1 x d2 x d3
M % d1d2 x d3
for i=1:d3
    t_slice = t(:,:,i);
    m = reshape(t_slice, [d1d2, 1]); %columns of t_slice are the vector
    M(:,i) = m;
end

but it seemed something that should already be implemented or some library in matlab that already does this. Doing this by hand seems a little inefficient and I was suspecting that there was some clever MATLAB trick to do this. Am I right?

Ideally I thought something like:

M = reshape(T,[d1d2, d3])

would exist, but wasn't sure or couldn't find it yet...



via Chebli Mohamed

Xcode Swift: Could not cast value of type '__NSCFString' (0x102e8ac50) to 'NSDictionary' (0x102e8b8d0)

I am trying to display my JSON information in the debug area but I am having a problem in which I have not found a solution.

First of all, let me display the code I have so far:

BBUpJSON.swift

import Foundation

class BBUpJSON {

    func loadBbup(completion: ((AnyObject) -> Void)!) {

        var urlString = "http://ift.tt/1T0gelg"

        let session = NSURLSession.sharedSession()
        let bbupUrl = NSURL(string: urlString)

        var task = session.dataTaskWithURL(bbupUrl!){
            (data, response, error) -> Void in

            if error != nil {
                println(error.localizedDescription)
            } else {

                var error : NSError?

                var bbupData = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: &error) as! NSArray

                var jnslst = [JSONExtrct]()

                for jnsextrct in bbupData{
                    let jnsextrct = JSONExtrct(data: jnsextrct as! NSDictionary)
                    jnslst.append(jnsextrct)
                }

                let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
                dispatch_async(dispatch_get_global_queue(priority, 0)) {
                    dispatch_async(dispatch_get_main_queue()) {
                        completion(jnslst)
                    }
                }

            }
        }

        task.resume()
    }

}

JSONExtrct.swift

import Foundation

class JSONExtrct {

    var titulo : String!
    var imageUrl : String!
    var imageData : NSData?
    var imageUrl2 : String!
    var imageData2 : NSData?
    var imageUrl3 : String!
    var imageData3 : NSData?
    var marca : String!
    var color : String!
    var tipo : String!
    var ref : Int!

    init(data : NSDictionary) {

        self.titulo = getStringFromJSON(data, key: "titulo")

        let image = data["image"] as! NSDictionary
        self.imageUrl = getStringFromJSON(image, key: "image")

        let image2 = data["image2"] as! NSDictionary
        self.imageUrl2 = getStringFromJSON(image, key: "image2")

        let image3 = data["image3"] as! NSDictionary
        self.imageUrl3 = getStringFromJSON(image, key: "image3")

        self.marca = getStringFromJSON(data, key: "marca")

        self.color = getStringFromJSON(data, key: "color")

        self.tipo = getStringFromJSON(data, key: "tipo")

        self.ref = data["ref"] as! Int

    }

    func getStringFromJSON(data: NSDictionary, key: String) ->String{

        //let info : AnyObject? = data[key]

        if let info = data[key] as? String {
            return info
        }

        return ""

    }

}

ViewController.swift

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let json = BBUpJSON()
        json.loadBbup(nil)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

So, when I run the app with a breakpoint in for jnsextrct in bbupData{ in the BBUpJSON.swift file, it shows in the left side of the debug area that I have 20 values. Everytime I run po bbupData in the right output of the debug area it just partially shows me 3 of the values out of the 20 I have in my JSON file. When I add another breakpoint in completion(jnslst) located at the end of the same swift file and press Continue program execution, I get the following error: Could not cast value of type '__NSCFString' (0x10c3c2c50) to 'NSDictionary' (0x10c3c38d0). It then redirects the error to let image = data["image"] as! NSDictionary that is located in my JSONExtrct.swift.

This is the link to the json file that is trying to extract the information.

-----UPDATE------

Modified the values of the strings in JSONExtrct.swift to:

if let imageURL = data["image"] as? String {
            self.imageUrl = imageURL
        }

        if let imageURL2 = data["image2"] as? String {
            self.imageUrl2 = imageURL2
        }

        if let imageURL3 = data["image3"] as? String {
            self.imageUrl3 = imageURL3
        }

And added the same breakpoints to see the results in BBUpJSON.swift. From the breakpoint for jnsextrct in bbupData{, it still displays me the same 3 values out of the 20 I have (don't know if that should show that way) when I type po bbupData in the output area. When I Continue program execution to completion(jnslst), it doesn't show me the previous error but it shows me the following output result when typing po jnslst:

(lldb) po jnslst
[BonBonUp.JSONExtrct, BonBonUp.JSONExtrct, BonBonUp.JSONExtrct, BonBonUp.JSONExtrct, BonBonUp.JSONExtrct, BonBonUp.JSONExtrct, BonBonUp.JSONExtrct, BonBonUp.JSONExtrct, BonBonUp.JSONExtrct, BonBonUp.JSONExtrct, BonBonUp.JSONExtrct, BonBonUp.JSONExtrct, BonBonUp.JSONExtrct, BonBonUp.JSONExtrct, BonBonUp.JSONExtrct, BonBonUp.JSONExtrct, BonBonUp.JSONExtrct, BonBonUp.JSONExtrct, BonBonUp.JSONExtrct, BonBonUp.JSONExtrct]

When I continue and add one more breakpoint at the last bracket, it shows me the following error: fatal error: unexpectedly found nil while unwrapping an Optional value and it redirects the error to completion(jnslst) showing Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP,subcode=0x0)



via Chebli Mohamed

Parse load data in array swift

Im trying to load Parse data and set in a array as result, i check a few questions but many codes are outdate so I'm stuck, how i can set the query in a array? heres the code:

var array [String] = []

func loadData() {

    var query = PFQuery(className: "ParseClass")

    query.orderByAscending("column")

    query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]?, error: NSError?) -> Void in

        if error == nil {

            self.array.append( objects! )// error here

        } else {

            println( error?.userInfo )
        }
    }

}



via Chebli Mohamed

views_get_view_result array is missing data?

The array I get using views_get_view_result appears to return everything I need except the corresponding labels for keys in list fields. I want to print the labels, rather than the keys -- Is there a way to have them included in the array, without inserting them separately? Here's what I'm currently getting in the array:

< snip >
    [field_contact] => Array
      (
        [und] => Array
          (
            [0] => Array
              (
                [value] => db
              )
            )
          )
< snip >

When I setup this field, I created key|label pairs, and I want to print the label, not the pair. Such as:

db|Dries Buytaert

Any ideas? Thanks for looking!



via Chebli Mohamed

insert data into database from array

i need to add data to database from array(table). but this POST.php is not working properly. so can you guys please give me any solution for this.

this is the error that it give.

Illegal string offset 'h_name' in C:\wamp\www\confirm\post.php on line 11

line 11 is: VALUES ('$row[h_name]', '$row[room]', '$row[nors]', '$row[nights]', '$row[euro]', '$row[date]', '09090')";

all inserted value give that error. Array to string conversion Thank you.

                    </br>
                    <h4 id="italic">Hotel Details :</h4>
                    </br>

                        <div class="reqtable">
                            <table>
                                <tr ><td>Hotel Name</td><td>Room Type</td><td>Number of Rooms</td><td>Nights</td><td>EURO</td><td>Date</td></tr>
                                <tr><td><?php
                                    include "conn.php";
                                    $query = "SELECT h_id, h_name FROM hotels";
                                    $result = mysqli_query($conn, $query) or die(mysqli_error($conn)); // Run your query

                                    echo '<select name="list[h_name]" id="h_name"  ">';

                                    echo '<option value=""> Choose a Hotel </option>';
                                    while($row = mysqli_fetch_assoc($result)) {
                                        echo '<option value="'.$row['h_id'].'">'.$row['h_name'].'</option>';
                                    }

                                    echo '</select>';/

                                        ?>
                                </td>

                                <td>
                                    <?php echo '
                                                <select name="list[room]" id="room"  >
                                                    <option value="">Choose a Room Type</option>
                                                    <option value="1">Single Room</option>
                                                    <option value="2">Double Room</option>         
                                                    <option value="3">Triple Room</option>
                                                    <option value="4">Family Room</option>
                                                    <option value="5">Custom Room</option>
                                                </select>';
                                    ?>
                                </td>
                                <td><input type="text" name="list[nors]" placeholder="Number of Rooms"></td>
                                <td> <input type="text" class="zxc" nname="list[nights]" placeholder="Nights"></td>
                                <td><input type="text" name="list[euro]" placeholder="euro"></td>
                                <td><input type="date" name="list[date]" placeholder="Date"></td>
                                <td><pre>    </pre></td>
                                <td><input type='button' class='AddNew' value='Add new item'></td></tr>
                                <tr><td>Total</td><td></td><td></td><td><input name="result" id="result"></td><td></td><td></td></tr>
                            </table>    
                        </div>
                            </br>

                            <input type="submit" id="submit" name="submit" value="Register" color="red" style="width: 77px; height: 50px"></div>

                </form>





post.php(php process)





<?php
    include "conn.php";
    print_r($_POST['list']);





        foreach ($_POST as $row) {
            $query = "INSERT INTO reqhotels (reqh_h_name, reqh_rtype, reqh_nor, reqh_nights, reqh_euro, reqh_date, reqh_req_no) 
                    VALUES ('$row[h_name]', '$row[room]', '$row[nors]', '$row[nights]', '$row[euro]', '$row[date]', '09090')";

            $result = mysqli_query($conn, $query) or die(mysqli_error($conn)); 

            if($result > 0) {
                echo"successfull";
            }
            else {
                echo"fail";
            }
        }
?>



via Chebli Mohamed

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



via Chebli Mohamed

Find Next to Last Element in PHP Foreach

I need to write a script that returns the next-to-last element in a foreach loop. Something like the below concept. How would I go about doing so?

foreach($row as $r) {
    if (element index is last - 1) {
        echo "The next-to-last element is" . $r;
    }
}



via Chebli Mohamed

Syntax error in custom function

I'm getting a syntax error in the first line of the following code. I'm using array function parameters as shown in MSDN. After removing the brackets from String() the error disappears, but I need an array of strings. My code so far:

Private Function Contains(name As String, names As String()) As Boolean
Contains = False

Dim Index As Integer
For Index = 0 To names.GetUpperBound(0)
    If str = name Then
        Contains = True
        Exit For
    End If
Next
End Function



via Chebli Mohamed

Excluding/Including items from one array based on values from another

I have two arrays, one containing hashes, the other integers. They look like this (samples):

mainArray[0] = {"ID" => 23, "NAME" => "SALLY"}
mainArray[1] = {"ID" => 34, "NAME" => "BILL"}

idArray[0] = 432
idArray[1] = 34

I want to filter mainArray so that only entries in it whose ID values are in idArray make the cut. How can I best do this? I don't mind making a new array if that helps.



via Chebli Mohamed

Return array to excel from VBA function

My goal is to return a list of dates to excel based on some rules which I will post for code completeness but are not necessarily relevant to the question. Focus mostly on the FindDates function. I am trying to return an array of dates but I only get the first one. How can I get the entire array?

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   
For counter = 0 To length
If Holiday_Calendar(counter) = MyDate Then
IsInArray = True
Exit Function
End If
Next counter
IsInArray = False
End Function

Function MyPattern(ByVal MyDate As Date, ByRef Holiday_Calendar As Range) As Date     
 If Weekday(MyDate) = 1 Or Weekday(MyDate) = 7 Or IsInArray(MyDate, Holiday_Calendar) Then
 MyPattern = MyPattern(DateAdd("d", -1, MyDate), Holiday_Calendar)
 Else
 MyPattern = MyDate
 End If
End Function

Function FindDates(ByVal StartDate As Date, ByVal EndDate As Date, ByRef Holiday_Calendar As Range) As Variant
Dim result_dates(9999) As Date
Dim counter As Integer
counter = 0
Dim MyDate As Date
MyDate = StartDate
If Weekday(MyDate) = 7 Then
    MyDate = DateAdd("d", 2, MyDate)
End If
If Weekday(MyDate) = 1 Then
    MyDate = DateAdd("d", 1, MyDate)
End If
While MyDate <= EndDate
    If Weekday(MyDate) = 6 Then
        result_dates(counter) = MyPattern(MyDate, Holiday_Calendar)
        counter = counter + 1
    End If
    If MyDate = DateAdd("m", DateSerial(Year(MyDate), Month(MyDate), 1) - 1, MyDate) And Weekday(MyDate) <> 6 And Weekday(MyDate) <> 7 And Weekday(MyDate) <> 1 And (Weekday(MyDate) <> 2 Or Not IsInArray(MyDate, Holiday_Calendar)) Then
        result_dates(counter) = MyPattern(MyDate, Holiday_Calendar)
        counter = counter + 1
    End If
    MyDate = DateAdd("d", 1, MyDate)
Wend
FindDates = result_dates()
End Function



via Chebli Mohamed

Best way to get more than one value form Json?

I'm using bootstrap for my website, and in the center I need to display a series of item names with pictures. The name information I get form a Json that I request from a URL.

This is what the Json looks like

{
   "success": true,
   "rgInventory": {
      "3019159034": {
         "id": "3019159034",
         "classid": "469444882",
         "instanceid": "302028390",
         "amount": "1",
         "pos": 1
      },
      "3007405356": {
         "id": "3007405356",
         "classid": "520025252",
         "instanceid": "0",
         "amount": "1",
         "pos": 2
      }
   },
   "rgCurrency": [],
   "rgDescriptions": {
      "469444882_302028390": {
         "appid": "730",
         "classid": "469444882",
         "instanceid": "302028390",
         "icon_url": "-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgpoor-mcjhoyszMdS1D-OOjhoK0mvLwOq7c2D4B6pwijLiXpt6s3lDkrkJvZG-hLI7Ee1M7YVmC8gO-kunrjZK1tJXXiSw0uDynv1g",
         "icon_url_large": "-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgpoor-mcjhoyszMdS1D-OOjhoK0mvLwOq7cqWdQ-sJ0xLyR99WmjgXi-EFlZT3zcYeWdQBsaVCB8wS7we-9jcS875rNwXZqsig8pSGKg7HJkhk",
         "icon_drag_url": "",
         "name": "Tec-9 | Urban DDPAT",
         "market_hash_name": "Tec-9 | Urban DDPAT (Field-Tested)",
         "market_name": "Tec-9 | Urban DDPAT (Field-Tested)",
         "name_color": "D2D2D2",
         "background_color": "",
         "type": "Consumer Grade Pistol",
         "tradable": 1,
         "marketable": 1,
         "commodity": 0,
         "market_tradable_restriction": "7",
         "descriptions": [
            {
               "type": "html",
               "value": "Exterior: Field-Tested"
            },
            {
               "type": "html",
               "value": " "
            },
            {
               "type": "html",
               "value": "An ideal pistol for the Terrorist on the move, the Tec-9 is lethal in close quarters and features a high magazine capacity. It has been painted using a Digital Disruptive Pattern (DDPAT) hydrographic.\n\n<i>By the time you're close enough to notice the pixels it's already too late<\/i>"
            },
            {
               "type": "html",
               "value": " "
            },
            {
               "type": "html",
               "value": "The Bank Collection",
               "color": "9da1a9",
               "app_data": {
                  "def_index": "65535",
                  "is_itemset_name": 1
               }
            },
            {
               "type": "html",
               "value": " "
            }
         ],
         "actions": [
            {
               "name": "Inspect in Game...",
               "link": "http://steamrungame/730/76561202255233023/+csgo_econ_action_preview%20S%owner_steamid%A%assetid%D434632987144428496"
            }
         ],
         "market_actions": [
            {
               "name": "Inspect in Game...",
               "link": "http://steamrungame/730/76561202255233023/+csgo_econ_action_preview%20M%listingid%A%assetid%D434632987144428496"
            }
         ],
         "tags": [
            {
               "internal_name": "CSGO_Type_Pistol",
               "name": "Pistol",
               "category": "Type",
               "category_name": "Type"
            },
            {
               "internal_name": "weapon_tec9",
               "name": "Tec-9",
               "category": "Weapon",
               "category_name": "Weapon"
            },
            {
               "internal_name": "set_bank",
               "name": "The Bank Collection",
               "category": "ItemSet",
               "category_name": "Collection"
            },
            {
               "internal_name": "normal",
               "name": "Normal",
               "category": "Quality",
               "category_name": "Category"
            },
            {
               "internal_name": "Rarity_Common_Weapon",
               "name": "Consumer Grade",
               "category": "Rarity",
               "color": "b0c3d9",
               "category_name": "Quality"
            },
            {
               "internal_name": "WearCategory2",
               "name": "Field-Tested",
               "category": "Exterior",
               "category_name": "Exterior"
            }
         ]
      },
   "more": false,
   "more_start": false
}

And yes I'm trying to display my CS:GO inventory.

In short: what is the best way to get the market_hash_name value from the Json? and make it display a image?



via Chebli Mohamed

How can I group sequential numbers in a perl array?

I am trying to write a perl script in which if I have a sample array which looks like below :

@array = (0,1,2,3,4,8,9,10,12,14,16,17,19)

then I need to convert/format this array in way so that I get the output in a format which looks like below :

output_bus[0-4, 8-10, 12, 14, 16-17, 19]



via Chebli Mohamed

How to do array_push() dynamically in PHP?

Let say that we are going to add some array to a multidimensional array. I can select the number of arrays which should be added to the main array but what about 99 array? Here is my code that I can change $howmany to add the number of arrays that I need (up to 4 arrays):

$stack = array(array("foo" , "bar"));
    foreach ($rowF as $row) {
        switch ($howmany) {
        case 1:
            array_push($stack, array($row[$column1]));
            break;
        case 2:
            array_push($stack, array($row[$column1], $row[$column2]));
            break;
        case 3:
            array_push($stack, array($row[$column1], $row[$column2], $row[$column3]));
            break;
        case 4:
            array_push($stack, array($row[$column1], $row[$column2], $row[$column3], $row[$column4]));
            break;
        }
    }



via Chebli Mohamed

Failing to use numeric characters within Ruby array as indices for a string

I am trying to use the numeric charecters from the array held within the positions argument as indices to access the characters of the string inside the string argument to subsequently print a new string. I have an idea of what I need to do to get it to work, but I am hung up.

Total code thus far:

  def scramble_string(string, positions)
    str = string
    pos = positions.join
    newstr = []
    i = 0
    while i < pos.length do
      return newstr.push(str[pos[i]])
      i += 1
    end
  end
  scramble_string("hello", [2, 3, 4, 5])

I suspect my problem lies within this part of the code...

return newstr.push(str[pos[i]])



via Chebli Mohamed

Constructing objects for a user-defined generic Array in Java

If I defined my own generic array with this constructor:

public PublisherGenericArray(Class<E> c, int s)
{   
    // Use Array native method to create array  
    // of a type only known at run time
    @SuppressWarnings("unchecked")
    final E[] a = (E[]) Array.newInstance(c, s);
    this.a = a;
}

How do I create an object that satisfies the first parameter (class c)?

Basically:

PublisherGenericArray <String> newArray = new <String> PublisherGenericArray(???,newSize);

What would go in the first parameter labeled "???"



via Chebli Mohamed

Copy or Append first 13 index in Array of Strings to another and sort it - php

I am trying to work with array of string in php, its array of images and shuffle the array many times and i need to get the first 13 value from the huge array and place it in another array and then sort the second array of strings. but i am getting two errors :

Notice: Array to string conversion in /Applications/XAMPP/xamppfiles/htdocs/index.php on line 46

Warning: ksort() expects parameter 1 to be array, string given in /Applications/XAMPP/xamppfiles/htdocs//index.php on line 50
Array30.png41.png24.png31.png25.png44.png2.png15.png14.png50.png36.png38.png32.png

here is my code :

   $images = array("1.png","2.png","3.png","4.png","5.png","6.png","7.png","8.png",
        "9.png","10.png","11.png","12.png","13.png","14.png","15.png","16.png","17.png","18.png",
        "19.png","20.png","21.png","22.png","23.png","24.png","25.png","26.png","27.png","28.png",
        "29.png","30.png","31.png","32.png","33.png","34.png","35.png","36.png","37.png","38.png",
        "39.png","40.png","41.png","42.png","43.png","44.png","45.png","46.png","47.png","48.png",
        "49.png","50.png","51.png","52.png"
        );


        shuffle($images);      
        shuffle($images);      
        shuffle($images);  
        shuffle($images);  
        shuffle($images); 

        $playerArraySorted = array();

        for ($i = 0; $i < 13; $i++) {

            $playerArraySorted .= $images[$i];
        }


        ksort($playerArraySorted,2);
         echo "$playerArraySorted";



via Chebli Mohamed

How to get PHP object data?

I have these data formats of objects in php.

stdClass Object
(
    [@attributes] => stdClass Object
        (
            [currency] => JPY
            [rate] => 136.07
        )

)

How can I get currency and rate from this object? Thanks in advance..



via Chebli Mohamed

how to update or add a value to an existing json array using PHP forms?

I have a json array stored as a field in a database table. Now I want to use add, edit and delete functions on them. The following code modifies the entire 'conditional_elements_dependencies' array.

  • edit.php:

        $dependent = $_POST['dependent'];
        $term =$_POST['term'];
        $dependee = $_POST['dependee'];
        $json=get_option('conditional_elements_dependencies'); // here I use syntax as specified in Omeka
        if (!$json) { $json="null"; }
        $data = json_decode($json, 1);
        $newdata = array('0'=>$dependent, '1' => $term, '2'=>$dependee);
        $data[] = $newdata;
        $json= json_encode($data);
    
    

But I need to know how to add or delete the specific data items such as dependee, term or dependent and not the entire json array.



via Chebli Mohamed

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



via Chebli Mohamed

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.



via Chebli Mohamed

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...



via Chebli Mohamed

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!



via Chebli Mohamed

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



via Chebli Mohamed

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.



via Chebli Mohamed

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



via Chebli Mohamed

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?



via Chebli Mohamed

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?



via Chebli Mohamed

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.



via Chebli Mohamed

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"
}



via Chebli Mohamed

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();
                 }   

                 }

             }



via Chebli Mohamed

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?



via Chebli Mohamed

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"
    }
]



via Chebli Mohamed

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);
}



via Chebli Mohamed

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;
    }



via Chebli Mohamed

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?



via Chebli Mohamed

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



via Chebli Mohamed

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.



via Chebli Mohamed

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 %}



via Chebli Mohamed

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.



via Chebli Mohamed

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.



via Chebli Mohamed

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?



via Chebli Mohamed

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.



via Chebli Mohamed

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?



via Chebli Mohamed

lundi 29 juin 2015

this dictionary requires a model item of type

learning to work around c# and razor. I have this issue which I am struggling to get my head around. I have researched this forum to understand but to no avail. The model item passed into the dictionary is of type '', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable

Anyway this is the code I have been working with: However my data are coming from my VehicleClass. My VehicleClass

using LogViewer.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace LogViewer.Classes
{
    public class VehicleClass
    {
        public int id { get; set; }
        public String make { get; set; }
        public String type { get; set; }
        public byte taxBand { get; set; }
        public DateTime created { get; set; }
        public DateTime updated { get; set; }
        public DateTime deleted { get; set; }
        public bool isDeleted { get; set; }
        public decimal price { get; set; }
        public String description { get; set; }

        public List<Vehicles> _VehicleList = new List<Vehicles>();

        public VehicleClass()
        {
            _VehicleList.Add(new Vehicles
            {
                id = 001,
                make = "Renault",
                type = "Saloon",
                taxBand = 5,
                created = new DateTime(2015,1,1),
                updated = new DateTime(2015,3,1),
                deleted = DateTime.Now,
                isDeleted = true,
                price = 3000,
                description = "A very comfortable car to ride"
            });

            _VehicleList.Add(new Vehicles
            {
                id = 002,
                make = "Toyota",
                type = "Hatchback",
                taxBand = 2,
                created = new DateTime(2015,2,1),
                updated = new DateTime(2015,3,9),
                deleted = DateTime.Now,
                isDeleted = true,
                price = 2500,
                description = "Reliable, strong, fuel efficient"
            });

            _VehicleList.Add(new Vehicles
            {
                id = 003,
                make = "Audi",
                type= "Saloon",
                taxBand = 6,
                created = new DateTime(2015,4,3),
                updated = new DateTime(2015,6,1),
                deleted = DateTime.Now,
                isDeleted = true,
                price = 6000,
                description = "A high performance car"
            });
        }
    }
}

Controller Class: HomeController.cs

using LogViewer.Classes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace LogViewer.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index(string sortOrder)
        {
            VehicleClass _vehicles = new VehicleClass();
            ViewBag.IdSortParam = String.IsNullOrEmpty(sortOrder) ? "id_desc" : "";
            ViewBag.MakeSortParam = sortOrder == "Make" ? "make_desc" : "Make";

            switch(sortOrder)
            {
                case "id_desc":
                    _vehicles._VehicleList.OrderByDescending(v => v.id).ToList();
                    break;

                case "make_desc":
                    _vehicles._VehicleList.OrderByDescending(v => v.id).ToList();
                    break;

                default:
                    break;
            }
            return View(_vehicles._VehicleList.ToList());
        }
    }
}

Finally my View: Index.cshtml

@model LogViewer.Classes.VehicleClass

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<table>
    <thead>
        <tr>
            <th>
                @Html.ActionLink("ID", "Index", new { sortOrder = ViewBag.IdSortParam, currentFilter = ViewBag.CurrentFilter})
            </th>
            <th>
                @Html.ActionLink("Make", "Index", new { sortOrder = ViewBag.MakeSortParam, currentFilter = ViewBag.CurrentFilter})
            </th>
            <th>Type</th>
            <th>Tax Band</th>
            <th>Created</th>
            <th>Updated</th>
            <th>Deleted</th>
            <th>Is Deleted</th>
            <th>Price</th>
            <th>Description</th>
        </tr>
    </thead>
</table>

@foreach (var item in Model._VehicleList)
{
<table>
    <tbody>
        <tr>
            <td>@item.id</td>
            <td>@item.make</td>
            <td>@item.type</td>
            <td>@item.taxBand</td>
            <td>@item.created</td>
            <td>@item.updated</td>
            <td>@item.deleted</td>
            <td>@item.isDeleted</td>
            <td>@item.price</td>
            <td>@item.description</td>
        </tr>
    </tbody>
</table>
}

The error I have been receiving is this:

The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[LogViewer.Models.Vehicles]', but this dictionary requires a model item of type 'LogViewer.Classes.VehicleClass'.

The name does not exist in the current context (in ActionResult with MVC Entity Framework)

In ActionResult "Details(int? id)" of a controller I have:

            var TheUser = db.AspNetUsers.Where(u => u.Id == CurrentUser)
                         .Select(u => new
                         {
                             ID = u.Id,
                             Email = u.Email,
                             Username = u.UserName,
                             Surrname = u.Surname,
                             Name = u.Name,
                             Role = u.Role,
                             CreditBalance = u.CreditBalance
                         }).Single();

            var TheJournal = db.CreditJournal.Where(tj => tj.CvID == id && tj.UseBy == CurrentUser)
                            .Select(tj => new
                               {
                                   IdJournal = tj.IdJournal,
                                   Operation = tj.Operation,
                                   CvID = tj.CvID,
                                   CreditConsumed = tj.CreditConsumed,
                                   UseDate = tj.UseDate,
                                   UseBy = tj.UseBy
                               });

            var Counter = TheJournal.Count();

When I evaluate values in Debug Mode I have:

TheUser |>>>    { ID = "56cc2430-4db5-4799-ad41-fa1d103d1967", Email = "sales@maps4u.ro", Username = "sales@maps4u.ro", Surrname = "Laurentiu", Name = "LAZAR", Role = 3, CreditBalance = 75 }  <Anonymous Type>

TheJournal |>>> {System.Data.Entity.Infrastructure.DbQuery<<>f__AnonymousType9<int,string,int?,int?,System.DateTime?,string>>}  System.Linq.IQueryable<<>f__AnonymousType9<int,string,int?,int?,System.DateTime?,string>> {System.Data.Entity.Infrastructure.DbQuery<<>f__AnonymousType9<int,string,int?,int?,System.DateTime?,string>>}

Counter |>>>    The name 'Counter' does not exist in the current context

What can be wrong in simple code from above? (The equivalent SQL statement for TheJornal returns for the given criteria, at least 4 records). Somehow I think to declare the variables outside the condition, but what type have to be? (Anyway the first, TheUser is just ok, the issue start with second, TheJournal )

Approach for encrypting user data with user password

I have the following requirement: Users on my site have some sensitive data, meaning that ONLY the owner user should be able to read it. In other words: I have to make sure that not even the site/sql administrators can (human) read the content.

I am trying to implement the following approach: When saving the data, encrypt it by using the user password. When serving the data to the user, decrypt it using the user's password. I can handle the password-change scenario by re-encrypting the user data. However, the issue is that the only time I have the user password is during Loging-In and I am not sure it's a good idea to 'hold on to it' by storing it in the user profile in-mem object.

So, how would I go about such requirement? Again - the goal is that only the user should be able to en/decrypt their data on the fly. Any tips appreciated.

Fresh MVC project is giving 500 error for RequestFilteringModule

Hi I am getting following error for a fresh MVC project. Any idea how to fix it? 500 error

Title for Anchor tag with condition check in MVC

This code is showing Title on Mouse hover for Anchor tag even my div status is Locked, but I want to show Title for Anchor tag only when div status is not locked. Can anyone assist me to implement this?

 <div>
                <a <% if (!Model.ReservationStatus.IsPrintContractLocked){%> href="<%= Url.SignatureFormAction() %>"
                    <% }%> title=" <%= Html.Encode(Model.ReservationStatus.IsPrintContractComplete ? Resources.Edit : Resources.EnterInfo)%> <%=Resources.SignatureForm%>"><span class="accessibleText">
                        <%=Resources.SignatureForm%></span>
                    <div class="status<% if (Model.ReservationStatus.IsPrintContractComplete){%> complete<% }%><% if (Model.ReservationStatus.IsPrintContractLocked){%> locked<% }%>">
                    </div>
                    <div status="<%= Model.ReservationStatus.IsPrintContractComplete%>" locked="<%= Model.ReservationStatus.IsPrintContractLocked%>">
                        <%=Html.Encode(Model.ReservationStatus.IsPrintContractLocked ? Resources.Locked : (Model.ReservationStatus.IsPrintContractComplete ? Resources.Completed : Resources.Incomplete))%>
                    </div>
                    <div>
                        <% if (!Model.ReservationStatus.IsPrintContractLocked)
                           {%>
                        <%= Html.Encode(Model.ReservationStatus.IsPrintContractComplete ? Resources.Edit : Resources.EnterInfo)%>
                        <%} %>
                    </div>
                </a>
            </div>
        </div>
    </div>

ASP.NET MVC Ajax will only update first in list

I have a list of Posts in my index page, where you can vote up and down on each one. My problem is that I can only vote on the first one in the list.

My JS:

<script type="text/javascript">
    $(document).ready(function () {
        function voteAjax(pid, vurl, value) {
            // Show a loading gif or something
            // $(".loading").show(); .hide();
            $.ajax({
                url: vurl,
                type: "GET",
                data: { vote: value, id: pid },
                success: function (data) {
                    if (data.success) {
                        // All went well, say thanks
                        $('#vote-display').html(data.displayValue);
                    } else {
                        // show ex error
                    }
                },
                error: function (err) {
                    // the call thrown an error
                },
                complete: function () {
                    // Hide loading gif
                }
            });
        }
        $('#vote-up').click(function () {
            var pid = $(this).attr("data-pid");
            var value = 1;
            var vurl = '@Url.Action("VotePost", "Services")';

            $.ajax({
                url: vurl,
                type: "GET",
                data: { vote: value, id: pid },
                success: function (data) {
                    if (data.success) {
                        // All went well, say thanks
                        $('#vote-display').html(data.displayValue);
                    } else {
                        // show ex error
                    }
                },
                error: function (err) {
                    // the call thrown an error
                },
                complete: function () {
                    // Hide loading gif
                }
            });
        });
    });
</script>

and my view where I display the posts in a list:

@foreach (var post in Model.Posts)
{
    <div class="row">
        <div class="col-md-1 vote-i">
            <a id="vote-up" data-pid="@post.PostID" class="glyphicon glyphicon-chevron-up vote-up"></a><br />
            <span id="vote-display">@Html.DisplayFor(modelPost => post.Vote.Value)</span><br/>
            <a id="vote-down" data-pid="@post.PostID" class="glyphicon glyphicon-chevron-down vote-down"></a><br/>
        </div>
    </div>
}

I suspect there is something going on when I get the postID and that Im only able to get the first one for some reason, but I can't figure it out.