samedi 27 juin 2015

Printing whats inside the array

import java.io.*;
public class redtry4 {
    public static void main(String[]args)throws IOException{
        BufferedReader IN = new BufferedReader(new InputStreamReader(System.in));
        int[]numx = new int[10];
        System.out.println("Enter 10 different numbers:");
        for(int b=0; b<10; b++)
        {
            System.out.print("Number"+(b+1)+":");
            numx[b]=Integer.parseInt(IN.readLine());


        }
        System.out.print("Accepted numbers are:"+"\n");

    }
}

This is a working code. I wonder how would your print all the numbers youve inputed inside the array like for example:

Accepted numbers are: 1 2 3 4 5 6 7 8 9 12

and can i have ideas on how can i only put numbers that are not the same when inputed.

thanks!

C Program crashes when accessing specific array element of struct field

I have this code:

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

struct game_s {
  bool isOccupied[20][10];
};

int main() {
  struct game_s* game_p;
  game_p->isOccupied[0][8] = false;
  printf("0,8 works\n");
  game_p->isOccupied[2][8] = false;
  printf("2,8 works\n");
  game_p->isOccupied[1][7] = false;
  printf("1,7 works\n");
  game_p->isOccupied[1][9] = false;
  printf("1,9 works\n");
  game_p->isOccupied[1][8] = false; // crashes the program
  printf("1,8??");
}

As you can see from the comment, the program crashes when I try to access a specific element of the array. (More specifically, Windows tells me that "a.exe has stopped working" with the attached information.) If I use something other than 10 for the second dimension, the element will be another one. If I don't use a struct, it doesn't crash. If I use int instead of bool, it doesn't crash. If I make a variable of the struct instead of a pointer, it doesn't crash.

I'm compiling this with gcc main.c on Windows. If I use ideone, it runs without a problem.

Can someone tell me what's going on here?


Additional information Windows provides about the crash:

Problem signature:
  Problem Event Name:   APPCRASH
  Application Name: a.exe
  Application Version:  0.0.0.0
  Application Timestamp:    558f50c8
  Fault Module Name:    KERNELBASE.dll
  Fault Module Version: 6.1.7600.17206
  Fault Module Timestamp:   50e6605e
  Exception Code:   c0000005
  Exception Offset: 00011bcd
  OS Version:   6.1.7600.2.0.0.768.3
  Locale ID:    1031
  Additional Information 1: 0a9e
  Additional Information 2: 0a9e372d3b4ad19135b953a78882e789
  Additional Information 3: 0a9e
  Additional Information 4: 0a9e372d3b4ad19135b953a78882e789

Read our privacy statement online:
  http://ift.tt/WDU7ZV

If the online privacy statement is not available, please read our privacy statement offline:
  C:\Windows\system32\en-US\erofflps.txt

N-dimensional std::vector to N-dimensional C-array

How do you convert a N-dimensional std::vector to the corresponding N-dimensional C-array?

E.g. std::vector<std::vector<int>> to int arr[n][m], where n is the dimension of the outer vector and m of the inner vector?

Memory corrupted across single-line function call?

I am getting a seg fault from some code which accesses an array consisting of strings. The odd thing is I lose the memory across a one-line function call.

So this is my code:

class A {

    void method1(){

        std::cout << _myArray[ID] << std::endl;               //This outputs fine
        _pointerToObjectB->method2(ID, side);
    }

    std::array<std::string, 30000> _myArray;
    B* _pointerToObjectB;
};

In a different class:

class B {

    void method2(const int16_t ID, const int8_t Side) {
        std::cout << _objectA._myArray[ID] << std::endl;          //Seg fault
    }

    A _objectA;
};

GDB reports a seg fault, backtrace:

#0  0x00007ffff05cd81c in std::string::_M_data() const () from /debug/bin/../lib/libstdc++.so.6
#1  0x00007ffff05cd85a in std::string::_M_rep() const () from /debug/bin/../lib/libstdc++.so.6
#2  0x00007ffff05cdeb8 in std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(std::string const&) ()
   from /debug/bin/../lib/libstdc++.so.6
#3  0x00007fffe32f8bb1 in B<(short)-2, (short)1, (short)30000>::method2 (this=0x0, ID=362, Side=0 '\000')
#4  0x00007fffe32eafdf in A<(short)-2, (short)1, (short)30000>::method1 (this=0x2754400, ID=362, Side=0 '\000')

The pointer must be fine as it was able to invoke method2(). What else could be wrong?!

Its as if _objectA has been deleted across the call?

This seg fault is consistent, it happens every time I run the program. I'm at a bit of a loss what to do next.

Convert Python string to array in JavaScript

I have a JavaScript script which receives information from a Python server. The Python server outputs a list, which is converted to a string prior to being sent to the JavaScript script.

I'd like to be able to convert the received string into a form that can be indexed with JavaScript. Here's an example output string from the Python server:

var Message = [['Word1A', 'Word1B'], ['Word2A', 'Word2B'], ['Word3A', 'Word3B']];

Given the above example, I'd like to be able to query the received string as as an indexed array:

var x;
for (x in Message) {
    alert(x[0]};

The above example should return:

Word1A
Word2A
Word3A

What's the best way to go about this?

Overwritting null character in C array

Consider the case:

char s1[] = "abc";
s1[3] = 'x';
printf("%s", s1);

As I know, printf prints characters until it finds the null character and then stops.

When I overwrite the null character by 'x', why does printf print the s1 array correctly? How does it find the null character?

php array_filter dynamic filters from json

I got the two following arrays as input data:

$filters = [ { "Key": "ao", "Value": "5", "FilterComperator": ">=", "FilterOperator": " && " }, { "Key": "name", "Value": "Joe", "FilterComperator": "<>", "FilterOperator": " && " }, { "Key": "ao", "MySQLOP": "<=", "Value": "10", "FilterOperator": " && " } ]

$arr = [ { "ao": 13 }, { "ao": 10 }, { "ao": 6 } ]

What I am trying to achieve is use the filters from $filters array so I can filter $arr without using php eval

return array_filter($arr, function($k){
   return $k->ao >= '5' && $k->name <> 'Joe' && $k->ao <= '10';
});

Is there any suggestion? perhaps I could use create_function() instead or anything else that could do the job.

Array of chars to linked list - Using the address in array

i am trying to pass words from a string to a linked list, the thing is, i can't reallocate memory to my string inside my struct, i should be using the address of each word inside the array.

my struct:

typedef struct slist{
    char *string;
    struct slist * prox;
} *SList;

my function:

int words (char t[], SList *l){
    int i, p;
    p=0;
    *l = (SList) calloc(1, sizeof(struct slist));

    SList aux = NULL;


    SList li = *l;
    for(i=0; t[i]!='\0' ;){
        aux = (SList) calloc(1, sizeof(struct slist));

        li->string = &t[i];
        li->prox = aux;
        li = aux;

        while(t[i]!=' ') i++;

        //t[i++] = '\0'; -> this doesn't work, bus error 10;

        while(t[i]==' ') i++;

        p++; //This counts words
    }

    return p;

}

This works, kind of, my doubt is, i can't change the initial array to include a NULL char at the end of each word (Strings declared in C are read-only right?)

So, i tried to add the t[i]='\0' in vain.

At this moment, running the code with this string

char *str = "this is one sentence";

will get me the following strings in my linked list:

this is one sentence
is one sentence
one sentence
sentence

the expected result is not this one, it should add the NULL char after the first word inside my list->string

PS: The linked list is not well defined, it adds a NULL at the end unnecessarily but i can deal with that later on.

Thank you for your help!

How to find all maximas if x and y values of the function are given as np.array

I have two numpy arrays x and y, I have plotted a curve with these values. Now I want to find all the values of x where local maxima exists on that curve. How it will be done?

Please give a method to fit the best possible curve with these x and y values and the values of x (or the indices of the value of x in array x) where local maxima exists.

Looping Array in wordpress

I have problem with my code here, I want convert serialize data in wordpress like this

$data ='a:2:{i:0;a:8:{s:8:"order_id";s:2:"19";s:5:"print";s:18:"type-canvas-framed";s:4:"size";s:12:"08-x-10-inch";s:18:"frame_canvas_color";s:10:"blackframe";s:11:"orientation";s:8:"portrait";s:3:"qty";s:1:"1";s:5:"price";d:42.990000000000002;s:8:"shipping";d:13.800000000000001;}i:1;a:7:{s:8:"order_id";s:2:"19";s:5:"print";s:11:"type-poster";s:4:"size";s:12:"36-x-48-inch";s:11:"orientation";s:8:"portrait";s:3:"qty";s:1:"1";s:5:"price";d:42.990000000000002;s:8:"shipping";d:14.800000000000001;}}' ;

I do parse the data using unseriliaze using unserialize the result like this

$result=array (
  0 => 
  array (
    'order_id' => '19',
    'print' => 'type-canvas-framed',
    'size' => '08-x-10-inch',
    'frame_canvas_color' => 'blackframe',
    'orientation' => 'portrait',
    'qty' => '1',
    'price' => 42.99,
    'shipping' => 13.8,
  ),
  1 => 
  array (
    'order_id' => '19',
    'print' => 'type-poster',
    'size' => '36-x-48-inch',
    'orientation' => 'portrait',
    'qty' => '1',
    'price' => 42.99,
    'shipping' => 14.8,
  ),
);

I want to looping the array, how to do that in wordpress.

Thanks

How to generate 2D array from a set of string in rails?

I need to generate 2D array in rails from a set of given strings. For example:

days =[ "Monday",
     "Tuesday",
     "Wednesday",
  ]

Now I want to create a 2D array and the data in this array will be fill by from days string in random manner.

Example:

[monday, tuesday, wednesday],
[tuesday, wednesday, monday]
...

and so on depends on given dimensions

How to do it?

Search An Array Consisting of Sub-Arrays For the Largest Number and Return in a New Array

I am working on a coding challenge to take a given array which consists of sub-arrays, search for the largest number in each sub-array, and finally return a new array consisting only of the largest numbers. My thought process was to create variables out of each subarray, write a for-loop comparing each value within the array, then push the largest value to a new array. After writing my first for-loop I tested my code and see that I am getting an unexpected result of the entire first subarray being pushed into my new array. I am looking for the mistake before I write the next three loops. Thank you. Edit: This is for beginner JavaScript coders and the suggestion indicates to use comparison operators in your solution.

function largestOfFour(arr) {
      var one = arr[0];
      var two = arr[1];
      var three = arr[2];
      var four = arr[3];
      var newArr = [];

      for (var i = 0; i < one.length; i++){
        var oneLrg = 0;
        if (one[i] > oneLrg){
          oneLrg = one[i];
          }
        newArr.push(oneLrg);
      }  

  return arr;
}

console.log(largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]])); //This test case returns [4,5,1,3] instead of just [5]

Click on an element and delete it from an array

itemElement.onclick=function(){
        //remove element from view
        this.parentNode.removeChild(this);

        //find the element that was clicked on in the array
        //which should be itemElement(aka this)????
        var index=itemArray.indexOf(this);

        //remove it from the array
        itemArray.splice(index,1);

        //console.log to check
        console.log(itemArray);
    }

That is my code I am currently using to delete items from a list. I want the user to be able to click on the item in their list they want to delete, delete it from the view and then delete it from an array of items. Deleting the element from the view is working fine, but for some reason its only deleting the last element added to the array, not the actual element that was clicked on. So if the user makes a list that has Bob,Tom,Rob and then clicks on Tom, Tom is no longer displayed in the list but Rob will be deleted from the array.

Here is that whole block of code

const addButton =<HTMLButtonElement>document.querySelector("#addButton");
const saveButton = document.querySelector("#saveButton");
const itemsSection = document.querySelector("#itemsSection");
const itemArray: Array<string> = [];

let itemElement;
let newItem: string;
let itemText: string;

//add new item to shopping list
addButton.onclick=function addItem(){

    //add each item to the list
    itemElement = document.createElement("li");
    newItem = (<HTMLInputElement>document.querySelector("#newItem")).value;
    itemText = document.createTextNode(newItem);
    itemElement.appendChild(itemText);
    itemsSection.appendChild(itemElement);
    document.querySelector("#newItem").value="";

    //push each item to our array to store in local storage
    itemArray.push(newItem);
    console.log(itemArray);

    itemElement.onclick=function deleteItem(){
        var index=itemArray.indexOf(this);
        this.parentNode.removeChild(this);

        itemArray.splice(index,1);

        console.log(itemArray);
    }

}

As you can see im using typescript

AS3: hitTestObject turning up null for no apparent reason

I'm currently coding a game, and in one part of the code, it's checking to see if the player is close enough to a monster in mArray for its health bar to appear. I use hitTestObject for this with var i incrementing to go through the list. However, I will randomly get this error message:

TypeError: Error #2007: Parameter hitTestObject must be non-null.

After seeing this for the first time, I put the test all under the conditional if (mArray.length > 0) to make sure the Array() was filled before even attempting the test... but it still occurs at random times. I even used trace(i) to see if it happened on a certain part of the list, but it's completely random each debug session! I know the player portion can't be null since it is on the screen at all times during the hitTest, so I'm at a loss for words right now.

The portion of code in question (nothing else is related to this except for the use of mArray[i] in different places):

for (var i:int = 0; i < mArray.length; i++) {
    if (mArray.length > 0) {

        trace(i); //my attempt to see if it occurred at a specific incrementation of i

        if (player.hitTestObject(mArray[i])) {
            mArray[i].healthBar.visible = true;
        } else {
            mArray[i].healthBar.visible = false;
        }

    }
}

Again, it works perfectly for everything all of the time except for random cases it gives me the TypeError. Is this just a hiccup in my code, is there some obvious problem that I'm overlooking, or does the code just like to throwback to 2007?

EDIT: The debug session ALWAYS points to the line with if (player.hitTestObject(mArray[i])).

Segmentation Fault C (1d array to 2d array and back)

I am given a 1d array that contains color values for an image's pixels. The array is of size cols*rows. I want to change the color of a specific region. The function call is given the 1d array, its size, left, top, bottom, right, and also the desired color. What I tried to do is copy the values of the 1d array into a 2d array, do the deed on the 2d array then copy back the new values to the 1d array. I keep getting a segmentation fault error. Here's the code:

void region_set( uint8_t array[], 
     unsigned int cols, 
     unsigned int rows,
     unsigned int left,
     unsigned int top,
     unsigned int right,
     unsigned int bottom,
     uint8_t color )

{

if(!(left == right || top == bottom)){


    uint8_t Array2[cols][rows];


    int x, y;

    for(int i= 0; i < rows * cols; i++){            
        x = i / rows;
        y = i % cols;
        Array2[y][x] = array[i];
    }

    for(int y=left; y < right-1; y++){
         for(int x = top; x < bottom-1 ; x++){
            Array2[y][x] = color;
        }
    }

    for(int i= 0; i < rows * cols; i++){            
        x = i / rows;
        y = i % cols;
        array[i] = Array2[y][x];
    }


}

}

Basic Tic Tac Toe in java

I am trying to make a simple tic tac toe game in java and i'm almost done but my program doesn't declare a winner and doesn't declare if the game is a draw or not even when in my code i told it to declare a winner.

Here is my code:

 import java.util.*;

 public class TicTacToe {

/**
 * @param args the command line arguments
 */
    public  static int row,colm;
public  static char board[][]=new char [3][4];
public static Scanner console=new Scanner(System.in);
public static char turn='X';

public static void main(String[] args) {
 for(int i=0;i<3;i++){
     for(int j=0;j<4;j++){
         board[i][j]='_';
     }

}
 board();
 play();
 winner(row,colm);



 }
  public static void board(){
  for(int i=0;i<3;i++){


    for(int j=0;j<4;j++){
        if(j==0){
            System.out.print("|");
        }else{

        System.out.print(board[i][j]+"|");
    }

}
    System.out.println();



 }}


 public static void play(){
boolean playing=true;
while(playing){
  row=console.nextInt();
  colm=console.nextInt();
  board[row][colm]=turn;


  if(winner(row,colm)){
      playing=false;
      System.out.print("you win");
  }
   board();
  if(turn=='X'){
      System.out.println("Player 2 your O");
      turn='O';
  }else
      turn='X';


  }
 }
  public static boolean  winner(int move1,int move2){
 if(board[0][move2]==board[1][move2]&&board[0][move2]==board[2][move2])
 return true;

if(board[move1][0]==board[move1][1]&&board[move1][0]==board[move1][2])
    return true;
 if(board[0][0]==board[1][1]&&board[0][0]==board[2][2]&&board[1][1]!='_')
return true;

if(board[0][2]==board[1][1]&&board[0][2]==board[2][0]&board[1][1]!='_')
return true;
return false;

How do I find all word combinations that add up to a certain length?

I need a little help with coming up with an algorithm to traverse through a sorted word array and finding all the possible combinations that add up to a certain length. Any help is greatly appreciated! Thanks :)

Bulk Rename Files using PowerShell

I have looked a fair bit and tried many different ways of doing what I'm about to explain.

I have 310 files as of right now, that seemlessly fit along side each other, they're tiles. Like a jigsaw puzzle.

They're named by their column and then their row with an extra variable on the end as such:

IMG_0-0-15.jpg IMG_0-1-15.jpg IMG_0-2-15.jpg IMG_0-3-15.jpg IMG_0-4-15.jpg
IMG_1-0-15.jpg IMG_1-1-15.jpg IMG_1-2-15.jpg IMG_1-3-15.jpg IMG_1-4-15.jpg
IMG_2-0-15.jpg IMG_2-1-15.jpg IMG_2-2-15.jpg IMG_2-3-15.jpg IMG_2-4-15.jpg

This continues up to 61 (62 x 5 = 310).

I need to rename them so that they are simply taking the second number and then the first so as an example:

    IMG_1-4-15.jpg would become 4x1.jpg
    IMG_3-2-15.jpg would become 2x3.jpg
    IMG_32-1-15.jpg would become 1-32.jpg

Essentially switching the "column" and "row" values and eliminating all other parts of the string.

My code is as follows:

$arr =
"0x0.jpg","1x0.jpg","2x0.jpg","3x0.jpg","4x0.jpg","0x1.jpg","1x1.jpg",
"2x1.jpg","3x1.jpg","4x1.jpg","0x2.jpg","1x2.jpg","2x2.jpg","3x2.jpg",
"4x2.jpg","0x3.jpg","1x3.jpg","2x3.jpg","3x3.jpg","4x3.jpg","0x4.jpg",
"1x4.jpg","2x4.jpg","3x4.jpg","4x4.jpg","0x5.jpg","1x5.jpg","2x5.jpg",
"3x5.jpg","4x5.jpg","0x6.jpg","1x6.jpg","2x6.jpg","3x6.jpg","4x6.jpg",
"0x7.jpg","1x7.jpg","2x7.jpg","3x7.jpg","4x7.jpg","0x8.jpg","1x8.jpg",
"2x8.jpg","3x8.jpg","4x8.jpg","0x9.jpg","1x9.jpg","2x9.jpg","3x9.jpg",
"4x9.jpg","0x10.jpg","1x10.jpg","2x10.jpg","3x10.jpg","4x10.jpg","0x11.jpg",
"1x11.jpg","2x11.jpg","3x11.jpg","4x11.jpg","0x12.jpg","1x12.jpg","2x12.jpg",
"3x12.jpg","4x12.jpg","0x13.jpg","1x13.jpg","2x13.jpg","3x13.jpg","4x13.jpg",
"0x14.jpg","1x14.jpg","2x14.jpg","3x14.jpg","4x14.jpg","0x15.jpg","1x15.jpg",
"2x15.jpg","3x15.jpg","4x15.jpg","0x16.jpg","1x16.jpg","2x16.jpg","3x16.jpg",
"4x16.jpg","0x17.jpg","1x17.jpg","2x17.jpg","3x17.jpg","4x17.jpg","0x18.jpg",
"1x18.jpg","2x18.jpg","3x18.jpg","4x18.jpg","0x19.jpg","1x19.jpg","2x19.jpg",
"3x19.jpg","4x19.jpg","0x20.jpg","1x20.jpg","2x20.jpg","3x20.jpg","4x20.jpg",
"0x21.jpg","1x21.jpg","2x21.jpg","3x21.jpg","4x21.jpg","0x22.jpg","1x22.jpg",
"2x22.jpg","3x22.jpg","4x22.jpg","0x23.jpg","1x23.jpg","2x23.jpg","3x23.jpg",
"4x23.jpg","0x24.jpg","1x24.jpg","2x24.jpg","3x24.jpg","4x24.jpg","0x25.jpg",
"1x25.jpg","2x25.jpg","3x25.jpg","4x25.jpg","0x26.jpg","1x26.jpg","2x26.jpg",
"3x26.jpg","4x26.jpg","0x27.jpg","1x27.jpg","2x27.jpg","3x27.jpg","4x27.jpg",
"0x28.jpg","1x28.jpg","2x28.jpg","3x28.jpg","4x28.jpg","0x29.jpg","1x29.jpg",
"2x29.jpg","3x29.jpg","4x29.jpg","0x30.jpg","1x30.jpg","2x30.jpg","3x30.jpg",
"4x30.jpg","0x31.jpg","1x31.jpg","2x31.jpg","3x31.jpg","4x31.jpg","0x32.jpg",
"1x32.jpg","2x32.jpg","3x32.jpg","4x32.jpg","0x33.jpg","1x33.jpg","2x33.jpg",
"3x33.jpg","4x33.jpg","0x34.jpg","1x34.jpg","2x34.jpg","3x34.jpg","4x34.jpg",
"0x35.jpg","1x35.jpg","2x35.jpg","3x35.jpg","4x35.jpg","0x36.jpg","1x36.jpg",
"2x36.jpg","3x36.jpg","4x36.jpg","0x37.jpg","1x37.jpg","2x37.jpg","3x37.jpg",
"4x37.jpg","0x38.jpg","1x38.jpg","2x38.jpg","3x38.jpg","4x38.jpg","0x39.jpg",
"1x39.jpg","2x39.jpg","3x39.jpg","4x39.jpg","0x40.jpg","1x40.jpg","2x40.jpg",
"3x40.jpg","4x40.jpg","0x41.jpg","1x41.jpg","2x41.jpg","3x41.jpg","4x41.jpg",
"0x42.jpg","1x42.jpg","2x42.jpg","3x42.jpg","4x42.jpg","0x43.jpg","1x43.jpg",
"2x43.jpg","3x43.jpg","4x43.jpg","0x44.jpg","1x44.jpg","2x44.jpg","3x44.jpg",
"4x44.jpg","0x45.jpg","1x45.jpg","2x45.jpg","3x45.jpg","4x45.jpg","0x46.jpg",
"1x46.jpg","2x46.jpg","3x46.jpg","4x46.jpg","0x47.jpg","1x47.jpg","2x47.jpg",
"3x47.jpg","4x47.jpg","0x48.jpg","1x48.jpg","2x48.jpg","3x48.jpg","4x48.jpg",
"0x49.jpg","1x49.jpg","2x49.jpg","3x49.jpg","4x49.jpg","0x50.jpg","1x50.jpg",
"2x50.jpg","3x50.jpg","4x50.jpg","0x51.jpg","1x51.jpg","2x51.jpg","3x51.jpg",
"4x51.jpg","0x52.jpg","1x52.jpg","2x52.jpg","3x52.jpg","4x52.jpg","0x53.jpg",
"1x53.jpg","2x53.jpg","3x53.jpg","4x53.jpg","0x54.jpg","1x54.jpg","2x54.jpg",
"3x54.jpg","4x54.jpg","0x55.jpg","1x55.jpg","2x55.jpg","3x55.jpg","4x55.jpg",
"0x56.jpg","1x56.jpg","2x56.jpg","3x56.jpg","4x56.jpg","0x57.jpg","1x57.jpg",
"2x57.jpg","3x57.jpg","4x57.jpg","0x58.jpg","1x58.jpg","2x58.jpg","3x58.jpg",
"4x58.jpg","0x59.jpg","1x59.jpg","2x59.jpg","3x59.jpg","4x59.jpg","0x60.jpg",
"1x60.jpg","2x60.jpg","3x60.jpg","4x60.jpg","0x61.jpg","1x61.jpg","2x61.jpg",
"3x61.jpg","4x61.jpg"

cd 'D:\Apps\Temp'
$i = 0
Get-ChildItem -Path D:\Apps\Temp | ForEach-Object {
    Rename-Item -Path $_.FullName -NewName $arr[$i]
    $i++
}

Now this was a drastically different way of approaching this, but I've never really used PowerShell and I'm only drawing on my other scripting languages, mostly web-based and some batch to try and get me through.

Is there an easier way of doing this? In PHP I'd use explode.

How to load an array based on selected cell value from previous controller in Swift

I'm trying to build something close to the way the note app works but when you select the note instead of text you have a collectionView with cells loaded from an array.

Say I have two viewControllers connected to each other. The firstViewController has a collectionView loaded with the note names and upon selecting a note it will segue to the secondViewController that will load the array for that note.

I have a hard time understanding the logic... Do I work with NSUserDefaults and create an objectForKey for every note or do I create a new array for every note. How would I store these?

firstViewController

class MainViewController: UIViewController, UICollectionViewDelegate {

 var objects = Array<NSDate>()


 @IBAction func insertNewObject(sender: AnyObject) {

    objects.insert(NSDate(), atIndex: 0)
    let indexPath = NSIndexPath(forRow: 0, inSection: 0)
    collectionView.insertItemsAtIndexPaths([indexPath])
}

 func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath){

storyboard?.instantiateViewControllerWithIdentifier("secondtView") as! SecondViewController

//How do I proceed here? 

}
}

secondViewController

var myArray:[[AnyObject]] = []
class SecondViewController: UIViewController, UICollectionViewDelegate {


override func viewDidLoad() {
    super.viewDidLoad()
    if (NSUserDefaults.standardUserDefaults().objectForKey("myArray") != nil) {
    myArray = NSUserDefaults.standardUserDefaults().objectForKey("myArray") as! [[AnyObject]]
    }
}

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
      myArray.count
}



 func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> CollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! CollectionViewCell 
 cell.cellLabel.text = myArray[indexPath.row][0] as? String
 return cell 
}

array subscript operator overloading in c++

int &HTable::operator[](const string &key){
    int hashVal = hash(key);
    list<City> citylist = _pht->at(hashVal);
    std::list<City>::iterator it = citylist.begin();
    for (; it != citylist.end(); it++){
        std::cout << "came_inside" << endl;
        City ob = (*it);
        if (ob.city == key){
            return ob.population;
        }
    }
    City newcity(key,0);
    citylist.push_front(newcity);
    _pht->erase(_pht->begin() + hashVal);
    _pht->insert(_pht->begin() + hashVal, citylist);
    return newcity.population;

}

My class is

class HTable { public: HTable( int );

    int &operator[ ]( const string & );
    void print ( ) const;
    int  size  ( ) const;

private:
    int _size;
    vector< list< City > > *_pht;

    int hash( const string & ) const;

};

My problem is when I try to use this

HTable fl_cities( n );                      // hash table with n lists


fl_cities["abcd"] = 1000;
fl_cities["abc"] = 111;
fl_cities["abcdefdf"] = 111;

cout << fl_cities["abc"] << endl;    // return 0
cout << fl_cities["abcdefdf"] << endl; // return 0
cout << fl_cities["abcd"] << endl;  // return 0

I don't get expected value, it shows 0 because I am assigning 0 then returning the value. It is suppose to return the pointer and then when I assign the value it should go there but it doesn't work.

I have tried this operator with simple int array and it worked perfect in that case. But in this problem, list inside a vector it doesn't work.

Any help is appreciated !

get the index of the last negative value in a 2d array per column

I'm trying to get the index of the last negative value of an array per column (in order to slice it after). a simple working example on a 1d vector is :

import numpy as np

A = np.arange(10) - 5
A[2] = 2
print A # [-5 -4  2 -2 -1  0  1  2  3  4]

idx = np.max(np.where(A <= 0)[0])
print idx # 5

A[:idx] = 0
print A # [0 0 0 0 0 0 1 2 3 4]

Now I wanna do the same thing on each column of a 2D array :

A = np.arange(10) - 5
A[2] = 2
A2 = np.tile(A, 3).reshape((3, 10)) - np.array([0, 2, -1]).reshape((3, 1))
print A2
# [[-5 -4  2 -2 -1  0  1  2  3  4]
#  [-7 -6  0 -4 -3 -2 -1  0  1  2]
#  [-4 -3  3 -1  0  1  2  3  4  5]]

And I would like to obtain :

print A2
# [[0 0 0 0 0 0 1 2 3 4]
#  [0 0 0 0 0 0 0 0 1 2]
#  [0 0 0 0 0 1 2 3 4 5]]

but I can't manage to figure out how to translate the max/where statement to the this 2d array...

Using an Array Across two SubFunctions in VBA

I'm writing a macro that compares two columns of data and then identifies the rows where there is duplicate data found across both columns. That part of my program works. However, I dont know how to use arrays across two separate "Subs" in VBA. It's easier to explain if you first see my code.

Function DuplicateFinder(SheetName1 As String, SheetName2 As String)

Dim D As Object, C
Dim nda As Long, ndb As Long
Dim test As Range
Dim StorageArray(1000)
Dim increment
increment=0   

Set D = CreateObject("scripting.dictionary")
Sheets(SheetName2).Select
ndb = Range("O" & Rows.count).End(xlUp).Row
Sheets(SheetName1).Select
nda = Range("O" & Rows.count).End(xlUp).Row

For Each C In Range("O2:O" & nda)
    D(C.Value) = 1
    C.Select
Next C

Sheets(SheetName2).Select
For Each C In Range("O2:O" & ndb)
    If D(C.Value) = 1 Then
        C.Select

        StorageArray(increment) = C.Value ' this is where i want to store the C value.
    End If
    If Len(C) = 0 Then
        C.Interior.Color = vbRed
        MsgBox "Macro terminated at the blank red cell," & Chr(10) & _
            "as per instructions"

    End If
Next C

End Function

Sub MainFunction()

Dim A As String
Dim B As String
Dim C As String
Dim D As String

A = "Sheet 1 Name"
B = "Sheet 2 Name"
C = "Sheet 3 Name"
D = "Sheet 4 Name"
increment = 0


Call DuplicateFinder(Sheet 1 Name, Sheet 2 Name)
'I would then call the function 5 more times to compare each column in each sheet to one another

End Sub

The first function is used to compare the data across column '1' and column '2', and then identify the cells where there is duplicate data across each column. Again, that part works. The second sub is just the main function used to run the code. What I want to do, and don't know how to, is every time the DuplicateFinder finds a duplicate, it saves that 'data' in an array. However, I need to run the DuplicateFinder Function 6 times to compare the data across each sheet in my workbook. For example, if the sheets name's were A, B, C, and D. I need to run the function that compares A to B, A to C, A to D, B to C, B to D, and finally C to D. However, the data saved in the array is only available in the DuplicateFinder Function.

I was thinking maybe the solution was to have the function return the value, but I don't understand how that works. I would appreciate anyone's input.

How to get batch of array value from an array by incremental or decrements values

I have an array, It contains bunch of values in it. I would like to slice the array by increasing value of the count number or decreasing value of the count.

the count is updated by next and prev buttons. when user click on next the count increase and the user click on prev button the count decrease. using this wan to slice array values by my batch numbers.

here is my try:

var arr = [1,2,3,4,5,6,7,8,9];
var batch = 2;
var num = 2;
var total = arr.length;
var group = arr.slice(0, (batch % total));


var add = function (amount) {
     num = (num + total - 1 + amount) % total + (2)
     console.log(arr.slice((num-batch), (num % total)))
}

$('a').click(function (e) {
    var num = e.target.className == 'prev' ? -1 : 1;
    add(num);
})

console.log(group)

Live Demo

How to write json reader if its more than one array?

Below is snipets of My json reader

    @Override
    protected Void doInBackground(Void... params) {
        // Create an array
        arraylist = new ArrayList<HashMap<String, String>>();
        // Retrieve JSON Objects from the given URL address
        jsonobject = JSONfunctions
                .getJSONfromURL("http://ift.tt/1ebqb1O");

        try {


            // Locate the array name in JSON
            jsonarray = jsonobject.getJSONArray("worldpopulation");

            for  (int i = 0; i < jsonarray.length(); i++) {
                HashMap<String, String> map = new HashMap<String, String>();
                jsonobject = jsonarray.getJSONObject(i);
                // Retrive JSON Objects
                map.put("rank", jsonobject.getString("rank"));
                map.put("country", jsonobject.getString("country"));
                map.put("population", jsonobject.getString("population"));
                map.put("flag", jsonobject.getString("flag"));
                map.put("afakul", jsonobject.getString("afakul"));
                // Set the JSON Objects into the array
                arraylist.add(map);
            }
        } catch (JSONException e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

And my json file is like this

{ 
"bingung":"apa",
"worldpopulation": 

    [

         {
         "rank":6,"country":"Pakistan",
         "population":"182,912,000",
                  "afakul":"amfunah"    ,

         "flag":"http://ift.tt/1kKjxlj"
         }, 

         {
         "rank":7,"country":"Nigeria",
         "population":"170,901,000",
 "afakul":"amfunJa ajajas ausjsjsushnah"    ,
         "flag":"http://ift.tt/1gnVIIk"
         }, 



    ],

}

I am confused at the "bingung" array ..how to read that array in json reader??????

Return null if any of the integers are negative or more than 10

I am trying to trying to return null if any of the integers are negative or more than 10. When I use this code, I get null, null, null. Instead of just null once. Expected: null, instead got: [null,null,null].

What could be the reason for this?

function upArray(arr) {
    for (var i = 0, len = arr.length; i < len; i++) {
        var num = arr[i];
        if (num > 9 || num <= 0) {
            var x = null;
            return x;
        }  
    }
    {
            var toNum = parseInt(arr.join('')) + 1;
            arr = toNum.toString().split('').map(Number);
            return arr;
        }
}

http://ift.tt/1GSTyA7

Split String into Array of Words to find Longest

Hey guys I am working on a task to search any given string for the longest word. I am thinking the ideal way to do this is to split the string into an array consisting of each word then looping through that array and comparing each length to return the longest. I am stuck on just separating the string into an array of words. The questions i have seen answered similar in topic seem to use much to complicated methods for such a simple task. I am looking for help on a beginner level as this is my first time incorporating regular expressions into my code. Thank you.

function findLongestWord(str) {
     str = str.toLowerCase().split("/\w+");
     return str;
}

findLongestWord('The quick brown fox jumped over the lazy dog');

How can I compare what a user has typed in the editText with an element of an array that i've created inbuilt in my project

I have an array of strings and below the array I have a toast that randomly chooses the element from the array and displays it on screen.

In the screen when the toast is displayed the user types in what he has seen as toast into the editText.

My question: how do I compare that string in the editText to the random element chosen from the array of strings?

extract elements from array and subtract them

What I want to do is that if for example I have a list of items that I wanna sell, every item has a String name and int price, and I add them to an array(could be an arrayList I'm not sure what would be better, cause I would like it to be userinput) and say I add many elements to that array like this: [item1, 50, item2, 100, item3, 200] What I want to do is extract one of the items, item1 for example with its price: 50 and sell it for an amount equal to the price or bigger, and then put the item1 that I sold for a 100 into another array of my sold items. I wanna be able to do this with every item. I don't even wanna start coding cause I have no idea how to do it.

Using radio buttons to tally a score in a quiz

I am trying to make a simple Javascript Quiz with radio buttons. Each question and options should be stored in an array, the questions being replaced dynamically with getElementById(). I am stuck trying to assign values for the radio buttons so that I can display the score at the end.

I am new to javascript and this is the first project I'm working on.

This is what I have so far:

var questionsArray = new Array;
questionsArray[0] = ["1. Who is the president of the US?"];
questionsArray[1] = ["2. What is the capital city of France?"];
questionsArray[2] = ["3. What is your favorite food?"];
var choicesArray = new Array();
choicesArray[0] = ["Lebron James", "Barack Obama", "George Bush"];
choicesArray[1] = ["Nairobi", "London", "Paris"];
choicesArray[2] = ["Pizza", "Sushi", "Pasta"];
var i = 0;
var theScore = 0;

function btnOnclick() {
   var radElement = document.form1.options;
   var showDiv = document.getElementById("questionsDiv");
   showDiv.className = "showClass";
   document.getElementById("next").value = "Next";
   while(i < questionsArray.length && i < choicesArray.length) {
      var currQues = questionsArray[i];
      var option1 = choicesArray[i][0];
      var option2 = choicesArray[i][1];
      var option3 = choicesArray[i][2];
      i++;
      document.getElementById("question").innerHTML = currQues;
      document.getElementById("choice1").innerHTML = option1;
      document.getElementById("choice2").innerHTML = option2;
      document.getElementById("choice3").innerHTML = option3;
      return true
   }
   if(questionsArray[0] && radElement[1].checked == true) {
      theScore += 10
   } else {
      theScore += 0
   }
   if(questionsArray[1] && radElement[2].checked == true) {
      theScore += 10
   } else {
      theScore += 0
   }
   if(questionsArray[2] && radElement[1].checked == true) {
      theScore += 10
   } else {
      theScore += 0
   }
   alert(theScore)
}

function bodyOnload() {
   var hideDiv = document.getElementById("questionsDiv");
   hideDiv.className = "hideClass";
   document.getElementById("next").value = "Start Quiz"
}
.hideClass{
  display: none;
}

.showClass{
  display: block;
}
<body onload="bodyOnload()">
  <h1>QUIZ</h1>
  <div id="questionsDiv">
    <form name="form1">
      <p id="question" class="showQuestion"></p>
      <tr>
        <span id="choice1"></span>
        <td>
          <input type="radio" id="radio1" value="0" name="options" />
        </td>
        <td>
          <span id="choice2"></span>
          <input type="radio" id="radio2" value="0" name="options" />
        </td>
        <td>
          <span id="choice3"></span>
          <input type="radio" id="radio3" value="0" name="options" />
        </td>
      </tr>
      </div>
    <br />
    <br />
    <hr>
    <tr>
      <td>
        <input type="button" id="next" value="Next" name="nextButton"   onclick="btnOnclick()"/>
      </td>
    </tr>
    </form>
</body>

How to find the $k$th smallest item among the union of $C$ disjoint, sorted arrays?

There is an explanation here http://ift.tt/1Hn1TNN but I find it very unclear.

Is there a more rigorously-outlined and easily-understood algorithm for how to find the $k$th smallest item among $C$ disjoint, sorted arrays?

Sort two array of hashes by the same criteria on Ruby

I am working on Ruby with two arrays of hashes like these:

a = [{'name'=> 'Ana', 'age'=> 42 },
     {'name'=> 'Oscar', 'age'=> 22 },
     {'name'=> 'Dany', 'age'=> 12 }]

b = [{'name'=> 'Dany', 'country'=> 'Canada' },
     {'name'=> 'Oscar', 'country'=> 'Peru'},
     {'name'=> 'Ana', 'country'=>'France'}]

I am sorting them like this:

a.sort_by!{|c| c['name']}
b.sort_by!{|c| c['name']}

and it works, but since I doing the same on both arrays, I would like doing the same but in one line; I mean, sort the two arrays at once.

How can I do it?

Validation of the input

I need to validate the inputs of the first name and lastname.

I think the clone portion is ok, but I don't know how to combine the last and firstname for the input information so it is easy to validate.

 public Clone() {

    }

}
class Person implements Cloneable{
    private String firstname;
    private String lastname;

    @Override
    public Object clone() {
        Person person = new Person();
        person.setFirstname(this.firstname);
        person.setLastname(this.lastname);
        return person;
    }

    public void setFirstname(String firstname){
            this.firstname = firstname;
    } 

    public void setLastname(String lastname){
        this.lastname=lastname;
    }
    public String getFirstname(){
        return firstname;
    }
    public String getLastname(){
        return lastname;
    }

    public static void Person(){

     String Fname ="";
       String Lname=""; 

      Scanner input2 = new Scanner(System.in);
      Scanner input3 = new Scanner(System.in);
       Person person = new Person();
       int i = 2;
       char c;
        /* This will take the values of first name
        and last name.
         */

       if (input2.nextLine().length()<=6) {  
      System.out.println("Enter your First Name:");
        Fname = input2.nextLine();}

     else  if (input2.nextLine().length()>6){
           throw new InputMismatchException();}

        System.out.println("Enter your Last Name");
        Lname =input3.nextLine();





        person.setFirstname(Fname);
        person.setLastname(Lname);

        /* This method will produce firs and last name
        also will produce the introduction.
        */
      Person cloned = (Person)person.clone();


      //** This method will print welcome to the world of Java.
       Introduction();

      System.out.println(cloned.getFirstname()+ " " + cloned.getLastname());

     System.out.println("*******************\n\n");


}

Get Last Element of a/an List/Array

Sometimes I need to get the last element in an Array if I split something. Although I didn't found any way to do it better than this way:

_Path.Split('\\')[_Path.Split('\\').Length - 1]

Is there maybe an easier way to do this than this one? In this case it's pretty nice to understand, but if it gets longer, it isn't anymore.

formatting an array using php

I have the following array which have duplicate data:

Array
(
    [0] => Array
        (
            [orders] => Array
                (
                    [id] => 9
                    [name] => Abdus Sattar Bhuiyan
                    [email] => sattar.kuet@gmail.com
                    [mobile] => 01673050495
                    [alt_mobile] => 01818953250
                    [city_id] => 2
                    [location_id] => 5
                    [status] => No contact
                    [chashed] => NO
                    [created] => 2015-06-27 12:49:34
                    [modified] => 2015-06-27 12:49:34
                    [comment] => 
                )

            [order_products] => Array
                (
                    [id] => 2
                    [order_id] => 9
                    [product_id] => 1
                    [pieces] => 1
                )

            [products] => Array
                (
                    [id] => 1
                    [category_id] => 1
                    [name] => নভোযানের নাম সি প্রোগ্রামিং
                    [writer] => Engr. Abdus Sattar Bhuiyan
                    [created] => 2015-06-24 16:17:45
                )

            [psettings] => Array
                (
                    [id] => 1
                    [category_id] => 1
                    [product_id] => 1
                    [img] => 1.jpg
                    [desc] => description
                    [created] => 2015-06-28 00:28:26
                    [bppp] => 44000
                    [sppp] => 45000
                    [discount] => 25
                    [service_charge] => 30
                )

        )

    [1] => Array
        (
            [orders] => Array
                (
                    [id] => 9
                    [name] => Abdus Sattar Bhuiyan
                    [email] => sattar.kuet@gmail.com
                    [mobile] => 01673050495
                    [alt_mobile] => 01818953250
                    [city_id] => 2
                    [location_id] => 5
                    [status] => No contact
                    [chashed] => NO
                    [created] => 2015-06-27 12:49:34
                    [modified] => 2015-06-27 12:49:34
                    [comment] => 
                )

            [order_products] => Array
                (
                    [id] => 3
                    [order_id] => 9
                    [product_id] => 2
                    [pieces] => 1
                )

            [products] => Array
                (
                    [id] => 2
                    [category_id] => 1
                    [name] => Resonance of creativity with C++
                    [writer] => Engr. Abdus Sattar Bhuiyan
                    [created] => 2015-06-26 07:32:52
                )

            [psettings] => Array
                (
                    [id] => 2
                    [category_id] => 1
                    [product_id] => 2
                    [img] => 2.jpg
                    [desc] => 
                    [created] => 2015-06-26 07:33:41
                    [bppp] => 150
                    [sppp] => 250
                    [discount] => 20
                    [service_charge] => 30
                )

        )

    [2] => Array
        (
            [orders] => Array
                (
                    [id] => 9
                    [name] => Abdus Sattar Bhuiyan
                    [email] => sattar.kuet@gmail.com
                    [mobile] => 01673050495
                    [alt_mobile] => 01818953250
                    [city_id] => 2
                    [location_id] => 5
                    [status] => No contact
                    [chashed] => NO
                    [created] => 2015-06-27 12:49:34
                    [modified] => 2015-06-27 12:49:34
                    [comment] => 
                )

            [order_products] => Array
                (
                    [id] => 4
                    [order_id] => 9
                    [product_id] => 3
                    [pieces] => 1
                )

            [products] => Array
                (
                    [id] => 3
                    [category_id] => 1
                    [name] => programming by story C
                    [writer] => Hasibul Hasan Shanto
                    [created] => 2015-06-26 07:35:57
                )

            [psettings] => Array
                (
                    [id] => 3
                    [category_id] => 1
                    [product_id] => 3
                    [img] => 3.jpg
                    [desc] => 
                    [created] => 2015-06-26 07:36:26
                    [bppp] => 150
                    [sppp] => 250
                    [discount] => 10
                    [service_charge] => 30
                )

        )

)

I want to format this array and produce the following array:

Array
(
    [0] => Array
        (
            [orders] => Array
                (
                    [id] => 9
                    [name] => Abdus Sattar Bhuiyan
                    [email] => sattar.kuet@gmail.com
                    [mobile] => 01673050495
                    [alt_mobile] => 01818953250
                    [city_id] => 2
                    [location_id] => 5
                    [status] => No contact
                    [chashed] => NO
                    [created] => 2015-06-27 12:49:34
                    [modified] => 2015-06-27 12:49:34
                    [comment] => 
                )
             [order_products] => Array
                            (
                                  [0] => Array(
                                           [id] => 2
                                           [order_id] => 9
                                           [product_id] => 1
                                           [pieces] => 1
                                        )
                                   [1] => Array(
                                           [id] => 3
                                           [order_id] => 9
                                           [product_id] => 2
                                           [pieces] => 1
                                        )   
                                     [2] => Array(
                                          [id] => 4
                                          [order_id] => 9
                                          [product_id] => 3
                                          [pieces] => 1
                                        ) 

                            )

                    [products] => Array
                    (
                          [0] => Array(
                                    [id] => 1
                                    [category_id] => 1
                                    [name] => C programming
                                    [writer] => Engr. Abdus Sattar Bhuiyan
                                    [created] => 2015-06-24 16:17:45
                                )
                           [1] => Array(
                                    [id] => 2
                                    [category_id] => 1
                                    [name] => Resonance of creativity with C++
                                    [writer] => Engr. Abdus Sattar Bhuiyan
                                    [created] => 2015-06-26 07:32:52
                                )   
                             [2] => Array(
                                     [id] => 3
                                    [category_id] => 1
                                    [name] => programming by story C
                                    [writer] => Hasibul Hasan Shanto
                                    [created] => 2015-06-26 07:35:57
                                ) 

                    )     

                    [psettings] => Array
                    (
                          [0] => Array(
                                    [id] => 1
                                    [category_id] => 1
                                    [product_id] => 1
                                    [img] => 1.jpg
                                    [desc] => description
                                    [created] => 2015-06-28 00:28:26
                                    [bppp] => 44000
                                    [sppp] => 45000
                                    [discount] => 25
                                    [service_charge] => 30
                                )
                           [1] => Array(
                                    [id] => 2
                                    [category_id] => 1
                                    [product_id] => 2
                                    [img] => 2.jpg
                                    [desc] => 
                                    [created] => 2015-06-26 07:33:41
                                    [bppp] => 150
                                    [sppp] => 250
                                    [discount] => 20
                                    [service_charge] => 30
                                )   
                             [2] => Array(
                                    [id] => 3
                                    [category_id] => 1
                                    [product_id] => 3
                                    [img] => 3.jpg
                                    [desc] => 
                                    [created] => 2015-06-26 07:36:26
                                    [bppp] => 150
                                    [sppp] => 250
                                    [discount] => 10
                                    [service_charge] => 30
                                ) 

                    ) 
            ) 
    )       

How can I do this. I reformat simple array but this does not make sense to me to format. It makes me cry. Please help me. If any helper function is suggested it will be really a gift. Thanks in advance.

how to get an integer from a char array

I have a char array that has '4''5'. But I want to convert those characters into actual integers so I subtract '0' from each index of the char array and store it into the same array. If I want to set an int called value to the 45 (the stuff inside the char array) How would I do it?

Why isn't Pinterest button adding an image path when Pinterest Pin It button is selected

I added a Pinterest button to my website and I'm not quite sure how to make the Pinterest button grab the img URL from my mysqli_fetch_array code. As of now when I click the button and try to pick a board to pin it to, I get this error:

Oops! You need to upload an image or provide the 'image_url' parameter

On top of that I have this in a thumbnail slider gallery with four different pictures. IS this why it is giving me this error? I would ideally like whichever current picture in the slider they are on when the Pinterest button is clicked to be the picture that is carried forward. If it helps to see this, my site is buyfarbest.com . Do I need to do anything different with the Pinterest HTML code that was provided from the site to grab the img?

<div class="pinItButton"><a href="//www.pinterest.com/pin/create/button/" data-pin-do="buttonBookmark" data-pin-height="28" target="_blank"><img src="//assets.pinterest.com/images/pidgets/pinit_fg_en_rect_gray_28.png" /></a>

My code from my page:

<div class="viewproductpiccontainer">
<div class="slideshow">
    <div class="pinItButton"><a href="//www.pinterest.com/pin/create/button/" data-pin-do="buttonBookmark" data-pin-height="28" target="_blank"><img src="//assets.pinterest.com/images/pidgets/pinit_fg_en_rect_gray_28.png" /></a>
    </div>
    <ul class='big'>
        <li>
            <?php $result=m ysqli_query($con, "SELECT * FROM products where product_id =".$_GET[ 'view_product']); if($row= mysqli_fetch_array($result)) { $products[$row[ 'product_id']]=$ row; echo "<img class='sizedimg' src='productpics/".$row[ 'img'] . "' alt='Product Pic'>"; } ?>
        </li>
    </ul>
    <ul class='controls'>
        <li class='prev'>&lt;</li>
        <li class='next'>&gt;</li>
    </ul>
    <ul class='thumb' id="bxslider-horizontal">
        <div class="bxslider">
            <div class="slide">
                <li>
                    <?php $result= mysqli_query($con, "SELECT * FROM products where product_id =".$_GET[ 'view_product']); if($row=m ysqli_fetch_array($result)) { $products[$row[ 'product_id']]=$ row; echo "<img class='sizedimg' src='productpics/".$row[ 'img'] . "' alt='Product Pic'>"; } ?>
                </li>
            </div>
        </div>

HTML source code:

<div class="viewproductpiccontainer">
<div class="slideshow">
    <div class="pinItButton"><a href="//www.pinterest.com/pin/create/button/" data-pin-do="buttonBookmark" data-pin-height="28" target="_blank"><img src="//assets.pinterest.com/images/pidgets/pinit_fg_en_rect_gray_28.png" /></a>
    </div>
    <ul class='big'>
        <li>
            <img class='sizedimg' src='productpics/blueCollar.jpg' alt='Product Pic'>
        </li>
        <li>
            <img class='sizedimg' src='productpics/blueCollar2.jpg' alt='Product Pic'>
        </li>
        <li>
            <img class='sizedimg' src='productpics/allCollars.jpg' alt='Product Pic'>
        </li>
        <li>
            <img class='sizedimg' src='productpics/allCollars2.jpg' alt='Product Pic'>
        </li>
        <!--<li>
                                <img src="http://ift.tt/1eQqss7" />
                            </li>
                            <li>
                                <img src="http://ift.tt/1eQqvnA" />
                            </li>-->
    </ul>
    <ul class='controls'>
        <li class='prev'>&lt;</li>
        <li class='next'>&gt;</li>
    </ul>
    <ul class='thumb' id="bxslider-horizontal">
        <div class="bxslider">
            <div class="slide">
                <li>
                    <img class='sizedimg' src='productpics/blueCollar.jpg' alt='Product Pic'>
                </li>
            </div>
            <div class="slide">
                <li>
                    <img class='sizedimg' src='productpics/blueCollar2.jpg' alt='Product Pic'>
                </li>
            </div>
            <div class="slide">
                <li>
                    <img class='sizedimg' src='productpics/allCollars.jpg' alt='Product Pic'>
                </li>
            </div>
            <div class="slide">
                <li>
                    <img class='sizedimg' src='productpics/allCollars2.jpg' alt='Product Pic'>
                </li>
            </div>
            <!--<div class="slide"><li>
                                    <img src="http://ift.tt/1eQqss7" />
                                </li></div>
                                <div class="slide"><li>
                                    <img src="http://ift.tt/1eQqvnA" />
                                </li></div>--></div>
    </ul>

Is there a way to make what I have work?

Sorting infinite depth array - php

I have the following array: (ordered by parent_id)

array(9) {
  [1]=>
  array(3) {
    ["name"]=>
    string(6) "Tennis"
    ["parent_id"]=>
    NULL
    ["depth"]=>
    int(0)
  }
  [7]=>
  array(3) {
    ["name"]=>
    string(11) "TOP LEVEL 2"
    ["parent_id"]=>
    NULL
    ["depth"]=>
    int(0)
  }
  [8]=>
  array(3) {
    ["name"]=>
    string(11) "TOP LEVEL 3"
    ["parent_id"]=>
    NULL
    ["depth"]=>
    int(0)
  }
  [2]=>
  array(3) {
    ["name"]=>
    string(5) "Shoes"
    ["parent_id"]=>
    string(1) "1"
    ["depth"]=>
    int(1)
  }
  [3]=>
  array(3) {
    ["name"]=>
    string(5) "Women"
    ["parent_id"]=>
    string(1) "2"
    ["depth"]=>
    int(2)
  }
  [4]=>
  array(3) {
    ["name"]=>
    string(4) "Mens"
    ["parent_id"]=>
    string(1) "2"
    ["depth"]=>
    int(2)
  }
  [5]=>
  array(3) {
    ["name"]=>
    string(12) "Mens Running"
    ["parent_id"]=>
    string(1) "4"
    ["depth"]=>
    int(3)
  }
  [6]=>
  array(3) {
    ["name"]=>
    string(11) "Mens Tennis"
    ["parent_id"]=>
    string(1) "4"
    ["depth"]=>
    int(3)
  }
  [9]=>
  array(3) {
    ["name"]=>
    string(9) "2nd level"
    ["parent_id"]=>
    string(1) "8"
    ["depth"]=>
    int(1)
  }
}

I want to sort it in a way that it can be used in a drop down menu. The format for a drop down menu is:

$categories[$CATEGORY_ID] = str_repeat('&nbsp;&nbsp;', $value['depth']).$value['name'];

The above array up top is sorted by parent_id where top levels have a parent_id of NULL.

I need to sort it in such a way that the array is in order. For example:

[1] => 'Tennis';
[2] => '&nbsp;&nbspShoes'
[3] => '&nbsp;&nbsp;&nbsp;&nbsp; Womens'
[4] => '&nbsp;&nbsp;&nbsp;&nbsp; Men'
[5] => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Mens Running
[6] => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Mens Tennis
[7] => 'TOP LEVEL 2'
[8] => 'TOP LEVEL 3'
[9] => '&nbsp;&nbsp;2nd level'

How can i make a function which has a multidimensional array input, transforms it, and ouputs the new multidimensional array

Input & Output

Back story

(my english isnt the best)

Hey, im trying to build a game that will teach children about words and letters. Im making it with HTML/CSS & JS(little JQuery) and a little PHP. I have build a tree that holds leaves with letters inside it. I want to build lots of levels, but i would have to type a very big array myself(and i know it should be possible to do it automatic).

I would really appreciate some help!


Problem

I have a multidimensional array which looks like this:

var words = [
    [
        ['SNEL'],
        ['WORD'],
        ['TIJD'],
        ['BORD'],
        [etc]
    ],
    [
        [BORDE]
        [etc]
    ],
    [
        etc
    ],
    [
        ['BEWUSTER']
    ]
];

Im trying to build a function that will output this into:

var modifiedWords1 = [
    [
        ['img/Letters_normal/S.png', 'img/Letters_normal/N.png', 'img/Letters_normal/E.png', 'img/Letters_normal/L.png'],
        ['img/Letters_normal/W.png', 'img/Letters_normal/O.png', 'img/Letters_normal/R.png', 'img/Letters_normal/D.png'],
        [img/Letters_normal/etc]
    ],
    [
        ['img/Letters_normal/B.png', 'img/Letters_normal/O.png', 'img/Letters_normal/R.png', 'img/Letters_normal/D.png', 'img/Letters_normal/E.png']
        [etc]
    ],
    [
        etc
    ],
    [
        ['img/Letters_normal/B.png', 'img/Letters_normal/E.png', 'img/Letters_normal/W.png', 'img/Letters_normal/U.png', 'img/Letters_normal/S.png', 'img/Letters_normal/T.png', 'img/Letters_normal/E.png', 'img/Letters_normal/R.png']
    ]
];

And this:

var Modifiedwords2 = [
    [
        ['S.png', 'N.png', 'E.png', 'L.png'],
        ['W.png', 'O.png', 'R.png', 'D.png'],
        ['T.png', 'I.png', 'J.png', 'D.png'],
        ['B.png', 'O.png', 'R.png', 'D.png'],
        [etc]
    ],
    [
        ['B.png', 'O.png', 'R.png', 'D.png', 'E.png']
        [etc]
    ],
    [
        etc
    ],
    [
        ['B.png', 'E.png', 'W.png', 'U.png', 'S.png', 'T.png', 'E.png', 'R.png']
    ]
];


Sorry for my bad english, but thanks in advance! Feel free to ask anything!

How to detect the next n words in a string after a word (that can occur multiple times) and separate them in an array

I have a string s in which I have to detect the word "car" and print the next 2 words. However, currently when I print words[i1], it gives me "is awesome. but it should give me "is",then "cool", then "is", then "awesome" in different lines(n=2 in the above case).

Can anybody tell me what is wrong with this code?

                String s="car is cool car is awesome.";
                int index = contents.indexOf(s);
                while(index >= 0) {
                   String[] words = new String[n];
                   for (int i3=0;i3<n;i3++){
                       words[i3]="";
                   }
                   int i1=0, i2=index;
                   while(true){
                       if(i1==n) break;
                       if(i2>=contents.length()) break;
                       while(true) {
                           if(i2>=contents.length()) break;
                           if((contents.charAt(i2)+"")==" ") break;
                           words[i1]+=(contents.charAt(i2)+"");
                           i2++;
                       }
                       System.out.println(words[i1]);
                       i1++;
                   }
                    index = contents.indexOf(s, index+1);
                }

Populate a JCombo Box using Array from Another Class in Java

First of all this is the code that I currently have:

 //adds each organism to the JComboBox with their corresponding organism id for later use 
    //Currently if user doesn't click on 1st option an error occurs.. change this error - perhaps display error message
    Organism organisms[] = new Organism[224];
    organisms[0] = new Organism("Please Select an Organism...", "");
    organisms[1] = new Organism("Acacia auriculiformis", ">aau");
    organisms[2] = new Organism("Acacia mangium", ">amg");
    organisms[3] = new Organism("Acyrthosiphon pisum", ">api");
    organisms[4] = new Organism("Aedes aegypti", ">aae");
    organisms[5] = new Organism("Aegilops tauschii", ">ata");
    organisms[6] = new Organism("Amborella trichopoda", ">atr");
    organisms[7] = new Organism("Amphimedon queenslandica", ">aqu");
    organisms[8] = new Organism("Anolis carolinensis", ">aca");
    organisms[9] = new Organism("Anopheles gambiae", ">aga");
    organisms[10] = new Organism("Apis mellifera", ">ame");

....... etc etc

    selectOrganism = new JComboBox(organisms);
    selectOrganism.setBounds(10, 10, 330, 25);
    add(selectOrganism);
    selectOrganism.addItemListener(new ItemListener() {

        @Override
        public void itemStateChanged(ItemEvent e) {
            Organism o = (Organism) e.getItem();
            organismId = o.getId();
            //System.out.println(organismId);
            //label.setText("You selected customer id: " + o.getId());

        }

    });

Then in another class I have this:

public class Organism{
    private String name;
    public String id;

    public Organism(String name, String id){
        this.name = name;
        this.id = id;
    }

    public String toString(){
        return getName();
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }
}

This code displays the organisms (i.e. Arabidopsis thaliana) in the JCombo box and when the organism is selected from the JCombo box the id (i.e. >ath) is selected for use elsewhere. However as you can probably see this code is extremely messy as most of it is hard coded.

Therefore in a new class I have manipulated a text file in order to retrieve the required information into an array:

public static void main(String[] args) throws IOException{
    BufferedReader bReader = new BufferedReader(new FileReader("organisms.txt"));

    bReader.readLine(); // this will read the first line


    String line = null;
    while ((line = bReader.readLine()) != null){

        //removes the first space 
        String test = line.replaceFirst("\\s+", "");


        //used regex lookaround to split wherever there are 3 capital letters present, or where any of the tree are present

        String[] peopleInfo = test.split("(\\p{Upper}(?=\\p{Upper})\\p{Upper}\\p{Upper})|(?=Chromalveolata)|(?=Metazoa)|(?=Mycetozoa)|(?=Viridiplantae)|(?=Viruses)|\\;");

        //creates arrays for id, organism and tree
        String id = ">" + peopleInfo[0];
        String organism = peopleInfo[1];
        String tree = peopleInfo[2].replaceAll(";", "").replaceAll("\\d+.*", "");
       System.out.println(tree);
}
    }

Therefore my question is how do I go about populating my JCombo box with organism array and then associating each of the ids from the id array with the appropriate organism from my organism array.

I think there's probably a relatively simple solution however I'm new to Java so I'm having a little trouble.

Sorry for the long post but thought that if you could see the code it may make it easier for you to help.

Any help would be greatly appreciated.

Thanks :)

C# Nest: How to index array of geo-poinst

Hello I am new to elastic and nest. I used a example of how to index geo point location that worked fine as I can see the geo-points in kibana map visualize.

This is my data structure:

public class LocationArray
{
    public string ArrayNameArtical { get; set; }
    [ElasticProperty(Type = FieldType.GeoPoint)]
    public IEnumerable<Location> Locations { get; set; }
}
public class Location
{
    public string Name { get; set; }

    [ElasticProperty(Type = FieldType.GeoPoint)]
    public Coordinate Coordinate { get; set; }
}


public class Coordinate
{
    public double Lat { get; set; }
    public double Lon { get; set; }
}

And my code to index as follow:

var response = client.CreateIndex(indexName, s => s
      .AddMapping<Location>(f => f
        .MapFromAttributes() 
        .Properties(p => p
          .GeoPoint(g => g.Name(n => n.Coordinate).IndexGeoHash().IndexLatLon())
        )
      )
    );
    client.IndexMany(new[]{
        new Location
        {
            Name = "Amsterdam",
            Coordinate = new Coordinate { Lat =  52.3740300, Lon = 4.8896900}
        },
        new Location
        {
            Name = "Rotterdam",
            Coordinate = new Coordinate { Lat = 51.9225000, Lon = 4.4791700}
        },
        new Location
        {
            Name = "Utrecht",
            Coordinate = new Coordinate { Lat =  52.0908300,  Lon = 5.1222200}
        },new Location
        {
            Name = "Den Haag",
            Coordinate = new Coordinate { Lat =  52.3740300, Lon = 4.8896900}
        }
    });

Now i want to index the LocationArray class, it seems that in need to change my mapping but i colund't figure out how to do it..anyway i can see the array data in kibana but cant view it over map. Is there any problem with indexing array of geo-point?

Link Specific Redirection Script

I have a below script, is it possible to add link specific redirect like -

  • http://ift.tt/1GDMx2N : http://ift.tt/1Ho2r81
  • www.Link2.com/z/x : http://ift.tt/1GDMx2P

I tried adding variables but unable to add subfolders in the link url to the redirect.

<a href="http://link1.com">link 1</a>
<a href="http://ift.tt/1TV4y6K">link 2</a>
<a href="http://wikipedia.org">not redirected</a>

<script>
var aTags = document.getElementsByTagName("a");
var redirects = {
    "http://link1.com": "http://google.com",
    "link2.com": "http://google.com"
};

for(var i = 0;i < aTags.length; i++) {
    var url = aTags[i].getAttribute("href");

    for (var redirect in redirects) {
        var pattern = new RegExp(redirect);

        if (pattern.test(url)) {
            aTags[i].setAttribute("href", redirects[redirect]);
        }
    }
}
</script>

what exactly is fiber safe optimizations in VC++?

I was reading about Fiber Safe optimizations on MSDN. It says that

Data declared with __declspec(thread) is referenced through a thread-local storage (TLS) array. The TLS array is an array of addresses that the system maintains for each thread. Each address in this array gives the location of thread-local storage data. A fiber is a lightweight object that consists of a stack and a register context and can be scheduled on various threads. A fiber can run on any thread. Because a fiber may get swapped out and restarted later on a different thread, the address of the TLS array must not be cached or optimized as a common sub expression across a function call

What is this fiber safe optimizations? What is the actual purpose of using it? Why they are saying that "Because a fiber may get swapped out and restarted later on a different thread, the address of the TLS array must not be cached or optimized as a common sub expression across a function call." ? Why & when should it be prevented?

How to implement a loop in php [on hold]

Hi I'm totally new here and with and would glad if someone could help as I'm stuck with how I can create a loop with some php code.

$TotalUniques = $this->TotalUniquesHits($Counts[$xx]['ID']);

The value I'm after is [$xx] which represents a position in the array. How to change it so that I get $TotalUniques looping through all the values of $xx?

Correctly iterating through array and open pages with CasperJS

I'm working on a little project with CasperJS. The main idea is to get a links to pictures with title and description from subpages of some website. I already tried many different ways to achieve what I want, but I'm stuck with some piece of code and I don't want to continue with uncorrectly way of coding for "probably very easy thing". I just started using CasperJS, so I think that the solution to my problem must be easy.

This is current sequence of events in my code:

casper.start(url);
casper.thenEvaluate(openPicturesSubpage);
casper.then(getPicturesInfo);
casper.then(getPictureFullRes);
casper.run();

First two commands are working as expected, so I will skip to the structure of third function. The code of function (I'm using jQuery, because I need to get some specific stuff in other function) getPicturesInfo (variable pictures is global):

getPicturesInfo = function() {
  pictures = this.evaluate(function() {
    var array = [];
    $('.picture-box a').each(function() {
      arr.push({
        'name': $(this).text(),
        'subpage': $(this).attr('href')
      });
    });
    return array;
  });
}

Basically I have everything I need to continue "browsing" for actual full resolution links of pictures. So the next step is to append new data to already created array. This is also the main problem I want to solve. How to correctly iterate through array of previously saved data? So there's the code of the last function getPictureFullRes:

getPictureFullRes = function() {
  for (var i = 0; i < pictures.length; i++) {
    this.thenOpen(pictures[i]['subpage'], getFullResLink);
  }
}

The problem there is that I can't pass counter variable i to my nect function getFullResLink. I also tried to add another argument to thisOpen method and argument to getFullResLink function, but it doesn't work, because method don't have that functionallity.

How could I access appropriate index of array inside getFullResLink? Thanks for any help!

C# Concatenate strings or array of chars

I'm facing a problem while developing an application. Basically, I have a fixed string, let's say "IHaveADream"

I now want to user to insert another string, for my purpose of a fixed length, and then concatenate every character of the fixed string with every character of the string inserted by the user. e.g. The user inserts "ByeBye" then the output would be: "IBHyaevBeyAeDream".

How to accomplish this?

I have tried with String.Concat and String.Join, inside a for statement, with no luck.

SystemVerilog: Creating an array of classes with different parameters

this topic has a similar question like mine. But they don't figured out any solution.

I have defined a class with subclasses. The subclass contains a vector, which width should be different in the array.

array[0] class with subclasses and vector width 32

array[1] class with subclasses and vector width 64

array[2] class with subclasses and vector width 128

and so on.

The definition of the class is the same, only the size of the vector differs.

Example

Class-definition:

package classes;

    class subsubclass#(int width);
          logic  [width:0]                  data3;      
    endclass

    class subclass#(int width); 
          subsubclass #(width)              data2 = new;
          logic                             auto2;
    endclass 

    class my_class#(int width);
          subclass #(width)                 data1 = new;
          logic                             auto1;      
    endclass

endpackage

Testbench:

my_class#(32) my_array [0:5];

initial begin
        int x;
        for (int x=0; x<6; x++) begin
           my_array[x] = new;       
        end
end

In this situation i am creating an array of classes with same width. How can i change this? I tried various things, but i can't figure out if there is a solution.

for e.g.   
    my_array[0].subclass.subsubclass.data3 
    and 
    my_array[1].subclass.subsubclass.data3

should differ. But how? And yes in need it with an array because of using it later in many for loops.

update#1 @dave_59

simplified Class-definition:

virtual class base;
    pure virtual function logic [511:0] get_data();
    pure virtual function int getwidth();
endclass

 class my_class#(int width) extends base;
    logic                                   auto;
    logic  [width:0]                        data; 
    virtual function logic [511:0] get_data();
              return data;
    endfunction
    virtual function int getwidth(); 
             return width; 
    endfunction
endclass

base  my_array [0:4];

Testbench:

    initial begin
           my_array[0] = my_class#(16)::new;     
           my_array[1] = my_class#(8)::new;     
           my_array[2] = my_class#(64)::new;     
           my_array[3] = my_class#(128)::new;     
           my_array[4] = my_class#(256)::new;
    end

I tried different definitions: test0, test1 and test2. I got an error that "my_array" is an unkown type. Any idea how to fix it? :)

my_array[0] test0; // or
my_array    test1; // or
my_array[0].get_data() test2;

update#2 @dave_59

    package classes;

    class subsubclass#(int width);
       logic  [width-1:0]                  data3 = '1;      
    endclass

    class subclass#(int width); 
       subsubclass #(width)              data2 = new;
       logic                             auto2;
    endclass 

       virtual               class base;
          pure virtual function logic [511:0] get_data();
       pure virtual function int get_width();
    endclass

    class my_class#(int width) extends base;
       logic                 auto;
       subclass#(width)          data1 = new;

       virtual               function logic [511:0] get_data();
          return data1.data2.data3;
       endfunction
       virtual               function int get_width(); 
          return width; 
       endfunction
    endclass

    endpackage : classes

Testbench

       module top;

       import classes::*;
       base  my_array [0:4];

        initial begin
               my_array[0] = my_class#(16)::new;     
               my_array[1] = my_class#(8)::new;     
               my_array[2] = my_class#(64)::new;     
               my_array[3] = my_class#(128)::new;     
               my_array[4] = my_class#(256)::new;
           foreach(my_array[i]) $display("i: %0d, width:%0d, data3:%0h",
                         i, my_array[i].get_width(), my_array[i].get_data());
        end

my_array[0].data1.auto2 = 1;

    endmodule : top

How can i set for example a "1" for auto? I tried

my_array[0].data1.auto2 = 1;

I got this error

near "[": syntax error, unexpected '[', expecting IDENTIFIER or TYPE_IDENTIFIER

mysqli_real_escape_string foreach function db_array_update

Someone wrote a PHP program many times ago for me, and now I got this error when I run the code :

mysqli_real_escape_string() expects parameter 2 to be string, array given in....

I cannot fix this here is the code :

function db_array_update($table, $a, $where) 
{    
    $q = "update $table set ";
    $b = NULL;  

    foreach($a as $key => $value)   
    {   
        if (is_int($key))
            continue;   

        $con = mysqli_connect("localhost", MYSQLUSER , MYSQLPASS, MYSQLDB);
        $b[] = "$key='".mysqli_real_escape_string($con, $value)."'";        
    }

    $q .= implode(",", $b);
    $q .= " where ".$where;

    db_query($q);

}

and I use it like this :

db_array_update("all_data",array('last_fetched' =>date("Y/m/d H:i:s"),'name'=>$name, 'creation'=>$creat, 'expiration' =>$expire,"id=".$res['id']);

Can someone help me how should I fix this ? Tried many things but not work...

Deep copies of 2d object array

how can I make on a button press a new deep copy of a 2 dimensional array?

Basically I created a game field with buttons. The game is called sokoban and it's a puzzle. The player is moving from one button to the other with arrow keys on a fixed map (8x8 buttons). I want to implement an undo function. So I thought that I just create a deep copy of the JButton array before each move and save it into a stack. So when I press the undo button it calls the pop function of my stack. The problem is that I need to declare and initialize another JButton[][] where I can save the game field to before each move. Since I want infinite possible moves and also undos it seems impossible to me. I can't declare and initalize infite diffrent JButton[][] arrays. Any idea on how I can solve that?

That's how I copy a 2d object array:

    JButton[][] tempArray = new JButton[jbArray.length][jbArray[0].length];

    for (int i = 0; i < getJbArray().length; i++) {
        for (int j=0;j<getJbArray()[0].length;j++) {
            tempArray[i][j]=jbArray[i][j];
        }
    } 

    movesStack.push(tempArray);

Rotating array anti-clockwise, unexpected debug output in one step

I'm using the simplest approach to rotate array anti-clockwise i.e by storing elements from index=0 to index=number of rotating positions required, in a temporary array and finally inserting these elements int he end of another array. Here's the code:

#include<stdio.h>
#include<stdlib.h>
int main()
{
    int *a, *temp, i, j=0, n,np,*b;
    printf("Enter no. of elements in arr:\n");
    scanf("%d",&n);
    a=(int*) malloc(n*sizeof(int));//Primary array
    b=(int*) malloc(n*sizeof(int));//Final array that would be printed in the end
    printf("Enter elements:\n");
    for(i=0;i<n;i++)
        scanf("%d",&a[i]);
    printf("Enter positions to be rotated anti-clockwise:\n");
    scanf("%d",&np);
    temp=(int*) malloc(np*sizeof(int));//storing elements left of index=0
    for(i=0;i<np;i++,j++)
    {
        //printf("hi\n");
        temp[j]=a[i];
        printf("temp[%d]=%d\n",j,temp[j]);
    }
    j=0;
    printf("After rotating:\n");
    for(i=n-1;i>=0;i--)
    {
        printf("i=%d ",i);
        b[i-np]=a[i];
        printf("b[%d]=%d\n",i-np,b[i]); /*Here is 1 unexpected thing happening, the program is not picking up correct value of array a at index i.*/
    }
    for(i=np-1;i<n;i++,j++)
        b[i]=temp[j];//storing temp elements in final array

    printf("Finally matrix is\n");

    for(i=0;i<n;i++)
        printf("%d\n",b[i]);

    getch();
    return 0;
}