Search Results

Search found 1486 results on 60 pages for 'counter'.

Page 12/60 | < Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >

  • PHP - uninitialized array offset

    - by kimmothy16
    Hey everyone, I am using PHP to create a form with an array of fields. Basically you can add an unlimited number of 'people' to the form and each person has a first name, last name, and phone number. The form requires that you add a phone number for the first person only. If you leave the phone number field blank on any others, the handler file is supposed to be programmed to use the phone number from the first person. So, my fields are: person[] - a hidden field with a value that is this person's primary key. fname[] - an input field lname[] - an input field phone[] - an input field my form handler looks like this: $people = $_POST['person'] $counter = 0; foreach($people as $person): if(phone[$counter] == '') { // use $phone[0]'s phone number } else { // use $phone[$counter] number } $counter = $counter + 1; endforeach; PHP doesn't like this though, it is throwing me an Notice: Uninitialized string offset error. I debugged it by running the is_array function on people, fname, lname, and phone and it returns true to being an array. I can also manually echo out $phone[2], etc. and get the correct value. I've also ran is_int on the $counter variable and it returned true, so I'm unsure why this isn't working as intended? Any help would be great!

    Read the article

  • Replace string with incremented value

    - by Andrei
    Hello, I'm trying to write a CSS parser to automatically dispatch URLs in background images to different subdomains in order to parallelize downloads. Basically, I want to replace things like url(/assets/some-background-image.png) with url(http://assets[increment].domain.com/assets/some-background-image.png) I'm using this inside a class that I eventually want to evolve into doing various CSS parsing tasks. Here are the relevant parts of the class : private function parallelizeDownloads(){ static $counter = 1; $newURL = "url(http://assets".$counter.".domain.com"; The counter needs to be reset when it reaches 4 in order to limit to 4 subdomains. if ($counter == 4) { $counter = 1; } $counter ++; return $newURL; } public function replaceURLs() { This is mostly nonsense, but I know the code I'm looking for looks somewhat like this. Note : $this-css contains the CSS string. preg_match("/url/i",$this->css,$match); foreach($match as $URL) { $newURL = self::parallelizeDownloads(); $this->css = str_replace($match, $newURL,$this->css); } }

    Read the article

  • [php] Firefox refreshes page 1, even after redirection to page 2

    - by Znarkus
    Hi! This is a quite weird and annoying problem, which is reproduced with the script below. Say we have two pages: script.php and script.php?second. Page 1 creates some database entries and redirects to page 2. On page 2, the user is presented with an editor for said entries. If page 1 for some reason crashes on the first try, and prints some error message, a strange thing will happend. If we refresh page 1 (and this time it redirects fine), every consecutive refresh (of page 2) will actually refresh page 1 and again redirect to page 2. In the above example this would create new database entries for every refresh, which is the problem I want to circumvent by redirecting to page 2. <?php header('Content-type: text/plain'); session_start(); if (!isset($_GET['second'])) { $_SESSION['counter'] = isset($_SESSION['counter']) ? $_SESSION['counter'] + 1 : 1; /*$_SESSION['counter'] = 0; exit('asd');*/ header("Location: {$_SERVER['PHP_SELF']}?second", true, 303); exit; } echo "Counter: {$_SESSION['counter']}"; To try the above complete script, first run it with the commented code intact, then by enabling the commented code. I've tried 301, 302 and 303 redirections. Does someone know why this is happening?

    Read the article

  • Trying to write priority queue in Java but getting "Exception in thread "main" java.lang.ClassCastEx

    - by Dan
    For my data structure class, I am trying to write a program that simulates a car wash and I want to give fancy cars a higher priority than regular ones using a priority queue. The problem I am having has something to do with Java not being able to type cast "Object" as an "ArrayQueue" (a simple FIFO implementation). What am I doing wrong and how can I fix it? public class PriorityQueue<E> { private ArrayQueue<E>[] queues; private int highest=0; private int manyItems=0; public PriorityQueue(int h) { highest=h; queues = (ArrayQueue[]) new Object[highest+1]; <----problem is here } public void add(E item, int priority) { queues[priority].add(item); manyItems++; } public boolean isEmpty( ) { return (manyItems == 0); } public E remove() { E answer=null; int counter=0; do { if(!queues[highest-counter].isEmpty()) { answer = queues[highest-counter].remove(); counter=highest+1; } else counter++; }while(highest-counter>=0); return answer; } }

    Read the article

  • Infile incomplete type error

    - by kd7vdb
    I am building a program that takes a input file in this format: title author title author etc and outputs to screen title (author) title (author) etc The Problem I am currently getting is a error "ifstream infile has incomplee type and cannot be defined" #include <iostream> #include <string> #include <ifstream> using namespace std; string bookTitle [14]; string bookAuthor [14]; int loadData (string pathname); void showall (int counter); int main () { int counter; string pathname; cout<<"Input the name of the file to be accessed: "; cin>>pathname; loadData (pathname); showall (counter); } int loadData (string pathname) // Loads data from infile into arrays { ifstream infile; int counter = 0; infile.open(pathname); //Opens file from user input in main if( infile.fail() ) { cout << "File failed to open"; return 0; } while (!infile.eof()) { infile >> bookTitle [14]; //takes input and puts into parallel arrays infile >> bookAuthor [14]; counter++; } infile.close; } void showall (int counter) // shows input in title(author) format { cout<<bookTitle<<"("<<bookAuthor<<")"; } Thanks ahead of time, kd7vdb

    Read the article

  • Java loop to collect the second and third elements every three in an array

    - by mhollander38
    I have a file with data in the form timestamp, coordinate, coordinate, seperated by spaces, as here; 14:25:01.215 370.0 333.0 I need to loop through and add the coordinates only to an array. The data from the file is read in and put into as String[] called info, from split(" "). I have two problems, I think the end of the file has a extra " " which I need to lose appropriately and I also want confirmation/suggestions of my loop, at the moment I am getting sporadic out of bounds exceptions. My loop is as follows; String[] info; info = dataHolder.split(" "); ArrayList<String> coOrds1 = new ArrayList<String>(); for (int counter = 0; counter < info.length; counter = counter+3) { coOrds1.add(info[counter+1]); coOrds1.add(info[counter+2]); } Help and suggestions appreciated. The text file is here but the class receives in a UDP packet from another class so I am unsure if this potentially adds " " at the end or not.

    Read the article

  • Timer in Java swing

    - by Yesha
    I'm trying to replace Thread.sleep with a java swing timer as I hear that is much better for graphics. Before, I had something set up like this, but it was interfering with the graphics. while(counter < array.size){ Thread.sleep(array.get(counter).startTime); //do first task Thread.sleep(array.get(counter).secondTime); //do second task Thread.sleep(array.get(counter).thirdTime); //do third task counter++ } Now, I'm trying to replace each Thread.sleep with one of these and then I have the actual events that happen after this, but it does not seem to be waiting at all. int test = array.get(counter).time; ActionListener taskPerformer = new ActionListener(){ public void actionPerformed(ActionEvent evt){ } }; Timer t = new Timer(test, taskPerformer); t.setRepeats(false); t.start(); Basically, how do I ensure that the program will wait without giving it any code to execute inside of the timer? Thank you!

    Read the article

  • Matlab N-Queen Problem

    - by Kay
    main.m counter = 1; n = 8; board = zeros(1,n); back(0, board); disp(counter); sol.m function value = sol(board) for ( i = 1:(length(board))) for ( j = (i+1): (length(board)-1)) if (board(i) == board(j)) value = 0; return; end if ((board(i) - board(j)) == (i-j)) value = 0; return; end if ((board(i) - board(j)) == (j-i)) value = 0; return; end end end value = 1; return; back.m function back(depth, board) disp(board); if ( (depth == length(board)) && (sol2(board) == 1)) counter = counter + 1; end if ( depth < length(board)) for ( i = 0:length(board)) board(1,depth+1) = i; depth = depth + 1; solv2(depth, board); end end I'm attempting to find the maximum number of ways n-queen can be placed on an n-by-n board such that those queens aren't attacking eachother. I cannot figure out the problem with the above matlab code, i doubt it's a problem with my logic since i've tested out this logic in java and it seems to work perfectly well there. The code compiles but the issue is that the results it produces are erroneous. Java Code which works: public static int counter=0; public static boolean isSolution(final int[] board){ for (int i = 0; i < board.length; i++) { for (int j = i + 1; j < board.length; j++) { if (board[i] == board[j]) return false; if (board[i]-board[j] == i-j) return false; if (board[i]-board[j] == j-i) return false; } } return true; } public static void solve(int depth, int[] board){ if (depth == board.length && isSolution(board)) { counter++; } if (depth < board.length) { // try all positions of the next row for (int i = 0; i < board.length; i++) { board[depth] = i; solve(depth + 1, board); } } } public static void main(String[] args){ int n = 8; solve(0, new int[n]); System.out.println(counter); }

    Read the article

  • Is it a good way to close a thread?

    - by Roman
    I have a short version of the question: I start a thread like that: counter.start();, where counter is a thread. At the point when I want to stop the thread I do that: counter.interrupt() In my thread I periodically do this check: Thread.interrupted(). If it gives true I return from the thread and, as a consequence, it stops. And here are some details, if needed: If you need more details, they are here. From the invent dispatch thread I start a counter thread in this way: public static void start() { SwingUtilities.invokeLater(new Runnable() { public void run() { showGUI(); counter.start(); } }); } where the thread is defined like that: public static Thread counter = new Thread() { public void run() { for (int i=4; i>0; i=i-1) { updateGUI(i,label); try {Thread.sleep(1000);} catch(InterruptedException e) {}; } // The time for the partner selection is over. SwingUtilities.invokeLater(new Runnable() { public void run() { frame.remove(partnerSelectionPanel); frame.add(selectionFinishedPanel); frame.invalidate(); frame.validate(); } }); } }; The thread performs countdown in the "first" window (it shows home much time left). If time limit is over, the thread close the "first" window and generate a new one. I want to modify my thread in the following way: public static Thread counter = new Thread() { public void run() { for (int i=4; i>0; i=i-1) { if (!Thread.interrupted()) { updateGUI(i,label); } else { return; } try {Thread.sleep(1000);} catch(InterruptedException e) {}; } // The time for the partner selection is over. if (!Thread.interrupted()) { SwingUtilities.invokeLater(new Runnable() { public void run() { frame.remove(partnerSelectionPanel); frame.add(selectionFinishedPanel); frame.invalidate(); frame.validate(); } }); } else { return; } } };

    Read the article

  • boost multi_index_container and erase performance

    - by rjoshi
    I have a boost multi_index_container declared as below which is indexed by hash_unique id(unsigned long) and hash_non_unique transaction id(long). Insertion and retrieval of elements is fast but when I delete elements, it is much slower. I was expecting it to be constant time as key is hashed. e.g To erase elements from container for 10,000 elements, it takes around 2.53927016 seconds for 15,000 elements, it takes around 7.137100068 seconds for 20,000 elements, it takes around 21.391720757 seconds Is it something I am missing or is it expected behavior? class Session { public: Session() { //increment unique id static unsigned long counter = 0; boost::mutex::scoped_lock guard(mx); counter++; m_nId = counter; } unsigned long GetId() { return m_nId; } long GetTransactionHandle(){ return m_nTransactionHandle; } .... private: unsigned long m_nId; long m_nTransactionHandle; boost::mutext mx; .... }; typedef multi_index_container< Session*, indexed_by< hashed_unique< mem_fun<Session,unsigned long,&Session::GetId> >, hashed_non_unique< mem_fun<Session,unsigned long,&Session::GetTransactionHandle> > > //end indexed_by > SessionContainer; typedef SessionContainer::nth_index<0>::type SessionById; int main() { ... SessionContainer container; SessionById *pSessionIdView = &get<0>(container); unsigned counter = atoi(argv[1]); vector<Session*> vSes(counter); //insert for(unsigned i = 0; i < counter; i++) { Session *pSes = new Session(); container.insert(pSes); vSes.push_back(pSes); } timespec ts; lock_settime(CLOCK_PROCESS_CPUTIME_ID, &ts); //erase for(unsigned i = 0; i < counter; i++) { pSessionIdView->erase(vSes[i]->getId()); delete vSes[i]; } lock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts); std::cout << "Total time taken for erase:" << ts.tv_sec << "." << ts.tv_nsec << "\n"; return (EXIST_SUCCESS); }

    Read the article

  • Stop running this script, IE7 using PHP

    - by Jomel Dicen
    I incorporate javascript in my PHP program: Try to check my codes. It loops depend on the number of records in database. for instance: $counter = 0; foreach($row_value as $data): echo $this->javascript($counter, $data->exrate, $data->tab); endforeach; private function javascript($counter=NULL, $exrate=NULL, $tab=NULL){ $js = " <script type='text/javascript'> $(function () { var textBox0 = $('input:text[id$=quantity{$counter}]').keyup(foo); var textBox1 = $('input:text[id$=mc{$counter}]').keyup(foo); var textBox2 = $('input:text[id$=lc{$counter}]').keyup(foo); function foo() { var value0 = textBox0.val(); var value1 = textBox1.val(); var value2 = textBox2.val(); var sum = add(value1, value2) * (value0 * {$exrate}); $('input:text[id$=result{$counter}]').val(parseFloat(sum).toFixed(2)); // Compute Total Quantity var qtotal = 0; $('.quantity{$tab}').each(function() { qtotal += Number($(this).val()); }); $('#tquantity{$tab}').text(qtotal); // Compute MC UNIT var mctotal = 0; $('.mc{$tab}').each(function() { mctotal += Number($(this).val()); }); $('#tmc{$tab}').text(mctotal); // Compute LC UNIT var lctotal = 0; $('.lc{$tab}').each(function() { lctotal += Number($(this).val()); }); $('#tlc{$tab}').text(lctotal); // Compute Result var result = 0; $('.result{$tab}').each(function() { result += Number($(this).val()); }); $('#tresult{$tab}').text(result); } function add() { var sum = 0; for (var i = 0, j = arguments.length; i < j; i++) { if (IsNumeric(arguments[i])) { sum += parseFloat(arguments[i]); } } return sum; } function IsNumeric(input) { return (input - 0) == input && input.length > 0; } }); </script> "; return $js; } When I running this on IE this message is always annoying me " Stop running this script? A script on this page is causing your web browser to run slowly. If it continues to run, your computer might become unresponsive." but in firefox it's functioning well.

    Read the article

  • Using SocialCounter.NET with ASP.NET MVC

    - by DigiMortal
    I found small library called SocialCounter.NET that is able to display some data from popular social sites. Although it is possible to use widgets offered by social networks there are also scenarios when you don’t want or can’t use these JavaScript based widgets. In this posting I will show you how to use SocialCounter.NET. Start with downloading SocialCounter.NET. You can also use NuGet package manager to download SocialCounter.NET. Using SocialCounter.NET is very easy as you can see from this example view: @using SocialCounter.NET; @{      ViewBag.Title = "Home Page"; } <h2>Social</h2> <p>     Twitter followers: @Counter.GetTwitterFollowersCount("gpeipman")<br />     Facebook friends: @Counter.GetFacebookFriendsCount("gpeipman")<br />     Facebook likes: @Counter.GetFacebookLikes("http://www.eindhovenmetalmeeting.nl/")<br />     Delicious saves count: @Counter.GetDeliciousSaveCount("http://youreffectiveleadership.com/")<br /> </p> And the result is shown on image on right. You can use SocialCounter.NET by example on user profile pages and on your content pages where you want to show how many people have saved current page as bookmark. SocialCounter.NET supports also LinkedIn, RSS-feeds and Google Plus accounts. In future – I hope – they will add support for more social networks to their library.

    Read the article

  • Multithreading in Windows Phone 7 emulator: A bug

    - by Laurent Bugnion
    Multithreading is supported in Windows Phone 7 Silverlight applications, however the emulator has a bug (which I discovered and was confirmed to me by the dev lead of the emulator team): If you attempt to start a background thread in the MainPage constructor, the thread never starts. The reason is a problem with the emulator UI thread which doesn’t leave any time to the background thread to start. Thankfully there is a workaround (see code below). Also, the bug should be corrected in a future release, so it’s not a big deal, even though it is really confusing when you try to understand why the *%&^$£% thread is not &$%&%$£ starting (that was me in the plane the other day ;) This code does not work: public partial class MainPage : PhoneApplicationPage { public MainPage() { InitializeComponent(); SupportedOrientations = SupportedPageOrientation.Portrait | SupportedPageOrientation.Landscape; var counter = 0; ThreadPool.QueueUserWorkItem(o => { while (true) { Dispatcher.BeginInvoke(() => { textBlockListTitle.Text = (counter++).ToString(); }); } }); } } This code does work: public MainPage() { InitializeComponent(); SupportedOrientations = SupportedPageOrientation.Portrait | SupportedPageOrientation.Landscape; var counter = 0; ThreadPool.QueueUserWorkItem(o => { while (true) { Dispatcher.BeginInvoke(() => { textBlockListTitle.Text = (counter++).ToString(); }); // NOTICE THIS LINE!!! Thread.Sleep(0); } }); } Note that even if the thread is started in a later event (for example Click of a Button), the behavior without the Thread.Sleep(0) is not good in the emulator. As of now, i would recommend always sleeping when starting a new thread. Happy coding: Laurent   Laurent Bugnion (GalaSoft) Subscribe | Twitter | Facebook | Flickr | LinkedIn

    Read the article

  • Query a Log4Net-database

    - by pinhack
    So if you use Log4Net to log into a database (i.e. using the AdoNetAppender), how can you conveniently get an overview of what has happend ? Well, you could try the following Query ( T-SQL ):   SELECT convert(varchar(10),LogDB.Date,121) as Datum, LogDB.Level, LogDB.Logger,COUNT(LogDB.Logger) as Counter From Log4Net.dbo.Log as LogDB  where Level <> 'DEBUG' AND convert(varchar(10),LogDB.Date,121) like '2010-03-25' GROUP BY convert(varchar(10),LogDB.Date,121),LogDB.Level,LogDB.Logger ORDER BY counter desc This query will give you the number of events by the Logger at a specified date - and it's easy to customize, just adjust the Date and the Level to your needs. You need a bit more information than that? How about this query:  Select  convert(varchar(10),LogDB.Date,121) as Datum,LogDB.Level,LogDB.Message,LogDB.Logger ,count(LogDB.Message) as counter From Log4Net.dbo.Log as LogDB where Level <> 'DEBUG' AND convert(varchar(10),LogDB.Date,121) like '2010-03-25' GROUP BY convert(varchar(10),LogDB.Date,121),LogDB.Level,LogDB.Message,LogDB.Logger ORDER BY counter desc Similar to the first one, but inclusive the Message - which will return a much larger resultset.

    Read the article

  • Pause and Resume and get the value of a countdown timer by savedInstanceState [closed]

    - by Catherine grace Balauro
    I have developed a countdown timer and I am not sure how to pause and resume the timer as the TextView for the timer is being clicked. Click to start then click again to pause and to resume, click again the timer's text view. This is my code: Timer = (TextView)this.findViewById(R.id.time); //TIMER Timer.setOnClickListener(TimerClickListener); counter = new MyCount(600000, 1000); }//end of create private OnClickListener TimerClickListener = new OnClickListener() { public void onClick(View v) { updateTimeTask(); } private void updateTimeTask() { if (decision==0){ counter.start(); decision=1;} else if(decision==2){ counter.onResume1(); decision=1; } else{ counter.onPause1(); decision=2; }//end if }; }; class MyCount extends CountDownTimer { public MyCount(long millisInFuture, long countDownInterval) { super(millisInFuture, countDownInterval); }//MyCount public void onResume1(){ onResume(); } public void onPause1() { onPause();} public void onFinish() { Timer.setText("00:00"); p1++; if (p1<=4){ TextView PScore = (TextView) findViewById(R.id.pscore); PScore.setText(p1 + ""); }//end if }//finish public void onTick(long millisUntilFinished) { Integer milisec = new Integer(new Double(millisUntilFinished).intValue()); Integer cd_secs = milisec / 1000; Integer minutes = (cd_secs % 3600) / 60; Integer seconds = (cd_secs % 3600) % 60; Timer.setText(String.format("%02d", minutes) + ":" + String.format("%02d", seconds)); //long timeLeft = millisUntilFinished / 1000; }//on tick }//class MyCount protected void onResume() { super.onResume(); //handler.removeCallbacks(updateTimeTask); //handler.postDelayed(updateTimeTask, 1000); }//onResume @Override protected void onPause() { super.onPause(); //do stuff }//onPause I am only beginner in android programming and I don't know how to get the value of the countdown timer using savedInstanceState. How do I do this?

    Read the article

  • Animating sprites in HTML5 canvas

    - by fnx
    I'm creating a 2D platformer game with HTML5 canvas and javascript. I'm having a bit of a struggle with animations. Currently I animate by getting preloaded images from an array, and the code is really simple, in player.update() I call a function that does this: var animLength = this.animations[id].length; this.counter++; this.counter %= 3; if (this.counter == 2) this.spriteCounter++; this.spriteCounter %= animLength; return this.animations[id][this.spriteCounter]; There are a couple of problems with this one: When the player does 2 actions that require animating at the same time, animation speed doubles. Apparently this.counter++ is working twice at the same time. I imagine that if I start animating multiple sprites with this, the animation speed will multiply by the amount of sprites. Other issue is that I couldn't make the animation run only once instead of looping while key is held down. Someone told me that I should create a function Animation(animation id, isLooped boolean) and the use something like player.sprite = new Animation("explode", false) but I don't know how to make it work. Yes I'm a noob... :)

    Read the article

  • What makes one language any better than another when both are designed for the same goals? [closed]

    - by Justin808
    I'm in the process of creating a grammar for a scripting language but as I'm working on it I started to wonder what makes a language good in the first place. I know the goals for my script but there are always 1000 different ways to go about doing things. Goals: Easy to use and understand (not my grandma could do it easy, but the secretary at the front desk could do it or the VP of marketing could do it type of easy) No user defined functions or subroutines. Its use would be in events of objects in a system similar to HyperCard. Conceptually I was thinking of a language like this: set myVariable to 'Hello World' set counter to 0 repeat 5 times with x begin set counter to counter add x end set myVariable to myVariable plus ' ' plus counter popup myVariable set text of label named 'label' to 'new text' set color of label named 'label' to blue The end result would popup a dialog with the contents Hello World 15 it would also change the text of a label and make it blue. But I could do the same thing 1000 different ways. So what makes one language any better than another when both are designed for the same goals?

    Read the article

  • Using AChartEngine library for graphs, not able to get value for diffrent x-axis value

    - by kundan Chaudhary
    public static ArrayList<double[]> Value = new ArrayList<double[]>(); private double[] x = new double[10]; private double[] y = new double[10]; int counter = -1; add.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { counter++; x[counter] = Double.parseDouble(income_1.getText().toString()); y[counter] = Double.parseDouble(income_2.getText().toString()); income_1.setText(""); income_2.setText(""); } }); publish.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (Value != null) { Value.add(x); Value.add(y); Intent intent = salesStackedBarChart.execute(BarChart.this, Value, counter); startActivity(intent); } } }); //and in SalesStackedBarChart.java class public Intent execute(Context context, ArrayList<double[]> values ,int counter) { int count = counter + 1; double fcount = counter + 1.5; String[] titles = new String[] { "Android", "iPhone" }; int[] colors = new int[] { Color.GREEN, Color.CYAN }; XYMultipleSeriesRenderer renderer = buildBarRenderer(colors); setChartSettings(renderer, "Yearly revenue in the last "+count+" years", "Years", "revenue in $", 0.5, fcount, 0, 24000, Color.GRAY, Color.LTGRAY); renderer.setXLabels(count); renderer.setYLabels(10); renderer.setDisplayChartValues(true); renderer.setXLabelsAlign(Align.LEFT); renderer.setYLabelsAlign(Align.LEFT); renderer.setZoomRate(1.1f); renderer.setBarSpacing(0.5); return ChartFactory.getBarChartIntent(context, buildBarDataset(titles, values), renderer, Type.DEFAULT); } // in AbstractDemoChart.java class protected XYMultipleSeriesDataset buildBarDataset(String[] titles, List<double[]> values) { XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset(); int length = titles.length; for (int i = 0; i < length; i++) { CategorySeries series = new CategorySeries(titles[i]); double[] v = values.get(i); int seriesLength = v.length; for (int k = 0; k < seriesLength; k++) { series.add(v[k]); } dataset.addSeries(series.toXYSeries()); } return dataset; } Run this project i get graph with x- axis value: 1,2,3,4,5.... But I want to print value: 2005,2006,2007,2008..... I changed in some code like: setChartSettings(renderer, "Yearly revenue in the last "+count+" years", "Years", "revenue in $", 2005, 2010, 0, 24000, Color.GRAY, Color.LTGRAY); and run project i get value of x-axis like: 2005,2006,2007.... but not get graph bar value. Values of all x-axis are null. How can I make this work?

    Read the article

  • C++, using stack.h read a string, then display it in reverse

    - by user1675108
    For my current assignment, I have to use the following header file, #ifndef STACK_H #define STACK_H template <class T, int n> class STACK { private: T a[n]; int counter; public: void MakeStack() { counter = 0; } bool FullStack() { return (counter == n) ? true : false ; } bool EmptyStack() { return (counter == 0) ? true : false ; } void PushStack(T x) { a[counter] = x; counter++; } T PopStack() { counter--; return a[counter]; } }; #endif To write a program that will take a sentence, store it into the "stack", and then display it in reverse, and I have to allow the user to repeat this process as much as they want. The thing is, I am NOT allowed to use arrays (otherwise I wouldn't need help with this), and am finding myself stumped. To give an idea of what I am attempting, here is my code as of posting, which obviously does not work fully but is simply meant to give an idea of the assignment. #include <iostream> #include <cstring> #include <ctime> #include "STACK.h" using namespace std; int main(void) { auto time_t a; auto STACK<char, 256> s; auto string curStr; auto int i; // Displays the current time and date time(&a); cout << "Today is " << ctime(&a) << endl; s.MakeStack(); cin >> curStr; i = 0; do { s.PushStack(curStr[i]); i++; } while (s.FullStack() == false); do { cout << s.PopStack(); } while (s.EmptyStack() == false); return 0; } // end of "main" **UPDATE This is my code currently #include <iostream> #include <string> #include <ctime> #include "STACK.h" using namespace std; time_t a; STACK<char, 256> s; string curStr; int i; int n; // Displays the current time and date time(&a); cout << "Today is " << ctime(&a) << endl; s.MakeStack(); getline(cin, curStr); i = 0; n = curStr.size(); do { s.PushStack(curStr[i++]); i++; }while(i < n); do { cout << s.PopStack(); }while( !(s.EmptyStack()) ); return 0;

    Read the article

  • How do encrypt a long or int using the Bouncy Castle crypto routines for BlackBerry?

    - by DanG
    How do encrypt/decrypt a long or int using the Bouncy Castle crypto routines for BlackBerry? I know how to encrypt/decrypt a String. I can encrypt a long but can't get a long to decrypt properly. Some of this is poorly done, but I'm just trying stuff out at the moment. I've included my entire crypto engine here: import org.bouncycastle.crypto.BufferedBlockCipher; import org.bouncycastle.crypto.DataLengthException; import org.bouncycastle.crypto.InvalidCipherTextException; import org.bouncycastle.crypto.engines.AESFastEngine; import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher; import org.bouncycastle.crypto.params.KeyParameter; public class CryptoEngine { // Global Variables // Global Objects private static AESFastEngine engine; private static BufferedBlockCipher cipher; private static KeyParameter key; public static boolean setEncryptionKey(String keyText) { // adding in spaces to force a proper key keyText += " "; // cutting off at 128 bits (16 characters) keyText = keyText.substring(0, 16); keyText = HelperMethods.cleanUpNullString(keyText); byte[] keyBytes = keyText.getBytes(); key = new KeyParameter(keyBytes); engine = new AESFastEngine(); cipher = new PaddedBufferedBlockCipher(engine); // just for now return true; } public static String encryptString(String plainText) { try { byte[] plainArray = plainText.getBytes(); cipher.init(true, key); byte[] cipherBytes = new byte[cipher.getOutputSize(plainArray.length)]; int cipherLength = cipher.processBytes(plainArray, 0, plainArray.length, cipherBytes, 0); cipher.doFinal(cipherBytes, cipherLength); String cipherString = new String(cipherBytes); return cipherString; } catch (DataLengthException e) { Logger.logToConsole(e); } catch (IllegalArgumentException e) { Logger.logToConsole(e); } catch (IllegalStateException e) { Logger.logToConsole(e); } catch (InvalidCipherTextException e) { Logger.logToConsole(e); } catch (Exception ex) { Logger.logToConsole(ex); } // else return "";// default bad value } public static String decryptString(String encryptedText) { try { byte[] cipherBytes = encryptedText.getBytes(); cipher.init(false, key); byte[] decryptedBytes = new byte[cipher.getOutputSize(cipherBytes.length)]; int decryptedLength = cipher.processBytes(cipherBytes, 0, cipherBytes.length, decryptedBytes, 0); cipher.doFinal(decryptedBytes, decryptedLength); String decryptedString = new String(decryptedBytes); // crop accordingly int index = decryptedString.indexOf("\u0000"); if (index >= 0) { decryptedString = decryptedString.substring(0, index); } return decryptedString; } catch (DataLengthException e) { Logger.logToConsole(e); } catch (IllegalArgumentException e) { Logger.logToConsole(e); } catch (IllegalStateException e) { Logger.logToConsole(e); } catch (InvalidCipherTextException e) { Logger.logToConsole(e); } catch (Exception ex) { Logger.logToConsole(ex); } // else return "";// default bad value } private static byte[] convertLongToByteArray(long longToConvert) { return new byte[] { (byte) (longToConvert >>> 56), (byte) (longToConvert >>> 48), (byte) (longToConvert >>> 40), (byte) (longToConvert >>> 32), (byte) (longToConvert >>> 24), (byte) (longToConvert >>> 16), (byte) (longToConvert >>> 8), (byte) (longToConvert) }; } private static long convertByteArrayToLong(byte[] byteArrayToConvert) { long returnable = 0; for (int counter = 0; counter < byteArrayToConvert.length; counter++) { returnable += ((byteArrayToConvert[byteArrayToConvert.length - counter - 1] & 0xFF) << counter * 8); } if (returnable < 0) { returnable++; } return returnable; } public static long encryptLong(long plainLong) { try { String plainString = String.valueOf(plainLong); String cipherString = encryptString(plainString); byte[] cipherBytes = cipherString.getBytes(); long returnable = convertByteArrayToLong(cipherBytes); return returnable; } catch (Exception e) { Logger.logToConsole(e); } // else return Integer.MIN_VALUE;// default bad value } public static long decryptLong(long encryptedLong) { byte[] cipherBytes = convertLongToByteArray(encryptedLong); cipher.init(false, key); byte[] decryptedBytes = new byte[cipher.getOutputSize(cipherBytes.length)]; int decryptedLength = cipherBytes.length; try { cipher.doFinal(decryptedBytes, decryptedLength); } catch (DataLengthException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidCipherTextException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } long plainLong = convertByteArrayToLong(decryptedBytes); return plainLong; } public static boolean encryptBoolean(int plainBoolean) { return false; } public static boolean decryptBoolean(int encryptedBoolean) { return false; } public static boolean testLongToByteArrayConversion() { boolean returnable = true; // fails out of the bounds of an integer, the conversion to long from byte // array does not hold, need to figure out a better solution for (long counter = -1000000; counter < 1000000; counter++) { long test = counter; byte[] bytes = convertLongToByteArray(test); long result = convertByteArrayToLong(bytes); if (result != test) { returnable = false; Logger.logToConsole("long conversion failed"); Logger.logToConsole("test = " + test + "\n result = " + result); } // regardless } // the end Logger.logToConsole("final returnable result = " + returnable); return returnable; } }

    Read the article

  • List of Commonly Used Value Types in XNA Games

    - by Michael B. McLaughlin
    Most XNA programmers are concerned about generating garbage. More specifically about allocating GC-managed memory (GC stands for “garbage collector” and is both the name of the class that provides access to the garbage collector and an acronym for the garbage collector (as a concept) itself). Two of the major target platforms for XNA (Windows Phone 7 and Xbox 360) use variants of the .NET Compact Framework. On both variants, the GC runs under various circumstances (Windows Phone 7 and Xbox 360). Of concern to XNA programmers is the fact that it runs automatically after a fixed amount of GC-managed memory has been allocated (currently 1MB on both systems). Many beginning XNA programmers are unaware of what constitutes GC-managed memory, though. So here’s a quick overview. In .NET, there are two different “types” of types: value types and reference types. Only reference types are managed by the garbage collector. Value types are not managed by the garbage collector and are instead managed in other ways that are implementation dependent. For purposes of XNA programming, the important point is that they are not managed by the GC and thus do not, by themselves, increment that internal 1 MB allocation counter. (n.b. Structs are value types. If you have a struct that has a reference type as a member, then that reference type, when instantiated, will still be allocated in the GC-managed memory and will thus count against the 1 MB allocation counter. Putting it in a struct doesn’t change the fact that it gets allocated on the GC heap, but the struct itself is created outside of the GC’s purview). Both value types and reference types use the keyword ‘new’ to allocate a new instance of them. Sometimes this keyword is hidden by a method which creates new instances for you, e.g. XmlReader.Create. But the important thing to determine is whether or not you are dealing with a value types or a reference type. If it’s a value type, you can use the ‘new’ keyword to allocate new instances of that type without incrementing the GC allocation counter (except as above where it’s a struct with a reference type in it that is allocated by the constructor, but there are no .NET Framework or XNA Framework value types that do this so it would have to be a struct you created or that was in some third-party library you were using for that to even become an issue). The following is a list of most all of value types you are likely to use in a generic XNA game: AudioCategory (used with XACT; not available on WP7) AvatarExpression (Xbox 360 only, but exposed on Windows to ease Xbox development) bool BoundingBox BoundingSphere byte char Color DateTime decimal double any enum (System.Enum itself is a class, but all enums are value types such that there are no GC allocations for enums) float GamePadButtons GamePadCapabilities GamePadDPad GamePadState GamePadThumbSticks GamePadTriggers GestureSample int IntPtr (rarely but occasionally used in XNA) KeyboardState long Matrix MouseState nullable structs (anytime you see, e.g. int? something, that ‘?’ denotes a nullable struct, also called a nullable type) Plane Point Quaternion Ray Rectangle RenderTargetBinding sbyte (though I’ve never seen it used since most people would just use a short) short TimeSpan TouchCollection TouchLocation TouchPanelCapabilities uint ulong ushort Vector2 Vector3 Vector4 VertexBufferBinding VertexElement VertexPositionColor VertexPositionColorTexture VertexPositionNormalTexture VertexPositionTexture Viewport So there you have it. That’s not quite a complete list, mind you. For example: There are various structs in the .NET framework you might make use of. I left out everything from the Microsoft.Xna.Framework.Graphics.PackedVector namespace, since everything in there ventures into the realm of advanced XNA programming anyway (n.b. every single instantiable thing in that namespace is a struct and thus a value type; there are also two interfaces but interfaces cannot be instantiated at all and thus don’t figure in to this discussion). There are so many enums you’re likely to use (PlayerIndex, SpriteSortMode, SpriteEffects, SurfaceFormat, etc.) that including them would’ve flooded the list and reduced its utility. So I went with “any enum” and trust that you can figure out what the enums are (and it’s rare to use ‘new’ with an enum anyway). That list also doesn’t include any of the pre-defined static instances of some of the classes (e.g. BlendState.AlphaBlend, BlendState.Opaque, etc.) which are already allocated such that using them doesn’t cause any new allocations and therefore doesn’t increase that 1 MB counter. That list also has a few misleading things. VertexElement, VertexPositionColor, and all the other vertex types are structs. But you’re only likely to ever use them as an array (for use with VertexBuffer or DynamicVertexBuffer), and all arrays are reference types (even arrays of value types such as VertexPositionColor[ ] or int[ ]). * So that’s it for now. The note below may be a bit confusing (it deals with how the GC works and how arrays are managed in .NET). If so, you can probably safely ignore it for now but feel free to ask any questions regardless. * Arrays of value types (where the value type doesn’t contain any reference type members) are much faster for the GC to examine than arrays of reference types, so there is a definite benefit to using arrays of value types where it makes sense. But creating arrays of value types does cause the GC’s allocation counter to increase. Indeed, allocating a large array of a value type is one of the quickest ways to increment the allocation counter since a .NET array is a sequential block of memory. An array of reference types is just a sequential block of references (typically 4 bytes each) while an array of value types is a sequential block of instances of that type. So for an array of Vector3s it would be 12 bytes each since each float is 4 bytes and there are 3 in a Vector3; for an array of VertexPositionNormalTexture structs it would typically be 32 bytes each since it has two Vector3s and a Vector2. (Note that there are a few additional bytes taken up in the creation of an array, typically 12 but sometimes 16 or possibly even more, which depend on the implementation details of the array type on the particular platform the code is running on).

    Read the article

  • javascript game loop and game update design

    - by zuo
    There is a main game loop in my program, which calls game update every frame. However, to make better animation and better control, there is a need to implement a function like updateEveryNFrames(n, func). I am considering implementing a counter for each update. The counter will be added by one each frame. The update function will be invoked according to the counter % n. For example, in a sequence of sprites animation, I can use the above function to control the speed of the animation. Can some give some advice or other solutions?

    Read the article

  • Shared hosting banwidth limits

    - by mike
    I have a shared hosting account with a 20GB monthly bandwidth limit. I have exceeded my monthly limit and according to my host my counter is never reset, they say they use a continuous 30 day counter. So for example, I make payment on the 1st of each month, say I use 20GB in the last week of the month. My bandwidth counter is not reset on the 1st of the new month and my bandwidth will only become available in the last week of the new month. Is this common practice by shared hosting companies? Sounds a bit shady to me. Surely my counters should be reset on the 1st of every month when I make payment and 20GB of bandwidth should be available from the day payment is made?

    Read the article

  • Initialize array in amortized constant time -- what is this trick called?

    - by user946850
    There is this data structure that trades performance of array access against the need to iterate over it when clearing it. You keep a generation counter with each entry, and also a global generation counter. The "clear" operation increases the generation counter. On each access, you compare local vs. global generation counters; if they differ, the value is treated as "clean". This has come up in this answer on Stack Overflow recently, but I don't remember if this trick has an official name. Does it? One use case is Dijkstra's algorithm if only a tiny subset of the nodes has to be relaxed, and if this has to be done repeatedly.

    Read the article

  • Barrier implementation with mutex and condition variable

    - by kkp
    I would like to implement a barrier using mutex locks and conditional variables. Please let me know whether my implementation below is fine or not? static int counter = 0; static int Gen = 999; void* thread_run(void*) { pthread_mutex_lock(&lock); int g = Gen; if (++counter == nThreads) { counter = 0; Gen++; pthread_cond_broadcast(&cond_var); } else { while (Gen == g) pthread_cond_wait(&cond_var, &lock); } pthread_mutex_unlock(&lock); return NULL; }

    Read the article

< Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >