Search Results

Search found 2342 results on 94 pages for 'valter minute'.

Page 19/94 | < Previous Page | 15 16 17 18 19 20 21 22 23 24 25 26  | Next Page >

  • Display real time years, months, weeks and days between 2 days in JavaScript

    - by alex
    This is what I've coded it up, and it appears to work. window.onload = function() { var currentSpan = document.getElementById('current'); var minute = 60000, hour = minute * 60, day = hour * 24, week = day * 7, month = week * 4, year = day * 365; var start = new Date(2009, 6, 1); setInterval(function() { var now = new Date(); var difference = now - start; var years = Math.floor(difference / year), months = Math.floor((difference - (years * year)) / month), weeks = Math.floor((difference - (months * month + years * year)) / week), days = Math.floor((difference - (weeks * week + months * month + years * year)) / day); currentSpan.innerHTML = 'Since has passed: ' + years + ' years, ' + months + ' months, ' + weeks + ' weeks and ' + days + ' days'; }, 500); }; This seems to update my span fine, and all the numbers look correct. However, the code looks quite ugly. Do I really need to set up faux constants like that, and then do all that math to calculate what I want? It's been a while since I've worked with the Date object. Is this the best way to do this?

    Read the article

  • Could Python's logging SMTP Handler be freezing my thread for 2 minutes?

    - by Oddthinking
    A rather confusing sequence of events happened, according to my log-file, and I am about to put a lot of the blame on the Python logger, which is a bold claim. I thought I should get some second opinions about whether what I am saying could be true. I am trying to explain why there is are several large gaps in my log file (around two minutes at a time) during stressful periods for my application when it is missing deadlines. I am using Python's logging module on a remote server, and have set-up, with a configuration file, for all logs of severity of ERROR or higher to be emailed to me. Typically, only one error will be sent at a time, but during periods of sustained problems, I might get a dozen in a minute - annoying, but nothing that should stress SMTP. I believe that, after a short spurt of such messages, the Python logging system (or perhaps the SMTP system it is sitting on) is encountering errors or congestion. The call to Python's log is then BLOCKING for two minutes, causing my thread to miss its deadlines. (I was smart enough to move the logging until after the critical path of the application - so I don't care if logging takes me a few seconds, but two minutes is far too long.) This seems like a rather awkward architecture (for both a logging system that can freeze up, and for an SMTP system (Ubuntu, sendmail) that cannot handle dozens of emails in a minute**), so this surprises me, but it exactly fits the symptoms. Has anyone had any experience with this? Can anyone describe how to stop it from blocking? ** EDIT: I actually counted. A little under 4000 short emails in two hours. So far more than I suggested, sorry. But enough to over-fill a Sendmail's buffers?

    Read the article

  • "hour" int taken from NSDate not behaving as expected at midnight??

    - by Eric
    I feel like I've lost my mind. Can someone tell me what's going on here? Also, I'm sure there is a better way to do what I'm trying to do, but I'm not interested in that now. I'd just like to solve the mystery of why my ints are not responding to logic as expected. // Set "At: " field close to current time NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"HH"]; int hour = [[dateFormatter stringFromDate:[NSDate date]] intValue]; [dateFormatter setDateFormat:@"mm"]; int minute = [[dateFormatter stringFromDate:[NSDate date]] intValue]; NSLog(@"currently %i:%i",hour, minute); if(hour >= 12){ // convert to AM/PM selectedMeridiem = 1; if(hour != 12){ hour = hour - 12; } } else{ selectedMeridiem = 0; } selectedHour = hour - 1; if(selectedHour <= 0){ selectedHour = 11; } When I debug the above code with my clock set to 12:XX AM, the integer "hour" returned is 0. But then any if statements with the condition if(hour == 0) are not evaluated. Likewise, this would not be evaluated either: if(hour < 1). The code above puts the hour int into another int, selectedHour (don't worry about why I'm doing this for now), but selectedHour suffers from the same weird behavior; the if(selectedHour <= 0) line is never evaluated. Am I going crazy, or am I just an idiot? Maybe there's some behavior of 0 integers that I'm not aware of. All of my code runs fine as long as it's not 12:XX AM.

    Read the article

  • Strange behaviour with GregorianCalendar

    - by Spark
    I just encountered a strange behaviour with the GregorianCalendar class, and I was wondering if I really was doing something bad. This only appends when the initialization date's month has an actualMaximum bigger than the month I'm going to set the calendar to. Here is the example code : // today is 2010/05/31 GregorianCalendar cal = new GregorianCalendar(); cal.set(Calendar.YEAR, 2010); cal.set(Calendar.MONTH, 1); // FEBRUARY cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH)); cal.set(Calendar.HOUR_OF_DAY, cal.getActualMaximum(Calendar.HOUR_OF_DAY)); cal.set(Calendar.MINUTE, cal.getActualMaximum(Calendar.MINUTE)); cal.set(Calendar.SECOND, cal.getActualMaximum(Calendar.SECOND)); cal.set(Calendar.MILLISECOND, cal.getActualMaximum(Calendar.MILLISECOND)); return cal.getTime(); // => 2010/03/03, wtf I know the problem is caused by the fact that the calendar initialization date is a 31 day month ( may ), which mess with the month set to february (28 days). The fix is easy ( just set day_of_month to 1 before setting year and month ), but I was wondering is this really was the wanted behaviour. Any thoughts ?

    Read the article

  • MySQL table data transformation -- how can I dis-aggreate MySQL time data?

    - by lighthouse65
    We are coding for a MySQL data warehousing application that stores descriptive data (User ID, Work ID, Machine ID, Start and End Time columns in the first table below) associated with time and production quantity data (Output and Time columns in the first table below) upon which aggregate (SUM, COUNT, AVG) functions are applied. We now wish to dis-aggregate time data for another type of analysis. Our current data table design: +---------+---------+------------+---------------------+---------------------+--------+------+ | User ID | Work ID | Machine ID | Event Start Time | Event End Time | Output | Time | +---------+---------+------------+---------------------+---------------------+--------+------+ | 080025 | ABC123 | M01 | 2008-01-24 16:19:15 | 2008-01-24 16:34:45 | 2120 | 930 | +---------+---------+------------+---------------------+---------------------+--------+------+ Reprocessing dis-aggregation that we would like to do would be to transform table content based on a granularity of minutes, rather than the current production event ("Event Start Time" and "Event End Time") granularity. The resulting reprocessing of existing table rows would look like: +---------+---------+------------+---------------------+--------+ | User ID | Work ID | Machine ID | Production Minute | Output | +---------+---------+------------+---------------------+--------+ | 080025 | ABC123 | M01 | 2010-01-24 16:19 | 133 | | 080025 | ABC123 | M01 | 2010-01-24 16:20 | 133 | | 080025 | ABC123 | M01 | 2010-01-24 16:21 | 133 | | 080025 | ABC123 | M01 | 2010-01-24 16:22 | 133 | | 080025 | ABC123 | M01 | 2010-01-24 16:23 | 133 | | 080025 | ABC123 | M01 | 2010-01-24 16:24 | 133 | | 080025 | ABC123 | M01 | 2010-01-24 16:25 | 133 | | 080025 | ABC123 | M01 | 2010-01-24 16:26 | 133 | | 080025 | ABC123 | M01 | 2010-01-24 16:27 | 133 | | 080025 | ABC123 | M01 | 2010-01-24 16:28 | 133 | | 080025 | ABC123 | M01 | 2010-01-24 16:29 | 133 | | 080025 | ABC123 | M01 | 2010-01-24 16:30 | 133 | | 080025 | ABC123 | M01 | 2010-01-24 16:31 | 133 | | 080025 | ABC123 | M01 | 2010-01-24 16:22 | 133 | | 080025 | ABC123 | M01 | 2010-01-24 16:33 | 133 | | 080025 | ABC123 | M01 | 2010-01-24 16:34 | 133 | +---------+---------+------------+---------------------+--------+ So the reprocessing would take an existing row of data created at the granularity of production event and modify the granularity to minutes, eliminating redundant (Event End Time, Time) columns while doing so. It assumes a constant rate of production and divides output by the difference in minutes plus one to populate the new table's Output column. I know this can be done in code...but can it be done entirely in a MySQL insert statement (or otherwise entirely in MySQL)? I am thinking of a INSERT ... INTO construction but keep getting stuck. An additional complexity is that there are hundreds of machines to include in the operation so there will be multiple rows (one for each machine) for each minute of the day. Any ideas would be much appreciated. Thanks.

    Read the article

  • How to maintain the state of button cutom listview in android

    - by Akshay
    I have custom ListView with three TextView three Button and three Chronometer. And the situation is I am loading the ListView properly.But while loading ListView I am disabling some button in the ListView by checking one parameter. Up to this point ListView is showing it's row properly. But when I am scrolling the ListView at that time previously enabled Button are getting disabled.What I am doing wrong I am not getting can one please point out my mistake Or any suggestion. Here is my Adapter class. public class OrderSmartKitchenAdapter extends BaseAdapter { private int flagDeliveryComplete = 0; private int flagPreparationComplete = 0; private int flagPreparationStarted = 0; private List<OrderitemdetailsBO> list = new ArrayList<OrderitemdetailsBO(); private int orderStatus; public OrderSmartKitchenAdapter() { // TODO Auto-generated constructor stub } public void setOrderList(List<OrderitemdetailsBO> orderList) { this.list = orderList; } @Override public int getCount() { // TODO Auto-generated method stub Log.i("OrderItemList Size :-", Integer.toString(list.size())); return list.size(); } @Override public Object getItem(int position) { // TODO Auto-generated method stub return null; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return 0; } @Override public View getView(final int position, View convertView,ViewGroup parent) { // TODO Auto-generated method stub final ViewHolder viewHolder ; if (convertView == null) { layoutInflater = LayoutInflater.from(myContext); convertView = layoutInflater.inflate(R.layout.table_row_view,null); viewHolder = new ViewHolder(); viewHolder.txtTableNumber = (TextView) convertView.findViewById(R.id.txtTableNumber); viewHolder.txtMenuItem = (TextView) convertView.findViewById(R.id.txtMenuItem); viewHolder.txtQuantity = (TextView) convertView.findViewById(R.id.txtQuantity); viewHolder.txtOrderAcceptanceTime = (TextView) convertView.findViewById(R.id.txtOrderAcceptanceTime); viewHolder.txtElapsedTimeOfOrderAcceptance = (Chronometer) convertView.findViewById(R.id.txtElapsedTimeOfOrderAcceptance); viewHolder.btnPreparationStart = (Button) convertView.findViewById(R.id.btnPreparationStart); viewHolder.btnPreparationStart.setTag(position); viewHolder.txtElapsedTimeForPreparation = (Chronometer) convertView.findViewById(R.id.txtElapsedTimeForPrepatration); viewHolder.btnPreparationComplete = (Button) convertView.findViewById(R.id.btnPreparationCompleted); viewHolder.btnPreparationComplete.setTag(position); viewHolder.txtElapsedTimeForDeliveryComplete = (Chronometer) convertView.findViewById(R.id.txtElapsedTimeForCompleation); viewHolder.btnDeliveryComplete = (Button) convertView.findViewById(R.id.btnOrderComplete); viewHolder.btnDeliveryComplete.setTag(position); convertView.setTag(viewHolder); } else{ viewHolder = (ViewHolder)convertView.getTag(); viewHolder.btnDeliveryComplete.setTag(position); viewHolder.btnPreparationComplete.setTag(position); viewHolder.btnPreparationStart.setTag(position); } if (list.get(position) != null) { OrderitemdetailsBO orderitemdetailsBO = new OrderitemdetailsBO(); orderitemdetailsBO = list.get(position); viewHolder.txtTableNumber.setText(orderitemdetailsBO.getOrderitemid().toString()); viewHolder.txtMenuItem.setText(orderitemdetailsBO.getMenuitemname().toString()); viewHolder.txtQuantity.setText(orderitemdetailsBO.getQuantity().toString()); Log.i("Table Number :-", Long.toString(orderitemdetailsBO.getOrderitemid())); Log.i("Menu Name :-", orderitemdetailsBO.getMenuitemname().toString()); Log.i("Quantity", orderitemdetailsBO.getQuantity().toString()); Date acceptTime = new Date(); acceptTime = orderitemdetailsBO.getOrderdatetime(); viewHolder.txtOrderAcceptanceTime.setText(DateUtil.getDateAsString(acceptTime,"HH:mm")); Log.i("Order Accept Time :-", acceptTime.getMinutes() + ":"+ acceptTime.getSeconds()); orderStatus = orderitemdetailsBO.getOrderstatus(); Date preparationStartTime = new Date(); preparationStartTime = orderitemdetailsBO.getPreparationstarttime(); if(preparationStartTime != null) { Log.i("OrderSmartKitchenActivity", "2 Order Acceptance Time :-" + "Menu Item id "+ orderitemdetailsBO.getOrderitemid() + " Preparation Start time " + orderitemdetailsBO.getPreparationstarttime() ); viewHolder.txtElapsedTimeOfOrderAcceptance.stop(); Log.i("Preparation Start Time :-",preparationStartTime.getMinutes() + ":" + preparationStartTime.getSeconds()); viewHolder.txtElapsedTimeOfOrderAcceptance.setText(DateUtil.getDateAsString(preparationStartTime,"MM:ss")); viewHolder.txtElapsedTimeOfOrderAcceptance.stop(); viewHolder.btnPreparationStart.setEnabled(false); viewHolder.btnPreparationStart.setClickable(false); viewHolder.btnPreparationStart.setBackgroundColor(Color.LTGRAY); } else { Long n = acceptTime.getTime(); Log.i("OrderSmartKitchenActivity", "Order Acceptance Time :-" + "Menu Item id "+ orderitemdetailsBO.getOrderitemid() + " Acceptance time" + Long.toString(n) + " Preparation Start time " + orderitemdetailsBO.getPreparationstarttime() ); // Calculate Time difference viewHolder.txtElapsedTimeOfOrderAcceptance.setBase(SystemClock.elapsedRealtime() - System.currentTimeMillis() + n); viewHolder.txtElapsedTimeOfOrderAcceptance.getBase(); viewHolder.txtElapsedTimeOfOrderAcceptance.start(); viewHolder.txtElapsedTimeOfOrderAcceptance.setFormat("%s"); } viewHolder.btnPreparationStart.setOnClickListener(new OnClickListener() { @Override public void onClick(final View v) { // TODO Auto-generated method stub if (flagPreparationStarted == 0) { flagPreparationStarted++; v.startAnimation(playAnimation()); handler.postDelayed(new Runnable() { @Override public void run() { // TODO Auto-generated method stub v.clearAnimation(); Date currentTime = new Date(); // Set Preparation Start Time. viewHolder.txtElapsedTimeOfOrderAcceptance.stop(); Date setTime = new Date(currentTime.getTime() * 1000); OrderitemdetailsBO orderitemdetailsBO = list.get(position); orderitemdetailsBO.setPreparationstarttime(setTime); String orderDetails = "2"; String getPosition = Integer.toString(position); viewHolder.btnPreparationStart.setBackgroundColor(Color.LTGRAY); new sendOrderStatusToServer().execute(orderDetails,getPosition); } }, 5000); } else { handler.removeCallbacksAndMessages(null); v.clearAnimation(); flagPreparationStarted = 0; Log.i("Handler Removed. :-", "Here"); } } }); String preparationTime = orderitemdetailsBO.getOrderpreparationtime(); if(preparationTime != null && orderStatus == order_preparationComplete) { viewHolder.txtElapsedTimeForPreparation.setText(preparationTime); viewHolder.txtElapsedTimeForPreparation.stop(); viewHolder.btnPreparationComplete.getTag(position); viewHolder.btnPreparationComplete.setEnabled(false); viewHolder.btnPreparationComplete.setClickable(false); viewHolder.btnPreparationComplete.setBackgroundColor(Color.LTGRAY); } else if( orderStatus == order_preparationStart || orderStatus == orderReceived || orderStatus == order_delivered){ Long n = acceptTime.getTime(); Log.i("Preparation Start Time :-", Long.toString(n)); viewHolder.txtElapsedTimeForPreparation.setBase(SystemClock.elapsedRealtime() - System.currentTimeMillis() + n); viewHolder.txtElapsedTimeForPreparation.getBase(); viewHolder.txtElapsedTimeForPreparation.start(); viewHolder.txtElapsedTimeForPreparation.setFormat("%s"); } viewHolder.btnPreparationComplete.setOnClickListener(new OnClickListener() { @Override public void onClick(final View v) { // TODO Auto-generated method if (flagPreparationComplete == 0) { flagPreparationComplete++; v.startAnimation(playAnimation()); handler.postDelayed(new Runnable() { @Override public void run() { // TODO Auto-generated method stub v.clearAnimation(); OrderitemdetailsBO orderitemdetailsBO = list.get(position); Date date = orderitemdetailsBO.getPreparationstarttime(); if(date != null) { viewHolder.txtElapsedTimeForPreparation.stop(); Date currentTime = new Date(); Calendar calendar = Calendar.getInstance(); int minute = calendar.get(Calendar.MINUTE); int second = calendar.get(Calendar.SECOND); orderitemdetailsBO.setOrderpreparationtime(calendar.get(Calendar.MINUTE) +":" +calendar.get(Calendar.SECOND)); String orderDetails = "3"; String getPosition = Integer.toString(position); viewHolder.btnPreparationComplete.setBackgroundColor(Color.LTGRAY); new sendOrderStatusToServer().execute(orderDetails,getPosition); } else { Toast.makeText(myContext, "Please Enter Preparation Start Time.", Toast.LENGTH_LONG).show(); } } }, 5000); } else { handler.removeCallbacksAndMessages(null); v.clearAnimation(); flagPreparationComplete = 0; } } }); String deleveredTime = orderitemdetailsBO.getOrderdeliverytime(); if(deleveredTime != null && orderStatus == order_delivered) { Date delevered = new Date(Long.parseLong(deleveredTime)); viewHolder.txtElapsedTimeForPreparation.setText(DateUtil.getDateAsString(delevered,"MM:ss")); Log.i("Preparation Start Time :-", delevered.getMinutes()+":"+delevered.getSeconds()); viewHolder.txtElapsedTimeForPreparation.stop(); viewHolder.btnDeliveryComplete.getTag(position); viewHolder.btnDeliveryComplete.setEnabled(false); viewHolder.btnDeliveryComplete.setClickable(false); viewHolder.btnDeliveryComplete.setBackgroundColor(Color.LTGRAY); } else if(orderStatus == 3 || orderStatus == 2 || orderStatus == 1) { Long n = acceptTime.getTime(); Log.i("Preparation Start Time :-", Long.toString(n)); viewHolder.txtElapsedTimeForDeliveryComplete.setTag(list.get(position)); viewHolder.txtElapsedTimeForDeliveryComplete.setBase(SystemClock.elapsedRealtime() - System.currentTimeMillis() + n); viewHolder.txtElapsedTimeForDeliveryComplete.getBase(); viewHolder.txtElapsedTimeForDeliveryComplete.start(); viewHolder.txtElapsedTimeForDeliveryComplete.setFormat("%s"); } viewHolder.btnDeliveryComplete.setOnClickListener(new OnClickListener() { @Override public void onClick(final View v) { // TODO Auto-generated method stub if (flagDeliveryComplete == 0) { flagDeliveryComplete++; v.startAnimation(playAnimation()); handler.postDelayed(new Runnable() { @Override public void run() { // TODO Auto-generated method stub v.clearAnimation(); OrderitemdetailsBO orderitemdetailsBO = list.get(position); Date date = orderitemdetailsBO.getPreparationstarttime(); String preparationComplete = orderitemdetailsBO.getOrderpreparationtime(); if(date != null && preparationComplete != null ) { Date currentTime = new Date(); Calendar calendar = Calendar.getInstance(); viewHolder.txtElapsedTimeForDeliveryComplete.stop(); orderitemdetailsBO.setOrderdeliverytime(calendar.get(Calendar.MINUTE) +":"+calendar.get(Calendar.SECOND)); String orderDetails = Integer.toString(order_delivered); String getPosition = Integer.toString(position); viewHolder.btnDeliveryComplete.setBackgroundColor(Color.LTGRAY); new sendOrderStatusToServer().execute(orderDetails,getPosition); } else { Toast.makeText(myContext, "Please Enter Preparation Start Time & Preparation Complete Time.", Toast.LENGTH_LONG).show(); } } }, 5000); } else { handler.removeCallbacksAndMessages(null); v.clearAnimation(); flagDeliveryComplete = 0; } } }); } return convertView; } } private static class ViewHolder { protected TextView txtTableNumber; protected TextView txtMenuItem; protected TextView txtQuantity; protected TextView txtOrderAcceptanceTime; protected Chronometer txtElapsedTimeOfOrderAcceptance; protected Button btnPreparationStart; protected Chronometer txtElapsedTimeForPreparation; protected Button btnPreparationComplete; protected Chronometer txtElapsedTimeForDeliveryComplete; protected Button btnDeliveryComplete; }

    Read the article

  • IE 8 issue where window.close() is not occuring after winword.exe is fired to print a document

    - by Dave
    In my web application, a popup page is called using window.open javascript. There is a Print button on the page that has an onclick event that calls a printchecks() function. The code in the printchecks() function is function printchecks(){ window.print(); window.close(); } Issue is that the window.print brings up the printer dialog fine and then you select a printer. The page is actually then printed and is a reference to an rtf document that opens in winword.exe behind the scenes. For some reason in IE 8, the window.close() does not occur. This worked in IE 7. In both cases, WINWORD.EXE process appears to run in the background after the page is printed but in the case of IE 8, control is not give back to that popup page until the WINWORD.EXE process dies which takes a minute or so. I am thinking that becasue control is not being sent back to the page in IE 8, the page is not closed automatically. You can close the page after control is given back after the minute or so. This does happen in IE on both Windows XP and Windows 7. Any ideas if there is a setting in IE 8 or some other reason this may be occuring?

    Read the article

  • new Statefull session bean instance without calling lookup

    - by kislo_metal
    Hi! Scenario: I have @Singleton UserFactory (@Stateless could be) , it`s method createSession() generating @Statefull UserSession bean by manual lookup. If I am injecting by DI @EJB - i will get same instance during calling fromFactory() method(as it should be) What I want - is to get new instance of UserSession without preforming lookup. Q1: how could I call new instance of @Statefull session bean? Code: @Singleton @Startup @LocalBean public class UserFactory { @EJB private UserSession session; public UserFactory() { } @Schedule(second = "*/1", minute = "*", hour = "*") public void creatingInstances(){ try { InitialContext ctx = new InitialContext(); UserSession session2 = (UserSession) ctx.lookup("java:global/inferno/lic/UserSession"); System.out.println("in singleton UUID " +session2.getSessionUUID()); } catch (NamingException e) { e.printStackTrace(); } } @Schedule(second = "*/1", minute = "*", hour = "*") public void fromFactory(){ System.out.println("in singleton UUID " +session.getSessionUUID()); } public UserSession creatSession(){ UserSession session2 = null; try { InitialContext ctx = new InitialContext(); session2 = (UserSession) ctx.lookup("java:global/inferno/lic/UserSession"); System.out.println("in singleton UUID " +session2.getSessionUUID()); } catch (NamingException e) { e.printStackTrace(); } return session2; } } As I understand, calling of session.getClass().newInstance(); is not a best idea Q2 : is it true? I am using glassfish v3, ejb 3.1.

    Read the article

  • Java library class to handle scheduled execution of "callbacks"?

    - by Hanno Fietz
    My program has a component - dubbed the Scheduler - that lets other components register points in time at which they want to be called back. This should work much like the Unix cron service, i. e. you tell the Scheduler "notify me at ten minutes past every full hour". I realize there are no real callbacks in Java. Here's my approach, is there a library which already does this stuff? Feel free to suggest improvements, too. Register call to Scheduler passes: a time specification containing hour, minute, second, year month, dom, dow, where each item may be unspecified, meaning "execute it every hour / minute etc." (just like crontabs) an object containing data that will tell the calling object what to do when it is notified by the Scheduler. The Scheduler does not process this data, just stores it and passes it back upon notification. a reference to the calling object Upon startup, or after a new registration request, the Scheduler starts with a Calendar object of the current system time and checks if there are any entries in the database that match this point in time. If there are, they are executed and the process starts over. If there aren't, the time in the Calendar object is incremented by one second and the entreis are rechecked. This repeats until there is one entry or more that match(es). (Discrete Event Simulation) The Scheduler will then remember that timestamp, sleep and wake every second to check if it is already there. If it happens to wake up and the time has already passed, it starts over, likewise if the time has come and the jobs have been executed. Edit: Thanks for pointing me to Quartz. I'm looking for something much smaller, however.

    Read the article

  • Cannot access Class methods from previous windows form - C#

    - by George
    I am writing an app, still, where I need to test some devices every minute for 30 minutes. It made sense to use a timer set to kick off every 60 secs and do whats required in the event handler. However, I need the app to wait for the 30 mins until I have finished with the timer since the following code alters the state of the devices I am trying to monitor. I obviously don't want to use any form of loop to do this. I thought of using another windows form, since I also display the progress, which will simply kick off the timer and wait until its complete. The problem I am having with this is that I use a device Class and cant seem to get access to the methods in the device class from the 2nd (3rd actually - see below) windows form. I have an initial windows form where I get input from the user, then call the 2nd windows form where it work out which tests need to be done and which device classes need to be used, and then I want to call the 3rd windows form to handle the timer. I will have up to 6-7 device classes and so wanted to only instantiate them when actually requiring them, from the 2nd form. Should I have put this logic into the 1st windows form (program class ??) ? Would I not still have the problem of not being able to access device class methods from there too ? Anyway, perhaps someone knows of a better way to do the checks every minute without the rest of the code executing (and changing the status of the devices) or how I should be accessing the methods in the app ?? Well that's the problem, I cant get that part of it to work correctly. Here is the definition for the calling form including the device class - namespace NdtStart { public partial class fclsNDTCalib : Form { NDTClass NDT = new NDTClass(); public fclsNDTCalib() (new fclsNDTTicker(NDT)).ShowDialog(); Here is the class def for the called form - namespace NdtStart { public partial class fclsNDTTicker : Form { public fclsNDTTicker() I tried lots but couldn't get the arguments to work.

    Read the article

  • 500 Worker Threads, what kind of thread pool?

    - by Submerged
    I am wondering if this is the best way to do this. I have about 500 threads that run indefinitely, but Thread.sleep for a minute when done one cycle of processing. ExecutorService es = Executors.newFixedThreadPool(list.size()+1); for (int i = 0; i < list.size(); i++) { es.execute(coreAppVector.elementAt(i)); //coreAppVector is a vector of extends thread objects } The code that is executing is really simple and basically just this class aThread extends Thread { public void run(){ while(true){ Thread.sleep(ONE_MINUTE); //Lots of computation every minute } } } I do need a separate threads for each running task, so changing the architecture isn't an option. I tried making my threadPool size equal to Runtime.getRuntime().availableProcessors() which attempted to run all 500 threads, but only let 8 (4xhyperthreading) of them execute. The other threads wouldn't surrender and let other threads have their turn. I tried putting in a wait() and notify(), but still no luck. If anyone has a simple example or some tips, I would be grateful! Well, the design is arguably flawed. The threads implement Genetic-Programming or GP, a type of learning algorithm. Each thread analyzes advanced trends makes predictions. If the thread ever completes, the learning is lost. That said, I was hoping that sleep() would allow me to share some of the resources while one thread isn't "learning"

    Read the article

  • gen_server with a dict vs mnesia table vs ets

    - by pablo
    Hi, I'm building an erlang server. Users sends http requests to the server to update their status. The http request process on the server saves the user status message in memory. Every minute the server sends all messages to a remote server and clear the memory. If a user update his status several times in a minute, the last message overrides the previous one. It is important that between reading all the messages and clearing them no other process will be able to write a status message. What is the best way to implement it? gen_server with a dict. The key will be the userid. dict:store/3 will update or create the status. The gen_server solves the 'transaction' issue. mnesia table with ram_copies. Handle transactions and I don't need to implement a gen_server. Is there too much overhead with this solution? ETS table which is more light weight and have a gen_server. Is it possible to do the transaction in ETS? To lock the table between reading all the messages and clearing them? Thanks

    Read the article

  • Pump Messages During Long Operations + C# (it is urgent)

    - by Newbie
    Hi I have a web service that is doing huge computation and is taking more than a minute. I have generated the proxy file of the web service and then from my client end I am using the dll(of course I generated the proxy dll). My client side code is TimeSeries3D t = new TimeSeries3D(); int portfolioId = 4387919; string[] str = new string[2]; str[0] = "MKT_CAP"; DateRange dr = new DateRange(); dr.mStartDate = DateTime.Today; dr.mEndDate = DateTime.Today; Service1 sc = new Service1(); t = sc.GetAttributesForPortfolio(portfolioId, true, str, dr); But since it is taking to much time for the server to compute, after 1 minute I am receiving an error message The CLR has been unable to transition from COM context 0x33caf30 to COM context 0x33cb0a0 for 60 seconds. The thread that owns the destination context/apartment is most likely either doing a non pumping wait or processing a very long running operation without pumping Windows messages. This situation generally has a negative performance impact and may even lead to the application becoming non responsive or memory usage accumulating continually over time. To avoid this problem, all single threaded apartment (STA) threads should use pumping wait primitives (such as CoWaitForMultipleHandles) and routinely pump messages during long running operations. Kindly guide me what to do? It is very urgent. Thanks

    Read the article

  • Using a randomly generated token for flood control.

    - by James P
    Basic setup of my site is: user enters a message on the homepage, hits enter and the message is sent though a AJAX request to a file called like.php where it echo's a link that gets sent back to the user. I have made the input disable when the user presses enter, but there's nothing stopping the user from just constantly flooding like.php with POST request and filling up my database. Someone here on SO told me to use a token system but didn't mention how. I've seen this being done before and from what I know it is effective. The only problem I have is how will like.php know it's a valid token? My code is this at the moment: $token = md5(rand(0, 9999) * 1000000); and the markup: <input type="hidden" name="token" value="<?php echo $token ?>" /> Which will send the token to like.php through POST. But how will like.php know that this is a valid token? Should I instead token something that's linked to the user? Like their IP address? Or perhaps token the current minute and check that it's the same minute in like.php... Any help on this amtter would be greatly appreciated, thanks. :)

    Read the article

  • MySQL query does not return any data

    - by Alex L
    Hi, I need to retrieve data from a specific time period. The query works fine until I specify the time period. Is there something wrong with the way I specify time period? I know there are many entries within that time-frame. This query returns empty: SELECT stop_times.stop_id, STR_TO_DATE(stop_times.arrival_time, '%H:%i:%s') as stopTime, routes.route_short_name, routes.route_long_name, trips.trip_headsign FROM trips JOIN stop_times ON trips.trip_id = stop_times.trip_id JOIN routes ON routes.route_id = trips.route_id WHERE stop_times.stop_id = 5508 HAVING stopTime BETWEEN DATE_SUB(stopTime,INTERVAL 1 MINUTE) AND DATE_ADD(stopTime,INTERVAL 20 MINUTE); Here is it's EXPLAIN: +----+-------------+------------+--------+------------------+---------+---------+-------------------------------+------+-------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+------------+--------+------------------+---------+---------+-------------------------------+------+-------------+ | 1 | SIMPLE | stop_times | ref | trip_id,stop_id | stop_id | 5 | const | 605 | Using where | | 1 | SIMPLE | trips | eq_ref | PRIMARY,route_id | PRIMARY | 4 | wmata_gtfs.stop_times.trip_id | 1 | | | 1 | SIMPLE | routes | eq_ref | PRIMARY | PRIMARY | 4 | wmata_gtfs.trips.route_id | 1 | | +----+-------------+------------+--------+------------------+---------+---------+-------------------------------+------+-------------+ 3 rows in set (0.00 sec) The query works if I remove the HAVING clause (don't specify time range). Returns: +---------+----------+------------------+-----------------+---------------+ | stop_id | stopTime | route_short_name | route_long_name | trip_headsign | +---------+----------+------------------+-----------------+---------------+ | 5508 | 06:31:00 | "80" | "" | "FORT TOTTEN" | | 5508 | 06:57:00 | "80" | "" | "FORT TOTTEN" | | 5508 | 07:23:00 | "80" | "" | "FORT TOTTEN" | | 5508 | 07:49:00 | "80" | "" | "FORT TOTTEN" | | 5508 | 08:15:00 | "80" | "" | "FORT TOTTEN" | | 5508 | 08:41:00 | "80" | "" | "FORT TOTTEN" | | 5508 | 09:08:00 | "80" | "" | "FORT TOTTEN" | I am using Google Transit format Data loaded into MySQL. The query is supposed to provide stop times and bus routes for a given bus stop. For a bus stop, I am trying to get: Route Name Bus Name Bus Direction (headsign) Stop time The results should be limited only to buses times from 1 min ago to 20 min from now. Please let me know if you could help.

    Read the article

  • Problem using the prependTo() in jQuery

    - by raulriera
    Hi all, I am having a problem trying to use the prependTo() function in jQuery... for some reason I can't get this to work $(" <div id="note178" class="note"> <div class="delete"><a href="/chart-notes/delete/178" onclick="$.ajax({ dataType: 'script', url: '/chart-notes/delete/178'}); return false;"><img src='/images/icons/delete.png'></a></div> <div class="timestamp">1 minute ago </div> <div class="content">ñasdas dasdasdasd conclusión</div> </div> ").prependTo(".notes").fadeIn("slow"); Although when doing it like this, it works fine $.ajax({ url:'/chart-notes/show/<cfoutput>#chartnote.id#</cfoutput>', success: function(data) { $(data).prependTo(".notes").fadeIn("slow"); // Scroll to the top of the annotations $('html, body').animate({scrollTop: $(".notes").offset().top}, 1000); // Clear the form $('#chartnote-notes').val(""); } }); The "data" response from that success function is the same <div id="note178" class="note"> <div class="delete"><a href="/chart-notes/delete/178" onclick="$.ajax({ dataType: 'script', url: '/chart-notes/delete/178'}); return false;"><img src='/images/icons/delete.png'></a></div> <div class="timestamp">1 minute ago </div> <div class="content">ñasdas dasdasdasd conclusión</div> </div> As before

    Read the article

  • Pump Messages During Long Operations + C#

    - by Newbie
    Hi I have a web service that is doing huge computation and is taking more than a minute. I have generated the proxy file of the web service and then from my client end I am using the dll(of course I generated the proxy dll). My client side code is TimeSeries3D t = new TimeSeries3D(); int portfolioId = 4387919; string[] str = new string[2]; str[0] = "MKT_CAP"; DateRange dr = new DateRange(); dr.mStartDate = DateTime.Today; dr.mEndDate = DateTime.Today; Service1 sc = new Service1(); t = sc.GetAttributesForPortfolio(portfolioId, true, str, dr); But since it is taking to much time for the server to compute, after 1 minute I am receiving an error message The CLR has been unable to transition from COM context 0x33caf30 to COM context 0x33cb0a0 for 60 seconds. The thread that owns the destination context/apartment is most likely either doing a non pumping wait or processing a very long running operation without pumping Windows messages. This situation generally has a negative performance impact and may even lead to the application becoming non responsive or memory usage accumulating continually over time. To avoid this problem, all single threaded apartment (STA) threads should use pumping wait primitives (such as CoWaitForMultipleHandles) and routinely pump messages during long running operations. Kindly guide me what to do? Thanks

    Read the article

  • How do I correcly handle ZoneLocalMapping.ResultType.Ambiguous?

    - by RWC
    In my code I try to handle ZoneLocalMapping.ResultType.Ambiguous. The line unambiguousLocalDateTime = localDateTimeMapping.EarlierMapping; throws an InvalidOperationException with message "EarlierMapping property should not be called on a result of type Ambiguous". I have no clue how I should handle it. Can you give me an example? This is what my code looks like: public Instant getInstant(int year, int month, int day, int hour, int minute) { var localDateTime = new LocalDateTime(year, month, day, hour, minute); //invalidated, might be not existing var timezone = DateTimeZone.ForId(TimeZoneId); //TimeZone is set elsewhere, example "Brazil/East" var localDateTimeMapping = timezone.MapLocalDateTime(localDateTime); ZonedDateTime unambiguousLocalDateTime; switch (localDateTimeMapping.Type) { case ZoneLocalMapping.ResultType.Unambiguous: unambiguousLocalDateTime = localDateTimeMapping.UnambiguousMapping; break; case ZoneLocalMapping.ResultType.Ambiguous: unambiguousLocalDateTime = localDateTimeMapping.EarlierMapping; break; case ZoneLocalMapping.ResultType.Skipped: unambiguousLocalDateTime = new ZonedDateTime(localDateTimeMapping.ZoneIntervalAfterTransition.Start, timezone); break; default: throw new InvalidOperationException(string.Format("Unexpected mapping result type: {0}", localDateTimeMapping.Type)); } return unambiguousLocalDateTime.ToInstant(); } If I look at class ZoneLocalMapping I see the following code: /// <summary> /// In an ambiguous mapping, returns the earlier of the two ZonedDateTimes which map to the original LocalDateTime. /// </summary> /// <exception cref="InvalidOperationException">The mapping isn't ambiguous.</exception> public virtual ZonedDateTime EarlierMapping { get { throw new InvalidOperationException("EarlierMapping property should not be called on a result of type " + type); } } That's why I am receiving the exception, but what should I do to get the EarlierMapping?

    Read the article

  • How to send a future email using AT command.

    - by BHare
    I just need to send one email into the future, so I figured i'd be best at using at rather than using cron. This is what I have so far, its messy and ugly and not that great at escaping: <pre> <?php $out = array(); // Where is the email going? $email = "[email protected]"; // What is the body of the email (make sure to escape any double-quotes) $body = "This is what is actually emailed to me"; $body = escapeshellcmd($body); $body = str_replace('!', '\!', $body); // What is the subject of the email (make sure to escape any double-quotes) $subject = "It's alive!"; $subject = escapeshellcmd($subject); $subject = str_replace('!', '\!', $subject); // How long from now should this email be sent? IE: 1 minute, 32 days, 1 month 2 days. $when = "1 minute"; $command= <<<END echo " echo \"$body\" > /tmp/email; mail -s \"$subject\" $email < /tmp/email; rm /tmp/email; " | at now + $when; END; $ret = exec($command, $out); print_r($out); ?> </pre> The output should be something like warning: commands will be executed using /bin/sh job 60 at Thu Dec 30 19:39:00 2010 However I am doing something wrong with exec and not getting the result? The main thing is this seem very messy. Is there any alternative better methods for doing this? PS: I had to add apache's user (www-data for me) to /etc/at.allow ...Which I don't like, but I can live with it.

    Read the article

  • PHP - Drilling down Data and Looping with Loops

    - by stogdilla
    I'm currently having difficulty finding a way of making my loops work. I have a table of data with 15 minute values. I need the data to pull up in a few different increments $filters=Array('Yrs','Qtr','Day','60','30','15'); I think I have a way of finding out what I need to be able to drill down to but the issue I'm having is after the first loop to cycle through all the Outter most values (ex: the user says they want to display by Hours, each hour should be able to have a "+" that will then add a new div to display the half hour data, then each half hour data have a "+" to display the 15 minute data upon request. Now I can just program the number of outputs for each value (6 different outputs) just in-case... but isn't there a way I can make it do the drill down for each one in a loop? so I only have to code one output once and have it just check if there are any more intervals after it and check for those? I'm sure I'm just overlooking some very simple way of doing this but my brain isn't being clever today. Sorry in advance if this is a simple solution. I guess the best way I could think of it as a reply on a form. How you would check to see if it's a reply of a reply, and then if that reply has any replys...etc for output. Can anyone help or at least point me in the right direction? Or am I stuck coding each possible check? Thanks in advance!

    Read the article

  • new Stateful session bean instance without calling lookup

    - by kislo_metal
    Scenario: I have @Singleton UserFactory (@Stateless could be) , its method createSession() generating @Stateful UserSession bean by manual lookup. If I am injecting by DI @EJB - i will get same instance during calling fromFactory() method(as it should be) What I want - is to get new instance of UserSession without preforming lookup. Q1: how could I call new instance of @Stateful session bean? Code: @Singleton @Startup @LocalBean public class UserFactory { @EJB private UserSession session; public UserFactory() { } @Schedule(second = "*/1", minute = "*", hour = "*") public void creatingInstances(){ try { InitialContext ctx = new InitialContext(); UserSession session2 = (UserSession) ctx.lookup("java:global/inferno/lic/UserSession"); System.out.println("in singleton UUID " +session2.getSessionUUID()); } catch (NamingException e) { e.printStackTrace(); } } @Schedule(second = "*/1", minute = "*", hour = "*") public void fromFactory(){ System.out.println("in singleton UUID " +session.getSessionUUID()); } public UserSession creatSession(){ UserSession session2 = null; try { InitialContext ctx = new InitialContext(); session2 = (UserSession) ctx.lookup("java:global/inferno/lic/UserSession"); System.out.println("in singleton UUID " +session2.getSessionUUID()); } catch (NamingException e) { e.printStackTrace(); } return session2; } } As I understand, calling of session.getClass().newInstance(); is not a best idea Q2 : is it true? I am using glassfish v3, ejb 3.1.

    Read the article

  • Database for managing large volumes of (system) metrics

    - by symcbean
    Hi, I'm looking at building a system for managing and reporting stats on web page performance. I'll be collecting a lot more stats than are available in the standard log formats (approx 20 metrics) but compared to most types of database applications, the base data structure will be very simple. My problem is that I'll be accumulating a lot of data - in the region of 100,000 records (i.e. sets of metrics) per hour. Of course, resources are very limited! So that its possible to sensibly interact with the data, I'd need to consolidate each metric into one minute bins, broken down by URL, then for anything more than 1 day old, consolidated into 10 minute bins, then at 1 week, hourly bins. At the front end, I want to provide a view (prefereably as plots) of the last hour of data, with the facility for users to drill up/down through defined hierarchies of URLs (which do not always map directly to the hierarchy expressed in the path of the URL) and to view different time frames. Rather than coding all this myself and using a relational database, I was wondering if there were tools available which would facilitate both the management of the data and the reporting. I had a look at Mondrian however I can't see from the documentation I've looked at whether it's possible to drop the more granular information while maintaining the consolidated views of the data. RRDTool looks promising in terms of managing the data consolidation, but seems to be rather limited in terms of querying the dataset as a multi-dimensional/relational database. What else whould I be looking at?

    Read the article

  • Android Service setForeground While Display Sleeps

    - by c12
    I have a background Android Service that's purpose is to communicate with another device (non-phone) using a Bluetooth socket. Everything works fine except that the service gets stopped and restarted by the OS when the phone display is sleeping. This restart sometimes leaves a 15-20 minute gaps where there is no communication between the Service and the Bluetooth device and I need to be able to query the device every minute. Is startForeground the proper approach? Attempted to use: startForeground(int, Notification) //still see gaps when phone sleeps Service: public class ForegroundBluetoothService extends Service{ private boolean isStarted = false; @Override public void onDestroy() { super.onDestroy(); stop(); } /** * @see android.app.Service#onBind(android.content.Intent) */ @Override public IBinder onBind(Intent intent) { return null; } /** * @see android.app.Service#onStartCommand(android.content.Intent, int, int) */ @Override public int onStartCommand(Intent intent, int flags, int startId) { loadServiceInForeground(); return(START_STICKY); } private void loadServiceInForeground() { if (!isStarted) { isStarted=true; Notification notification = new Notification(R.drawable.icon, "Service is Running...", System.currentTimeMillis()); Intent notificationIntent = new Intent(this, MainScreen.class); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); notification.setLatestEventInfo(this, "Notification Title", "Service is Running...", pendingIntent); startForeground(12345, notification); try{ queryTheBluetoothDevice(); } catch(Exception ex){ ex.printStackTrace(); } } } private void stop() { if (isStarted) { isStarted=false; stopForeground(true); } } }

    Read the article

  • Parsing localized date strings in PHP

    - by Mikeage
    Hi, I have some code (it's part of a wordpress plugin) which takes a text string, and the format specifier given to date(), and attempts to parse it into an array containing hour, minute, second, day, month, year. Currently, I use the following code (note that strtotime is horribly unreliable with things like 01/02/03) // $format contains the string originally given to date(), and $content is the rendered string if (function_exists('date_parse_from_format')) { $content_parsed = date_parse_from_format($format, $content); } else { $content = preg_replace("([0-9]st|nd|rd|th)","\\1",$content); $content_parsed = strptime($content, dateFormatToStrftime($format)); $content_parsed['hour']=$content_parsed['tm_hour']; $content_parsed['minute']=$content_parsed['tm_min']; $content_parsed['day']=$content_parsed['tm_mday']; $content_parsed['month']=$content_parsed['tm_mon'] + 1; $content_parsed['year']=$content_parsed['tm_year'] + 1900; } This actually works fairly well, and seems to handle every combination I've thrown at it. However, recently someone gave me 24 ??????, 2010. This is Russian for November 24, 2010 [the date format was j F, Y], and it is parsed as year = 2010, month = null, day = 24. Are there any functions that I can use that know how to translate both November and ?????? into 11? EDIT: Running print_r(setlocale(LC_ALL, 0)); returns C. Switching back to strptime() seems to fix the problem, but the docs warn: Internally, this function calls the strptime() function provided by the system's C library. This function can exhibit noticeably different behaviour across different operating systems. The use of date_parse_from_format(), which does not suffer from these issues, is recommended on PHP 5.3.0 and later. Is date_parse_from_format() the correct API, and if so, how do I get it to recognize the language?

    Read the article

  • android use local service to refresh map UI

    - by urobo
    I don't need a strict code related answer I just need somebody to tell me what I am missing. My application has to retrieve from a web service (xmlrpc) the positions of some users I know and update their position on a MapView. So I decided to use a Service and an Activity extending MapActivity to show results. I thought about two solutions: I ) start the service and make it ask every minute for these positions and send them to the activity as a bundle via intent. (This didn't work out well, since once shown I couldn't find a method to let the activity continue refresh itself until she stop receiving intents+data from the service) II ) Incorporate a thread within the activity which starts the service via context.startService(...) every minute. And the MapUI refresh itself once the service send back an intent and stop itself. (Maybe I will fall in the same problem category as before I haven't tryied yet). I am also giving directions (via maps.google ws) in this way I'd like to refresh only users positions on the map and save the route. What Am I missing do you have any suggestions? related to activities/services internal mechanics, don't know launch modes, use broadcast receivers or intent filters? Thanks in advance

    Read the article

< Previous Page | 15 16 17 18 19 20 21 22 23 24 25 26  | Next Page >