Search Results

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

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

  • Insert Update using Nhibernate

    - by Pankaj
    Hello All I am inserting Product on database, My Product Model like this public class Product { public int ProductID { get; set; } public string ProductNumber { get; set; } public string Description { get; set; } public string KeyWords { get; set; } } here my ProductNumber is coming on counter table Table- Counter Field- Counter- int when product insert then its ProductNumber come from Counter table, after insert counter increase 1. In update counter not increase. How can i insert Product in such situation using Nhibernate? Thanks

    Read the article

  • GAE JCache NumberFormatException, will I need to write Java to avoid?

    - by Jasper
    This code below produces a NumberFormatException in this line: val cache = cf.createCache(Collections.emptyMap()) Do you see any errors? Will I need to write a Java version to avoid this, or is there a Scala way? ... import java.util.Collections import net.sf.jsr107cache._ object QueryGenerator extends ServerResource { private val log = Logger.getLogger(classOf[QueryGenerator].getName) } class QueryGenerator extends ServerResource { def getCounter(cache:Cache):long = { if (cache.containsKey("counter")) { cache.get("counter").asInstanceOf[long] } else { 0l } } @Get("html") def getHtml(): Representation = { val cf = CacheManager.getInstance().getCacheFactory() val cache = cf.createCache(Collections.emptyMap()) val counter = getCounter(cache) cache.put("counter", counter + 1) val q = QueueFactory.getQueue("query-generator") q.add(TaskOptions.Builder.url("/tasks/query-generator").method(Method.GET).countdownMillis(1000L)) QueryGenerator.log.warning(counter.toString) new StringRepresentation("QueryGenerator started!", MediaType.TEXT_HTML) } } Thanks!

    Read the article

  • allignment issue of div tag

    - by Quasar the space thing
    I am trying to create a web page where on click of a button I can add div tags. What I thought to do was that I'll create two div tags within a single div so that over all presentation will be uniform and similar to a table having two columns and multiple rows and the first column contains only label's and second column will contain textbox. Here is the JS file : var counter = 0; function create_div(type){ var dynDiv = document.createElement("div"); dynDiv.id = "divid_"+counter; dynDiv.class="main"; document.body.appendChild(dynDiv); question(); if(type == 'ADDTEXTBOX'){ ADDTEXTBOX(); } counter=counter+1; } function question(){ var question_div = document.createElement("div"); question_div.class="question"; question_div.id = "question_div_"+counter; var Question = prompt("Enter The Question here:", ""); var node=document.createTextNode(Question); question_div.appendChild(node); var element=document.getElementById("divid_"+counter); element.appendChild(question_div); } function ADDTEXTBOX(){ var answer_div = document.createElement("div"); answer_div.class="answer"; answer_div.id = "answer_div_"+counter; var answer_tag = document.createElement("input"); answer_tag.id = "answer_tag_"+counter; answer_tag.setAttribute("type", "text"); answer_tag.setAttribute("name", "textbox"); answer_div.appendChild(answer_tag); var element=document.getElementById("divid_"+counter); element.appendChild(answer_div); } Here is the css file : .question { width: 40%; height: auto; float: left; display: inline-block; text-align: justify; word-wrap:break-word; } .answer { padding-left:10%; width: 40%; height: auto; float: left; overflow: auto; word-wrap:break-word; } .main { width: auto; background-color:gray; height: auto; overflow: auto; word-wrap:break-word; } My problem is that the code is working properly but both the divisions are not coming in a straight line. after the first div prints on the screen the second divisions comes in another line. How can I make both the div's come in the same line ? Thank You. PS : should I stick with the current idea of using div or should I try some other approach ? like tables ?

    Read the article

  • HPET for x86 BSP (how to build it for WCE8)

    - by Werner Willemsens
    Originally posted on: http://geekswithblogs.net/WernerWillemsens/archive/2014/08/02/157895.aspx"I needed a timer". That is how we started a few blogs ago our series about APIC and ACPI. Well, here it is. HPET (High Precision Event Timer) was introduced by Intel in early 2000 to: Replace old style Intel 8253 (1981!) and 8254 timers Support more accurate timers that could be used for multimedia purposes. Hence Microsoft and Intel sometimes refers to HPET as Multimedia timers. An HPET chip consists of a 64-bit up-counter (main counter) counting at a frequency of at least 10 MHz, and a set of (at least three, up to 256) comparators. These comparators are 32- or 64-bit wide. The HPET is discoverable via ACPI. The HPET circuit in recent Intel platforms is integrated into the SouthBridge chip (e.g. 82801) All HPET timers should support one-shot interrupt programming, while optionally they can support periodic interrupts. In most Intel SouthBridges I worked with, there are three HPET timers. TIMER0 supports both one-shot and periodic mode, while TIMER1 and TIMER2 are one-shot only. Each HPET timer can generate interrupts, both in old-style PIC mode and in APIC mode. However in PIC mode, interrupts cannot freely be chosen. Typically IRQ11 is available and cannot be shared with any other interrupt! Which makes the HPET in PIC mode virtually unusable. In APIC mode however more IRQs are available and can be shared with other interrupt generating devices. (Check the datasheet of your SouthBridge) Because of this higher level of freedom, I created the APIC BSP (see previous posts). The HPET driver code that I present you here uses this APIC mode. Hpet.reg [HKEY_LOCAL_MACHINE\Drivers\BuiltIn\Hpet] "Dll"="Hpet.dll" "Prefix"="HPT" "Order"=dword:10 "IsrDll"="giisr.dll" "IsrHandler"="ISRHandler" "Priority256"=dword:50 Because HPET does not reside on the PCI bus, but can be found through ACPI as a memory mapped device, you don't need to specify the "Class", "SubClass", "ProgIF" and other PCI related registry keys that you typically find for PCI devices. If a driver needs to run its internal thread(s) at a certain priority level, by convention in Windows CE you add the "Priority256" registry key. Through this key you can easily play with the driver's thread priority for better response and timer accuracy. See later. Hpet.cpp (Hpet.dll) This cpp file contains the complete HPET driver code. The file is part of a folder that you typically integrate in your BSP (\src\drivers\Hpet). It is written as sample (example) code, you most likely want to change this code to your specific needs. There are two sets of #define's that I use to control how the driver works. _TRIGGER_EVENT or _TRIGGER_SEMAPHORE: _TRIGGER_EVENT will let your driver trigger a Windows CE Event when the timer expires, _TRIGGER_SEMAPHORE will trigger a Windows CE counting Semaphore. The latter guarantees that no events get lost in case your application cannot always process the triggers fast enough. _TIMER0 or _TIMER2: both timers will trigger an event or semaphore periodically. _TIMER0 will use a periodic HPET timer interrupt, while _TIMER2 will reprogram a one-shot HPET timer after each interrupt. The one-shot approach is interesting if the frequency you wish to generate is not an even multiple of the HPET main counter frequency. The sample code uses an algorithm to generate a more correct frequency over a longer period (by reducing rounding errors). _TIMER1 is not used in the sample source code. HPT_Init() will locate the HPET I/O memory space, setup the HPET counter (_TIMER0 or _TIMER2) and install the Interrupt Service Thread (IST). Upon timer expiration, the IST will run and on its turn will generate a Windows CE Event or Semaphore. In case of _TIMER2 a new one-shot comparator value is calculated and set for the timer. The IRQ of the HPET timers are programmed to IRQ22, but you can choose typically from 20-23. The TIMERn_INT_ROUT_CAP bits in the TIMn_CONF register will tell you what IRQs you can choose from. HPT_IOControl() can be used to set a new HPET counter frequency (actually you configure the counter timeout value in microseconds), start and stop the timer, and request the current HPET counter value. The latter is interesting because the Windows CE QueryPerformanceCounter() and QueryPerformanceFrequency() APIs implement the same functionality, albeit based on other counter implementations. HpetDrvIst() contains the IST code. DWORD WINAPI HpetDrvIst(LPVOID lpArg) { psHpetDeviceContext pHwContext = (psHpetDeviceContext)lpArg; DWORD mainCount = READDWORD(pHwContext->g_hpet_va, GenCapIDReg + 4); // Main Counter Tick period (fempto sec 10E-15) DWORD i = 0; while (1) { WaitForSingleObject(pHwContext->g_isrEvent, INFINITE); #if defined(_TRIGGER_SEMAPHORE) LONG p = 0; BOOL b = ReleaseSemaphore(pHwContext->g_triggerEvent, 1, &p); #elif defined(_TRIGGER_EVENT) BOOL b = SetEvent(pHwContext->g_triggerEvent); #else #pragma error("Unknown TRIGGER") #endif #if defined(_TIMER0) DWORD currentCount = READDWORD(pHwContext->g_hpet_va, MainCounterReg); DWORD comparator = READDWORD(pHwContext->g_hpet_va, Tim0_ComparatorReg + 0); SETBIT(pHwContext->g_hpet_va, GenIntStaReg, 0); // clear interrupt on HPET level InterruptDone(pHwContext->g_sysIntr); // clear interrupt on OS level _LOGMSG(ZONE_INTERRUPT, (L"%s: HpetDrvIst 0 %06d %08X %08X", pHwContext->g_id, i++, currentCount, comparator)); #elif defined(_TIMER2) DWORD currentCount = READDWORD(pHwContext->g_hpet_va, MainCounterReg); DWORD previousComparator = READDWORD(pHwContext->g_hpet_va, Tim2_ComparatorReg + 0); pHwContext->g_counter2.QuadPart += pHwContext->g_comparator.QuadPart; // increment virtual counter (higher accuracy) DWORD comparator = (DWORD)(pHwContext->g_counter2.QuadPart >> 8); // "round" to real value WRITEDWORD(pHwContext->g_hpet_va, Tim2_ComparatorReg + 0, comparator); SETBIT(pHwContext->g_hpet_va, GenIntStaReg, 2); // clear interrupt on HPET level InterruptDone(pHwContext->g_sysIntr); // clear interrupt on OS level _LOGMSG(ZONE_INTERRUPT, (L"%s: HpetDrvIst 2 %06d %08X %08X (%08X)", pHwContext->g_id, i++, currentCount, comparator, comparator - previousComparator)); #else #pragma error("Unknown TIMER") #endif } return 1; } The following figure shows how the HPET hardware interrupt via ISR -> IST is translated in a Windows CE Event or Semaphore by the HPET driver. The Event or Semaphore can be used to trigger a Windows CE application. HpetTest.cpp (HpetTest.exe)This cpp file contains sample source how to use the HPET driver from an application. The file is part of a separate (smart device) VS2013 solution. It contains code to measure the generated Event/Semaphore times by means of GetSystemTime() and QueryPerformanceCounter() and QueryPerformanceFrequency() APIs. HPET evaluation If you scan the internet about HPET, you'll find many remarks about buggy HPET implementations and bad performance. Unfortunately that is true. I tested the HPET driver on an Intel ICH7M SBC (release date 2008). When a HPET timer expires on the ICH7M, an interrupt indeed is generated, but right after you clear the interrupt, a few more unwanted interrupts (too soon!) occur as well. I tested and debugged it for a loooong time, but I couldn't get it to work. I concluded ICH7M's HPET is buggy Intel hardware. I tested the HPET driver successfully on a more recent NM10 SBC (release date 2013). With the NM10 chipset however, I am not fully convinced about the timer's frequency accuracy. In the long run - on average - all is fine, but occasionally I experienced upto 20 microseconds delays (which were immediately compensated on the next interrupt). Of course, this was all measured by software, but I still experienced the occasional delay when both the HPET driver IST thread as the application thread ran at CeSetThreadPriority(1). If it is not the hardware, only the kernel can cause this delay. But Windows CE is an RTOS and I have never experienced such long delays with previous versions of Windows CE. I tested and developed this on WCE8, I am not heavily experienced with it yet. Internet forum threads however mention inaccurate HPET timer implementations as well. At this moment I haven't figured out what is going on here. Useful references: http://www.intel.com/content/dam/www/public/us/en/documents/technical-specifications/software-developers-hpet-spec-1-0a.pdf http://en.wikipedia.org/wiki/High_Precision_Event_Timer http://wiki.osdev.org/HPET Windows CE BSP source file package for HPET in MyBsp Note that this source code is "As Is". It is still under development and I cannot (and never will) guarantee the correctness of the code. Use it as a guide for your own HPET integration.

    Read the article

  • What is the proper jargon to refer to a variable wrapped inside a function closure?

    - by Rice Flour Cookies
    In JavaScript, there is no such thing as a "private" variable. In order to achieve encapsulation and information hiding in JavaScript, I can wrap a variable inside a function closure, like so: var counter = (function() { var i = 0; var fn = {}; fn.increment = function() { i++; }; fn.get = function() { return i; }; return fn; {)(); counter.increment(); counter.increment(); alert(counter.get()); // alerts '2' Since I don't call i a private variable in JavaScript, what do I call it?

    Read the article

  • Restoring databases to a set drive and directory

    - by okeofs
     Restoring databases to a set drive and directory Introduction Often people say that necessity is the mother of invention. In this case I was faced with the dilemma of having to restore several databases, with multiple ‘ndf’ files, and having to restore them with different physical file names, drives and directories on servers other than the servers from which they originated. As most of us would do, I went to Google to see if I could find some code to achieve this task and found some interesting snippets on Pinal Dave’s website. Naturally, I had to take it further than the code snippet, HOWEVER it was a great place to start. Creating a temp table to hold database file details First off, I created a temp table which would hold the details of the individual data files within the database. Although there are a plethora of fields (within the temp table below), I utilize LogicalName only within this example. The temporary table structure may be seen below:   create table #tmp ( LogicalName nvarchar(128)  ,PhysicalName nvarchar(260)  ,Type char(1)  ,FileGroupName nvarchar(128)  ,Size numeric(20,0)  ,MaxSize numeric(20,0), Fileid tinyint, CreateLSN numeric(25,0), DropLSN numeric(25, 0), UniqueID uniqueidentifier, ReadOnlyLSN numeric(25,0), ReadWriteLSN numeric(25,0), BackupSizeInBytes bigint, SourceBlocSize int, FileGroupId int, LogGroupGUID uniqueidentifier, DifferentialBaseLSN numeric(25,0), DifferentialBaseGUID uniqueidentifier, IsReadOnly bit, IsPresent bit,  TDEThumbPrint varchar(50) )    We now declare and populate a variable(@path), setting the variable to the path to our SOURCE database backup. declare @path varchar(50) set @path = 'P:\DATA\MYDATABASE.bak'   From this point, we insert the file details of our database into the temp table. Note that we do so by utilizing a restore statement HOWEVER doing so in ‘filelistonly’ mode.   insert #tmp EXEC ('restore filelistonly from disk = ''' + @path + '''')   At this point, I depart from what I gleaned from Pinal Dave.   I now instantiate a few more local variables. The use of each variable will be evident within the cursor (which follows):   Declare @RestoreString as Varchar(max) Declare @NRestoreString as NVarchar(max) Declare @LogicalName  as varchar(75) Declare @counter as int Declare @rows as int set @counter = 1 select @rows = COUNT(*) from #tmp  -- Count the number of records in the temp                                    -- table   Declaring and populating the cursor At this point I do realize that many people are cringing about the use of a cursor. Being an Oracle professional as well, I have learnt that there is a time and place for cursors. I would remind the reader that the data that will be read into the cursor is from a local temp table and as such, any locking of the records (within the temp table) is not really an issue.   DECLARE MY_CURSOR Cursor  FOR  Select LogicalName  From #tmp   Parsing the logical names from within the cursor. A small caveat that works in our favour,  is that the first logical name (of our database) is the logical name of the primary data file (.mdf). Other files, except for the very last logical name, belong to secondary data files. The last logical name is that of our database log file.   I now open my cursor and populate the variable @RestoreString Open My_Cursor  set @RestoreString =  'RESTORE DATABASE [MYDATABASE] FROM DISK = N''P:\DATA\ MYDATABASE.bak''' + ' with  '   We now fetch the first record from the temp table.   Fetch NEXT FROM MY_Cursor INTO @LogicalName   While there are STILL records left within the cursor, we dynamically build our restore string. Note that we are using concatenation to create ‘one big restore executable string’.   Note also that the target physical file name is hardwired, as is the target directory.   While (@@FETCH_STATUS <> -1) BEGIN IF (@@FETCH_STATUS <> -2) -- As long as there are no rows missing select @RestoreString = case  when @counter = 1 then -- This is the mdf file    @RestoreString + 'move  N''' + @LogicalName + '''' + ' TO N’’X:\DATA1\'+ @LogicalName + '.mdf' + '''' + ', '   -- OK, if it passes through here we are dealing with an .ndf file -- Note that Counter must be greater than 1 and less than the number of rows.   when @counter > 1 and @counter < @rows then -- These are the ndf file(s)    @RestoreString + 'move  N''' + @LogicalName + '''' + ' TO N’’X:\DATA1\'+ @LogicalName + '.ndf' + '''' + ', '   -- OK, if it passes through here we are dealing with the log file When @LogicalName like '%log%' then    @RestoreString + 'move  N''' + @LogicalName + '''' + ' TO N’’X:\DATA1\'+ @LogicalName + '.ldf' +'''' end --Increment the counter   set @counter = @counter + 1 FETCH NEXT FROM MY_CURSOR INTO @LogicalName END   At this point we have populated the varchar(max) variable @RestoreString with a concatenation of all the necessary file names. What we now need to do is to run the sp_executesql stored procedure, to effect the restore.   First, we must place our ‘concatenated string’ into an nvarchar based variable. Obviously this will only work as long as the length of @RestoreString is less than varchar(max) / 2.   set @NRestoreString = @RestoreString EXEC sp_executesql @NRestoreString   Upon completion of this step, the database should be restored to the server. I now close and deallocate the cursor, and to be clean, I would also drop my temp table.   CLOSE MY_CURSOR DEALLOCATE MY_CURSOR GO   Conclusion Restoration of databases on different servers with different physical names and on different drives are a fact of life. Through the use of a few variables and a simple cursor, we may achieve an efficient and effective way to achieve this task.

    Read the article

  • Parallel.For Inconsistency results

    - by ni Gue ???
    I am using VB.net to write a parallel based code. I use Parallel.For to generate pairs of 500 objects or in combination C(500,2) such as the following code; but I found that it didn't always generate all combinations which should be 124750 (shown from variable Counter). No other thread was runing when this code was run. I am using a Win-7 32 Bit desktop with Intel Core i5 CPU [email protected], 3.33 GHz and RAM 2GB. What's wrong with the code and how to solve this problem? Thank You. Dim Counter As Integer = 0 Parallel.For(0, 499, Sub(i) For j As Integer = i + 1 To 499 Counter += 1 Console.Write(i & ":" & j) Next End Sub) Console.Writeline("Iteration number: " & Counter)

    Read the article

  • Trouble converting an MP3 file to a WAV file using Naudio

    - by WebDevHobo
    Naudio Library: http://naudio.codeplex.com/ I'm trying to convert an MP3 file to a WAV file, but I've run in to a small error. I know what's going wrong, but I don't really know how to go about fixing it. Here's the piece of code I'm running: private void button1_Click(object sender, EventArgs e) { using(Mp3FileReader reader = new Mp3FileReader(@"path\to\MP3")) { using(WaveFileWriter writer = new WaveFileWriter(@"C:\test.wav", new WaveFormat())) { int counter = 0; while(reader.Read(test, counter, test.Length + counter) != 0) { writer.WriteData(test, counter, test.Length + counter); counter += 512; } } } } reader.Read() goes into the Mp3FileReader class, and the method looks like this: public override int Read(byte[] sampleBuffer, int offset, int numBytes) { if (numBytes % waveFormat.BlockAlign != 0) //throw new ApplicationException("Must read complete blocks"); numBytes -= (numBytes % waveFormat.BlockAlign); return mp3Stream.Read(sampleBuffer, offset, numBytes); } mp3Stream is an object of the Stream class. The problem is: I'm getting an ArgumentException. MSDN says that this is because the sum of offset and numBytes is greater than the length of sampleBuffer. Documentation: http://msdn.microsoft.com/en-us/library/system.io.stream.read.aspx This happens because I increase the counter every time, but the size of the byte array test remains the same. What I've been wondering is: do I need to increase the size of the array dynamically, or do I need to find out the needed size at the beginning and set it right away? And also, instead of 512, the method in Mp3FileReader returns 365 the first time. Which is the size of a whole block. But I'm writing the full 512. I'm basically just using the read to check if I'm not at the end of the file yet. Do I need to catch the return value and do something with that, or am I good here?

    Read the article

  • T-SQL While Loop and concatenation

    - by JustinT
    I have a SQL query that is supposed to pull out a record and concat each to a string, then output that string. The important part of the query is below. DECLARE @counter int; SET @counter = 1; DECLARE @tempID varchar(50); SET @tempID = ''; DECLARE @tempCat varchar(255); SET @tempCat = ''; DECLARE @tempCatString varchar(5000); SET @tempCatString = ''; WHILE @counter <= @tempCount BEGIN SET @tempID = ( SELECT [Val] FROM #vals WHERE [ID] = @counter); SET @tempCat = (SELECT [Description] FROM [Categories] WHERE [ID] = @tempID); print @tempCat; SET @tempCatString = @tempCatString + '<br/>' + @tempCat; SET @counter = @counter + 1; END When the script runs, @tempCatString outputs as null while @tempCat always outputs correctly. Is there some reason that concatenation won't work inside a While loop? That seems wrong, since incrementing @counter works perfectly. So is there something else I'm missing?

    Read the article

  • C# StackOverflowException

    - by KSwift87
    Problem: I am trying to update a List. If a certain item's ID already exists in the List, I want to add onto that item's quantity. If not, then I want to add another item to the list. cart = (List<OrderItem>)Session["cart"]; for(int counter = cart.Count-1; counter >= 0; counter--) { if (cart[counter].productId == item.productId) { cart[counter].productQuantity += item.productQuantity; } else if (counter == 0) { cart.Add(item); } } "cart[counter]" and "item" represent an instance(s) of a custom object of mine. Currently when I finally find a matching ID, everything APPEARS as though it should work, but I get a StackOverflowException thrown in my custom object class. public int productQuantity { get { return _productQuantity; } set { productQuantity = value; } } It gets thrown right at the open-bracket of the "set". Could somebody please tell me what the heck is wrong because I've been going at this for the past 2+ hours to no avail. Thank you in advance.

    Read the article

  • Programmatically added SummaryLinkWebPart doesn't display Links

    - by Mac
    Hi All, I am using below code to Add SummaryLinkWebPart to a Page and also adding few links to that wehbpart. I can see the webpart now on the page but it doesn't have any links inside it. Does anyone know what is wrong with the code? SPLimitedWebPartManager wpm = web.GetLimitedWebPartManager("Pages/default.aspx",PersonalizationScope.Shared); SummaryLinkWebPart slwp = new SummaryLinkWebPart(); for (int counter = 0; counter < list.ItemCount; counter++) { urlField = list.Items[counter]["URL"].ToString().Split(','); SummaryLink link = new SummaryLink(urlField[1].Trim()); slwp.SummaryLinkValue.SummaryLinks.Add(link); slwp.SummaryLinkValue.SummaryLinks[counter].OpenInNewWindow = true; slwp.SummaryLinkValue.SummaryLinks[counter].LinkUrl = urlField[0].Trim(); slwp.SummaryLinkValue.SummaryLinks[counter].Description = urlField[1]; slwp.Style = "Image on left"; Console.WriteLine(link.LinkUrl + link.Title); } wpm.AddWebPart(slwp, lvwp.ZoneID, slwp.ZoneIndex + 1);

    Read the article

  • java - coding errors causing endless loop

    - by Daniel Key
    Im attempting to write a program that takes a population's birthrate and deathrate and loops the annual population until it either reaches 0 or doubles. My problem it that it continuously loops an endless amount of illegible numbers and i cant fix it. please help. //***************************************** //This program displays loop statements //Written by: Daniel Kellogg //Last Edited: 9/28/12 //**************************************** import java.util.Scanner; public class Hwk6 { public static void main (String[] args) { int currentYear, currentPopulation; double birthRate, deathRate; Scanner stdin = new Scanner(System.in); System.out.println("\nPopulation Estimator\n"); System.out.println("Enter Year"); currentYear = stdin.nextInt(); System.out.println("Enter Current Population"); currentPopulation = stdin.nextInt(); System.out.println("Enter Birthrate of Population"); birthRate = stdin.nextDouble(); System.out.println("Enter Deathrate of Population"); deathRate = stdin.nextDouble(); int counter = currentPopulation; System.out.println("Population: "); while (currentPopulation != -1) while (counter < currentPopulation * 2) { System.out.print(counter + " "); counter = counter + (int)(counter * birthRate - counter * deathRate); } System.exit(0); } }

    Read the article

  • How can I convert seconds to minutes in jQuery while updating an element with the current time?

    - by pghtech
    So I see a number of ways to display allot of seconds in a (static) hr/min/sec. However, I am trying to produce a visual count down timer: $('#someelement').html(minCounter + ' minutes ' + ((secCounter == 0) ? '' : (secCounter + ' seconds'))); My counter is reduced inside a SetInterval that triggers ever 1 second: //....... var counter = redirectTimer; jQuery('#WarningDialogMsg').html(minCounter + ' minutes ' + ((secCounter == 0) ? '' : (secCounter + ' seconds'))); //........ SetInternval( function() { counter -= 1; secCounter = Math.floor(counter % 60); minCounter = Math.floor(counter / 60); //....... $('#someelement').html(minCounter + ' minutes ' + ((secCounter == 0) ? '' : (secCounter + ' seconds'))); }, 1000) It is a two minute counter but I don't want to display 120 seconds. I want to display 1 : 59 (and counting down). I have managed to get it to work using the above, but my main question is: is there a more elegant way to accomplish the above? (note: I am redirecting once "counter == 0").

    Read the article

  • Implementing Tagging System with PHP and mySQL. Caching help!!!

    - by Hamid Sarfraz
    With reference to this post: http://stackoverflow.com/questions/2122546/how-to-implement-tag-counting I have implemented the suggested 3 table tagging system completely. To count the number of Articles per tag, i am using another column named tagArticleCount in the tag definition table. (other columns are tagId, tagText, tagUrl, tagArticleCount). If i implement realtime editing of this table, so that whenever user adds another tag to article or deletes an existing tag, the tag_definition_table is updated to update the counter of the added/removed tag. This will cost an extra query each time any modification is made. (at the same time, related link entry for tag and article is deleted from tagLinkTable). An alternative to this is not allowing any real time editing to the counter, instead use CRONs to update counter of each tag after a specified time period. Here comes the problem that i want to discuss. This can be seen as caching the article count in database. Can you please help me find a way to present the articles in a list when a tag is explored and when the article counter for that tag is not up to date. For example: 1. Counter shows 50 articles, but there are infact 55 entries in the tag link table (that links tags and articles). 2. Counter shows 50 articles, but there are infact 45 extries in the tag link table. How to handle these 2 scenerios given in example. I am going to use APC to keep cache of these counters. Consider it too in your solution. Also discuss performance in the realtime / CRONNED counter updates.

    Read the article

  • lock statement not working when there is a loop inside it?

    - by Ngu Soon Hui
    See this code: public class multiply { public Thread myThread; public int Counter { get; private set; } public string name { get; private set; } public void RunConsolePrint() { lock(this) { RunLockCode("lock"); } } private void RunLockCode(string lockCode) { Console.WriteLine("Now thread "+lockCode+" " + name + " has started"); for (int i = 1; i <= Counter; i++) { Console.WriteLine(lockCode+" "+name + ": count has reached " + i + ": total count is " + Counter); } Console.WriteLine("Thread " + lockCode + " " + name + " has finished"); } public multiply(string pname, int pCounter) { name = pname; Counter = pCounter; myThread = new Thread(new ThreadStart(RunConsolePrint)); } } And this is the test run code: static void Main(string[] args) { int counter = 50; multiply m2 = new multiply("Second", counter); multiply m1 = new multiply("First", counter); m1.myThread.Start(); m2.myThread.Start(); Console.ReadLine(); } I would expect that m2 must execute from start to finish before m1 starts executing, or vice versa, because of the lock statement. But the result I found was the call to lock first and lock second was intermingled together, i.e., something like this Now thread lock First has started Now thread lock Second has started lock First: Count has reached 1: total count is 50 lock First: Count has reached 2: total count is 50 lock Second: Count has reached 1: total count is 50 What did I do wrong?

    Read the article

  • I'm writing a diagnostic app for iOS that loads a predetermined set of webpages and records the time it takes for the page to render on the device.

    - by user1754840
    I'm writing a sort of diagnostic app for iOS that opens a predetermined list of websites and records the elapsed time it takes each to load. I have the app open a UIWebView within a ViewController. Here are the important bits of the ViewController source: - (void)viewDidLoad { [super viewDidLoad]; DataClass *obj = [DataClass getInstance]; obj.startOfTest = [NSDate date]; //load the first webpage NSString *urlString = [websites objectAtIndex:obj.counter]; //assume firstWebsite is already instantiated and counter is initially set to zero obj.counter = obj.counter + 1; NSURL *url = [NSURL URLWithString:urlString]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; [obj.websiteStartTimes addObject:[NSDate date]]; [webView loadRequest:request]; } - (void)webViewDidFinishLoading:(UIWebView *)localWebView{ DataClass *obj = [DataClass getInstance]; //gets 'global' variables if(!webView.loading){ NSString *urlString = [websites objectAt:obj.counter]; obj.counter = obj.counter + 1; NSURL *url = [NSURL URLWithString:urlString]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; [obj.websiteStartTimes addObject:[NSDate date]]; [webView loadRequest:request]; } The problem with this code is that it seems to load the next website before the one before it has finished. I would have thought that both the call to webViewDidFinishLoading AND the if statement within that would ensure that the website would be done, but that's not the case. I've noticed that sometimes, a single website will invoke the didFinishLoading method more than once, but it would only enter the if statement once. For example, if I have a list of ten websites, the webView would only really show the 3rd and the 6th website on the list and then indicate that it was "done" rendering them all. What else can I do to ensure that a website is done loading completely and rendered to the screen before the app moves on to the next one?

    Read the article

  • Why can't Logman start?

    - by Bill Paetzke
    I'm setting up my first logman counter. But it's not working! There is some file or folder permissions problem. Or maybe I wrote the create-counter statement wrong. Here's my counter commands: logman create counter BillTest -si 30 -v nnnnnn -max 200 -o "C:\Temp" -c "\Processor(*)\*" "\Memory(*)\*" "\LogicalDisk(*)\*" logman start BillTest The first command works. It says counter creation successful. The second command fails: Collection "BillTest" did not start, check the application event log for any errors Here's the error in the Event Viewer: The service was unable to open the log file C:\Temp_000001.blg for log BillTest and will be stopped. Check the log folder for existence, spelling, permissions, and ensure that no other logs or applications are writing to this log file. You can reenter the log file name using the configuration program. This log will not be started. The error returned is: Access is denied. I verified that C:\Temp exists. I'm not a permissions guru, but I did set all the accounts in the security tab of that folder to "full control." Still, the logman start command failed with the same error. I noticed that it was trying to write to C:\Temp_000001.blg instead of C:\Temp\000001.blg. That might be part of the problem. So, I tried to update my counter to "C:\Temp\" instead of "C:\Temp", but that failed with a path-invalid error. Also, all the examples I saw online used did not put a trailing slash. So, no dice there. I tried this on my machine (Windows XP) and my dev server (Windows Server 2003). Both failed with the same error. How can I fix this?

    Read the article

  • Prevent 'Run-time error '7' out of memory' error in Excel when using macro

    - by MasterJedi
    I keep getting this error whenever I run a macro in my excel file. Is there any way I can prevent this? My code is below. Debugging highlights the following line as the issue: ActiveSheet.Shapes.SelectAll My macro: Private Sub Save() Dim sh As Worksheet ActiveWorkbook.Sheets("Report").Copy 'Create new workbook with Sheets("Report"(2)) as only sheet. Set sh = ActiveWorkbook.Sheets(1) 'Set the new sheet to a variable. New workbook is now active workbook. sh.Name = sh.Range("B9") & "_" & Format(Date, "mmyyyy") 'Rename the new sheet to B9 value + date. With sh.UsedRange.Cells .Value = .Value 'eliminate all formulas .Validation.Delete 'remove all validation .FormatConditions.Delete 'remove all conditional formatting ActiveSheet.Buttons.Delete ActiveSheet.Shapes.SelectAll Selection.Delete lrow = Range("I" & Rows.Count).End(xlUp).Row 'select rows from bottom up to last containing data in column I Rows(lrow + 1 & ":" & Rows.Count).Delete 'delete rows with no data in column I Application.ScreenUpdating = False .Range("A410:XFD1048576").Delete Shift:=xlUp 'delete all cells outwith report range Application.ScreenUpdating = True Dim counter Dim nameCount nameCount = ActiveWorkbook.Names.Count counter = nameCount Do While counter > 0 ActiveWorkbook.Names(counter).Delete counter = counter - 1 Loop 'remove named ranges from workbook End With ActiveWorkbook.SaveAs "\\Marko\Report\" & sh.Name & ".xlsx" 'Save new workbook using same name as new sheet. ActiveWorkbook.Close False 'Close the new workbook. MsgBox ("Export complete. Choose the next ADP in cell B9 and click 'Calculate'.") 'Display message box to inform user that report has been saved. End Sub Not sure how to make this more efficient or to prevent this error.

    Read the article

  • How can I set a counter column value in MySQL?

    - by Jon Tackabury
    I have a table with a "SortID" column that is numbered using consecutive numbers. Whenever a row is deleted, it leaves a gap. Is there a way using pure SQL to update the rows with their row number? Something like this: UPDATE tbl SET SortID={rowindex} ORDER BY SortID (I realize this isn't valid SQL, that's why I'm asking for help) This should set the first row to #1, the second row to #2... etc. Is this possible using SQL? Please forgive the poorly worded question, I'm not really sure the best way to ask this. :)

    Read the article

  • How does the event dispatch thread work?

    - by Roman
    With the help of people on stackoverflow I was able to get the following working code of the simples GUI countdown (it just displays a window counting down seconds). My main problem with this code is the invokeLater stuff. As far as I understand the invokeLater send a task to the event dispatching thread (EDT) and then the EDT execute this task whenever it "can" (whatever it means). Is it right? To my understanding the code works like that: In the main method we use invokeLater to show the window (showGUI method). In other words, the code displaying the window will be executed in the EDT. In the main method we also start the counter and the counter (by construction) is executed in another thread (so it is not in the event dispatching thread). Right? The counter is executed in a separate thread and periodically it calls updateGUI. The updateGUI is supposed to update GUI. And GUI is working in the EDT. So, updateGUI should also be executed in the EDT. It is why the code for the updateGUI is inclosed in the invokeLater. Is it right? What is not clear to me is why we call the counter from the EDT. Anyway it is not executed in the EDT. It starts immediately a new thread and the counter is executed there. So, why we cannot call the counter in the main method after the invokeLater block? import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.SwingUtilities; public class CountdownNew { static JLabel label; // Method which defines the appearance of the window. public static void showGUI() { JFrame frame = new JFrame("Simple Countdown"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); label = new JLabel("Some Text"); frame.add(label); frame.pack(); frame.setVisible(true); } // Define a new thread in which the countdown is counting down. public static Thread counter = new Thread() { public void run() { for (int i=10; i>0; i=i-1) { updateGUI(i,label); try {Thread.sleep(1000);} catch(InterruptedException e) {}; } } }; // A method which updates GUI (sets a new value of JLabel). private static void updateGUI(final int i, final JLabel label) { SwingUtilities.invokeLater( new Runnable() { public void run() { label.setText("You have " + i + " seconds."); } } ); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { showGUI(); counter.start(); } }); } }

    Read the article

  • Why does Scala apply thunks automatically, sometimes?

    - by Anonymouse
    At just after 2:40 in ShadowofCatron's Scala Tutorial 3 video, it's pointed out that the parentheses following the name of a thunk are optional. "Buh?" said my functional programming brain, since the value of a function and the value it evaluates to when applied are completely different things. So I wrote the following to try this out. My thought process is described in the comments. object Main { var counter: Int = 10 def f(): Int = { counter = counter + 1; counter } def runThunk(t: () => Int): Int = { t() } def main(args: Array[String]): Unit = { val a = f() // I expect this to mean "apply f to no args" println(a) // and apparently it does val b = f // I expect this to mean "the value f", a function value println(b) // but it's the value it evaluates to when applied to no args println(b) // and the evaluation happens immediately, not in the call runThunk(b) // This is an error: it's not println doing something funny runThunk(f) // Not an error: seems to be val doing something funny } }   To be clear about the problem, this Scheme program (and the console dump which follows) shows what I expected the Scala program to do. (define counter (list 10)) (define f (lambda () (set-car! counter (+ (car counter) 1)) (car counter))) (define runThunk (lambda (t) (t))) (define main (lambda args (let ((a (f)) (b f)) (display a) (newline) (display b) (newline) (display b) (newline) (runThunk b) (runThunk f)))) > (main) 11 #<procedure:f> #<procedure:f> 13   After coming to this site to ask about this, I came across this answer which told me how to fix the above Scala program: val b = f _ // Hey Scala, I mean f, not f() But the underscore 'hint' is only needed sometimes. When I call runThunk(f), no hint is required. But when I 'alias' f to b with a val then apply it, it doesn't work: the evaluation happens in the val; and even lazy val works this way, so it's not the point of evaluation causing this behaviour.   That all leaves me with the question: Why does Scala sometimes automatically apply thunks when evaluating them? Is it, as I suspect, type inference? And if so, shouldn't a type system stay out of the language's semantics? Is this a good idea? Do Scala programmers apply thunks rather than refer to their values so much more often that making the parens optional is better overall? Examples written using Scala 2.8.0RC3, DrScheme 4.0.1 in R5RS.

    Read the article

  • How to attach boost::shared_ptr (or another smart pointer) to reference counter of object's parent?

    - by Checkers
    I remember encountering this concept before, but can't find it in Google now. If I have an object of type A, which directly embeds an object of type B: class A { B b; }; How can I have a smart pointer to B, e. g. boost::shared_ptr<B>, but use reference count of A? Assume an instance of A itself is heap-allocated I can safely get its shared count using, say, enable_shared_from_this.

    Read the article

  • How can I make my counter look less fake?

    - by Eddy Pronk
    I'm using this bit of code to display the number of users on a site. My customer is complaining it looks fake. Any suggestions? var visitors = 187584; var updateVisitors = function() { visitors++; var vs = visitors.toString(), i = Math.floor(vs.length / 3), l = vs.length % 3; while (i-->0) if (!(l==0&&i==0)) vs = vs.slice(0,i*3+l) + ',' + vs.slice(i*3+l); $('#count').text(vs); setTimeout(updateVisitors, Math.random()*2000); }; setTimeout(updateVisitors, Math.random()*2000);

    Read the article

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