Search Results

Search found 1038 results on 42 pages for 'jon galloway'.

Page 21/42 | < Previous Page | 17 18 19 20 21 22 23 24 25 26 27 28  | Next Page >

  • Implementing a robust async stream reader

    - by Jon
    I recently provided an answer to this question: C# - Realtime console output redirection. As often happens, explaining stuff (here "stuff" was how I tackled a similar problem) leads you to greater understanding and/or, as is the case here, "oops" moments. I realized that my solution, as implemented, has a bug. The bug has little practical importance, but it has an extremely large importance to me as a developer: I can't rest easy knowing that my code has the potential to blow up. Squashing the bug is the purpose of this question. I apologize for the long intro, so let's get dirty. I wanted to build a class that allows me to receive input from a Stream in an event-based manner. The stream, in my scenario, is guaranteed to be a FileStream and there is also an associated StreamReader already present to leverage. The public interface of the class is this: public class MyStreamManager { public event EventHandler<ConsoleOutputReadEventArgs> StandardOutputRead; public void StartSendingEvents(); public void StopSendingEvents(); } Obviously this specific scenario has to do with a console's standard output, but that is a detail and does not play an important role. StartSendingEvents and StopSendingEvents do what they advertise; for the purposes of this discussion, we can assume that events are always being sent without loss of generality. The class uses these two fields internally: protected readonly StringBuilder inputAccumulator = new StringBuilder(); protected readonly byte[] buffer = new byte[256]; The functionality of the class is implemented in the methods below. To get the ball rolling: public void StartSendingEvents(); { this.stopAutomation = false; this.BeginReadAsync(); } To read data out of the Stream without blocking, and also without requiring a carriage return char, BeginRead is called: protected void BeginReadAsync() { if (!this.stopAutomation) { this.StandardOutput.BaseStream.BeginRead( this.buffer, 0, this.buffer.Length, this.ReadHappened, null); } } The challenging part: BeginRead requires using a buffer. This means that when reading from the stream, it is possible that the bytes available to read ("incoming chunk") are larger than the buffer. Since we are only handing off data from the stream to a consumer, and that consumer may well have inside knowledge about the size and/or format of these chunks, I want to call event subscribers exactly once for each chunk. Otherwise the abstraction breaks down and the subscribers have to buffer the incoming data and reconstruct the chunks themselves using said knowledge. This is much less convenient to the calling code, and detracts from the usefulness of my class. To this end, if the buffer is full after EndRead, we don't send its contents to subscribers immediately but instead append them to a StringBuilder. The contents of the StringBuilder are only sent back whenever there is no more to read from the stream (thus preserving the chunks). private void ReadHappened(IAsyncResult asyncResult) { var bytesRead = this.StandardOutput.BaseStream.EndRead(asyncResult); if (bytesRead == 0) { this.OnAutomationStopped(); return; } var input = this.StandardOutput.CurrentEncoding.GetString( this.buffer, 0, bytesRead); this.inputAccumulator.Append(input); if (bytesRead < this.buffer.Length) { this.OnInputRead(); // only send back if we 're sure we got it all } this.BeginReadAsync(); // continue "looping" with BeginRead } After any read which is not enough to fill the buffer, all accumulated data is sent to the subscribers: private void OnInputRead() { var handler = this.StandardOutputRead; if (handler == null) { return; } handler(this, new ConsoleOutputReadEventArgs(this.inputAccumulator.ToString())); this.inputAccumulator.Clear(); } (I know that as long as there are no subscribers the data gets accumulated forever. This is a deliberate decision). The good This scheme works almost perfectly: Async functionality without spawning any threads Very convenient to the calling code (just subscribe to an event) Maintains the "chunkiness" of the data; this allows the calling code to use inside knowledge of the data without doing any extra work Is almost agnostic to the buffer size (it will work correctly with any size buffer irrespective of the data being read) The bad That last almost is a very big one. Consider what happens when there is an incoming chunk with length exactly equal to the size of the buffer. The chunk will be read and buffered, but the event will not be triggered. This will be followed up by a BeginRead that expects to find more data belonging to the current chunk in order to send it back all in one piece, but... there will be no more data in the stream. In fact, as long as data is put into the stream in chunks with length exactly equal to the buffer size, the data will be buffered and the event will never be triggered. This scenario may be highly unlikely to occur in practice, especially since we can pick any number for the buffer size, but the problem is there. Solution? Unfortunately, after checking the available methods on FileStream and StreamReader, I can't find anything which lets me peek into the stream while also allowing async methods to be used on it. One "solution" would be to have a thread wait on a ManualResetEvent after the "buffer filled" condition is detected. If the event is not signaled (by the async callback) in a small amount of time, then more data from the stream will not be forthcoming and the data accumulated so far should be sent to subscribers. However, this introduces the need for another thread, requires thread synchronization, and is plain inelegant. Specifying a timeout for BeginRead would also suffice (call back into my code every now and then so I can check if there's data to be sent back; most of the time there will not be anything to do, so I expect the performance hit to be negligible). But it looks like timeouts are not supported in FileStream. Since I imagine that async calls with timeouts are an option in bare Win32, another approach might be to PInvoke the hell out of the problem. But this is also undesirable as it will introduce complexity and simply be a pain to code. Is there an elegant way to get around the problem? Thanks for being patient enough to read all of this.

    Read the article

  • How to tell if XUL menupopup opens down or up?

    - by Jon
    I have an extension that can be placed on any toolbar (like the bookmarks, menu or status bars). In general, the context menu opens downward, but when placed on the status bar and Firefox is closed to the bottom of the screen, the context menu opens upward. I'd like to try reordering the context menu based on its up or down orientation, so that the same options are always closest to the mouse. For example, when opened downward it appears like this: -- (mouse) --------------- - MenuItem A - --------------- - MenuItem B - --------------- - MenuItem C - --------------- - ....... - --------------- When it opens upwards its like this: --------------- - MenuItem A - --------------- - MenuItem B - --------------- - MenuItem C - --------------- - ....... - --------------- -- (mouse) However, I'd like "MenuItem A" to appear closest to the mouse at all times, since its the most common item. I can render the items dynamically, so I really just need to find out the orientation.

    Read the article

  • Java error on bilinear interpolation of 16 bit data

    - by Jon
    I'm having an issue using bilinear interpolation for 16 bit data. I have two images, origImage and displayImage. I want to use AffineTransformOp to filter origImage through an AffineTransform into displayImage which is the size of the display area. origImage is of type BufferedImage.TYPE_USHORT_GRAY and has a raster of type sun.awt.image.ShortInterleavedRaster. Here is the code I have right now displayImage = new BufferedImage(getWidth(), getHeight(), origImage.getType()); try { op = new AffineTransformOp(atx, AffineTransformOp.TYPE_BILINEAR); op.filter(origImage, displayImage); } catch (Exception e) { e.printStackTrace(); } In order to show the error I have created 2 gradient images. One has values in the 15 bit range (max of 32767) and one in the 16 bit range (max of 65535). Below are the two images 15 bit image 16 bit image These two images were created in identical fashions and should look identical, but notice the line across the middle of the 16 bit image. At first I thought that this was an overflow problem however, it is weird that it's manifesting itself in the center of the gradient instead of at the end where the pixel values are higher. Also, if it was an overflow issue than I would suspect that the 15 bit image would have been affected as well. Any help on this would be greatly appreciated.

    Read the article

  • Changing paths to images in Wordpress

    - by Jon Winstanley
    I recently moved a friends blog onto his new web hosts but unfortunately the images are not working. This is due to the old host having the following path for images: http://www.example.com/blog/wp-content/uploads/2009/07/imagename.jpg The new host uses a different layout and has this path for the file: http://www.example.com/wp-content/uploads/2009/07/imagename.jpg 'Blog' has been removed. Does anyone know the easiest way to fix this issue?

    Read the article

  • Dev environment - Cubicles or pods?

    - by jon
    We're reorganizing our workspaces at work, and are individually being given the choice of working in a more open space with a few other developers, or a more closed off space by ourselves. Which should I choose?

    Read the article

  • Useful Eclipse Java Code Templates

    - by Jon
    You can create various Java code templates in Eclipse via the Window->Preferences->Java -> Editor -> Templates e.g. sysout is expanded to: System.out.println(${word_selection}${});${cursor} You can activate this by typing sysout followed by CTRL+SPACE What useful Java code templates do you currently use? Include the name and description of it and why it's awesome. There's an open bounty on this for an original/novel use of a template rather than a built-in existing feature. Create Log4J logger Get swt color from display Syncexec - Eclipse Framework Singleton Pattern/Enum Singleton Generation Readfile Const Traceout Format String Comment Code Review String format Try Finally Lock Message Format i18n and log Equalsbuilder Hashcodebuilder Spring Object Injection Create FileOutputStream

    Read the article

  • Uploadify refuses to upload WMV, FLV and MP4 files - SOLVED

    - by Jon Winstanley
    The uploadify plugin for JQuery seems very good and works for most file types. However, it allows me to upload all file types apart from the ones I need! Namely .WMV, .FLV and .MP4 Uploads of any other type work. I have already tried changing the fileExt parameter and also tried removing it altogether. I have testing in Google Chrome, IE7 and Firefox and none work for these file types. I have a ton of local projects already and uploading is not an issue on any other project, I even use the same example files (This is the first time I have used Uploadify) Is there a known reason for this behaviour? EDIT: Have found the issue. I had forgotten to add my usual .htaccess file to the example project.

    Read the article

  • Language in a Sandbox in Rails

    - by Jon Romero
    I've found that there WAS a sandbox gem (created by the guys that made try ruby in your browser but it was compatible only with Ruby 1.8. Another problem is that I cannot find it anymore (it seems they stop serving the gem from the servers...). So, is there any secure way of running ruby in a sandbox (so you can run it from your browser)? Or an easy way to run (for example lua/python) in a sandbox (no filesystem access, no creation of objects etc) and be called from Ruby (Rails 2.2)? I want to make an application like try_ruby even without having a ruby underneath. But it has to be an easy language (I saw there was a prolog in ruby, even a lisp but I don't think they are easy to learn languages...). So, do you have any suggestions or tips? Or should I just start creating my own DSL in Ruby (if there is a solution in creating a somewhat safe system)? Thx

    Read the article

  • Distributed sequence number generation?

    - by Jon
    I've generally implemented sequence number generation using database sequences in the past. e.g. Using Postgres SERIAL type http://neilconway.org/docs/sequences/ I'm curious though as how to generate sequence numbers for large distributed systems where there is no database. Does anybody have any experience or suggestions of a best practice for achieving sequence number generation in a thread safe manner for multiple clients?

    Read the article

  • Useful Java Annotations

    - by Jon
    I'm interested in finding out exactly which Java annotations people think are most useful during development. This doesn't necessarily have to limited to the core Java API, you may include annotations you found in third party libraries or annotations you've developed yourself (make sure you include a link to the source). I'm really interested in common development tasks rather than knowing why the @ManyToOne(optional=false) in JPA is awesome... Include the annotation and a description of why it's useful for general development.

    Read the article

  • How to start recognizing design patterns as you are programming?

    - by Jon Erickson
    I have general academic knowledge of the various design patterns that are discussed in GoF and Head First Design Patterns, but I have a difficult time applying them to the code that I am writing. A goal for me this year is to be able to recognize design patterns that are emerging from the code that I write. Obviously this comes with experience (I have about 2 years in the field), but my question is how can I jumpstart my ability to recognize design patterns as I am coding, maybe a suggestion as to what patterns are easiest to start applying in client-server applications (in my case mainly c# webforms with ms sql db's, but this could definitely be language agnostic).

    Read the article

  • Retrieve Table Row Index of Current Row

    - by Jon
    Hi Everyone, I am trying to validate a text input when it loses focus. I would like to know which row of the table it is in. This is what I have so far and it keeps coming back as undefined. Any ideas? $("div#step-2 fieldset table tbody tr td input").blur(function() { var tableRow = $(this).parent().parent(); if ($.trim($(this).val()) == "") { $(this).addClass("invalid"); alert(tableRow.rowIndex); $(this).val(""); } else { $(this).removeClass("invalid"); checkTextChanges(); } });

    Read the article

  • Design Time Attribute For CSS Class in ASP.net Custom Server Control

    - by Jon P
    Hopefully some Custom Control Designers/Builders can help I'm attempting to build my first custom control that is essential a client detail collection form. There are to be a series of elements to this form that require various styles applied to them. Ideally I'd like the VS 2005/2008 properties interface to be able to apply the CSSClass as it does at the control level, i.e. with a dropdown list of available CSS Clases. Take for example the Class to be applied to the legend tag /// <summary>Css Class for Legend</summary> [Category("Appearance")] [Browsable(true)] [DefaultValue("")] //I am at a loss as to what goes in [Editor] [Editor(System.Web.UI.CssStyleCollection), typeof(System.Drawing.Design.UITypeEditor))] public string LegendCSSClass { get { return _LegendCSSClass; } set { _LegendCSSClass = value; } } I have tried a couple of options, as you can see from above, without much luck. Hopefully there is something simple I am missing. I'd also be happy for references pertaining to the [Editor] attribute

    Read the article

  • How can I convert convert docx or wordml xml files to xsl-fo?

    - by Jon Pastore
    I've been looking for a method to convert docx or wordml xml to xsl-fo. I read this post: http://stackoverflow.com/questions/156683/what-is-the-best-xslt-engine-for-perl but I'm having exceptional problems getting apache-fop going. I was able to download the bins and run it locally but the formatting was a little off and it didn't maintain the headers and footers or section 1 or section 3 (17 page doc 3 sections) it also overlapped the text over the outline numbers and did not maintain the font used. trying a more simple test caused fop to fail completely. I would like to find a way to create a PDF that is at least close to 100% accurate reproduction of the original doc.

    Read the article

  • Reading Source Code Aloud

    - by Jon Purdy
    After seeing this question, I got to thinking about the various challenges that blind programmers face, and how some of them are applicable even to sighted programmers. Particularly, the problem of reading source code aloud gives me pause. I have been programming for most of my life, and I frequently tutor fellow students in programming, most often in C++ or Java. It is uniquely aggravating to try to verbally convey the essential syntax of a C++ expression. The speaker must give either an idiomatic translation into English, or a full specification of the code in verbal longhand, using explicit yet slow terms such as "opening parenthesis", "bitwise and", et cetera. Neither of these solutions is optimal. On the one hand, an idiomatic translation is only useful to a programmer who can de-translate back into the relevant programming code—which is not usually the case when tutoring a student. In turn, education (or simply getting someone up to speed on a project) is the most common situation in which source is read aloud, and there is a very small margin for error. On the other hand, a literal specification is aggravatingly slow. It takes far far longer to say "pound, include, left angle bracket, iostream, right angle bracket, newline" than it does to simply type #include <iostream>. Indeed, most experienced C++ programmers would read this merely as "include iostream", but again, inexperienced programmers abound and literal specifications are sometimes necessary. So I've had an idea for a potential solution to this problem. In C++, there is a finite set of keywords—63—and operators—54, discounting named operators and treating compound assignment operators and prefix versus postfix auto-increment and decrement as distinct. There are just a few types of literal, a similar number of grouping symbols, and the semicolon. Unless I'm utterly mistaken, that's about it. So would it not then be feasible to simply ascribe a concise, unique pronunciation to each of these distinct concepts (including one for whitespace, where it is required) and go from there? Programming languages are far more regular than natural languages, so the pronunciation could be standardised. Speakers of any language would be able to verbally convey C++ code, and due to the regularity and fixity of the language, speech-to-text software could be optimised to accept C++ speech with a high degree of accuracy. So my question is twofold: first, is my solution feasible; and second, does anyone else have other potential solutions? I intend to take suggestions from here and use them to produce a formal paper with an example implementation of my solution.

    Read the article

  • Match entities fulfilling filter (strict superset of search)

    - by Jon
    I have an entity (let's say Person) with a set of arbitrary attributes with a known subset of values. I need to search for all of these entities that match all my filter conditions. That is, given a set of Attributes A, I need to find all people that have a set of Attributes that are a superset of A. For example, my table structures look like this: Person: id | name 1 | John Doe 2 | Jane Roe 3 | John Smith Attribute: id | attr_name 1 | Sex 2 | Eye Color ValidValue: id | attr_id | value_name 1 | 1 | Male 2 | 1 | Female 3 | 2 | Blue 4 | 2 | Green 5 | 2 | Brown PersonAttributes id | person_id | attr_id | value_id 1 | 1 | 1 | 1 2 | 1 | 2 | 3 3 | 2 | 1 | 2 4 | 2 | 2 | 4 5 | 3 | 1 | 1 6 | 3 | 2 | 4 In JPA, I have entities built for all of these tables. What I'd like to do is perform a search for all entities matching a given set of attribute-value pairs. For instance, I'd like to be able to find all males (John Doe and John Smith), all people with green eyes (Jane Roe or John Smith), or all females with green eyes (Jane Roe). I see that I can already take advantage of the fact that I only really need to match on value_id, since that's already unique and tied to the attr_id. But where can I go from there? I've been trying to do something like the following, given that the ValidValue is unique in all cases: select distinct p from Person p join p.personAttributes a where a.value IN (:values) Then I've tried putting my set of required values in as "values", but that gives me errors no matter how I try to structure that. I also have to get a little more complicated, as follows, but at this point I'd be happy with solving the first problem cleanly. However, if it's possible, the Attribute table actually has a field for default value: id | attr_name | default_value 1 | Sex | 1 2 | Eye Color | 5 If the value you're searching on happens to be the default value, I want it to return any people that have no explicit value set for that attribute, because in the application logic, that means they inherit the default value. Again, I'm more concerned about the primary question, but if someone who can help with that also has some idea of how to do this one, I'd be extremely grateful.

    Read the article

  • Snow Leopard - PHP 5.3.1 installed... but no PEAR?

    - by Jon Busby
    I've been trying to do some PHP work on my snow leopard machine.. but I've found issues when I need to use PEAR packages (as symfony handles its php plugins with PEAR). I've found some references that state that snow leopard includes PEAR.. but how come I cant find it?! Could someone confirm this.. if if so, where is my pear?

    Read the article

  • What do I have to do and how much does it cost to get a device driver for Windows Vista / 7 (32 and

    - by Jon Cage
    I've got some drivers which are basically LibUSB-Win32 with a new .inf file do describe product/vendor ids and strings which describe my hardware. This works fine for 32 bit windows, but 64 bit versions have problems; namely that Microsoft in their wisdom require all drivers to be digitally signed. So my questions are thus: Is there a version of the LibUSB-Win32 drivers which are already signed I could use? If there aren't already some signed ones I can canibalise, what exactly do I have to do to get my drivers signed. Do I need to get 64 and 32 bit versions signed separately and will this cost more? Is this a free alternative to getting them signed? Are there any other options I should consider besides requiring that my customers boot into test mode each time they start their machines (not an option I'd consider).

    Read the article

  • Mutating the expression tree of a predicate to target another type

    - by Jon
    Intro In the application I 'm currently working on, there are two kinds of each business object: the "ActiveRecord" type, and the "DataContract" type. So for example, we have: namespace ActiveRecord { class Widget { public int Id { get; set; } } } namespace DataContracts { class Widget { public int Id { get; set; } } } The database access layer takes care of "translating" between hierarchies: you can tell it to update a DataContracts.Widget, and it will magically create an ActiveRecord.Widget with the same property values and save that. The problem I have surfaced when attempting to refactor this database access layer. The Problem I want to add methods like the following to the database access layer: // Widget is DataContract.Widget interface DbAccessLayer { IEnumerable<Widget> GetMany(Expression<Func<Widget, bool>> predicate); } The above is a simple general-use "get" method with custom predicate. The only point of interest is that I 'm not passing in an anonymous function but rather an expression tree. This is done because inside DbAccessLayer we have to query ActiveRecord.Widget efficiently (LINQ to SQL) and not have the database return all ActiveRecord.Widget instances and then filter the enumerable collection. We need to pass in an expression tree, so we ask for one as the parameter for GetMany. The snag: the parameter we have needs to be magically transformed from an Expression<Func<DataContract.Widget, bool>> to an Expression<Func<ActiveRecord.Widget, bool>>. This is where I haven't managed to pull it off... Attempted Solution What we 'd like to do inside GetMany is: IEnumerable<DataContract.Widget> GetMany( Expression<Func<DataContract.Widget, bool>> predicate) { var lambda = Expression.Lambda<Func<ActiveRecord.Widget, bool>>( predicate.Body, predicate.Parameters); // use lambda to query ActiveRecord.Widget and return some value } This won't work because in a typical scenario, for example if: predicate == w => w.Id == 0; ...the expression tree contains a MemberAccessExpression instance which has a MemberInfo property (named Member) that point to members of DataContract.Widget. There are also ParameterExpression instances both in the expression tree and in its parameter expression collection (predicate.Parameters); After searching a bit, I found System.Linq.Expressions.ExpressionVisitor (its source can be found here in the context of a how-to, very helpful) which is a convenient way to modify an expression tree. Armed with this, I implemented a visitor. This simple visitor only takes care of changing the types in member access and parameter expressions. It may not be complete, but it's fine for the expression w => w.Id == 0. internal class Visitor : ExpressionVisitor { private readonly Func<Type, Type> dataContractToActiveRecordTypeConverter; public Visitor(Func<Type, Type> dataContractToActiveRecordTypeConverter) { this.dataContractToActiveRecordTypeConverter = dataContractToActiveRecordTypeConverter; } protected override Expression VisitMember(MemberExpression node) { var dataContractType = node.Member.ReflectedType; var activeRecordType = this.dataContractToActiveRecordTypeConverter(dataContractType); var converted = Expression.MakeMemberAccess( base.Visit(node.Expression), activeRecordType.GetProperty(node.Member.Name)); return converted; } protected override Expression VisitParameter(ParameterExpression node) { var dataContractType = node.Type; var activeRecordType = this.dataContractToActiveRecordTypeConverter(dataContractType); return Expression.Parameter(activeRecordType, node.Name); } } With this visitor, GetMany becomes: IEnumerable<DataContract.Widget> GetMany( Expression<Func<DataContract.Widget, bool>> predicate) { var visitor = new Visitor(...); var lambda = Expression.Lambda<Func<ActiveRecord.Widget, bool>>( visitor.Visit(predicate.Body), predicate.Parameters.Select(p => visitor.Visit(p)); var widgets = ActiveRecord.Widget.Repository().Where(lambda); // This is just for reference, see below Expression<Func<ActiveRecord.Widget, bool>> referenceLambda = w => w.Id == 0; // Here we 'd convert the widgets to instances of DataContract.Widget and // return them -- this has nothing to do with the question though. } Results The good news is that lambda is constructed just fine. The bad news is that it isn't working; it's blowing up on me when I try to use it (the exception messages are really not helpful at all). I have examined the lambda my code produces and a hardcoded lambda with the same expression; they look exactly the same. I spent hours in the debugger trying to find some difference, but I can't. When predicate is w => w.Id == 0, lambda looks exactly like referenceLambda. But the latter works with e.g. IQueryable<T>.Where, while the former does not (I have tried this in the immediate window of the debugger). I should also mention that when predicate is w => true, it all works just fine. Therefore I am assuming that I 'm not doing enough work in Visitor, but I can't find any more leads to follow on. Can someone point me in the right direction? Thanks in advance for your help!

    Read the article

  • How do I get a value of a reference type in an Expression?

    - by Jon Kruger
    I have this method: public void DoSomething<T>(Expression<Func<T, object>> method) { } If this method is called like this: DoSomething(c => c.SomeMethod(new TestObject())); ... how do I get the value of the parameter that was passed into SomeMethod()? If the parameter is a value type, this works: var methodCall = (MethodCallExpression)method.Body; var parameterValue = ((ConstantExpression)methodCall.Arguments[0]).Value; However, when I pass in a reference type, methodCall.Arguments[0] is a MemberExpression, and I can't seem to figure out how to write code to get the value out of it.

    Read the article

  • CM_Get_Device_ID gets correct values from win7 but not xp

    - by Jon W. Jones
    When using CM_Get_Device_ID(...) I am getting the correct value from windows 7. When using windows xp I am getting an incorrect value. For Example, on xp I get "USB\VID_2132&PID_0001\5&36FF4167&0&7" and on 7 I get "USB\VID_2132&PID_0001\413031000576". The value after the \ on PID is our serial number and it is correct on 7 but xp keeps giving back what appears to be a nonsensical value. My question is has anyone else encountered this and know of a workaround?

    Read the article

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