Search Results

Search found 2521 results on 101 pages for 'typed constants'.

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

  • Static Logger in seperate thread?

    - by SirLenz0rlot
    Hi all, I've made my Logger, that logs a string, a static class with a static so I can call it from my entire project without having to make an instance of it. quite nice, but I want to make it run in a seperate thread, since accessing the file costs time is that possible somehow and what's the best way to do it? Its a bit of a short discription, but I hope the idea is clear. if not, please let me know. Thanks in advance! btw: any other improvements on my code are welcome as well, i have the feeling not everthing is as efficient as it can be: internal static class MainLogger { internal static void LogStringToFile(string logText) { DateTime timestamp = DateTime.Now; string str = timestamp.ToString("dd-MM-yy HH:mm:ss ", CultureInfo.InvariantCulture) + "\t" + logText + "\n"; const string filename = Constants.LOG_FILENAME; FileInfo fileInfo = new FileInfo(filename); if (fileInfo.Exists) { if (fileInfo.Length > Constants.LOG_FILESIZE) { File.Create(filename).Dispose(); } } else { File.Create(filename).Dispose(); } int i = 0; while(true) { try { using (StreamWriter writer = File.AppendText(filename)) { writer.WriteLine(str); } break; } catch (IOException) { Thread.Sleep(10); i++; if (i >= 8) { throw new IOException("Log file \"" + Constants.LOG_FILENAME + "\" not accessible after 5 tries"); } } } } } enter code here

    Read the article

  • Implementing a bitfield using java enums

    - by soappatrol
    Hello, I maintain a large document archive and I often use bit fields to record the status of my documents during processing or when validating them. My legacy code simply uses static int constants such as: static int DOCUMENT_STATUS_NO_STATE = 0 static int DOCUMENT_STATUS_OK = 1 static int DOCUMENT_STATUS_NO_TIF_FILE = 2 static int DOCUMENT_STATUS_NO_PDF_FILE = 4 This makes it pretty easy to indicate the state a document is in, by setting the appropriate flags. For example: status = DOCUMENT_STATUS_NO_TIF_FILE | DOCUMENT_STATUS_NO_PDF_FILE; Since the approach of using static constants is bad practice and because I would like to improve the code, I was looking to use Enums to achieve the same. There are a few requirements, one of them being the need to save the status into a database as a numeric type. So there is a need to transform the enumeration constants to a numeric value. Below is my first approach and I wonder if this is the correct way to go about this? class DocumentStatus{ public enum StatusFlag { DOCUMENT_STATUS_NOT_DEFINED(1<<0), DOCUMENT_STATUS_OK(1<<1), DOCUMENT_STATUS_MISSING_TID_DIR(1<<2), DOCUMENT_STATUS_MISSING_TIF_FILE(1<<3), DOCUMENT_STATUS_MISSING_PDF_FILE(1<<4), DOCUMENT_STATUS_MISSING_OCR_FILE(1<<5), DOCUMENT_STATUS_PAGE_COUNT_TIF(1<<6), DOCUMENT_STATUS_PAGE_COUNT_PDF(1<<7), DOCUMENT_STATUS_UNAVAILABLE(1<<8), private final long statusFlagValue; StatusFlag(long statusFlagValue) { this.statusFlagValue = statusFlagValue } public long getStatusFlagValue(){ return statusFlagValue } } /** * Translates a numeric status code into a Set of StatusFlag enums * @param numeric statusValue * @return EnumSet representing a documents status */ public EnumSet<StatusFlag> getStatusFlags(long statusValue) { EnumSet statusFlags = EnumSet.noneOf(StatusFlag.class) StatusFlag.each { statusFlag -> long flagValue = statusFlag.statusFlagValue if ( (flagValue&statusValue ) == flagValue ) { statusFlags.add(statusFlag) } } return statusFlags } /** * Translates a set of StatusFlag enums into a numeric status code * @param Set if statusFlags * @return numeric representation of the document status */ public long getStatusValue(Set<StatusFlag> flags) { long value=0 flags.each { statusFlag -> value|=statusFlag.getStatusFlagValue() } return value } public static void main(String[] args) { DocumentStatus ds = new DocumentStatus(); Set statusFlags = EnumSet.of( StatusFlag.DOCUMENT_STATUS_OK, StatusFlag.DOCUMENT_STATUS_UNAVAILABLE) assert ds.getStatusValue( statusFlags )==258 // 0000.0001|0000.0010 long numericStatusCode = 56 statusFlags = ds.getStatusFlags(numericStatusCode) assert !statusFlags.contains(StatusFlag.DOCUMENT_STATUS_OK) assert statusFlags.contains(StatusFlag.DOCUMENT_STATUS_MISSING_TIF_FILE) assert statusFlags.contains(StatusFlag.DOCUMENT_STATUS_MISSING_PDF_FILE) assert statusFlags.contains(StatusFlag.DOCUMENT_STATUS_MISSING_OCR_FILE) } }

    Read the article

  • Java BCEL creating method with sipush?

    - by user1446924
    Well, I'm trying to recreate this method : public int getBaseX() { return this.x + 10000; } and it returns these instructions 0 aload_0 1 getfield #18 <TestClass.x> 4 sipush 10000 7 iadd 8 ireturn Now I'm having trouble withe the sipush, iadd. ClassGen injCG = cg; ConstantPoolGen cpg = injCG.getConstantPool(); InstructionList il = new InstructionList(); MethodGen mg = new MethodGen(Constants.ACC_PUBLIC, f.getType(), Type.NO_ARGS, null, name, injCG.getClassName(), il, cpg); InstructionFactory instrF = new InstructionFactory(injCG, cpg); if (!f.isStatic()) il.append(new org.apache.bcel.generic.ALOAD(0)); il.append(instrF.createFieldAccess(cg.getClassName(), f.getName(), f.getType(), (f.isStatic() ? Constants.GETSTATIC : Constants.GETFIELD))); il.append(InstructionFactory.createPop(1000)); il.append(InstructionFactory.createReturn(f.getType())); //il.append(InstructionFactory.createReturn(f.getType()), InstructionFactory.createDup(1000)); mg.setMaxLocals(); mg.setMaxStack(); injCG.addMethod(mg.getMethod()); that's what I have tried, but failed.

    Read the article

  • Response Redirect - Open Link in New Window

    - by bacis09
    First, I've taken the time to review this question which seems to be the most similar, however, the solution that seems to have been selected will not work in my scenario.Not to mention I worry about some of the comments claiming it to be brittle or an inadequate solution. http://stackoverflow.com/questions/104601/asp-net-response-redirect-to-new-window -We have an XML document which basically contains all of the information for a Side menu. -We have numerous URLS which are stored in a constants class. -One of the elements in a string of XML (well call it label) is used to determine if the menu item is created as a LinkButton or a Label. -Links use a custom user control that is used standard for all links across the application (why suggestion on similar thread doesn't work - I don't want all links to open in a new window - just one) -One of the elements in a string of XML (well call it function) is used in a Switch statement to generate our links using Response Redirect. It may look something like this. switch (function) { case goto 1: string url; if (user_group == 1) { url = Constants.CONSTANT1 } else { url = Constants.CONSTANT2 } Response.Redirect(url) case goto 2: ...... default: ...... break; } Given this scenario, I'm trying to find the best way to quickly open a New Window, when a specific case in this switch statement is met. Can it be done with Response Redirect (this seems to be arguable - people say no it can't, yet other people say they have made it work)? If not, what alternative can work here?

    Read the article

  • Dynamic Type to do away with Reflection

    - by Rick Strahl
    The dynamic type in C# 4.0 is a welcome addition to the language. One thing I’ve been doing a lot with it is to remove explicit Reflection code that’s often necessary when you ‘dynamically’ need to walk and object hierarchy. In the past I’ve had a number of ReflectionUtils that used string based expressions to walk an object hierarchy. With the introduction of dynamic much of the ReflectionUtils code can be removed for cleaner code that runs considerably faster to boot. The old Way - Reflection Here’s a really contrived example, but assume for a second, you’d want to dynamically retrieve a Page.Request.Url.AbsoluteUrl based on a Page instance in an ASP.NET Web Page request. The strongly typed version looks like this: string path = Page.Request.Url.AbsolutePath; Now assume for a second that Page wasn’t available as a strongly typed instance and all you had was an object reference to start with and you couldn’t cast it (right I said this was contrived :-)) If you’re using raw Reflection code to retrieve this you’d end up writing 3 sets of Reflection calls using GetValue(). Here’s some internal code I use to retrieve Property values as part of ReflectionUtils: /// <summary> /// Retrieve a property value from an object dynamically. This is a simple version /// that uses Reflection calls directly. It doesn't support indexers. /// </summary> /// <param name="instance">Object to make the call on</param> /// <param name="property">Property to retrieve</param> /// <returns>Object - cast to proper type</returns> public static object GetProperty(object instance, string property) { return instance.GetType().GetProperty(property, ReflectionUtils.MemberAccess).GetValue(instance, null); } If you want more control over properties and support both fields and properties as well as array indexers a little more work is required: /// <summary> /// Parses Properties and Fields including Array and Collection references. /// Used internally for the 'Ex' Reflection methods. /// </summary> /// <param name="Parent"></param> /// <param name="Property"></param> /// <returns></returns> private static object GetPropertyInternal(object Parent, string Property) { if (Property == "this" || Property == "me") return Parent; object result = null; string pureProperty = Property; string indexes = null; bool isArrayOrCollection = false; // Deal with Array Property if (Property.IndexOf("[") > -1) { pureProperty = Property.Substring(0, Property.IndexOf("[")); indexes = Property.Substring(Property.IndexOf("[")); isArrayOrCollection = true; } // Get the member MemberInfo member = Parent.GetType().GetMember(pureProperty, ReflectionUtils.MemberAccess)[0]; if (member.MemberType == MemberTypes.Property) result = ((PropertyInfo)member).GetValue(Parent, null); else result = ((FieldInfo)member).GetValue(Parent); if (isArrayOrCollection) { indexes = indexes.Replace("[", string.Empty).Replace("]", string.Empty); if (result is Array) { int Index = -1; int.TryParse(indexes, out Index); result = CallMethod(result, "GetValue", Index); } else if (result is ICollection) { if (indexes.StartsWith("\"")) { // String Index indexes = indexes.Trim('\"'); result = CallMethod(result, "get_Item", indexes); } else { // assume numeric index int index = -1; int.TryParse(indexes, out index); result = CallMethod(result, "get_Item", index); } } } return result; } /// <summary> /// Returns a property or field value using a base object and sub members including . syntax. /// For example, you can access: oCustomer.oData.Company with (this,"oCustomer.oData.Company") /// This method also supports indexers in the Property value such as: /// Customer.DataSet.Tables["Customers"].Rows[0] /// </summary> /// <param name="Parent">Parent object to 'start' parsing from. Typically this will be the Page.</param> /// <param name="Property">The property to retrieve. Example: 'Customer.Entity.Company'</param> /// <returns></returns> public static object GetPropertyEx(object Parent, string Property) { Type type = Parent.GetType(); int at = Property.IndexOf("."); if (at < 0) { // Complex parse of the property return GetPropertyInternal(Parent, Property); } // Walk the . syntax - split into current object (Main) and further parsed objects (Subs) string main = Property.Substring(0, at); string subs = Property.Substring(at + 1); // Retrieve the next . section of the property object sub = GetPropertyInternal(Parent, main); // Now go parse the left over sections return GetPropertyEx(sub, subs); } As you can see there’s a fair bit of code involved into retrieving a property or field value reliably especially if you want to support array indexer syntax. This method is then used by a variety of routines to retrieve individual properties including one called GetPropertyEx() which can walk the dot syntax hierarchy easily. Anyway with ReflectionUtils I can  retrieve Page.Request.Url.AbsolutePath using code like this: string url = ReflectionUtils.GetPropertyEx(Page, "Request.Url.AbsolutePath") as string; This works fine, but is bulky to write and of course requires that I use my custom routines. It’s also quite slow as the code in GetPropertyEx does all sorts of string parsing to figure out which members to walk in the hierarchy. Enter dynamic – way easier! .NET 4.0’s dynamic type makes the above really easy. The following code is all that it takes: object objPage = Page; // force to object for contrivance :) dynamic page = objPage; // convert to dynamic from untyped object string scriptUrl = page.Request.Url.AbsolutePath; The dynamic type assignment in the first two lines turns the strongly typed Page object into a dynamic. The first assignment is just part of the contrived example to force the strongly typed Page reference into an untyped value to demonstrate the dynamic member access. The next line then just creates the dynamic type from the Page reference which allows you to access any public properties and methods easily. It also lets you access any child properties as dynamic types so when you look at Intellisense you’ll see something like this when typing Request.: In other words any dynamic value access on an object returns another dynamic object which is what allows the walking of the hierarchy chain. Note also that the result value doesn’t have to be explicitly cast as string in the code above – the compiler is perfectly happy without the cast in this case inferring the target type based on the type being assigned to. The dynamic conversion automatically handles the cast when making the final assignment which is nice making for natural syntnax that looks *exactly* like the fully typed syntax, but is completely dynamic. Note that you can also use indexers in the same natural syntax so the following also works on the dynamic page instance: string scriptUrl = page.Request.ServerVariables["SCRIPT_NAME"]; The dynamic type is going to make a lot of Reflection code go away as it’s simply so much nicer to be able to use natural syntax to write out code that previously required nasty Reflection syntax. Another interesting thing about the dynamic type is that it actually works considerably faster than Reflection. Check out the following methods that check performance: void Reflection() { Stopwatch stop = new Stopwatch(); stop.Start(); for (int i = 0; i < reps; i++) { // string url = ReflectionUtils.GetProperty(Page,"Title") as string;// "Request.Url.AbsolutePath") as string; string url = Page.GetType().GetProperty("Title", ReflectionUtils.MemberAccess).GetValue(Page, null) as string; } stop.Stop(); Response.Write("Reflection: " + stop.ElapsedMilliseconds.ToString()); } void Dynamic() { Stopwatch stop = new Stopwatch(); stop.Start(); dynamic page = Page; for (int i = 0; i < reps; i++) { string url = page.Title; //Request.Url.AbsolutePath; } stop.Stop(); Response.Write("Dynamic: " + stop.ElapsedMilliseconds.ToString()); } The dynamic code runs in 4-5 milliseconds while the Reflection code runs around 200+ milliseconds! There’s a bit of overhead in the first dynamic object call but subsequent calls are blazing fast and performance is actually much better than manual Reflection. Dynamic is definitely a huge win-win situation when you need dynamic access to objects at runtime.© Rick Strahl, West Wind Technologies, 2005-2010Posted in .NET  CSharp  

    Read the article

  • Some problems after running ubuntu tweak application

    - by sachin
    I am a first time user of ubuntu 12.04 and must say that i am enjoying it. Somehow my skype on ubuntu is screwed up. The message that i am getting says (Disk IO error). Did any one face the problem before. Also i downloaded the ubuntu tweak application. After that application has clean some file, the application it self is not starting now.. I am quiet new to linux much and fear that if the tweak application has cleaned some files which were necessary. Is there anything i can fix these problems or short of auto-recovery, i have got some more leads: here seems to be the error but not sure how can i fix this. buntu-tweak:2887): Gtk-WARNING **: Locale not supported by C library. Using the fallback 'C' locale. Traceback (most recent call last): File "/usr/bin/ubuntu-tweak", line 122, in from ubuntutweak.main import UbuntuTweakWindow File "/usr/lib/python2.7/dist-packages/ubuntutweak/main.py", line 40, in from ubuntutweak.preferences import PreferencesDialog File "/usr/lib/python2.7/dist-packages/ubuntutweak/preferences.py", line 32, in from ubuntutweak.factory import WidgetFactory File "/usr/lib/python2.7/dist-packages/ubuntutweak/factory.py", line 24, in from ubuntutweak.gui.widgets import * File "/usr/lib/python2.7/dist-packages/ubuntutweak/gui/widgets.py", line 10, in from ubuntutweak.settings.compizsettings import CompizSetting File "/usr/lib/python2.7/dist-packages/ubuntutweak/settings/compizsettings.py", line 3, in import ccm File "/usr/lib/python2.7/dist-packages/ubuntutweak/settings/ccm/init.py", line 1, in from Conflicts import * File "/usr/lib/python2.7/dist-packages/ubuntutweak/settings/ccm/Conflicts.py", line 25, in from Constants import * File "/usr/lib/python2.7/dist-packages/ubuntutweak/settings/ccm/Constants.py", line 77, in locale.setlocale(locale.LC_ALL, "") File "/usr/lib/python2.7/locale.py", line 539, in setlocale return _setlocale(category, locale) locale.Error: unsupported locale setting

    Read the article

  • Make Firefox Show Google Results for Default Address Bar Searches

    - by The Geek
    Have you ever typed something incorrectly into the Firefox address bar, and then had it take you to a page you weren’t expecting? The reason is because Firefox uses Google’s “I’m Feeling Lucky” search, but you can change it. Scratching your head? Let’s take a quick run through what we’re talking about… Normally, if you typed in something like just “howtogeek” in the address bar, and then hit enter… you’ll be taken directly to the How-To Geek site. But how? Very simple! It’s the same place you would have been taken to if you typed “howtogeek” into Google, and then clicked the “I’m Feeling Lucky” button, which takes you to the first result. This is what Firefox does behind the scenes when you put something into the address bar that isn’t a URL. But what if you’d rather head to the search results page instead? Luckily, all you have to do is tweak an about:config parameter in Firefox. Just head into about:config in the address bar, and then filter for keyword.url like so: Double-click on the entry in the list, and then delete the &gfns=1 from the value. That’s the part of the URL that triggers Google to redirect to the first result. And now, the next time you type something into the address bar, either on purpose or because you typo’d it, you’ll be taken to the results page instead: About:Config tweaking is lots of fun. Similar Articles Productive Geek Tips Make Firefox Quick Search Use Google’s Beta Search KeysMake Firefox Built-In Search Box Use Google’s Experimental Search KeysCombine Wolfram Alpha & Google Search Results in FirefoxHow To Run 4 Different Google Searches at Once In the Same TabChange Default Feed Reader in Firefox TouchFreeze Alternative in AutoHotkey The Icy Undertow Desktop Windows Home Server – Backup to LAN The Clear & Clean Desktop Use This Bookmarklet to Easily Get Albums Use AutoHotkey to Assign a Hotkey to a Specific Window Latest Software Reviews Tinyhacker Random Tips DVDFab 6 Revo Uninstaller Pro Registry Mechanic 9 for Windows PC Tools Internet Security Suite 2010 Looking for Good Windows Media Player 12 Plug-ins? Find Out the Celebrity You Resemble With FaceDouble Whoa ! Use Printflush to Solve Printing Problems Icelandic Volcano Webcams Open Multiple Links At One Go

    Read the article

  • How to optimise Andengine's PathModifer (with singleton or pool)?

    - by Casla
    I am trying to build a game where the character find and follows a new path when a new destination is issued by the player, kinda like how units in RTS games work. This is done on a TMX map and I am using the A Star path finder utilities in Andengine to do this.David helped me on that: How can I change the path a sprite is following in real time? At the moment, every-time a new path is issued, I have to abandon the existing PathModifer and Path instances, and create new ones, and from what I read so far, creating new objects when you could re-use existing ones are a big waste for mobile applications. This is how I coded it at the moment: private void loadPathFound() { if (mAStarPath != null) { modifierPath = new org.andengine.entity.modifier.PathModifier.Path(mAStarPath.getLength()); /* replace the first node in the path as the player's current position */ modifierPath.to(player.convertLocalToSceneCoordinates(12, 31)[Constants.VERTEX_INDEX_X]-12, player.convertLocalToSceneCoordinates(12, 31)[Constants.VERTEX_INDEX_Y]-31); for (int i=1; i<mAStarPath.getLength(); i++) { modifierPath.to(mAStarPath.getX(i)*TILE_WIDTH, mAStarPath.getY(i)*TILE_HEIGHT); /* passing in the duration depended on the length of the path, so that the animation has a constant duration for every step */ player.registerEntityModifier(new PathModifier(modifierPath.getLength()/100, modifierPath, null, mIPathModifierListener)); } } The ideal implementation will be to always have just one object of PathModifer and just reset the destination of the path. But I don't know how you can apply the singleton patther on Andengine's PathModifer, there is no method to reset attribute of the path nor the pathModifer. So without re-write the PathModifer and the Path class, or use reflection, is there any other way to implement singleton PathModifer? Thanks for your help.

    Read the article

  • WP E Commerce Safe Mode restriction error [on hold]

    - by Mustafa Kamal
    I have my online shop, created with WP Ecommerce getting broken after I moved it to another server. I could be sure that the problem comes from WP Ecommerce because when I disable that plugin. Everything run as expected. This is the exact error message Warning: session_start() [function.session-start]: SAFE MODE Restriction in effect. The script whose uid is 515 is not allowed to access /tmp owned by uid 0 in /home/mikalu/public_html/wp-content/plugins/wp-e-commerce/wpsc-core/wpsc-constants.php on line 17 Fatal error: session_start() [<a href='function.session-start'>function.session-start</a>]: Failed to initialize storage module: files (path: ) in /home/mikalu/public_html/wp-content/plugins/wp-e-commerce/wpsc-core/wpsc-constants.php on line 17 I've tried to turn off safe mode on my php configuration. nothing happens. the error's still there. I thought it was some kind of permission issue, so I tried to change /tmp permission to 777. Nothing happens. I googled it some more and suspect it might have something to do with fastCGI configuration and stuff. Which I totally don't understand. My googling result mostly suggest me to consult the web hosting provider or even to move to another host. But in this case, I am the owner of the server (VPS with cPanel/WHM). And I don't have any idea how to solve this kind of problem.

    Read the article

  • USB3 boot device disappears post-grub

    - by JoBu1324
    I have an installation of Ubuntu 12.10 on a USB3 device, and it occasionally disappears during boot, dropping me into busybox. This is what I've been able to figure out so far: During a single boot, the following happened: At the grub2 menu, I typed c and dropped to the grub> prompt I typed ls -l and got a list of all the devices, including partitions and UUIDs - the USB3 partitions were available I escaped back to the boot select menu, selected the default item (ubuntu) and hit enter The screen went black for a second before turning into the purple Ubuntu boot screen with the dots (which usually indicates that the boot will fail. When all is well I don't get the black screen) The boot dropped into BusyBox v1.19.3 with the message `ALERT! /dev/disk/by-uuid/[uuid] does not exist blkid displays all of the partitions except those of the USB3 device, as does ls /dev/disk/by-uuid or any of the alternatives.

    Read the article

  • Sales and Procurement Contracts 12.1.3++ Release Information

    - by LuciaC
    New functionality has been released for Sales and Procurement Contracts in a new patch: Contracts 12.1.3++: Patch 13877401: 12.1.3 Rollup for Oracle Contracts Core. The new functionality includes: APIs for Import of Contract Templates, Contract Expert rules, Questions and Constants: The three APIs are as follows: API for Templates, API for Rules, and API for Questions and Constants. These can be used to both create entities and update existing templates and rules. The APIs will display error and warning messages which can be processed and analyzed by the customer. Ability to Apply Multiple Templates to a Sourcing, Procurement or Sales Document: The buyer can select and add multiple templates to a quote,sales agreement document, sourcing or purchasing odcument.  All the clauses and deliverables from the new templates are synchronized with the document. The Contract Expert rules are from the original template. The buyer can also view the list of templates that are added to any sales or procurement document. Ability to Define Multi-Row Variables: You can create user defined manual variables that are tables containing one row per line or multiple rows. Contract Preview will print the variable values according to the layout defined for the variable. These variables are not available for Contract Expert Rules and Supplier. Enhancement to Suggested Sections for Clauses by Contract Expert: You can associate multiple default sections with a clause. A clause is associated with multiple values of any system variable and for each such value a section name is associated in Contracts Terms Library. When Contract Expert is run in the contract authoring flow, the clause is automatically placed in the associated section name. Plus many more new features. Read the following notes for details on all the new and changed functionality: Oracle Procurement Contracts Release Notes, Release 12.1.3++ (Doc ID 1467140.1) Oracle Sales Contracts Release Notes, Release 12.1.3++ (Doc ID 1467149.1) Oracle E-Business Suite Releases 12.1 and 12.2 Release Content Documents (Doc ID 1302189.1)

    Read the article

  • Diving into Scala with Cay Horstmann

    - by Janice J. Heiss
    A new interview with Java Champion Cay Horstmann, now up on otn/java, titled  "Diving into Scala: A Conversation with Java Champion Cay Horstmann," explores Horstmann's ideas about Scala as reflected in his much lauded new book,  Scala for the Impatient.  None other than Martin Odersky, the inventor of Scala, called it "a joy to read" and the "best introduction to Scala". Odersky was so enthused by the book that he asked Horstmann if the first section could be made available as a free download on the Typesafe Website, something Horstmann graciously assented to. Horstmann acknowledges that some aspects of Scala are very complex, but he encourages developers to simply stay away from those parts of the language. He points to several ways Java developers can benefit from Scala: "For example," he says, " you can write classes with less boilerplate, file and XML handling is more concise, and you can replace tedious loops over collections with more elegant constructs. Typically, programmers at this level report that they write about half the number of lines of code in Scala that they would in Java, and that's nothing to sneeze at. Another entry point can be if you want to use a Scala-based framework such as Akka or Play; you can use these with Java, but the Scala API is more enjoyable. " Horstmann observes that developers can do fine with Scala without grasping the theory behind it. He argues that most of us learn best through examples and not through trying to comprehend abstract theories. He also believes that Scala is the most attractive choice for developers who want to move beyond Java and C++.  When asked about other choices, he comments: "Clojure is pretty nice, but I found its Lisp syntax a bit off-putting, and it seems very focused on software transactional memory, which isn't all that useful to me. And it's not statically typed. I wanted to like Groovy, but it really bothers me that the semantics seems under-defined and in flux. And it's not statically typed. Yes, there is Groovy++, but that's in even sketchier shape. There are a couple of contenders such as Kotlin and Ceylon, but so far they aren't real. So, if you want to do work with a statically typed language on the JVM that exists today, Scala is simply the pragmatic choice. It's a good thing that it's such a nice choice." Learn more about Scala by going to the interview here.

    Read the article

  • First languages with generic programming support

    - by oluies
    Which was the first language with generic programming support, and what was the first major staticly typed language (widely used) with generics support. Generics implement the concept of parameterized types to allow for multiple types. The term generic means "pertaining to or appropriate to large groups of classes." I have seen the following mentions of "first": First-order parametric polymorphism is now a standard element of statically typed programming languages. Starting with System F [20,42] and functional programming lan- guages, the constructs have found their way into mainstream languages such as Java and C#. In these languages, first-order parametric polymorphism is usually called generics. From "Generics of a Higher Kind", Adriaan Moors, Frank Piessens, and Martin Odersky Generic programming is a style of computer programming in which algorithms are written in terms of to-be-specified-later types that are then instantiated when needed for specific types provided as parameters. This approach, pioneered by Ada in 1983 From Wikipedia Generic Programming

    Read the article

  • First languages with generic programming support

    - by oluies
    Which was the first language with generic programming support, and what was the first major staticly typed language (widely used) with generics support. Generics implement the concept of parameterized types to allow for multiple types. The term generic means "pertaining to or appropriate to large groups of classes." I have seen the following mentions of "first": First-order parametric polymorphism is now a standard element of statically typed programming languages. Starting with System F [20,42] and functional programming lan- guages, the constructs have found their way into mainstream languages such as Java and C#. In these languages, first-order parametric polymorphism is usually called generics. From "Generics of a Higher Kind", Adriaan Moors, Frank Piessens, and Martin Odersky Generic programming is a style of computer programming in which algorithms are written in terms of to-be-specified-later types that are then instantiated when needed for specific types provided as parameters. This approach, pioneered by Ada in 1983 From Wikipedia Generic Programming

    Read the article

  • How can I install canon pixma ip100 driver for Ubuntu 12.04LTS 64bit?

    - by kina
    I tried installing the driver by typing the following commands in the terminal: sudo add-apt-repository ppa:michael-gruz/canon - the result was the following: You are about to add the following PPA to your system: More info: https://launchpad.net/~michael-gruz/+archive/canon Press [ENTER] to continue or ctrl-c to cancel adding it Then I typed: sudo apt-get update - the result was the following: Executing: gpg --ignore-time-conflict --no-options --no-default-keyring --secret-keyring /tmp/tmp.HDuHmOSJ0l --trustdb-name /etc/apt/trustdb.gpg --keyring /etc/apt/trusted.gpg --primary-keyring /etc/apt/trusted.gpg --keyserver hkp://keyserver.ubuntu.com:80/ --recv 84E550CD36EC35430A66AC5A03396E1C3F7B4A1D gpg: requesting key 3F7B4A1D from hkp server keyserver.ubuntu.com gpg: key 3F7B4A1D: "Launchpad Misakovi" not changed gpg: Total number processed: 1 gpg: unchanged: 1 I typed the next command: sudo apt-get install cnijfilter-ip100series The return response was: Reading package lists... Done Building dependency tree Reading state information... Done E: Unable to locate package cnijfilter-ip100series Does anyone know the solution? Kina

    Read the article

  • Catching typos or other errors in web-based scripting languages

    - by foreyez
    Hi, My background is mainly strongly typed languages (java, c++, c#). Having recently gotten back to a bit of javascript, I found it a bit annoying that if I misspell something by accident (for example I'll type 'myvar' instead of 'myVar') my entire script crashes. The browser itself most of the time doesn't even tell me I have an error, my program will just be blank, etc. Then I have to hunt down my code line by line and find the error which is very time consuming. In the languages I am used to the compiler lets me know if I made a typo. My question to you is, how do you overcome this issue in scripting (javascript)? Can you give me some tips? (this question is mainly aimed at people that have also come from a strongly typed language). Note: I mainly use the terminal/VIM ... this is mainly b/c I like terminal and I SSH alot too

    Read the article

  • Faster, Simpler access to Azure Tables with Enzo Azure API

    - by Herve Roggero
    After developing the latest version of Enzo Cloud Backup I took the time to create an API that would simplify access to Azure Tables (the Enzo Azure API). At first, my goal was to make the code simpler compared to the Microsoft Azure SDK. But as it turns out it is also a little faster; and when using the specialized methods (the fetch strategies) it is much faster out of the box than the Microsoft SDK, unless you start creating complex parallel and resilient routines yourself. Last but not least, I decided to add a few extension methods that I think you will find attractive, such as the ability to transform a list of entities into a DataTable. So let’s review each area in more details. Simpler Code My first objective was to make the API much easier to use than the Azure SDK. I wanted to reduce the amount of code necessary to fetch entities, remove the code needed to add automatic retries and handle transient conditions, and give additional control, such as a way to cancel operations, obtain basic statistics on the calls, and control the maximum number of REST calls the API generates in an attempt to avoid throttling conditions in the first place (something you cannot do with the Azure SDK at this time). Strongly Typed Before diving into the code, the following examples rely on a strongly typed class called MyData. The way MyData is defined for the Azure SDK is similar to the Enzo Azure API, with the exception that they inherit from different classes. With the Azure SDK, classes that represent entities must inherit from TableServiceEntity, while classes with the Enzo Azure API must inherit from BaseAzureTable or implement a specific interface. // With the SDK public class MyData1 : TableServiceEntity {     public string Message { get; set; }     public string Level { get; set; }     public string Severity { get; set; } } //  With the Enzo Azure API public class MyData2 : BaseAzureTable {     public string Message { get; set; }     public string Level { get; set; }     public string Severity { get; set; } } Simpler Code Now that the classes representing an Azure Table entity are defined, let’s review the methods that the Azure SDK would look like when fetching all the entities from an Azure Table (note the use of a few variables: the _tableName variable stores the name of the Azure Table, and the ConnectionString property returns the connection string for the Storage Account containing the table): // With the Azure SDK public List<MyData1> FetchAllEntities() {      CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConnectionString);      CloudTableClient tableClient = storageAccount.CreateCloudTableClient();      TableServiceContext serviceContext = tableClient.GetDataServiceContext();      CloudTableQuery<MyData1> partitionQuery =         (from e in serviceContext.CreateQuery<MyData1>(_tableName)         select new MyData1()         {            PartitionKey = e.PartitionKey,            RowKey = e.RowKey,            Timestamp = e.Timestamp,            Message = e.Message,            Level = e.Level,            Severity = e.Severity            }).AsTableServiceQuery<MyData1>();        return partitionQuery.ToList();  } This code gives you automatic retries because the AsTableServiceQuery does that for you. Also, note that this method is strongly-typed because it is using LINQ. Although this doesn’t look like too much code at first glance, you are actually mapping the strongly-typed object manually. So for larger entities, with dozens of properties, your code will grow. And from a maintenance standpoint, when a new property is added, you may need to change the mapping code. You will also note that the mapping being performed is optional; it is desired when you want to retrieve specific properties of the entities (not all) to reduce the network traffic. If you do not specify the properties you want, all the properties will be returned; in this example we are returning the Message, Level and Severity properties (in addition to the required PartitionKey, RowKey and Timestamp). The Enzo Azure API does the mapping automatically and also handles automatic reties when fetching entities. The equivalent code to fetch all the entities (with the same three properties) from the same Azure Table looks like this: // With the Enzo Azure API public List<MyData2> FetchAllEntities() {        AzureTable at = new AzureTable(_accountName, _accountKey, _ssl, _tableName);        List<MyData2> res = at.Fetch<MyData2>("", "Message,Level,Severity");        return res; } As you can see, the Enzo Azure API returns the entities already strongly typed, so there is no need to map the output. Also, the Enzo Azure API makes it easy to specify the list of properties to return, and to specify a filter as well (no filter was provided in this example; the filter is passed as the first parameter).  Fetch Strategies Both approaches discussed above fetch the data sequentially. In addition to the linear/sequential fetch methods, the Enzo Azure API provides specific fetch strategies. Fetch strategies are designed to prepare a set of REST calls, executed in parallel, in a way that performs faster that if you were to fetch the data sequentially. For example, if the PartitionKey is a GUID string, you could prepare multiple calls, providing appropriate filters ([‘a’, ‘b’[, [‘b’, ‘c’[, [‘c’, ‘d[, …), and send those calls in parallel. As you can imagine, the code necessary to create these requests would be fairly large. With the Enzo Azure API, two strategies are provided out of the box: the GUID and List strategies. If you are interested in how these strategies work, see the Enzo Azure API Online Help. Here is an example code that performs parallel requests using the GUID strategy (which executes more than 2 t o3 times faster than the sequential methods discussed previously): public List<MyData2> FetchAllEntitiesGUID() {     AzureTable at = new AzureTable(_accountName, _accountKey, _ssl, _tableName);     List<MyData2> res = at.FetchWithGuid<MyData2>("", "Message,Level,Severity");     return res; } Faster Results With Sequential Fetch Methods Developing a faster API wasn’t a primary objective; but it appears that the performance tests performed with the Enzo Azure API deliver the data a little faster out of the box (5%-10% on average, and sometimes to up 50% faster) with the sequential fetch methods. Although the amount of data is the same regardless of the approach (and the REST calls are almost exactly identical), the object mapping approach is different. So it is likely that the slight performance increase is due to a lighter API. Using LINQ offers many advantages and tremendous flexibility; nevertheless when fetching data it seems that the Enzo Azure API delivers faster.  For example, the same code previously discussed delivered the following results when fetching 3,000 entities (about 1KB each). The average elapsed time shows that the Azure SDK returned the 3000 entities in about 5.9 seconds on average, while the Enzo Azure API took 4.2 seconds on average (39% improvement). With Fetch Strategies When using the fetch strategies we are no longer comparing apples to apples; the Azure SDK is not designed to implement fetch strategies out of the box, so you would need to code the strategies yourself. Nevertheless I wanted to provide out of the box capabilities, and as a result you see a test that returned about 10,000 entities (1KB each entity), and an average execution time over 5 runs. The Azure SDK implemented a sequential fetch while the Enzo Azure API implemented the List fetch strategy. The fetch strategy was 2.3 times faster. Note that the following test hit a limit on my network bandwidth quickly (3.56Mbps), so the results of the fetch strategy is significantly below what it could be with a higher bandwidth. Additional Methods The API wouldn’t be complete without support for a few important methods other than the fetch methods discussed previously. The Enzo Azure API offers these additional capabilities: - Support for batch updates, deletes and inserts - Conversion of entities to DataRow, and List<> to a DataTable - Extension methods for Delete, Merge, Update, Insert - Support for asynchronous calls and cancellation - Support for fetch statistics (total bytes, total REST calls, retries…) For more information, visit http://www.bluesyntax.net or go directly to the Enzo Azure API page (http://www.bluesyntax.net/EnzoAzureAPI.aspx). About Herve Roggero Herve Roggero, Windows Azure MVP, is the founder of Blue Syntax Consulting, a company specialized in cloud computing products and services. Herve's experience includes software development, architecture, database administration and senior management with both global corporations and startup companies. Herve holds multiple certifications, including an MCDBA, MCSE, MCSD. He also holds a Master's degree in Business Administration from Indiana University. Herve is the co-author of "PRO SQL Azure" from Apress and runs the Azure Florida Association (on LinkedIn: http://www.linkedin.com/groups?gid=4177626). For more information on Blue Syntax Consulting, visit www.bluesyntax.net.

    Read the article

  • Best Practices for serializing/persisting String Object Dictionary entities

    - by Mark Heath
    I'm noticing a trend towards using a dictionary of string to object (or sometimes string to string), instead of strongly typed objects. For example, the new Katana project makes heavy use of IDictionary<string,object>. This approach avoids the need to continually update your entity classes/DTOs and the database tables that persist them with new properties. It also avoids the need to create new derived entity types to support new types of entity, since the Dictionary is flexible enough to store any arbitrary properties. Here's a contrived example: class StorageDevice { public int Id { get; set; } public string Name { get; set; } } class NetworkShare : StorageDevice { public string Path { get; set; } public string LoginName { get; set; } public string Password { get; set; } } class CloudStorage : StorageDevice { public string ServerUri { get; set } public string ContainerName { get; set; } public int PortNumber { get; set; } public Guid ApiKey { get; set; } } versus: class StorageDevice { public IDictionary<string, object> Properties { get; set; } } Basically I'm on the lookout for any talks, books or articles on this approach, so I can pick up on any best practices / difficulties to avoid. Here's my main questions: Does this approach have a name? (only thing I've heard used so far is "self-describing objects") What are the best practices for persisting these dictionaries into a relational database? Especially the challenges of deserializing them successfully with strongly typed languages like C#. Does it change anything if some of the objects in the dictionary are themselves lists of strongly typed entities? Should a second dictionary be used if you want to temporarily store objects that are not to be persisted/serialized across a network, or should you use some kind of namespacing on the keys to indicate this?

    Read the article

  • Are Java's public fields just a tragic historical design flaw at this point?

    - by Avi Flax
    It seems to be Java orthodoxy at this point that one should basically never use public fields for object state. (I don't necessarily agree, but that's not relevant to my question.) Given that, would it be right to say that from where we are today, it's clear that Java's public fields were a mistake/flaw of the language design? Or is there a rational argument that they're a useful and important part of the language, even today? Thanks! Update: I know about the more elegant approaches, such as in C#, Python, Groovy, etc. I'm not directly looking for those examples. I'm really just wondering if there's still someone deep in a bunker, muttering about how wonderful public fields really are, and how the masses are all just sheep, etc. Update 2: Clearly static final public fields are the standard way to create public constants. I was referring more to using public fields for object state (even immutable state). I'm thinking that it does seem like a design flaw that one should use public fields for constants, but not for state… a language's rules should be enforced naturally, by syntax, not by guidelines.

    Read the article

  • How do I get to the maintenace shell?

    - by Narida
    I'm asking this because initially, my problem was this (power failure during installation, so I typed the following instructions in the maintenance shell: sudo mount -o remount,rw / sudo dpkg --configure a sudo mount -o remount,ro / sudo sync sudo reboot The first three lines worked, afterwards, my computer (a Dell Inspiron 530) got stalled for several hours, so I unplugged it. When I turned it on, the log in screen appeared, and after I try to write my password, it leads me back to the log screen. I must note that when I typed the first three lines during the maintenance shell mode, it said that the errors which were encountered during processing were: initscripts bluez gnome-bluetooth So, what do I have to do in order to get back to the maintenance shell so I can type code again? And, what code do I have to write in order to restore my computer? Thank you for your attention.

    Read the article

  • Lost access to the unity interface how to fix? (ubuntu 11.10)

    - by Tal Galili
    o.k, this is embarrassing: I have installed Compiz Config Settings Manager and tried to fix it so that the transition time between changing tabs (using alt+tab) will be short. by accident I un-pressed V from something else, and it asked me about a conflict - I pressed the "x" button to close the window and as a result I stopped seeing the unity interface. That is - I can not see any buttons of the left side. I went to the terminal (ctrl+alt+F1) and ran ccsm As a result I got the following error: $ ccsm /usr/lib/python2.7/site-packages/gtk-2.0/gtk/__init__.py:57: GtkWarning: could not open display warnings.warn(str(e), _gtk.Warning) Traceback (most recent call last): File "/usr/bin/ccsm", line 93, in <module> import ccm File "/usr/lib/python2.7/site-packages/ccm/__init__.py", line 1, in <module> from ccm.Conflicts import * File "/usr/lib/python2.7/site-packages/ccm/Conflicts.py", line 26, in <module> from ccm.Constants import * File "/usr/lib/python2.7/site-packages/ccm/Constants.py", line 29, in <module> CurrentScreenNum = gtk.gdk.display_get_default().get_default_screen().get_number() AttributeError: 'NoneType' object has no attribute 'get_default_screen' What should I do next? Thanks.

    Read the article

  • Nvidia Linux Driver Huge Resolution

    - by darxsys
    I'm trying to setup a working CUDA SDK on my Linux Mint. I'm new to Linux and everything connected with it. So, I tried following some steps on how to install CUDA. Firstly, I downloaded a Linux driver from here: http://developer.nvidia.com/cuda/cuda-downloads version 295.41. After that, I barely found a way to run it. I did it like this: 1. typed in sudo init 1 in terminal and switched to root 2. typed service mdm stop 3. ran the *.run file downloaded from the link above Then it started installing the driver. It gave some warning messages, but I ignored it. After installation, I typed init 5 and it came back to GUI screen, BUT everything is huge. I restarted, still huge. My screen resolution is 640x480 on a 17 inch laptop monitor. I tried running Nvidia X Server Settings, but it says: "You do not appear to be using Nvidia X Driver. Please edit your X configuration file." I tried that. Nothing happened. I cant change the resolution because that Nvidia Settings thing gives no options. Then I googled some things, installing some packages - nothing. The biggest problem is I don't understand whats really going on. My laptop is a Samsung with i7 and Nvidia Gt 650M with optimus. I cant even install bumblebee, but that is something I will try if I manage to get my resolution to default. Please, help!

    Read the article

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