Daily Archives

Articles indexed Monday January 31 2011

Page 8/14 | < Previous Page | 4 5 6 7 8 9 10 11 12 13 14  | Next Page >

  • How to show/hide UIImageView when I want.

    - by Madness64
    I'm having a little problem with an iPhone app I'm currently developing. When the user touch a button, it calls an IBAction named refreshQuestion, which is supposed to show an image hover the screen to ask the user to wait a moment, then it has to call another function, and finally it has to hide the image. The problem is that the image won't appear. As well as the network activity indicator. Any help? Here is the code : - (IBAction)refreshQuestion:(id)sender{ pleaseWait.hidden = NO; [UIApplication sharedApplication].networkActivityIndicatorVisible = YES; [self loadData]; pleaseWait.hidden = YES; [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; }

    Read the article

  • JSF 2.0 sample or open source application

    - by Theo
    Does anyone know a complete JSF 2.0 sample or open source application using JSF 2.0 features (Facelets, Composite Component, Templates, Ajax, Navigation, etc.). Would be a good reference to learn some best practices. I'm talking about an application that you would also use in production. The only ones I know are ScrumToys and PetCatalog which are delivered with NetBeans 6.9 and are "tutorial-like" applications.

    Read the article

  • Hide anchors using jQuery

    - by Eric Di Bari
    I've created a dynamic page that, depending on the view type, will sometimes utilize the anchor tags and other times not. Essentially, I want to be able to control if on click the page jumps to the anchor. Is it possible to hide anchor tags using jQUery, so they are essentially removed? I need to be able to re-enable the anchors when necessary, and always show the current anchor in the browser's address bar. It seems to work in FireFox, but not in Internet Explorer. I have three sections: the 'table of contents', the content, and the javascript (jQuery) code Table of Contents <a id="expandLink0" class="expandLinksList" href="#green">What is green purchasing</a><br> <a id="expandLink1" class="expandLinksList" href="#before">Before you buy</a><br> Contents <ul id="makeIntoSlideshowUL">' <li id="slideNumber0" class="slideShowSlide"> <a name="green"></a> <div>Green Purchasing refers to the procurement of products and service...<a href="#topOfPageAnchor" class="topOfPageAnchorClass">Back to Top</a></div> </li> <li id="slideNumber1" class="slideShowSlide"> <a name="before"></a> <div>We easily accomplish the first four bullet points under...<a href="#topOfPageAnchor" class="topOfPageAnchorClass">Back to Top</a></div> </li> </ul> jQuery On Page Load $(".slideShowSlide").each(function() { $(this).children(":first-child").hide(); }); jQuery to re-enable links $(".slideShowSlide").each(function() { $(this).children(":first-child").show(); });

    Read the article

  • Perl TCP Server handling multiple Client connections

    - by Matt
    I'll preface this by saying I have minimal experience with both Perl and Socket programming, so I appreciate any help I can get. I have a TCP Server which needs to handle multiple Client connections simultaneously and be able to receive data from any one of the Clients at any time and also be able to send data back to the Clients based on information it's received. For example, Client1 and Client2 connect to my Server. Client2 sends "Ready", the server interprets that and sends "Go" to Client1. The following is what I have written so far: my $sock = new IO::Socket::INET { LocalHost => $host, // defined earlier in code LocalPort => $port, // defined earlier in code Proto => 'tcp', Listen => SOMAXCONN, Reuse => 1, }; die "Could not create socket $!\n" unless $sock; while ( my ($new_sock,$c_addr) = $sock->accept() ) { my ($client_port, $c_ip) = sockaddr_in($c_addr); my $client_ipnum = inet_ntoa($c_ip); my $client_host = ""; my @threads; print "got a connection from $client_host", "[$client_ipnum]\n"; my $command; my $data; while ($data = <$new_sock>) { push @threads, async \&Execute, $data; } } sub Execute { my ($command) = @_; // if($command) = "test" { // send "go" to socket1 print "Executing command: $command\n"; system($command); } I know both of my while loops will be blocking and I need a way to implement my accept command as a thread, but I'm not sure the proper way of writing it.

    Read the article

  • PySide / PyQt QStyledItemDelegate list in table

    - by danodonovan
    Dear All, I'm trying to create a table of lists in Python with Qt (PySide/PyQt - matters not) and my lists are squashed into the table cells. Is there a way to get the list delegates to 'pop out' of their cells? I've attached a simple code snippet - replace 'PySide' with 'PyQt4' depending on your preference from PySide import QtCore, QtGui class ListDelegate(QtGui.QStyledItemDelegate): def createEditor(self, parent, option, index): editor = QtGui.QListWidget(parent) for i in range( 12 ): editor.addItem('list item %d' % i) return editor if __name__ == '__main__': import sys app = QtGui.QApplication(sys.argv) model = QtGui.QStandardItemModel(2, 2) tableView = QtGui.QTableView() delegate = ListDelegate() tableView.setItemDelegate(delegate) tableView.setModel(model) for row in range(2): for column in range(2): item = QtGui.QStandardItem( 'None' ) model.setItem(row, column, item) tableView.setWindowTitle('example') tableView.show() sys.exit(app.exec_()) If you hadn't guessed I'm pretty new to this Qt lark Thanks in advance, Dan

    Read the article

  • GIt Deployment + Configuration Files + Heroku

    - by Andrew
    I'm using Heroku to host a Rails app, which means using Git to deploy to Heroku. Because of the "pure Git workflow" on Heroku, anything that needs to go upstream to the server has to be configured identically on my local box. However I need to have certain configuration files be different depending on whether I'm in the local setup or deployed on Heroku. Again, because of the deployment method Heroku uses I can't use .gitignore and a template (as I have seen suggested many times, and have used in other projects). What I need is for git to somehow track changes on a file, but selectively tell git not to override certain files when pulling from a particular repo -- basically to make certain changes one-way only. Can this be done? I'd appreciate any suggestions!

    Read the article

  • Find Date From Non Contiguous Ranges

    - by AGoodDisplayName
    I am looking to find an best way to find a date from date ranges that may or may not be contiguous (I am trying to avoid a cursor, or a heavy function if possible). Lets say I have hotel guests that come and go (check in, check out). I want to find the date that a certain guest stayed their 45th night with us. The database we use records the data as so: Create Table #GuestLog( ClientId int, StartDate DateTime, EndDate DateTime) Here is some data Insert Into #GuestLog Values(1, '01/01/2010', '01/10/2010') Insert Into #GuestLog Values(1, '01/16/2010', '01/29/2010') Insert Into #GuestLog Values(1, '02/13/2010', '02/26/2010') Insert Into #GuestLog Values(1, '04/05/2010', '06/01/2010') Insert Into #GuestLog Values(1, '07/01/2010', '07/21/2010') So far I can only think of solutions that involve functions with temp tables and crazy stuff like that, I feel like I'm over thinking it. Thanks ahead of time.

    Read the article

  • Django ForeignKey _set on an inherited model

    - by neolaser
    I have two models Category and Entry. There is another model ExtEntry that inherits from Entry class Category(models.Model): title = models.CharField('title', max_length=255) description = models.TextField('description', blank=True) ... class Entry(models.Model): title = models.CharField('title', max_length=255) categories = models.ManyToManyField(Category) ... class ExtEntry(Entry): groups= models.CharField('title', max_length=255) value= models.CharField('title', max_length=255) ... I am able to use the Category.entry_set but I want to be able to do Category.blogentry_set but it is not available. If this is not available,then I need another method to get all ExtEntryrelated to one particular Category Thanks

    Read the article

  • Rails - Dynamic name routes namespace

    - by Kuro
    Hi, Using Rails 2.3, I'm trying to configure my routes but I uncounter some difficulties. I would like to have something like : http:// mydomain.com/mycontroller/myaction/myid That should respond with controllers in :front namespace http:// mydomain.com/aname/mycontroller/myaction/mydi That should respond with controllers in :custom namespace I try something like this, but I'm totaly wrong : map.namespace :front, :path_prefix => "" do |f| f.root :controller => :home, :action => :index f.resources :home ... end map.namespace :custom, :path_prefix => "" do |m| m.root :controller => :home, :action => :index m.resources :home ... m.match ':sub_url/site/:controller/:action/:id' m.match ':sub_url/site/:controller/:action/:id' m.match ':sub_url/site/:controller/:action/:id.:format' m.match ':sub_url/site/:controller/:action.:format' end I put matching instruction in custom namespace but I'm not sure it's the right place for it. I think I really don't get the way to customize fields in url matching and I don't know how to find documentation about Rails 2.3, most of my research drove me to Rails 3 doc about the topic... Somebody to help me ?

    Read the article

  • As3 Communicate with C# or Asp.net

    - by brenjt
    I have been looking around for hours trying to find a clear simple solution to my question and have yet to find a good answer. I am trying to do a URL request in flash to my NOPCommerce site. I want to pass a GET value to the my .cs file which i'll then use that value to grab specific information and return it back to flash. How would I set up the C# or asp.net side of things? If anyone could give me an example of what I am looking for I would greatly appreciate it. I don't know if I am supposed to use a .aspx, .cs or .ascx file. Thanks, Brennan

    Read the article

  • RegEx to Reject Unescaped Character

    - by JDV72
    I want to restrict usage of unescaped ampersands in a particular input field. I'm having trouble getting a RegEx to kill usage of "&" unless followed by "amp;"...or perhaps just restrict usage of "& " (note the space). I tried to adapt the answer in this thread, but to no avail. Thanks. (FWIW, here's a RegEx I made to ensure that a filename field didn't contain restrited chars. and ended in .mp3. It works fine, but does it look efficient?)

    Read the article

  • position a div under another element

    - by user555222
    hi.. how can I position a div under another element without the rest of the layout is affected of the div element? <div style="margin:20px; padding:10px"> here is a little <span id="test" style="font-weight:bold">test</span> </div> <script> var elm = document.getElementById('test'); var div = elm.appendChild(document.createElement('div')); with(div){ style.position = 'absolute'; style.left = elm.offsetLeft; style.background = '#ffffff'; style.width = '100px'; style.height = '50px'; innerHTML = 'wooop'; } </script> this works in IE but not in FF.. FF ignores the style.left and position the element at 0px as if it was aligned to the left

    Read the article

  • Zend_Auth / Zend_Session error and storing objects in Auth Storage

    - by Martin
    Hi All, I have been having a bit of a problem with Zend_Auth and keep getting an error within my Acl. Within my Login Controller I setup my Zend_Auth storage as follows $auth = Zend_Auth::getInstance(); $result = $auth->authenticate($adapter); if ($result->isValid()) { $userId = $adapter->getResultRowObject(array('user_id'), null)->user_id; $user = new User_Model_User; $users = new User_Model_UserMapper; $users->find($userId, $user); $auth->getStorage()->write( $user ); } This seems to work well and I am able to use the object stored in the Zend_Auth storage within View Helpers without any problems. The problem that I seem to be having is when I try to use this within my Acl, below is a snippet from my Acl, as soon as it gets to the if($auth->hasIdentity()) { line I get the exception detailed further down. The $user->getUserLevel() is a methord within the User Model that allows me to convert the user_level_id that is stored in the database to a meaning full name. I am assuming that the auto loader sees these kind of methords and tries to load all the classes that would be required. When looking at the exception it appears to be struggling to find the class as it is stored in a module, I have the Auto Loader Name Space setup in my application.ini. Could anyone help with resolving this? class App_Controller_Plugin_Acl extends Zend_Controller_Plugin_Abstract { protected $_roleName; public function __construct() { $auth = Zend_Auth::getInstance(); if($auth->hasIdentity()) { $user = $auth->getIdentity(); $this->_roleName = strtolower($user->getUserLevel()); } else { $this->_roleName = 'guest'; } } } Fatal error: Uncaught exception 'Zend_Session_Exception' with message 'Zend_Session::start() - \Web\library\Zend\Loader.php(Line:146): Error #2 include_once() [&lt;a href='function.include'&gt;function.include&lt;/a&gt;]: Failed opening 'Menu\Model\UserLevel.php' for inclusion (include_path='\Web\application/../library;\Web\library;.;C:\php5\pear') Array' in \Web\library\Zend\Session.php:493 Stack trace: #0 \Web\library\Zend\Session\Namespace.php(143): Zend_Session::start(true) #1 \Web\library\Zend\Auth\Storage\Session.php(87): Zend_Session_Namespace-&gt;__construct('Zend_Auth') #2 \Web\library\Zend\Auth.php(91): Zend_Auth_Storage_Session-&gt;__construct() #3 \Web\library\Zend\A in \Web\library\Zend\Session.php on line 493 Thanks, Martin

    Read the article

  • Xpath: Selecting all of an element type?

    - by Johannes
    I'm just starting to learn Xpath, I'm trying to write a line of code that will select all of the actors in EACH movie parent (through Java!). Below, I have an example of one movie, but there are multiple <Movie> elements, each with <Actor> elements. <Movie Genre = 'Other'> <Title>Requiem For A Dream</Title> <ReleaseYear>2000</ReleaseYear> <Director>Darren Aronofsky</Director> <Actor Character = 'Sara Goldfarb'>Ellen Burstyn</Actor> <Actor Character = 'Harry Goldfarb'>Jared Leto</Actor> <Actor Character = 'Marion Silver'>Jennifer Connelly</Actor> <Actor Character = 'Tyrone C. Love'>Marlon Wayans</Actor> </Movie> Currently, I can only select the first <Actor> element of each <Movie> element -- is it possible to select all of them without using a for loop? Here is my current line of code that displays the first <Actor> element of every <Movie> element: System.out.println("Starring: " + xpath.evaluate("Actor", movieNode) + " as " + xpath.evaluate("Actor/@Character", movieNode) + "\n"); Any and all help if much appreciated!

    Read the article

  • Pylucene in Python 2.6 + MacOs Snow Leopard

    - by jbastos
    Greetings, I'm trying to install Pylucene on my 32-bit python running on Snow Leopard. I compiled JCC with success. But I get warnings while making pylucene: ld: warning: in build/temp.macosx-10.6-i386-2.6/build/_lucene/__init__.o, file is not of required architecture ld: warning: in build/temp.macosx-10.6-i386-2.6/build/_lucene/__wrap01__.o, file is not of required architecture ld: warning: in build/temp.macosx-10.6-i386-2.6/build/_lucene/__wrap02__.o, file is not of required architecture ld: warning: in build/temp.macosx-10.6-i386-2.6/build/_lucene/__wrap03__.o, file is not of required architecture ld: warning: in build/temp.macosx-10.6-i386-2.6/build/_lucene/functions.o, file is not of required architecture ld: warning: in build/temp.macosx-10.6-i386-2.6/build/_lucene/JArray.o, file is not of required architecture ld: warning: in build/temp.macosx-10.6-i386-2.6/build/_lucene/JObject.o, file is not of required architecture ld: warning: in build/temp.macosx-10.6-i386-2.6/build/_lucene/lucene.o, file is not of required architecture ld: warning: in build/temp.macosx-10.6-i386-2.6/build/_lucene/types.o, file is not of required architecture ld: warning: in /Developer/SDKs/MacOSX10.4u.sdk/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/JCC-2.3-py2.6-macosx-10.3-fat.egg/libjcc.dylib, file is not of required architecture ld: warning: in /Developer/SDKs/MacOSX10.4u.sdk/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/JCC-2.3-py2.6-macosx-10.3-fat.egg/libjcc.dylib, file is not of required architecture build of complete Then I try to import lucene: MacBookPro:~/tmp/trunk python Python 2.6.3 (r263:75184, Oct 2 2009, 07:56:03) [GCC 4.0.1 (Apple Inc. build 5493)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import pylucene Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named pylucene >>> import lucene Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/lucene-2.9.0-py2.6-macosx-10.6-i386.egg/lucene/__init__.py", line 7, in <module> import _lucene ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/lucene-2.9.0-py2.6-macosx-10.6-i386.egg/lucene/_lucene.so, 2): Symbol not found: __Z8getVMEnvP7_object Referenced from: /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/lucene-2.9.0-py2.6-macosx-10.6-i386.egg/lucene/_lucene.so Expected in: flat namespace in /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/lucene-2.9.0-py2.6-macosx-10.6-i386.egg/lucene/_lucene.so >>> Any hints?

    Read the article

  • HTML Calendar form and input arrays

    - by Christopher Ickes
    Hello. Looking for the best practice here... Have a form that consists of a calendar. Each day of the calendar has 2 text input fields - customer and check-in. What would be the best & most efficient way to send this form to PHP for processing? <form action="post"> <div class="day"> Day 1<br /> <label for="customer['.$current['date'].']">Customer</label> <input type="text" name="customer['.$current['date'].']" value="" size="20" /> <label for="check-in['.$current['date'].']">Check-In</label> <input type="text" name="check-in['.$current['date'].']" value="" size="20" /> <input type="submit" name="submit" value="Update" /> </day> <div class="day"> Day 2<br /> <label for="customer['.$current['date'].']">Customer</label> <input type="text" name="customer['.$current['date'].']" value="" size="20" /> <label for="check-in['.$current['date'].']">Check-In</label> <input type="text" name="check-in['.$current['date'].']" value="" size="20" /> <input type="submit" name="submit" value="Update" /> </day> </form> Is my current setup good? I feel there has to be a better option. My concern involves processing a whole year at once (which can happen) and adding additional text input fields.

    Read the article

  • audio stream sampling rate in linux

    - by farhan
    Im trying read and store samples from an audio microphone in linux using C/C++. Using PCM ioctls i setup the device to have a certain sampling rate say 10Khz using the SOUND_PCM_WRITE_RATE ioctl etc. The device gets setup correctly and im able to read back from the device after setup using the "read". int got = read(itsFd, b.getDataPtr(), b.sizeBytes()); The problem i have is that after setting the appropriate sampling rate i have a thread that continuously reads from /dev/dsp1 and stores these samples, but the number of samples that i get for 1 second of recording are way off the sampling rate and always orders of magnitude more than the set sampling rate. Any ideas where to begin on figuring out what might be the problem?

    Read the article

  • Parsing a URL - Php Question

    - by Adi Mathur
    I am using the Following code <?php $url = 'http://www.ewwsdf.org/012Q/rhod-05.php?arg=value#anchor'; $parse = parse_url($url); $lnk= "http://".$parse['host'].$parse['path']; echo $lnk; ?> This is giving me the output as http://www.ewwsdf.org/012Q/rhod-05.php How can i modify the code so that i get the output as http://www.ewwsdf.org/012Q/ Just need the Directory name without the file name ( I actually need the link so that i can link up the images which are on the pages, By appending the link behind the image Eg http://www.ewwsdf.org/012Q/hi.jpg )

    Read the article

  • SmartGWT Server File Browser

    - by jluzwick
    Hi All: I have been looking for a SmartGWT example that would show me how to build a File Browser widget that takes the files from the local server's root directory. The user would be shown the files through the browser which they could then select to perform some processing operations. So far I have thought of using SmartGWT's Tree-Data Binding-Load from Local Data Widget and then grabbing a list of the directories using: new File("\").listFiles(); My Question is: Is there a better way to do this? Has someone already thought of this and has an example of their code that I can see? PS: I'm fairly new to GWT and Web Services but fairly competent with Java. If you believe there is a better way to do this (while still doing this through the web and not using Applets, please tell me). Thanks

    Read the article

  • PHP no wait sem_acquire?

    - by SerEnder
    Not a specific code question, but more of a general coding question. I'm trying to use a semaphore in a work project to limit the number of users that can access certain processes at a concurrent time. From my understanding the following: $iKey = ftock($sSomeFileLocation,'sOneCharacterString'); //Generate the key if($sem_id = sem_get($iKey){ //1 user allowed if(sem_acquire($sem_id)){ //Do the limited process here sem_release($sem_id); } } The problem that I see here is that if there is already one user who has the semaphore key, then the next user just waits until the first user is done rather than just faulting out. Anyone know of a way that if the max_acquire number has been reached, sem_acquire (or similar) will just return false? Thanks

    Read the article

  • Welcome 2011

    - by PSteele
    About this time last year, I wrote a blog post about how January of 2010 was almost over and I hadn’t done a single blog post.  Ugh…  History repeats itself. 2010 in Review If I look back at 2010, it was a great year in terms of technology and development: Visited Redmond to attend the MVP Summit in February.  Had a great time with the MS product teams and got to connect with some really smart people. Continued my work on Visual Studio Magazine’s “C# Corner” column.  About mid-year, the column changed from an every-other-month print column to an every-other-month print column along with bi-monthly web-only articles.  Needless to say, this kept me even busier and away from my blog. Participated in another GiveCamp!  Thanks to the wonderful leadership of Michael Eaton and all of his minions, GiveCamp 2010 was another great success.  Planning for GiveCamp 2011 will be starting soon… I switched to DVCS full time.  After years of being a loyal SVN user, I got bit by the DVCS bug.  I played around with both Mercurial and Git and finally settled on Mercurial.  It’s seamless integration with Windows Explorer along with it’s wealth of plugins made me fall in love.  I can’t imagine going back and using a centralized version control system. Continued to work with the awesome group of talent at SRT Solutions.  Very proud that SRT won it’s third consecutive FastTrack award! Jumped off the BlackBerry train and enjoying the smooth ride of Android.  It was time to replace the old BlackBerry Storm so I did some research and settled on the Motorola DroidX.  I couldn’t be happier.  Android is a slick OS and the DroidX is a sweet piece of hardware.  Been dabbling in some Android development with both Eclipse and IntelliJ IDEA (I like IntelliJ IDEA a lot better!).   2011 Plans On January 1st I was pleasantly surprised to get an email from the Microsoft MVP program letting me know that I had received the MVP award again for my community work in 2010.  I’m honored and humbled to be recognized by Microsoft as well as my peers! I’ll continue to do some Android development.  I’m currently working on a simple app to get me feet wet.  It may even makes it’s way into the Android Market. I’ve got a project that could really benefit from WPF so I’ll be diving into WPF this year.  I’ve played around with WPF a bit in the past – simple demos and learning exercises – but this will give me a chance to build an entire application in WPF.  I’m looking forward to the increased freedom that a WPF UI should give me. I plan on blogging a lot more in 2011! Technorati Tags: Android,MVP,Mercurial,WPF,SRT,GiveCamp

    Read the article

  • Book review: Peopleware: Productive Projects and Teams

    - by DigiMortal
       Peopleware by Tom DeMarco and Timothy Lister is golden classic book that can be considered as mandatory reading for software project managers, team leads, higher level management and board members of software companies. If you make decisions about people then you cannot miss this book. If you are already good on managing developers then this book can make you even better – you will learn new stuff about successful development teams for sure. Why peopleware? Peopleware gives you very good hints about how to build up working environment for project teams where people can really do their work. Book also covers team building topics that are also important reading. As software developer I found practically all points in this book to be accurate and valid. Many times I have found my self thinking about same things and Peopleware made me more confident about my opinions. Peopleware covers also time management and planning topics that help you do way better job on using developers time effectively by minimizing the amount of interruptions by phone calls, pointless meetings and i-want-to-know-what-are-you-doing-right-now questions by managers who doesn’t write code anyway. I think if you follow suggestions given by Peopleware your developers are very happy. I suggest you to also read another great book – Death March by Edward Yourdon. Death March describes you effectively what happens when good advices given by Peopleware are totally ignored or worse yet – people are treated exactly opposite way. I consider also Death March as golden classics and I strongly recommend you to read this book too. Table of Contents Acknowledgments Preface to the Second Edition Preface to the First Edition Part 1: Managing the Human Resource Chapter 1: Somewhere Today, a Project Is Failing Chapter 2: Make a Cheeseburger, Sell a Cheeseburger Chapter 3: Vienna Waits for You Chapter 4: Quality-If Time Permits Chapter 5: Parkinson's Law Revisited Chapter 6: Laetrile Part II: The Office Environment Chapter 7: The Furniture Police Chapter 8: "You Never Get Anything Done Around Here Between 9 and 5" Chapter 9: Saving Money on Space Intermezzo: Productivity Measurement and Unidentified Flying Objects Chapter 10: Brain Time Versus Body Time Chapter 11: The Telephone Chapter 12: Bring Back the Door Chapter 13: Taking Umbrella Steps Part III: The Right People Chapter 14: The Hornblower Factor Chapter 15: Hiring a Juggler Chapter 16: Happy to Be Here Chapter 17: The Self-Healing System Part IV: Growing Productive Teams Chapter 18: The Whole Is Greater Than the Sum of the Parts Chapter 19: The Black Team Chapter 20: Teamicide Chapter 21: A Spaghetti Dinner Chapter 22: Open Kimono Chapter 23: Chemistry for Team Formation Part V: It't Supposed to Be Fun to Work Here Chapter 24: Chaos and Order Chapter 25: Free Electrons Chapter 26: Holgar Dansk Part VI: Son of Peopleware Chapter 27: Teamicide, Revisited Chapter 28: Competition Chapter 29: Process Improvement Programs Chapter 30: Making Change Possible Chapter 31: Human Capital Chapter 32:Organizational Learning Chapter 33: The Ultimate Management Sin Is Chapter 34: The Making of Community Notes Bibliography Index About the Authors

    Read the article

  • Workarounds for supporting MVVM in the Silverlight ContextMenu service

    - by cibrax
    As I discussed in my last post, some of the Silverlight controls does not support MVVM quite well out of the box without specific customizations. The Context Menu is another control that requires customizations for enabling data binding on the menu options. There are a few things that you might want to expose as view model for a menu item, such as the Text, the associated icon or the command that needs to be executed. That view model should look like this, public class MenuItemModel { public string Name { get; set; } public ICommand Command { get; set; } public Image Icon { get; set; } public object CommandParameter { get; set; } } This is how you can modify the built-in control to support data binding on the model above, public class CustomContextMenu : ContextMenu { protected override DependencyObject GetContainerForItemOverride() { CustomMenuItem item = new CustomMenuItem(); Binding commandBinding = new Binding("Command"); item.SetBinding(CustomMenuItem.CommandProperty, commandBinding);   Binding commandParameter = new Binding("CommandParameter"); item.SetBinding(CustomMenuItem.CommandParameterProperty, commandParameter);   return item; } }   public class CustomMenuItem : MenuItem { protected override DependencyObject GetContainerForItemOverride() { CustomMenuItem item = new CustomMenuItem();   Binding commandBinding = new Binding("Command"); item.SetBinding(CustomMenuItem.CommandProperty, commandBinding);   return item; } } The change is very similar to the one I made in the TreeView for manually data binding some of the Menu item properties to the model. Once you applied that change in the control, you can define it in your XAML like this. <toolkit:ContextMenuService.ContextMenu> <e:CustomContextMenu ItemsSource="{Binding MenuItems}"> <e:CustomContextMenu.ItemTemplate> <DataTemplate> <StackPanel Orientation="Horizontal" > <ContentPresenter Margin="0 0 4 0" Content="{Binding Icon}" /> <TextBlock Margin="0" Text="{Binding Name, Mode=OneWay}" FontSize="12"/> </StackPanel> </DataTemplate> </e:CustomContextMenu.ItemTemplate> </e:CustomContextMenu> </toolkit:ContextMenuService.ContextMenu> The property MenuItems associated to the “ItemsSource” in the parent model just returns a list of supported options (menu items) in the context menu. this.menuItems = new MenuItemModel[] { new MenuItemModel { Name = "My Command", Command = new RelayCommand(OnCommandClick), Icon = ImageLoader.GetIcon("command.png") } }; The only problem I found so far with this approach is that the context menu service does not support a HierarchicalDataTemplate in case you want to have an hierarchy in the context menu (MenuItem –> Sub menu items), but I guess we can live without that.

    Read the article

  • Plugin jQuery da Microsoft para Globalização

    - by Leniel Macaferi
    No mês passado eu escrevi sobre como a Microsoft está começando a fazer contribuições de código para a jQuery (em Inglês), e sobre algumas das primeiras contribuições de código nas quais estávamos trabalhando: Suporte para Templates jQuery e Linkagem de Dados (em Inglês). Hoje, lançamos um protótipo de um novo plugin jQuery para Globalização que te permite adicionar suporte à globalização/internacionalização para as suas aplicações JavaScript. Este plugin inclui informações de globalização para mais de 350 culturas que vão desde o Gaélico Escocês, o Frísio, Húngaro, Japonês, e Inglês Canadense. Nós estaremos lançando este plugin para a comunidade em um formato de código livre. Você pode baixar nosso protótipo do plugin jQuery para Globalização a partir do nosso repositório Github: http://github.com/nje/jquery-glob Você também pode baixar um conjunto de exemplos que demonstram alguns simples casos de uso com ele aqui. Entendendo Globalização O plugin jQuery para Globalização permite que você facilmente analise e formate números, moedas e datas para diferentes culturas em JavaScript. Por exemplo, você pode usar o plugin de globalização para mostrar o símbolo da moeda adequado para uma cultura: Você também pode usar o plugin de globalização para formatar datas para que o dia e o mês apareçam na ordem certa e para que os nomes dos dias e meses sejam corretamente traduzidos: Observe acima como o ano Árabe é exibido como 1431. Isso ocorre porque o ano foi convertido para usar o calendário Árabe. Algumas diferenças culturais, tais como moeda diferente ou nomes de meses, são óbvias. Outras diferenças culturais são surpreendentes e sutis. Por exemplo, em algumas culturas, o agrupamento de números é feito de forma irregular. Na cultura "te-IN" (Telugu na Índia), grupos possuem 3 dígitos e, em seguida, dois dígitos. O número 1000000 (um milhão) é escrito como "10,00,000". Algumas culturas não agrupam os números. Todas essas sutis diferenças culturais são tratadas pelo plugin de Globalização da jQuery automaticamente. Pegar as datas corretamente pode ser especialmente complicado. Diferentes culturas têm calendários diferentes, como o Gregoriano e os calendários UmAlQura. Uma única cultura pode até mesmo ter vários calendários. Por exemplo, a cultura Japonesa usa o calendário Gregoriano e um calendário Japonês que possui eras com nomes de imperadores Japoneses. O plugin de Globalização inclui métodos para a conversão de datas entre todos estes diferentes calendários. Usando Tags de Idioma O plugin de Globalização da jQuery utiliza as tags de idioma definidas nos padrões das RFCs 4646 e 5646 para identificar culturas (veja http://tools.ietf.org/html/rfc5646). Uma tag de idioma é composta por uma ou mais subtags separadas por hífens. Por exemplo: Tag do Idioma Nome do Idioma (em Inglês) en-UA English (Australia) en-BZ English (Belize) en-CA English (Canada) Id Indonesian zh-CHS Chinese (Simplified) Legacy Zu isiZulu Observe que um único idioma, como o Inglês, pode ter várias tags de idioma. Falantes de Inglês no Canadá formatam números, moedas e datas usando diferentes convenções daquelas usadas pelos falantes de Inglês na Austrália ou nos Estados Unidos. Você pode encontrar a tag de idioma para uma cultura específica usando a Language Subtag Lookup Tool (Ferramenta de Pesquisa de Subtags de Idiomas) em: http://rishida.net/utils/subtags/ O download do plugin de Globalização da jQuery inclui uma pasta chamada globinfo que contém as informações de cada uma das 350 culturas. Na verdade, esta pasta contém mais de 700 arquivos, porque a pasta inclui ambas as versões minified (tamanho reduzido) e não-minified de cada arquivo. Por exemplo, a pasta globinfo inclui arquivos JavaScript chamados jQuery.glob.en-AU.js para o Inglês da Austrália, jQuery.glob.id.js para o Indonésio, e jQuery.glob.zh-CHS para o Chinês (simplificado) Legacy. Exemplo: Definindo uma Cultura Específica Imagine que te pediram para criar um site em Alemão e que querem formatar todas as datas, moedas e números usando convenções de formatação da cultura Alemã de maneira correta em JavaScript no lado do cliente. O código HTML para a página pode ser igual a este: Observe as tags span acima. Elas marcam as áreas da página que desejamos formatar com o plugin de Globalização. Queremos formatar o preço do produto, a data em que o produto está disponível, e as unidades do produto em estoque. Para usar o plugin de Globalização da jQuery, vamos adicionar três arquivos JavaScript na página: a biblioteca jQuery, o plugin de Globalização da jQuery, e as informações de cultura para um determinado idioma: Neste caso, eu estaticamente acrescentei o arquivo JavaScript jQuery.glob.de-DE.js que contém as informações para a cultura Alemã. A tag de idioma "de-DE" é usada para o Alemão falado na Alemanha. Agora que eu tenho todos os scripts necessários, eu posso usar o plugin de Globalização para formatar os valores do preço do produto, data disponível, e unidades no estoque usando o seguinte JavaScript no lado do cliente: O plugin de Globalização jQuery amplia a biblioteca jQuery com novos métodos - incluindo novos métodos chamados preferCulture() e format(). O método preferCulture() permite que você defina a cultura padrão utilizada pelos métodos do plugin de Globalização da jQuery. Observe que o método preferCulture() aceita uma tag de idioma. O método irá buscar a cultura mais próxima que corresponda à tag do idioma. O método $.format() é usado para formatar os valores monetários, datas e números. O segundo parâmetro passado para o método $.format() é um especificador de formato. Por exemplo, passar um "c" faz com que o valor seja formatado como moeda. O arquivo LeiaMe (ReadMe) no github detalha o significado de todos os diferentes especificadores de formato: http://github.com/nje/jquery-glob Quando abrimos a página em um navegador, tudo está formatado corretamente de acordo com as convenções da língua Alemã. Um símbolo do euro é usado para o símbolo de moeda. A data é formatada usando nomes de dia e mês em Alemão. Finalmente, um ponto, em vez de uma vírgula é usado como separador numérico: Você pode ver um exemplo em execução da abordagem acima com o arquivo 3_GermanSite.htm neste download de amostras. Exemplo: Permitindo que um Usuário Selecione Dinamicamente uma Cultura No exemplo anterior, nós explicitamente dissemos que queríamos globalizar em Alemão (referenciando o arquivo jQuery.glob.de-DE.js). Vamos agora olhar para o primeiro de alguns exemplos que demonstram como definir dinamicamente a cultura da globalização a ser usada. Imagine que você deseja exibir uma lista suspensa (dropdown) de todas as 350 culturas em uma página. Quando alguém escolhe uma cultura a partir da lista suspensa, você quer que todas as datas da página sejam formatadas usando a cultura selecionada. Aqui está o código HTML para a página: Observe que todas as datas estão contidas em uma tag <span> com um atributo data-date (atributos data-* são um novo recurso da HTML 5, que convenientemente também ainda funcionam com navegadores mais antigos). Nós vamos formatar a data representada pelo atributo data-date quando um usuário selecionar uma cultura a partir da lista suspensa. A fim de mostrar as datas para qualquer cultura disponível, vamos incluir o arquivo jQuery.glob.all.js igual a seguir: O plugin de Globalização da jQuery inclui um arquivo JavaScript chamado jQuery.glob.all.js. Este arquivo contém informações de globalização para todas as mais de 350 culturas suportadas pelo plugin de Globalização. Em um tamanho de 367 KB minified (reduzido), esse arquivo não é pequeno. Devido ao tamanho deste arquivo, a menos que você realmente precise usar todas essas culturas, ao mesmo tempo, recomendamos que você adicione em uma página somente os arquivos JavaScript individuais para as culturas específicas que você pretende suportar, ao invés do arquivo jQuery.glob.all.js combinado. No próximo exemplo, eu vou mostrar como carregar dinamicamente apenas os arquivos de idioma que você precisa. A seguir, vamos preencher a lista suspensa com todas as culturas disponíveis. Podemos usar a propriedade $.cultures para obter todas as culturas carregadas: Finalmente, vamos escrever o código jQuery que pega cada elemento span com um atributo data-date e formataremos a data: O método parseDate() do plugin de Globalização da jQuery é usado para converter uma representação de uma data em string para uma data JavaScript. O método format() do plugin é usado para formatar a data. O especificador de formato "D" faz com que a data a ser formatada use o formato de data longa. E agora, o conteúdo será globalizado corretamente, independentemente de qual das 350 línguas o usuário que visita a página selecione. Você pode ver um exemplo em execução da abordagem acima com o arquivo 4_SelectCulture.htm neste download de amostras. Exemplo: Carregando Arquivos de Globalização Dinamicamente Conforme mencionado na seção anterior, você deve evitar adicionar o arquivo jQuery.glob.all.js em uma página, sempre que possível, porque o arquivo é muito grande. Uma melhor alternativa é carregar as informações de globalização que você precisa dinamicamente. Por exemplo, imagine que você tenha criado uma lista suspensa que exibe uma lista de idiomas: O seguinte código jQuery é executado sempre que um usuário seleciona um novo idioma na lista suspensa. O código verifica se o arquivo associado com a globalização do idioma selecionado já foi carregado. Se o arquivo de globalização ainda não foi carregado, o arquivo de globalização é carregado dinamicamente, tirando vantagem do método $.getScript() da jQuery. O método globalizePage() é chamado depois que o arquivo de globalização solicitado tenha sido carregado, e contém o código do lado do cliente necessário para realizar a globalização. A vantagem dessa abordagem é que ela permite evitar o carregamento do arquivo jQuery.glob.all.js inteiro. Em vez disso você só precisa carregar os arquivos que você vai usar e você não precisa carregar os arquivos mais de uma vez. O arquivo 5_Dynamic.htm neste download de amostras demonstra como implementar esta abordagem. Exemplo: Definindo o Idioma Preferido do Usuário Automaticamente Muitos sites detectam o idioma preferido do usuário a partir das configurações de seu navegador e as usam automaticamente quando globalizam o conteúdo. Um usuário pode definir o idioma preferido para o seu navegador. Então, sempre que o usuário solicita uma página, esta preferência de idioma está incluída no pedido no cabeçalho Accept-Language. Quando você usa o Microsoft Internet Explorer, você pode definir o seu idioma preferido, seguindo estes passos: Selecione a opção do menu Ferramentas, Opções da Internet. Selecione a guia/tab Geral. Clique no botão Idiomas na seção Aparência. Clique no botão Adicionar para adicionar um novo idioma na lista de idiomas. Mova seu idioma preferido para o topo da lista. Observe que você pode listar múltiplos idiomas na janela de diálogo de Preferências de Idioma. Todas estas línguas são enviadas na ordem em que você as listou no cabeçalho Accept-Language: Accept-Language: fr-FR,id-ID;q=0.7,en-US;q= 0.3 Estranhamente, você não pode recuperar o valor do cabeçalho Accept-Language a partir do código JavaScript no lado do cliente. O Microsoft Internet Explorer e o Mozilla Firefox suportam um grupo de propriedades relacionadas a idiomas que são expostas pelo objeto window.navigator, tais como windows.navigator.browserLanguage e window.navigator.language, mas essas propriedades representam tanto o idioma definido para o sistema operacional ou a linguagem de edição do navegador. Essas propriedades não permitem que você recupere o idioma que o usuário definiu como seu idioma preferido. A única maneira confiável para se obter o idioma preferido do usuário (o valor do cabeçalho Accept-Language) é escrever código no lado do servidor. Por exemplo, a seguinte página ASP.NET tira vantagem da propriedade do servidor Request.UserLanguages para atribuir o idioma preferido do usuário para uma variável JavaScript no lado do cliente chamada AcceptLanguage (a qual então permite que você acesse o valor usando código JavaScript no lado do cliente): Para que este código funcione, as informações de cultura associadas ao valor de acceptLanguage devem ser incluídas na página. Por exemplo, se a cultura preferida de alguém é fr-FR (Francês na França) então você precisa incluir tanto o arquivo jQuery.glob.fr-FR.js ou o arquivo jQuery.glob.all.js na página; caso contrário, as informações de cultura não estarão disponíveis. O exemplo "6_AcceptLanguages.aspx" neste download de amostras demonstra como implementar esta abordagem. Se as informações de cultura para o idioma preferido do usuário não estiverem incluídas na página, então, o método $.preferCulture() voltará a usar a cultura neutra (por exemplo, passará a usar jQuery.glob.fr.js ao invés de jQuery.glob.fr-FR.js). Se as informações da cultura neutra não estiverem disponíveis, então, o método $.preferCulture() retornará para a cultura padrão (Inglês). Exemplo: Usando o Plugin de Globalização com o jQuery UI DatePicker (Selecionador de Datas da jQuery) Um dos objetivos do plugin de Globalização é tornar mais fácil construir widgets jQuery que podem ser usados com diferentes culturas. Nós queríamos ter certeza de que o plugin de Globalização da jQuery pudesse funcionar com os plugins de UI (interface do usuário) da jQuery, como o plugin DatePicker. Para esse fim, criamos uma versão corrigida do plugin DatePicker que pode tirar proveito do plugin de Globalização na renderização de um calendário. A imagem a seguir ilustra o que acontece quando você adiciona o plugin de Globalização jQuery e o plugin DatePicker da jQuery corrigido em uma página e seleciona a cultura da Indonésia como preferencial: Note que os cabeçalhos para os dias da semana são exibidos usando abreviaturas dos nomes dos dias referentes ao idioma Indonésio. Além disso, os nomes dos meses são exibidos em Indonésio. Você pode baixar a versão corrigida do jQuery UI DatePicker no nosso site no github. Ou você pode usar a versão incluída neste download de amostras e usada pelo arquivo de exemplo 7_DatePicker.htm. Sumário Estou animado com a nossa participação contínua na comunidade jQuery. Este plugin de Globalização é o terceiro plugin jQuery que lançamos. Nós realmente apreciamos todos os ótimos comentários e sugestões sobre os protótipos do Suporte para Templates jQuery e Linkagem de Dados que lançamos mais cedo neste ano. Queremos também agradecer aos times da jQuery e jQuery UI por trabalharem conosco na criação deses plugins. Espero que isso ajude, Scott P.S. Além do blog, eu também estou agora utilizando o Twitter para atualizações rápidas e para compartilhar links. Você pode me acompanhar em: twitter.com/scottgu   Texto traduzido do post original por Leniel Macaferi.

    Read the article

  • Dark Sun Dispatch 001

    - by Chris Williams
    If you aren't into tabletop (aka pen & paper) RPGs, you might as well click to the next post now... Still here? Awesome. I've recently started running a new D&D 4.0 Dark Sun campaign. If you don't know anything about Dark Sun, here's a quick intro: The campaign take place on the world of Athas, formerly a lush green world that is now a desert wasteland. Forests are rare in the extreme, as is water and metal. Coins are made of ceramic and weapons are often made of hardened wood, bone or obsidian. The green age of Athas was centuries ago and the current state was brought about through the reckless use of sorcerous magic. (In this world, you can augment spells by drawing on the life force of the world & people around you. This is called defiling. Preserving magic draws upon the casters life force and does not damage the surrounding world, but it isn't as powerful.) Humans are pretty much unchanged, but the traditional fantasy races have changed quite a bit. Elves don't live in the forest, they are shifty and untrustworthy desert traders known for their ability to run long distances through the wastes. Halflings are not short, fat, pleasant little riverside people. Instead they are bloodthirsty feral cannibals that roam the few remaining forests and ride reptilians beasts akin to raptors. Gnomes are extinct, as are orcs. Dwarves are mostly farmers and gladiators, and live out in the sun instead of staying under the mountains. Goliaths are half-giants, not known for their intellect. Muls are a Dwarf & Human crossbreed that displays the best traits of both races (human height and dwarven stoutness.) Thri-Kreen are sentient mantis people that are extremely fast. Most of the same character classes are available, with a few new twists. There are no divine characters (such as Priests, Paladins, etc) because the gods are gone. Nobody alive today can remember a time when they were still around. Instead, some folks worship the elemental forces (although they don't give out spells.) The cities are all ruled by Sorcerer King tyrants (except one city: Tyr) who are hundreds of years old and still practice defiling magic whenever they please. Serving the Sorcerer Kings are the Templars, who are also defilers and psionicists. Crossing them is as bad, in many cases, as crossing the Kings themselves. Between the cities you have small towns and trading outposts, and mostly barren desert with sometimes 4-5 days on foot between towns and the nearest oasis. Being caught out in the desert without adequate supplies and protection from the elements is pretty much a death sentence for even the toughest heroes. When you add in the natural (and unnatural) predators that roam the wastes, often in packs, most people don't last long alone. In this campaign, the adventure begins in the (small) trading fortress of Altaruk, a couple weeks walking distance from the newly freed city of Tyr. A caravan carrying trade goods from Altaruk has not made it to Tyr and the local merchant house has dispatched the heroes to find out what happened and to retrieve the goods (and drivers) if possible. The unlikely heroes consist of a human shaman, a thri-kreen monk, a human wizard, a kenku assassin and a (void aspect) genasi swordmage. Gathering up supplies and a little liquid courage, they set out into the desert and manage to find the northbound tracks of the wagon. Shortly after finding the tracks, they are ambushed by a pack of silt-runners (small lizard people with very large teeth and poisoned pointy spears.) The party makes short work of the creatures, taking a few minor wounds in the process. Proceeding onward without resting, they find the remains of the wagon and manage to sneak up on a pack of Kruthiks picking through the rubble and spilled goods. Unfortunately, they failed to take advantage of the opportunity and had a hard fight ahead of them. The party defeated the kruthiks, but took heavy damage (and almost lost a couple of their own) in the process. Once the kruthiks were dispatched, they followed a set of tracks further north to a ruined tower...

    Read the article

< Previous Page | 4 5 6 7 8 9 10 11 12 13 14  | Next Page >