Search Results

Search found 616 results on 25 pages for 'divide'.

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

  • Placement/Positioning/Alignment of UIScrollView w.r.t. length of Title NSString

    - by Shoaibi
    I have a scenario where i show stuff like: ----------------------------------- titleview (UITextView) ______________ tArea (UIScrollView) ttextview (UITextView) ----------------------------------- Now here is the condition: Length of titleview's text is dynamic, varies based on user input. Because of the condition I have trouble placing tArea e.g. UIScrollView on the screen, it either appears way too below than the titleview, or overlaps it. Previously what i did: Count the number of characters in titleview.text.length and divide them by 27 (e.g. characters in one line when using boldSystemFontOfSize:20) and multiply by 10 to get the starting X of tArea e.g. UIScrollView. But that sucked. Because i had to duplicate code for rotation to landscape. What do i have now? : CGSize titlesize = [title sizeWithFont:[UIFont systemFontOfSize:20] constrainedToSize:CGSizeMake(5, 90) lineBreakMode:UILineBreakModeWordWrap]; ttitleview = [[UITextView alloc] initWithFrame:CGRectMake(5, 5, 310,titlesize.height)]; ttitleview.text = title; ttitleview.font = [UIFont boldSystemFontOfSize:20]; ttitleview.backgroundColor = [UIColor clearColor]; ttitleview.editable = NO; [self.view addSubview:ttitleview]; CGSize textsize = [ttext sizeWithFont:[UIFont systemFontOfSize:20] constrainedToSize:CGSizeMake(5, 350) lineBreakMode:UILineBreakModeWordWrap]; tArea = [[UIScrollView alloc] initWithFrame:CGRectMake(5, titlesize.height, 310, 230)]; tArea.contentSize = CGSizeMake(310, textsize.height+20); tArea.pagingEnabled = FALSE; tArea.scrollEnabled = TRUE; tArea.backgroundColor = [UIColor clearColor]; [self.view addSubview:tArea]; ttextview = [[UITextView alloc] initWithFrame:CGRectMake(0, 0, 310, textsize.height + 20)]; ttextview.text = ttext; ttextview.font = [UIFont systemFontOfSize:20]; ttextview.backgroundColor = [UIColor clearColor]; ttextview.editable = NO; [tArea addSubview:ttextview]; But its no use. Looking for an elegant solution than this.

    Read the article

  • Caching sitemaps in django

    - by michuk
    I implemented a simple sitemap class using django's default sitemap app. As it was taking a long time to execute, I added manual caching: class ShortReviewsSitemap(Sitemap): changefreq = "hourly" priority = 0.7 def items(self): # try to retrieve from cache result = get_cache(CACHE_SITEMAP_SHORT_REVIEWS, "sitemap_short_reviews") if result!=None: return result result = ShortReview.objects.all().order_by("-created_at") # store in cache set_cache(CACHE_SITEMAP_SHORT_REVIEWS, "sitemap_short_reviews", result) return result def lastmod(self, obj): return obj.updated_at The problem is that memcache allows only max 1MB object. This one was bigger that 1MB, so storing into cache failed: >7 SERVER_ERROR object too large for cache The problem is that django has an automated way of deciding when it should divide the sitemap file into smalled ones. According to the docs (http://docs.djangoproject.com/en/dev/ref/contrib/sitemaps/): You should create an index file if one of your sitemaps has more than 50,000 URLs. In this case, Django will automatically paginate the sitemap, and the index will reflect that. What do you think would be the best way to enable caching sitemaps? - Hacking into django sitemaps framework to restrict a single sitemap size to, let's say, 10,000 records seems like the best idea. Why was 50,000 chosen in the first place? Google advice? random number? - Or maybe there is a way to allow memcached store bigger files? - Or perhaps onces saved, the sitemaps should be made available as static files? This would mean that instead of caching with memcached I'd have to manually store the results in the filesystem and retrieve them from there next time when the sitemap is requested (perhaps cleaning the directory daily in a cron job). All those seem very low level and I'm wondering if an obvious solution exists...

    Read the article

  • A couple of questions about NHibernate's GuidCombGenerator

    - by Eyvind
    The following code can be found in the NHibernate.Id.GuidCombGenerator class. The algorithm creates sequential (comb) guids based on combining a "random" guid with a DateTime. I have a couple of questions related to the lines that I have marked with *1) and *2) below: private Guid GenerateComb() { byte[] guidArray = Guid.NewGuid().ToByteArray(); // *1) DateTime baseDate = new DateTime(1900, 1, 1); DateTime now = DateTime.Now; // Get the days and milliseconds which will be used to build the byte string TimeSpan days = new TimeSpan(now.Ticks - baseDate.Ticks); TimeSpan msecs = now.TimeOfDay; // *2) // Convert to a byte array // Note that SQL Server is accurate to 1/300th of a millisecond so we divide by 3.333333 byte[] daysArray = BitConverter.GetBytes(days.Days); byte[] msecsArray = BitConverter.GetBytes((long) (msecs.TotalMilliseconds / 3.333333)); // Reverse the bytes to match SQL Servers ordering Array.Reverse(daysArray); Array.Reverse(msecsArray); // Copy the bytes into the guid Array.Copy(daysArray, daysArray.Length - 2, guidArray, guidArray.Length - 6, 2); Array.Copy(msecsArray, msecsArray.Length - 4, guidArray, guidArray.Length - 4, 4); return new Guid(guidArray); } First of all, for *1), wouldn't it be better to have a more recent date as the baseDate, e.g. 2000-01-01, so as to make room for more values in the future? Regarding *2), why would we care about the accuracy for DateTimes in SQL Server, when we only are interested in the bytes of the datetime anyway, and never intend to store the value in an SQL Server datetime field? Wouldn't it be better to use all the accuracy available from DateTime.Now?

    Read the article

  • What's wrong with debugging in Eclipse on Android?

    - by Sebastian Dwornik
    I've obviously been spoiled by Visual Studio, because although I'm just learning Android and the Eclipse environment, debugging apps in Eclipse is becoming a serious detriment to further development. For example, Eclipse will compile this divide by zero just fine: public class Lesson2Main extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate (savedInstanceState); int i = 1 / 0; TextView tv = new TextView (this); tv.setText ("Hello, Android!"); setContentView (tv); } } And then, when it executes it under the debugger, I will get a full screen of useless debug info, non of which actually points me to the specific line containing the error. The stackTrace is null within the exception ('e') info tree, and it simply states a message stating 'ArithmeticException'. (that's nice, how about you point me in the direction of where you found it!?) I've looked all over the screen and am baffled that this IDE can't get this right. Does developing with Eclipse resort everyone back to 1991 with printf() like logging at every interval then to track down bugs? Seriously. Is there a configuration or plug-in that I'm missing to help with this? I haven't tested this case with XCode, but if the iPhone dev. IDE handles this more like Visual Studio, then no wonder the Android marketplace has so few apps. I'm excited about Android, but it seems that Eclipse is getting in the way.

    Read the article

  • Displaying recntangles in game window with XNA

    - by blerh
    I want to divide my game grid into an array of rectangles. Each rectangle is 40x40 and there are 14 rectangles in every column, with a total of 25 columns. This covers a game area of 560x1000. This is the code I have set up to make the first column of rectangles on the game grid: Rectangle[] gameTiles = new Rectangle[15]; for (int i = 0; i <= 15; i++) { gameTiles[i] = new Rectangle(0, i * 40, 40, 40); } I'm pretty sure this works, but of course I cannot confirm it because rectangles do not render on the screen for me to physically see them. What I would like to do for debugging purposes is to render a border, or fill the rectangle with color so I can see it on the game itself, just to make sure this works. Is there a way to make this happen? Or any relatively simple way I can just make sure that this works? Thank you very much.

    Read the article

  • Nested namespaces, correct static library design issues

    - by PeterK
    Hello all, I'm currently in the process of developing a fairly large static library which will be used by some tools when it's finished. Now since this project is somewhat larger than anything i've been involved in so far, I realized its time to think of a good structure for the project. Using namespaces is one of those logical steps. My current approach is to divide the library into parts (which are not standalone, but their purpose calls for such a separation). I have a 'core' part which now just holds some very common typedefs and constants (used by many different parts of the library). Other parts are for example some 'utils' (hash etc.), file i/o and so on. Each of these parts has its own namespace. I have nearly finished the 'utils' part and realized that my approach probably is not the best. The problem (if we want to call it so) is that in the 'utils' namespace i need something from the 'core' namespace which results in including the core header files and many using directives. So i began to think that this probably is not a good thing and should be changed somehow. My first idea is to use nested namespaces as to have something like core::utils. Since this will require some heavy refactoring i want to ask here first. What do you think? How would you handle this? Or more generally: How to correctly design a static library in terms of namespaces and code organization? If there are some guidelines or articles about it, please mentoin them too. Thanks. Note: i'm quite sure that there are more good approaches than just one. Feel free to post your ideas, suggestions etc. Since i'm designing this library i want it to be really good. The goal is to make it as clean and FAST as possible. The only problem is that i will have to integrate a LOT of existing code and refactor it, which will really be a painful process (sigh) - thats why good structure is so important)

    Read the article

  • How to increase the performance of a loop which runs for every 'n' minutes.

    - by GustlyWind
    Hi Giving small background to my requirement and what i had accomplished so far: There are 18 Scheduler tasks run at regular intervals (least being 30 mins) takes input of nearly 5000 eligible employees run into a static method for iteration and generates a mail content for that employee and mails. An average task takes about 9 min multiplied by 18 will be roughly 162 mins meanwhile there would be next tasks which will be in queue (I assume). So my plan is something like the below loop try { // Handle Arraylist of alerts eligible employees Iterator employee = empIDs.iterator(); while (employee.hasNext()) { ScheduledImplementation.getInstance().sendAlertInfoToEmpForGivenAlertType((Long)employee.next(), configType,schedType); } } catch (Exception vEx) { _log.error("Exception Caught During sending " + configType + " messages:" + configType, vEx); } Since I know how many employees would come to my method I will divide the while loop into two and perform simultaneous operations on two or three employees at a time. Is this possible. Or is there any other ways I can improve the performance. Some of the things I had implemented so far 1.Wherever possible made methods static and variables too Didn't bother to catch exceptions and send back because these are background tasks. (And I assume this improves performance) Get the DB values in one query instead of multiple hits. If am successful in optimizing the while loop I think i can save couple of mins. Thanks

    Read the article

  • Refactoring exercise with generics

    - by Berryl
    I have a variation on a Quantity (Fowler) class that is designed to facilitate conversion between units. The type is declared as: public class QuantityConvertibleUnits<TFactory> where TFactory : ConvertableUnitFactory, new() { ... } In order to do math operations between dissimilar units, I convert the right hand side of the operation to the equivalent Quantity of whatever unit the left hand side is in, and do the math on the amount (which is a double) before creating a new Quantity. Inside the generic Quantity class, I have the following: protected static TQuantity _Add<TQuantity>(TQuantity lhs, TQuantity rhs) where TQuantity : QuantityConvertibleUnits<TFactory>, new() { var toUnit = lhs.ConvertableUnit; var equivalentRhs = _Convert<TQuantity>(rhs.Quantity, toUnit); var newAmount = lhs.Quantity.Amount + equivalentRhs.Quantity.Amount; return _Convert<TQuantity>(new Quantity(newAmount, toUnit.Unit), toUnit); } protected static TQuantity _Subtract<TQuantity>(TQuantity lhs, TQuantity rhs) where TQuantity : QuantityConvertibleUnits<TFactory>, new() { var toUnit = lhs.ConvertableUnit; var equivalentRhs = _Convert<TQuantity>(rhs.Quantity, toUnit); var newAmount = lhs.Quantity.Amount - equivalentRhs.Quantity.Amount; return _Convert<TQuantity>(new Quantity(newAmount, toUnit.Unit), toUnit); } ... same for multiply and also divide I need to get the typing right for a concrete Quantity, so an example of an add op looks like: public static ImperialLengthQuantity operator +(ImperialLengthQuantity lhs, ImperialLengthQuantity rhs) { return _Add(lhs, rhs); } The question is those verbose methods in the Quantity class. The only change between the code is the math operator (+, -, *, etc.) so it seems that there should be a way to refactor them into a common method, but I am just not seeing it. How can I refactor that code? Cheers, Berryl

    Read the article

  • How do you organise your MVC controller tests?

    - by Andrew Bullock
    I'm looking for tidy suggestions on how people organise their controller tests. For example, take the "add" functionality of my "Address" controller, [AcceptVerbs(HttpVerbs.Get)] public ActionResult Add() { var editAddress = new DTOEditAddress(); editAddress.Address = new Address(); editAddress.Countries = countryService.GetCountries(); return View("Add", editAddress); } [RequireRole(Role = Role.Write)] [AcceptVerbs(HttpVerbs.Post)] public ActionResult Add(FormCollection form) { // save code here } I might have a fixture called "when_adding_an_address", however there are two actions i need to test under this title... I don't want to call both actions in my Act() method in my fixture, so I divide the fixture in half, but then how do I name it? "When_adding_an_address_GET" and "When_adding_an_address_POST"? things just seems to be getting messy, quickly. Also, how do you deal with stateless/setupless assertions for controllers, and how do you arrange these wrt the above? for example: [Test] public void the_requesting_user_must_have_write_permissions_to_POST() { Assert.IsTrue(this.SubjectUnderTest.ActionIsProtectedByRole(c => c.Add(null), Role.Write)); } This is custom code i know, but you should get the idea, it simply checks that a filter attribute is present on the method. The point is it doesnt require any Arrange() or Act(). Any tips welcome! Thanks

    Read the article

  • DSP - Filter sweep effect

    - by Trap
    I'm implementing a 'filter sweep' effect (I don't know if it's called like that). What I do is basically create a low-pass filter and make it 'move' along a certain frequency range. To calculate the filter cut-off frequency at a given moment I use a user-provided linear function, which yields values between 0 and 1. My first attempt was to directly map the values returned by the linear function to the range of frequencies, as in cf = freqRange * lf(x). Although it worked ok it looked as if the sweep ran much faster when moving through low frequencies and then slowed down during its way to the high frequency zone. I'm not sure why is this but I guess it's something to do with human hearing perceiving changes in frequency in a non-linear manner. My next attempt was to move the filter's cut-off frequency in a logarithmic way. It works much better now but I still feel that the filter doesn't move at a constant perceived speed through the range of frequencies. How should I divide the frequency space to obtain a constant perceived sweep speed? Thanks in advance.

    Read the article

  • Bootstrap: show/hide column divs with checkbox and change column span

    - by Berto Alvaro
    I'm using Bootstrap 3.2. I'm trying to figure out if there's a way to show/hide a "col-sz-#" div AND change the "col-sz-#" class in visible divs to resize them to fit the container using checkbox style buttons for each column. For example, if I start with <div class="row"> <div class="col-md-2">...</div> <div class="col-md-2">...</div> <div class="col-md-2">...</div> <div class="col-md-2">...</div> <div class="col-md-2">...</div> <div class="col-md-2">...</div> </div> Then if hide 2 of them and the others resize: <div class="row"> <div class="col-md-2 hidden">...</div> <div class="col-md-2 hidden">...</div> <div class="col-md-3">...</div> <div class="col-md-3">...</div> <div class="col-md-3">...</div> <div class="col-md-3">...</div> </div> if the total columns can't divide 12 evenly like 5, then it wouldn't change.

    Read the article

  • How to calculate this string-dissimilarity function efficiently?

    - by ybungalobill
    Hello, I was looking for a string metric that have the property that moving around large blocks in a string won't affect the distance so much. So "helloworld" is close to "worldhello". Obviously Levenshtein distance and Longest common subsequence don't fulfill this requirement. Using Jaccard distance on the set of n-grams gives good results but has other drawbacks (it's a pseudometric and higher n results in higher penalty for changing single character). [original research] As I thought about it, what I'm looking for is a function f(A,B) such that f(A,B)+1 equals the minimum number of blocks that one have to divide A into (A1 ... An), apply a permutation on the blocks and get B: f("hello", "hello") = 0 f("helloworld", "worldhello") = 1 // hello world -> world hello f("abba", "baba") = 2 // ab b a -> b ab a f("computer", "copmuter") = 3 // co m p uter -> co p m uter This can be extended for A and B that aren't necessarily permutations of each other: any additional character that can't be matched is considered as one additional block. f("computer", "combuter") = 3 // com uter -> com uter, unmatched: p and b. Observing that instead of counting blocks we can count the number of pairs of indices that are taken apart by a permutation, we can write f(A,B) formally as: f(A,B) = min { C(P) | P:|A|?|B|, P is bijective, ?i?dom(P) A[P(i)]=B[P(i)] } C(P) = |A| + |B| - |dom(P)| - |{ i | i,i+1?dom(P) and P(i)+1=P(i+1) }| - 1 The problem is... guess what... ... that I'm not able to calculate this in polynomial time. Can someone suggest a way to do this efficiently? Or perhaps point me to already known metric that exhibits similar properties?

    Read the article

  • exception in thread "main" java.lang.NoclassDefFoundError: cal/class

    - by Gaurav
    enter import java.io.*; class eval { double add(double a,double b) { return (a+b); } double sub(double a,double b) { return (a-b); } double mul(double a,double b) { return (a*b); } double div(double a,double b) { return (a/b); } } class cal extends eval { public static void main(String args[])throws IOException { eval a1=new eval(); try{ System.out.println("1) Add"); System.out.println("2) Subtract"); System.out.println("3) Multiply"); System.out.println("4) Divide"); System.out.println("5) Enter your choice"); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int ch;ch=Integer.parseInt(br.readLine()); System.out.println("Enter two number"); double a;a=Integer.parseInt(br.readLine()); double b;b=Integer.parseInt(br.readLine()); switch(ch) { case 1: a1.add(a,b); break; case 2: a1.sub(a,b); break; case 3: a1.mul(a,b); break; case 4: a1.div(a,b); break; } } catch (IOException e) { System.out.println("Error occured, please restart application."); } } }

    Read the article

  • division with wrong result

    - by PeterK
    Hi, I am trying to divide integers but get 0 as result. I just do not understand what i am doing wrong. I am using only int's in this example but get the same result testing with float or double. The code i use is: int wrongAnswers = askedQuestions - playerResult; int percentCorrect = (playerResult / askedQuestions) * 100; int percentWrong = (wrongAnswers / askedQuestions) * 100; NSLog(@"askedQuestions: %i", askedQuestions); NSLog(@"playerResult: %i", playerResult); NSLog(@"wrongAnswers: %i", wrongAnswers); NSLog(@"percentCorrect: %i", percentCorrect); NSLog(@"percentWrong: %i", percentWrong); NSLog(@"calc: %i", (wrongAnswers + playerResult)); NSLog(@"wrong answers %: %i %%", ((wrongAnswers / askedQuestions) * 100)); The result i get is: 2011-01-09 16:45:53.411 XX[8296:207] askedQuestions: 5 2011-01-09 16:45:53.412 XX[8296:207] playerResult: 2 2011-01-09 16:45:53.412 XX[8296:207] wrongAnswers: 3 2011-01-09 16:45:53.413 XX[8296:207] percentCorrect: 0 % 2011-01-09 16:45:53.414 XX[8296:207] percentWrong: 0 % 2011-01-09 16:45:53.414 XX[8296:207] calc: 5 2011-01-09 16:45:53.415 XX[8296:207] wrong answers : 0 % I would very much appreciate help :-)

    Read the article

  • Building Stored Procedure to group data into ranges with roughly equal results in each bucket

    - by Len
    I am trying to build one procedure to take a large amount of data and create 5 range buckets to display the data. the buckets ranges will have to be set according to the results. Here is my existing SP GO /****** Object: StoredProcedure [dbo].[sp_GetRangeCounts] Script Date: 03/28/2010 19:50:45 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER PROCEDURE [dbo].[sp_GetRangeCounts] @idMenu int AS declare @myMin decimal(19,2), @myMax decimal(19,2), @myDif decimal(19,2), @range1 decimal(19,2), @range2 decimal(19,2), @range3 decimal(19,2), @range4 decimal(19,2), @range5 decimal(19,2), @range6 decimal(19,2) SELECT @myMin=Min(modelpropvalue), @myMax=Max(modelpropvalue) FROM xmodelpropertyvalues where modelPropUnitDescriptionID=@idMenu set @myDif=(@myMax-@myMin)/5 set @range1=@myMin set @range2=@myMin+@myDif set @range3=@range2+@myDif set @range4=@range3+@myDif set @range5=@range4+@myDif set @range6=@range5+@myDif select @myMin,@myMax,@myDif,@range1,@range2,@range3,@range4,@range5,@range6 select t.range as myRange, count(*) as myCount from ( select case when modelpropvalue between @range1 and @range2 then 'range1' when modelpropvalue between @range2 and @range3 then 'range2' when modelpropvalue between @range3 and @range4 then 'range3' when modelpropvalue between @range4 and @range5 then 'range4' when modelpropvalue between @range5 and @range6 then 'range5' end as range from xmodelpropertyvalues where modelpropunitDescriptionID=@idmenu) t group by t.range order by t.range This calculates the min and max value from my table, works out the difference between the two and creates 5 buckets. The problem is that if there are a small amount of very high (or very low) values then the buckets will appear very distorted - as in these results... range1 2806 range2 296 range3 75 range5 1 Basically I want to rebuild the SP so it creates buckets with equal amounts of results in each. I have played around with some of the following approaches without quite nailing it... SELECT modelpropvalue, NTILE(5) OVER (ORDER BY modelpropvalue) FROM xmodelpropertyvalues - this creates a new column with either 1,2,3,4 or 5 in it ROW_NUMBER()OVER (ORDER BY modelpropvalue) between @range1 and @range2 ROW_NUMBER()OVER (ORDER BY modelpropvalue) between @range2 and @range3 or maybe i could allocate every record a row number then divide into ranges from this?

    Read the article

  • Drawing an honeycomb with as3

    - by vitto
    Hi, I'm trying to create an honeycomb with as3 but I have some problem on cells positioning. I've already created the cells (not with code) and for cycled them to a funcion and send to it the parameters which what I thought was need (the honeycomb cell is allready on a sprite container in the center of the stage). to see the structure of the cycle and which parameters passes, please see the example below, the only thing i calculate in placeCell is the angle which I should obtain directly inside tha called function Note: the angle is reversed but it isn't important, and the color are useful in example only for visually divide cases. My for cycle calls placeCell and passes cell, current_case, counter (index) and the honeycomb cell_lv (cell level). I thought it was what i needed but I'm not skilled in geometry and trigonometry, so I don't know how to position cells correctly: function placeCell (cell:Sprite, current_case:int, counter:int, cell_lv:int):void { var margin:int = 2; var angle:Number = (360 / (cell_lv * 6)) * (current_case + counter); var radius:Number = (cell.width + margin) * cell_lv; cell.x = radius * Math.cos (angle); cell.y = radius * Math.sin (angle); trace ("LV " + cell_lv + " current_case " + current_case + " counter " + counter + " angle " + angle + " radius " + radius) } how can I do to solve it?

    Read the article

  • How to use Caret to tell which line it is in from JTextPane? (Java)

    - by Alex Cheng
    Hi all. Problem: I have CaretListener and DocumentListener listening on a JTextPane. I need an algorithm that is able to tell which line is the caret at in a JTextPane, here's an illustrative example: Result: 3rd line Result: 2nd line Result: 4th line and if the algorithm can tell which line the caret is in the JTextPane, it should be fairly easy to substring whatever that is in between the parentheses as the picture (caret is at character m of metadata): -- This is how I divide the entire text that I retrieved from the JTextPane into sentences: String[] lines = textPane.getText().split("\r?\n|\r", -1); The sentences in the textPane is separated with \n. Problem is, how can I manipulate the caret to let me know at which position and which line it is in? I know the dot of the caret says at which position it is, but I can't tell which line it is at. Assuming if I know which line the caret is, then I can just do lines[<line number>] and manipulate the string from there. In Short: How do I use CaretListener and/or DocumentListener to know which line the caret is currently at, and retrieve the line for further string manipulation? Please help. Thanks. Do let me know if further clarification is needed. Thanks for your time.

    Read the article

  • Displaying rectangles in game window with XNA

    - by blerh
    I want to divide my game grid into an array of rectangles. Each rectangle is 40x40 and there are 14 rectangles in every column, with a total of 25 columns. This covers a game area of 560x1000. This is the code I have set up to make the first column of rectangles on the game grid: Rectangle[] gameTiles = new Rectangle[15]; for (int i = 0; i <= 15; i++) { gameTiles[i] = new Rectangle(0, i * 40, 40, 40); } I'm pretty sure this works, but of course I cannot confirm it because rectangles do not render on the screen for me to physically see them. What I would like to do for debugging purposes is to render a border, or fill the rectangle with color so I can see it on the game itself, just to make sure this works. Is there a way to make this happen? Or any relatively simple way I can just make sure that this works? Thank you very much.

    Read the article

  • Python FTP grabbing and saving images issue

    - by PylonsN00b
    OK So I have been messing with this all day long. I am fairly new to Python FTP. So I have searched through here and came up w/ this: images = notions_ftp.nlst() for image_name in image_names: if found_url == False: try: for image in images: ftp_image_name = "./%s" % image_name if ftp_image_name == image: found_url = True image_name_we_want = image_name except: pass # We failed to find an image for this product, it will have to be done manually if found_url == False: log.info("Image ain't there baby -- SKU: %s" % sku) return False # Hey we found something! Open the image.... notions_ftp.retrlines("RETR %s" % image_name_we_want, open(image_name_we_want, "rb")) 1/0 So I have narrowed the error down to the line before I divide by zero. Here is the error: Traceback (most recent call last): File "<console>", line 6, in <module> File "<console>", line 39, in insert_image IOError: [Errno 2] No such file or directory: '411483CC-IT,IM.jpg' So if you follow the code you will see that the image IS in the directory because image_name_we_want is set if found in that directory listing on the first line of my code. And I KNOW it's there because I am looking at the FTP site myself and ...it's freakin there. So at some point during all of this I got the image to save locally, which is most desired, but I have long since forgot what I used to make it do that. Either way, why does it think that the image isn't there when it clearly finds it in the listing.

    Read the article

  • Macro and array crossing

    - by Thomas
    I am having a problem with a lisp macro. I would like to create a macro which generate a switch case according to an array. Here is the code to generate the switch-case: (defun split-elem(val) `(,(car val) ',(cdr val))) (defmacro generate-switch-case (var opts) `(case ,var ,(mapcar #'split-elem opts))) I can use it with a code like this: (generate-switch-case onevar ((a . A) (b . B))) But when I try to do something like this: (defparameter *operators* '((+ . OPERATOR-PLUS) (- . OPERATOR-MINUS) (/ . OPERATOR-DIVIDE) (= . OPERATOR-EQUAL) (* . OPERATOR-MULT))) (defmacro tokenize (data ops) (let ((sym (string->list data))) (mapcan (lambda (x) (generate-switch-case x ops)) sym))) (tokenize data *operators*) I got this error: *** - MAPCAR: A proper list must not end with OPS. But I don't understand why. When I print the type of ops I get SYMBOL I was expecting CONS, is it related? Also, for my function tokenize how many times the lambda is evaluated (or the macro expanded)?

    Read the article

  • algorithm - How to sort a 0/1 array with 2n/3 comparisons?

    - by Jackson Tale
    In Algorithm Design Manual, there is such an excise 4-26 Consider the problem of sorting a sequence of n 0’s and 1’s using comparisons. For each comparison of two values x and y, the algorithm learns which of x < y, x = y, or x y holds. (a) Give an algorithm to sort in n - 1 comparisons in the worst case. Show that your algorithm is optimal. (b) Give an algorithm to sort in 2n/3 comparisons in the average case (assuming each of the n inputs is 0 or 1 with equal probability). Show that your algorithm is optimal. For (a), I think it is fairly easy. I can choose a[n-1] as pivot, then do something like in quicksort partition, scan 0 to n - 2, find the middle point where left side is all 0 and right side is all 1, this take n - 1 comparisons. But for (b), I can't get a clue. It says "each of the n inputs is 0 or 1 with equal probability", so I guess I can assume the numbers of 0 and 1 equal? But how can I get a result which is related to 1/3? divide the whole array into 3 groups? Thanks

    Read the article

  • Surely a foolish error, but I can't see it

    - by dnagirl
    I have a form (greatly simplified): <form action='http://example.com/' method='post' name='event_form'> <input type='text' name='foo' value='3'/> <input type='submit' name='event_submit' value='Edit'/> </form> And I have a class "EventForm" to process the form. The main method, process() looks like this: public function process($submitname=false){ $success=false; if ($submitname && isset($_POST[$submitname])){ //PROBLEM: isset($_POST[$submitname] is always FALSE for some reason if($success=$this->ruler->validate()){//check that dependancies are honoured and data types are correct if($success=$this->map_fields()){//divide input data into Event, Schedule_Element and Temporal_Expression(s) $success=$this->eventholder->save(); } } } else {//get the record from the db based on event_id or schedule_element_id foreach($this->gets as $var){//list of acceptable $_GET keys if(isset($_GET[$var])){ if($success= $this->__set($var,$_GET[$var])) break; } } } $this->action=(empty($this->eventholder->event_id))? ADD : EDIT; return $success; } When the form is submitted, this happens: $form->process('event_submit'); For some reason though, isset($_POST['event_submit']) always evaluates to FALSE. Can anyone see why?

    Read the article

  • CUDA - multiple kernels to compute a single value

    - by Roger
    Hey, I'm trying to write a kernel to essentially do the following in C float sum = 0.0; for(int i = 0; i < N; i++){ sum += valueArray[i]*valueArray[i]; } sum += sum / N; At the moment I have this inside my kernel, but it is not giving correct values. int i0 = blockIdx.x * blockDim.x + threadIdx.x; for(int i=i0; i<N; i += blockDim.x*gridDim.x){ *d_sum += d_valueArray[i]*d_valueArray[i]; } *d_sum= __fdividef(*d_sum, N); The code used to call the kernel is kernelName<<<64,128>>>(N, d_valueArray, d_sum); cudaMemcpy(&sum, d_sum, sizeof(float) , cudaMemcpyDeviceToHost); I think that each kernel is calculating a partial sum, but the final divide statement is not taking into account the accumulated value from each of the threads. Every kernel is producing it's own final value for d_sum? Does anyone know how could I go about doing this in an efficient way? Maybe using shared memory between threads? I'm very new to GPU programming. Cheers

    Read the article

  • extra new lines with several outputStream.write

    - by Sam
    Hi All, I am writing jsp to export data in excel format to user. An excel could be recieved on the cient side. However, since there's large amount of data, and I don't want to keep it in the server memory and write them at the end. I try to divide them and write serveral times. However, each extra write(..) will cause an extra new lines at the top of the excel worksheet and then the extra data is placed after these new lines. Does anyone know the reasons? The code is something like this: response.setHeader("Content-disposition","attachment;filename=DocuShareSearch.xls"); response.setHeader("Content-Type", "application/octet-stream"); responseContent ="<table><tr><td>12131</td></tr>......."; byte[] responseByte1 = responseContent.getBytes("utf-16"); outputStream.write(responseByte1, 0, responseByte1.length ); responseContent =".....<tr><td>12131</td></tr></table>"; byte[] responseByte2 = responseContent.getBytes("utf-16"); outputStream.write(responseByte2, 0, responseByte2.length ); outputStream.close();

    Read the article

  • Combining two data sets and plotting in matlab

    - by bautrey
    I am doing experiments with different operational amplifier circuits and I need to plot my measured results onto a graph. I have two data sets: freq1 = [.1 .2 .5 .7 1 3 4 6 10 20 35 45 60 75 90 100]; %kHz Vo1 = [1.2 1.6 1.2 2 2 2.4 14.8 20.4 26.4 30.4 53.6 68.8 90 114 140 152]; %mV V1 = 19.6; Acm = Vo1/(1000*V1); And: freq2 = [.1 .5 1 30 60 70 85 100]; %kHz Vo1 = [3.96 3.96 3.96 3.84 3.86 3.88 3.88 3.88]; %V V1 = .96; Ad = Vo1/(2*V1); (I would show my plots but apparently I need more reps for that) I need to plot the equation, CMRR vs freq: CMRR = 20*log10(abs(Ad/Acm)); The size of Ad and Acm are different and the frequency points do not match up, but the boundaries of both of these is the same, 100Hz to 100kHz (x-axis). On the line of CMRR, Matlab says that Ad and Acm matrix dimensions do not agree. How I think I would solve this is using freq1 as the x-axis for CMRR and then taking approximated points from Ad according to the value on freq1. Or I could do function approximations of Ad and Acm and then do the divide operator on those. I do not know how I would code up this two ideas. Any other ideas would helpful, especially simpler ones. Thanks

    Read the article

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