Daily Archives

Articles indexed Sunday October 28 2012

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

  • CEIL is one too high for exact integer divisions

    - by Synetech
    This morning I lost a bunch of files, but because the volume they were one was both internally and externally defragmented, all of the information necessary for a 100% recovery is available; I just need to fill in the FAT where required. I wrote a program to do this and tested it on a copy of the FAT that I dumped to a file and it works perfectly except that for a few of the files (17 out of 526), the FAT chain is one single cluster too long, and thus cross-linked with the next file. Fortunately I know exactly what the problem is. I used ceil in my EOF calculation because even a single byte over will require a whole extra cluster: //Cluster is the starting cluster of the file //Size is the size (in bytes) of the file //BPC is the number of bytes per cluster //NumClust is the number of clusters in the file //EOF is the last cluster of the file’s FAT chain DWORD NumClust = ceil( (float)(Size / BPC) ) DWORD EOF = Cluster + NumClust; This algorithm works fine for everything except files whose size happens to be exactly a multiple of the cluster size, in which case they end up being one cluster too much. I thought about it for a while but am at a loss as to a way to do this. It seems like it should be simple but somehow it is surprisingly tricky. What formula would work for files of any size?

    Read the article

  • Adjust Title Helper in Ruby on Rails Tutorial 3.2 to deal with & properly

    - by memoht
    I am using the title helper from the 3.2 edition of the Ruby on Rails Tutorial by Michael Hartl and just realized a snag with the & character showing up in the title as &Amp instead. The relevant snippet of code is here Official Sample App 2nd Edition The problem. I have a School model and am using the School name on the Show view as follows: <% provide(:title, @school.name) %> If my School has a & in the name, it is being replaced with &Amp in the browser title. Ryan Bates Railscasts site has a similiar title helper that solves this issue this way but it is using content_for instead of provide. Trying to adjust the Rails Tutorial helper, but having trouble getting it work properly. Works great expect for this issue.

    Read the article

  • MVC C# Controller Method to return Tables

    - by Rob Tiu
    I'm a real beginner with MVC and my issue is this, I have a mdf database with multiple tables and I want to have a method return "ANY" table from the database and pass it to a aspx view. Examples of other tables in the database: Articles, Products, Supplies Here is an example of my code to view an Article Table from the database: //USING LINQ-SQL CONTEXT DATABASE public ActionResult ArticlePage() { tinypeas_db_contextDataContext context = HttpContext.Application["context"] as tinypeas_db_contextDataContext; try { return View(context.Articles); } catch { return Json(false, JsonRequestBehavior.AllowGet); } } How would I modify this method to dynamically pass any table to the view? Or should I be using something else other than Linq-to-SQL

    Read the article

  • How to get query result even if JOIN hasn't found any results?

    - by user1734651
    I want select data for user, and join another info from other table that related to the user. The problem is that this extra data not always exist for any user, just for few. How can I write a query that will return NULL for not found data, instead just return null for the whole query? SELECT a.*, b.* FROM user AS a LEFT JOIN extra AS b ON (a.userid = b.userid) WHERE a.userid = {$userid} LIMIT 1 When extra data found for the user, I get the resource as expected. If not, I get NULL for the whole query. Bottom line, I don't care if "extra" exist for the user or not, if yes - select it as well, if not - ignore that.

    Read the article

  • How can I declare an object with properties that I will be passing around inside of my function using Typescript?

    - by Marilou
    I've been using the following: var modal = { content: '', form: '', href: '' } But now I have started to use Typescript is there a better way I can declare an object and how can I declare the types of my properties. The reason I am using this object is that it's inside of a function and inside that function I have other functions that set and use the values of the properties. Is this the best way for me to do this or is there another way I could better do this with typescript?

    Read the article

  • Dynamically get image URL from Imgur page link

    - by Jleagle
    I am trying to put some images on my website that are hosted on Imgur but i only have the link to the Imgur page, not the actual image URL. For example, on this album the URL I am trying to get is this: http://i.imgur.com/csb9Q.jpg (I only need the first image) I have noticed that when the page only has one image, the image file name is the same as the URL address, for example: http://imgur.com/sYlGa & http://i.imgur.com/sYlGa.jpg So this isnt a problem. But for pages with multiple images, this is not the case so how can i get the image URL?

    Read the article

  • Twitter Bootstrap modal spans, side-by-side divs and "control-group"?

    - by Federico Stango
    I'm trying my best to have a good looking modal login form but for some reasons it seems that no matter how I nest divs, I cannot obtain the proper shape. What I need is a big "lock" image side-by-side with a username/password form. The best I could do adds a horizontal scroller by the modal bottom and shows the input gadgets fairly distant from the image partly hidden on the right side of the modal canvas. Inspecting with FireBug it seems that the spans in row-fluid are ok but the "control-label" and "controls" class adds way too much space on the left by width (for the labels) and margin-left (for the controls). How would you solve it? Am I doing something wrong with divs and classes nesting? This is the current modal without the main wrapper as it gets added by some js code that loads modal contents through ajax: <form class="form-horizontal" id="login" name="login" method="post" action="<?php echo site_url('user/login'); ?>"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> <h3>Login</h3> </div> <div class="modal-body"> <?php if ( isset($error) ) { ?> <div class="row"> <div class="alert alert-error"> <strong>Warning!</strong> <?php echo $error; ?> </div> </div> <?php } ?> <div class="row-fluid"> <div class="span4"> <img src="skins/frontend/base/images/lock.png" width="96px" height="96px" /> </div> <div class="span8"> <div class="control-group"> <label class="control-label" for="email">Email</label> <div class="controls"><input type="text" placeholder="Type your email" id="email" name="email" /></div> <?php echo form_error('email', '<div id="error_email" class="alert alert-error">* ', '</div>'); ?> </div> <div class="control-group"> <label class="control-label" for="password">Password</label> <div class="controls"><input type="password" placeholder="Password" id="password" name="password" /></div> <?php echo form_error('password', '<div id="error_password" class="alert alert-error">* ', '</div>'); ?> </div> <div class="control-group"> <div class="controls"><label class="checkbox inline"><input type="checkbox" id="remember" name="remember" checked="checked" />&nbsp;Remember Me</label></div> </div> </div> </div> </div> <div class="modal-footer"> <button type="submit" class="btn btn-primary">Login</button> </div> </form> Just don't take into account the php code you see... :) Thanks in advance for all the support you can give! Federico

    Read the article

  • context.getContextResolved appliaction stopped - begginner in java

    - by Szymad
    I have a problem with my app. I'm trying to execute query, but app stops every time. This error occurs while trying to execute query. I'm learing from Android Pro 3 book, but code presented in this book is deprecated. package com.example.contactsabuout; import android.net.Uri; import android.os.Bundle; import android.provider.Contacts; import android.provider.ContactsContract; import android.app.Activity; import android.database.Cursor; import android.util.Log; import android.content.Context; import android.view.Menu; import android.view.View; import android.widget.TextView; public class MainActivity extends Activity { private static Context context; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); MainActivity.context = getApplicationContext(); Log.v("INFO", "Completed: onCreate."); } public static Context getAppContext() { return MainActivity.context; } public void doQuery(View view) { Uri peopleBaseUri = ContactsContract.Contacts.CONTENT_URI; Log.v("II","Button clicked."); Log.v("II", "Uri for ContactsContract.Contacts: " + peopleBaseUri); Context context = getAppContext(); Log.v("II", "Got context: " + context); Cursor cur; Log.v("II", "Created cursor: cur"); cur = context.getContentResolver().query(peopleBaseUri, null, null, null, null); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } } FROM LogCat 10-28 17:45:02.513: V/INFO(4677): Completed: onCreate. 10-28 17:45:02.613: D/libEGL(4677): loaded /system/lib/egl/libGLES_android.so 10-28 17:45:02.653: D/libEGL(4677): loaded /system/lib/egl/libEGL_adreno200.so 10-28 17:45:02.723: D/libEGL(4677): loaded /system/lib/egl/libGLESv1_CM_adreno200.so 10-28 17:45:02.723: D/libEGL(4677): loaded /system/lib/egl/libGLESv2_adreno200.so 10-28 17:45:03.014: I/Adreno200-EGLSUB(4677): <ConfigWindowMatch:2078>: Format RGBA_8888. 10-28 17:45:03.054: D/OpenGLRenderer(4677): Enabling debug mode 0 10-28 17:45:03.254: D/OpenGLRenderer(4677): has fontRender patch 10-28 17:45:03.274: D/OpenGLRenderer(4677): has fontRender patch 10-28 17:45:12.873: V/II(4677): Button clicked. 10-28 17:45:12.873: V/II(4677): Uri for ContactsContract.Contacts: content://com.android.contacts/contacts, rest will be null 10-28 17:45:12.873: V/II(4677): Got context: android.app.Application@40d83d90 10-28 17:45:12.873: V/II(4677): Created cursor: cur 10-28 17:45:12.933: D/AndroidRuntime(4677): Shutting down VM 10-28 17:45:12.933: W/dalvikvm(4677): threadid=1: thread exiting with uncaught exception (group=0x40aaf228) 10-28 17:45:12.953: E/AndroidRuntime(4677): FATAL EXCEPTION: main 10-28 17:45:12.953: E/AndroidRuntime(4677): java.lang.IllegalStateException: Could not execute method of the activity 10-28 17:45:12.953: E/AndroidRuntime(4677): at android.view.View$1.onClick(View.java:3071) 10-28 17:45:12.953: E/AndroidRuntime(4677): at android.view.View.performClick(View.java:3538) 10-28 17:45:12.953: E/AndroidRuntime(4677): at android.view.View$PerformClick.run(View.java:14330) 10-28 17:45:12.953: E/AndroidRuntime(4677): at android.os.Handler.handleCallback(Handler.java:608) 10-28 17:45:12.953: E/AndroidRuntime(4677): at android.os.Handler.dispatchMessage(Handler.java:92) 10-28 17:45:12.953: E/AndroidRuntime(4677): at android.os.Looper.loop(Looper.java:156) 10-28 17:45:12.953: E/AndroidRuntime(4677): at android.app.ActivityThread.main(ActivityThread.java:4977) 10-28 17:45:12.953: E/AndroidRuntime(4677): at java.lang.reflect.Method.invokeNative(Native Method) 10-28 17:45:12.953: E/AndroidRuntime(4677): at java.lang.reflect.Method.invoke(Method.java:511) 10-28 17:45:12.953: E/AndroidRuntime(4677): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784) 10-28 17:45:12.953: E/AndroidRuntime(4677): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551) 10-28 17:45:12.953: E/AndroidRuntime(4677): at dalvik.system.NativeStart.main(Native Method) 10-28 17:45:12.953: E/AndroidRuntime(4677): Caused by: java.lang.reflect.InvocationTargetException 10-28 17:45:12.953: E/AndroidRuntime(4677): at java.lang.reflect.Method.invokeNative(Native Method) 10-28 17:45:12.953: E/AndroidRuntime(4677): at java.lang.reflect.Method.invoke(Method.java:511) 10-28 17:45:12.953: E/AndroidRuntime(4677): at android.view.View$1.onClick(View.java:3066) 10-28 17:45:12.953: E/AndroidRuntime(4677): ... 11 more 10-28 17:45:12.953: E/AndroidRuntime(4677): Caused by: java.lang.SecurityException: Permission Denial: reading com.android.providers.contacts.HtcContactsProvider2 uri content://com.android.contacts/contacts from pid=4677, uid=10155 requires android.permission.READ_CONTACTS 10-28 17:45:12.953: E/AndroidRuntime(4677): at android.os.Parcel.readException(Parcel.java:1332) 10-28 17:45:12.953: E/AndroidRuntime(4677): at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:182) 10-28 17:45:12.953: E/AndroidRuntime(4677): at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:136) 10-28 17:45:12.953: E/AndroidRuntime(4677): at android.content.ContentProviderProxy.query(ContentProviderNative.java:406) 10-28 17:45:12.953: E/AndroidRuntime(4677): at android.content.ContentResolver.query(ContentResolver.java:315) 10-28 17:45:12.953: E/AndroidRuntime(4677): at com.example.contactsabuout.MainActivity.doQuery(MainActivity.java:47) 10-28 17:45:12.953: E/AndroidRuntime(4677): ... 14 more I'm trying to learn android.

    Read the article

  • Integrate Google Analytics Tracking Into IOS App

    - by user1781040
    I would like to Integrate Google Analytics Tracking into my IOS APP. I have integrated Google Analytics Library and Add It To my Application. cf. https://developers.google.com/analytics/devguides/collection/ios/v2/ into my code to tracking my view contact - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view from its nib. self.trackPageView = @"Contact Screen"; // } A have this error "Property 'TrackPageView' not found on object of the type 'ContactViewController'" Please help me

    Read the article

  • loading method based on URL

    - by steeped
    I am trying to build a small mvc-based application. How do I call a method in a class based on a query string? For example, the $_GET query string is being set as load_master_form http://www.domain.com/settings/load_master_form And to call the method within the settings class, I am doing: function __construct(){ $this->{$_GET['method']}(); } But obviously that doesn't work - it just isn't possible to load a method like that. So how would it be done?

    Read the article

  • How to anti-alias the fonts in visual studio in windows forms application?

    - by user1781077
    i want my font to be anti aliased like this so that it looks more professionalenter link description heredoes any one know the code to anti alias the fonts so that the project looks more professional.tell me the code and where to insert it in the project.As of now the fonts looks jaggy the programming language is visual C# 4.0 .net and IDE is VS 2010 for example this is a label1 what do I need to insert to anti alias this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.Location = new System.Drawing.Point(189, 187); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(31, 13); this.label1.TabIndex = 0; this.label1.Text = "from";

    Read the article

  • Error while sending email to Multiple Addresses From MYSQL Database using PHP

    - by user1751581
    I am trying to send an email to multiple email addresses which are contained in a database and sorted into a recordset... The recordset has multiple columns, but I only need one: "Email". I know that if I have them in an array I can implode them and separate them by commas, but I'm not sure how I could do that with a recordset column. Anyone know how? BTW I know I have the mail function commented out... The echo is returning null... Heres the code that I tried: $colname_rsAllLeads = "-1"; if (isset($_SESSION['MM_Username'])) { $colname_rsAllLeads = $_SESSION['MM_Username']; } mysql_select_db($database_myBackOfficeConn, $myBackOfficeConn); $query_rsAllLeads = sprintf("SELECT Email FROM Leads WHERE `User` = %s ORDER BY FullName ASC", GetSQLValueString($colname_rsAllLeads, "text")); $rsAllLeads = mysql_query($query_rsAllLeads, $myBackOfficeConn) or die(mysql_error()); $row_rsAllLeads = mysql_fetch_assoc($rsAllLeads); $totalRows_rsAllLeads = mysql_num_rows($rsAllLeads); $editFormAction = $_SERVER['PHP_SELF']; if (isset($_SERVER['QUERY_STRING'])) { $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']); } if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form")) { $startcode = $_POST['messagefield']; $replaced = preg_replace( '/\\\\(?="|\')/', '', $startcode ); echo $replaced; $collectedleads = implode(',', $row_rsAllLeads['Email']); echo $collectedleads; /* $to = $collectedleads; $subject = $_POST['subjectfield']; $body = $replaced; $headers = "MIME-Version: 1.0\r\n"; $headers .= "Content-type: text/html; charset=iso-8859-1\r\n"; $headers .= "From: " . $row_rs_CurrentUser['FirstName'] . " " . $row_rs_CurrentUser['LastName'] . " <" . $row_rs_CurrentUser['Email'] . ">"; if (mail($to, $subject, $body, $headers)) { } else { echo("<p>Message delivery failed...</p>"); } */ $insertSQL = sprintf("INSERT INTO PendingEmails (`to`, subject, message) VALUES (%s, %s, %s)", GetSQLValueString($row_rsAllLeads['Email'], "text"), GetSQLValueString($_POST['subjectfield'], "text"), GetSQLValueString($_POST['messagefield'], "text")); mysql_select_db($database_myBackOfficeConn, $myBackOfficeConn); $Result1 = mysql_query($insertSQL, $myBackOfficeConn) or die(mysql_error()); $insertGoTo = "Email Sent.php"; if (isset($_SERVER['QUERY_STRING'])) { $insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?"; $insertGoTo .= $_SERVER['QUERY_STRING']; } header(sprintf("Location: %s", $insertGoTo)); } When I use var_dump($row_rsAllLeads['Email']) it outputs string(16) "[email protected]" but I know that there is no error in my SQL query because when I put them in a select box, they all show up...

    Read the article

  • Evenly distribute range of specified values within a vector

    - by nofunsally
    I have a vector A and I want to populate it with values as evenly as possible. For example, if A is 1x30 and I want to use three values I would use a code like this below: % A = zeros(1,30); A([1:10])=0; A([11:20])=1; A([21:30])=2; This works, but seems a bit cumbersome to me. Is there a more elegant way to evenly (as possible) distribute a specified range of values within a vector? I am intent on keeping each of the values in "clumps." Thank you kindly in advance.

    Read the article

  • I am getting this error on using matplotlib

    - by Arun Abraham
    I get this error on typing this in python command prompt: import matplotlib.pyplot as plt Traceback (most recent call last): File "<pyshell#1>", line 1, in <module> import matplotlib.pyplot as plt File "/Library/Python/2.7/site-packages/matplotlib-1.3.x-py2.7-macosx-10.8-intel.egg/matplotlib/pyplot.py", line 97, in <module> _backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup() File "/Library/Python/2.7/site-packages/matplotlib-1.3.x-py2.7-macosx-10.8-intel.egg/matplotlib/backends/__init__.py", line 25, in pylab_setup globals(),locals(),[backend_name]) File "/Library/Python/2.7/site-packages/matplotlib-1.3.x-py2.7-macosx-10.8-intel.egg/matplotlib/backends/backend_macosx.py", line 21, in <module> from matplotlib.backends import _macosx ImportError: dlopen(/Library/Python/2.7/site-packages/matplotlib-1.3.x-py2.7-macosx-10.8-intel.egg/matplotlib/backends/_macosx.so, 2): Library not loaded: /System/Library/Frameworks/CoreText.framework/Versions/A/CoreText Referenced from: /Library/Python/2.7/site-packages/matplotlib-1.3.x-py2.7-macosx-10.8-intel.egg/matplotlib/backends/_macosx.so Reason: image not found Can someone suggest me, how i can fix this ? I had installed all the packages with this shell script https://github.com/fonnesbeck/ScipySuperpack Is there anything that i am missing ? Any additional configuration ?

    Read the article

  • JTable data only shown after scrolling

    - by Christian 'fuzi' Orgler
    I wrote a method, that creates my DefaultTableModel and there I'm going to add my records. When I set the model to my JTable, the data rows are blank. After scrolling the data gets displayed correct. How can I avoid this and display the data from the first moment? EDIT: I imported the javax.swing.table.DefaultTableModel -- is this correct? private DefaultTableModel _dtm; private void loadTable(Vector<Member> members) { loadTableModel(); try { lbl_state.setText("Please wait"); for (Member actMember : members) { String gender = ""; if (actMember.getGender() == MemberView.MEMBER_MALE) { gender = "männlich"; } else { gender = "weiblich"; } _dtm.addRow(new Object[]{ actMember.getNname(), actMember.getVname(), actMember.getCity(), actMember.getStreet(), actMember.getPlz(), actMember.getMail(), actMember.getPhonenumber(), actMember.getBirthdayString(), actMember.getStartDateString(), gender, actMember.getBankname(), actMember.getAccountnumber(), actMember.getBanknumber(), actMember.getGroup().toString(), (actMember.hasAccess() ? "JA" : "NEIN"), actMember.getWriteDateString(), (actMember.hasDrinkAbo() ? "JA" : "NEIN") }); } } catch (Exception ex) { System.err.println(ex.getMessage()); } tbl_results.setModel(_dtm); } private void loadTableModel() { _dtm = new DefaultTableModel(new Object[]{"Nachname", "Vorname", "Ort", "Straße", "PLZ", "E-Mail", "Telefon", "Geburtsdatum", "Beitrittsdatum", "Geschlecht", "Bankname", "Kontonummer", "Bankleitzahl", "Gruppe", "hat Zugriff", "Einschreibdatum", "Getränkeabo"}, 0); tbl_results.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS); }

    Read the article

  • Clicking the TableView leads you to the another View

    - by lakesh
    I am a newbie to iPhone development. I have already created an UITableView. I have wired everything up and included the delegate and datasource. However, instead of adding a detail view accessory by using UITableViewCellAccessoryDetailClosureButton, I would like to click the UITableViewCell and it should lead to another view with more details about the UITableViewCell. My view controller looks like this: ViewController.h #import <UIKit/UIKit.h> @interface ViewController : UIViewController<UITableViewDataSource,UITableViewDelegate>{ NSArray *tableItems; NSArray *images; } @property (nonatomic,retain) NSArray *tableItems; @property (nonatomic,retain) NSArray *images; @end ViewController.m #import "ViewController.h" #import <QuartzCore/QuartzCore.h> @interface ViewController () @end @implementation ViewController @synthesize tableItems,images; - (void)viewDidLoad { [super viewDidLoad]; tableItems = [[NSArray alloc] initWithObjects:@"Item1",@"Item2",@"Item3",nil]; images = [[NSArray alloc] initWithObjects:[UIImage imageNamed:@"clock.png"],[UIImage imageNamed:@"eye.png"],[UIImage imageNamed:@"target.png"],nil]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ return tableItems.count; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ //Step 1:Check whether if we can reuse a cell UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"]; //If there are no new cells to reuse,create a new one if(cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"cell"]; UIView *v = [[UIView alloc] init]; v.backgroundColor = [UIColor redColor]; cell.selectedBackgroundView = v; //changing the radius of the corners //cell.layer.cornerRadius = 10; } //Set the image in the row cell.imageView.image = [images objectAtIndex:indexPath.row]; //Step 3: Set the cell text content cell.textLabel.text = [tableItems objectAtIndex:indexPath.row]; //Step 4: Return the row return cell; } - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{ cell.backgroundColor = [ UIColor greenColor]; } @end Need some guidance on this.. Thanks.. Please pardon me if this is a stupid question.

    Read the article

  • JButton and next/previous object of treemap

    - by supacat
    I have this problem: 1) There are objects placed in the TreeMap through the JTextField. (Phonebook-like program). 2)There are buttons that implement view of available records in TreeMap. When you click on these buttons next / previous available objects of TreeMap displaying in JTextField. (scroll through the available records). I tried this code, but I didn't work :/ btn[4].addActionListener(new ActionListener(){ Iterator iter = tree.keySet().iterator(); public void actionPerformed(ActionEvent e) { if (iter.hasNext()){ String str = iter.next().toString(); fldFio.setText(str); fldNumber.setText(tree.get(str)); } } });

    Read the article

  • Best practice for error handling in an Android Service

    - by Omar Kohl
    I have an Android Service that does some background processing on an image using a separate Thread. If an error occurs in this Service or even worse in the thread, what is the best practice to inform the launching Activity of the problem and allow the application to recover to a stable state (i.e. the state it was in before launching the service). From within the Service I could post a Toast or a Notification, but that doesn't help me. I would like to inform the user about the problem but at the same time recover the application to a stable state.

    Read the article

  • One page of responsive site is blurry/fuzzy on iphone

    - by Gwendydd
    Here's a weird one. I'm developing a responsive site here: http://74.209.178.54:3000/index.html There are three pages built so far: the home page, the "Why" page, and the "Pricing" page. The Home and Why pages are just fine on my iPhone 4. The "Pricing" page is really blurry. And I don't just mean the images are blurry - absolutely everything is blurry: text, borders, backgrounds... Has anyone seen this before? Do you know what's happening?

    Read the article

  • Using layout view in Express with Consolidate and Mustache

    - by Raphael Caixeta
    I just started going through Node using Express and finally got Consolidate JS working properly to use Mustache as the templating view system per the instructions on the Consolidate JS Github page. Mustache is loading properly, but I'm now wondering how to include the layout file along in the rendering of the template. The default Jade system loads the content of the .render method inside of the layout.jade file. I'm just wondering how to do the same, but with Mustache. Any help is greatly appreciated! Code: index.js exports.index = function(req, res){ res.render('index', { title: "Work pl0x?" }); }); index.mustache Welcome to {{title}} I just want the index.mustache content to come in the "{{content}}" portion of the code below (layout.mustache). How can I do this? <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="UTF-8" /> <title>Project Name | {{title}}</title> <link href="/stylesheets/style.css" rel="stylesheet" /> </head> <body> {{content}} </body> </html>

    Read the article

  • Browsing PDF in a web page without using Flash

    - by alesdario
    I Have an N-Pages PDF linked in a my web page. I want to be able to browse the PDF, with next and prev arrows, page numbers, etc etc I want to be able to browse the PDF without using any Flash Plugin. I also want to normalize the browsing behaviour, so i don't want to use the default PDF plugin of the browser. I'm looking for a JS plugin but i don't find interesting solutions. Any other suggestions ? Thanks

    Read the article

  • MVC Html.ActionLink with post funtionality?

    - by Levitikon
    I'm checking to see if anyone has written an MVC extension for Html.ActionLink that you can pass in Post parameters like such: <% Html.ActionLink("Click me", "Index", "Home", new { MyRouteValue = "123" }, null, new { postParam1 = "a", postParam2 = "b" }); %> That would render the link like normal but having an onClick event that submits an also rendered form with an Action url for the Action, Controller, and Route Values with additional hidden inputs from the Post Parameters like such: <a href="#" onClick="$('#theform').submit(); return false;">Click me</a> <form id="theform" action="/Home/Index/123" method="post"> <input type="hidden" name="postParam1" value="a"> <input type="hidden" name="postParam2" value="b"> </form> I'm looking to redirect users to various pages with potentially a lot of data. Not only from page to page, but from email to page also. This would be highly reusable and I think would clean up a lot of code, and would save a bunch of time writing this if its already floating around out there. I hate recreating the wheel when I don't have to. Thanks!

    Read the article

  • Facebook Thumbnails Issue Traced to safe_image.php

    - by talkinggoat
    For some reason, facebook's safe_image.php script isn't generating thumbnails, properly. It's generating a 1x1 image... even though the correct image is linked in the script's parameters. Example: <img class="img" alt="" src="https://s-external.ak.fbcdn.net /safe_image.php?d=AQBtrCt_Es_KsED0&w=90&h=90&url=http%3A%2F %2Fwww.southlapatriots.info%2Fimages%2FScamra%2FJayCastilleCouncil2.jpg" The linked image is correct, but it is still only generating a 1x1 image.

    Read the article

  • Wrapping ASP.NET Client Callbacks

    - by Ricardo Peres
    Client Callbacks are probably the less known (and I dare say, less loved) of all the AJAX options in ASP.NET, which also include the UpdatePanel, Page Methods and Web Services. The reason for that, I believe, is it’s relative complexity: Get a reference to a JavaScript function; Dynamically register function that calls the above reference; Have a JavaScript handler call the registered function. However, it has some the nice advantage of being self-contained, that is, doesn’t need additional files, such as web services, JavaScript libraries, etc, or static methods declared on a page, or any kind of attributes. So, here’s what I want to do: Have a DOM element which exposes a method that is executed server side, passing it a string and returning a string; Have a server-side event that handles the client-side call; Have two client-side user-supplied callback functions for handling the success and error results. I’m going to develop a custom control without user interface that does the registration of the client JavaScript method as well as a server-side event that can be hooked by some handler on a page. My markup will look like this: 1: <script type="text/javascript"> 1:  2:  3: function onCallbackSuccess(result, context) 4: { 5: } 6:  7: function onCallbackError(error, context) 8: { 9: } 10:  </script> 2: <my:CallbackControl runat="server" ID="callback" SendAllData="true" OnCallback="OnCallback"/> The control itself looks like this: 1: public class CallbackControl : Control, ICallbackEventHandler 2: { 3: #region Public constructor 4: public CallbackControl() 5: { 6: this.SendAllData = false; 7: this.Async = true; 8: } 9: #endregion 10:  11: #region Public properties and events 12: public event EventHandler<CallbackEventArgs> Callback; 13:  14: [DefaultValue(true)] 15: public Boolean Async 16: { 17: get; 18: set; 19: } 20:  21: [DefaultValue(false)] 22: public Boolean SendAllData 23: { 24: get; 25: set; 26: } 27:  28: #endregion 29:  30: #region Protected override methods 31:  32: protected override void Render(HtmlTextWriter writer) 33: { 34: writer.AddAttribute(HtmlTextWriterAttribute.Id, this.ClientID); 35: writer.RenderBeginTag(HtmlTextWriterTag.Span); 36:  37: base.Render(writer); 38:  39: writer.RenderEndTag(); 40: } 41:  42: protected override void OnInit(EventArgs e) 43: { 44: String reference = this.Page.ClientScript.GetCallbackEventReference(this, "arg", "onCallbackSuccess", "context", "onCallbackError", this.Async); 45: String script = String.Concat("\ndocument.getElementById('", this.ClientID, "').callback = function(arg, context, onCallbackSuccess, onCallbackError){", ((this.SendAllData == true) ? "__theFormPostCollection.length = 0; __theFormPostData = ''; WebForm_InitCallback(); " : String.Empty), reference, ";};\n"); 46:  47: this.Page.ClientScript.RegisterStartupScript(this.GetType(), String.Concat("callback", this.ClientID), script, true); 48:  49: base.OnInit(e); 50: } 51:  52: #endregion 53:  54: #region Protected virtual methods 55: protected virtual void OnCallback(CallbackEventArgs args) 56: { 57: EventHandler<CallbackEventArgs> handler = this.Callback; 58:  59: if (handler != null) 60: { 61: handler(this, args); 62: } 63: } 64:  65: #endregion 66:  67: #region ICallbackEventHandler Members 68:  69: String ICallbackEventHandler.GetCallbackResult() 70: { 71: CallbackEventArgs args = new CallbackEventArgs(this.Context.Items["Data"] as String); 72:  73: this.OnCallback(args); 74:  75: return (args.Result); 76: } 77:  78: void ICallbackEventHandler.RaiseCallbackEvent(String eventArgument) 79: { 80: this.Context.Items["Data"] = eventArgument; 81: } 82:  83: #endregion 84: } And the event argument class: 1: [Serializable] 2: public class CallbackEventArgs : EventArgs 3: { 4: public CallbackEventArgs(String argument) 5: { 6: this.Argument = argument; 7: this.Result = String.Empty; 8: } 9:  10: public String Argument 11: { 12: get; 13: private set; 14: } 15:  16: public String Result 17: { 18: get; 19: set; 20: } 21: } You will notice two properties on the CallbackControl: Async: indicates if the call should be made asynchronously or synchronously (the default); SendAllData: indicates if the callback call will include the view and control state of all of the controls on the page, so that, on the server side, they will have their properties set when the Callback event is fired. The CallbackEventArgs class exposes two properties: Argument: the read-only argument passed to the client-side function; Result: the result to return to the client-side callback function, set from the Callback event handler. An example of an handler for the Callback event would be: 1: protected void OnCallback(Object sender, CallbackEventArgs e) 2: { 3: e.Result = String.Join(String.Empty, e.Argument.Reverse()); 4: } Finally, in order to fire the Callback event from the client, you only need this: 1: <input type="text" id="input"/> 2: <input type="button" value="Get Result" onclick="document.getElementById('callback').callback(callback(document.getElementById('input').value, 'context', onCallbackSuccess, onCallbackError))"/> The syntax of the callback function is: arg: some string argument; context: some context that will be passed to the callback functions (success or failure); callbackSuccessFunction: some function that will be called when the callback succeeds; callbackFailureFunction: some function that will be called if the callback fails for some reason. Give it a try and see if it helps!

    Read the article

  • ASPNET WebAPI REST Guidance

    - by JoshReuben
    ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework. While I may be more partial to NodeJS these days, there is no denying that WebAPI is a well engineered framework. What follows is my investigation of how to leverage WebAPI to construct a RESTful frontend API.   The Advantages of REST Methodology over SOAP Simpler API for CRUD ops Standardize Development methodology - consistent and intuitive Standards based à client interop Wide industry adoption, Ease of use à easy to add new devs Avoid service method signature blowout Smaller payloads than SOAP Stateless à no session data means multi-tenant scalability Cache-ability Testability   General RESTful API Design Overview · utilize HTTP Protocol - Usage of HTTP methods for CRUD, standard HTTP response codes, common HTTP headers and Mime Types · Resources are mapped to URLs, actions are mapped to verbs and the rest goes in the headers. · keep the API semantic, resource-centric – A RESTful, resource-oriented service exposes a URI for every piece of data the client might want to operate on. A REST-RPC Hybrid exposes a URI for every operation the client might perform: one URI to fetch a piece of data, a different URI to delete that same data. utilize Uri to specify CRUD op, version, language, output format: http://api.MyApp.com/{ver}/{lang}/{resource_type}/{resource_id}.{output_format}?{key&filters} · entity CRUD operations are matched to HTTP methods: · Create - POST / PUT · Read – GET - cacheable · Update – PUT · Delete - DELETE · Use Uris to represent a hierarchies - Resources in RESTful URLs are often chained · Statelessness allows for idempotency – apply an op multiple times without changing the result. POST is non-idempotent, the rest are idempotent (if DELETE flags records instead of deleting them). · Cache indication - Leverage HTTP headers to label cacheable content and indicate the permitted duration of cache · PUT vs POST - The client uses PUT when it determines which URI (Id key) the new resource should have. The client uses POST when the server determines they key. PUT takes a second param – the id. POST creates a new resource. The server assigns the URI for the new object and returns this URI as part of the response message. Note: The PUT method replaces the entire entity. That is, the client is expected to send a complete representation of the updated product. If you want to support partial updates, the PATCH method is preferred DELETE deletes a resource at a specified URI – typically takes an id param · Leverage Common HTTP Response Codes in response headers 200 OK: Success 201 Created - Used on POST request when creating a new resource. 304 Not Modified: no new data to return. 400 Bad Request: Invalid Request. 401 Unauthorized: Authentication. 403 Forbidden: Authorization 404 Not Found – entity does not exist. 406 Not Acceptable – bad params. 409 Conflict - For POST / PUT requests if the resource already exists. 500 Internal Server Error 503 Service Unavailable · Leverage uncommon HTTP Verbs to reduce payload sizes HEAD - retrieves just the resource meta-information. OPTIONS returns the actions supported for the specified resource. PATCH - partial modification of a resource. · When using PUT, POST or PATCH, send the data as a document in the body of the request. Don't use query parameters to alter state. · Utilize Headers for content negotiation, caching, authorization, throttling o Content Negotiation – choose representation (e.g. JSON or XML and version), language & compression. Signal via RequestHeader.Accept & ResponseHeader.Content-Type Accept: application/json;version=1.0 Accept-Language: en-US Accept-Charset: UTF-8 Accept-Encoding: gzip o Caching - ResponseHeader: Expires (absolute expiry time) or Cache-Control (relative expiry time) o Authorization - basic HTTP authentication uses the RequestHeader.Authorization to specify a base64 encoded string "username:password". can be used in combination with SSL/TLS (HTTPS) and leverage OAuth2 3rd party token-claims authorization. Authorization: Basic sQJlaTp5ZWFslylnaNZ= o Rate Limiting - Not currently part of HTTP so specify non-standard headers prefixed with X- in the ResponseHeader. X-RateLimit-Limit: 10000 X-RateLimit-Remaining: 9990 · HATEOAS Methodology - Hypermedia As The Engine Of Application State – leverage API as a state machine where resources are states and the transitions between states are links between resources and are included in their representation (hypermedia) – get API metadata signatures from the response Link header - in a truly REST based architecture any URL, except the initial URL, can be changed, even to other servers, without worrying about the client. · error responses - Do not just send back a 200 OK with every response. Response should consist of HTTP error status code (JQuery has automated support for this), A human readable message , A Link to a meaningful state transition , & the original data payload that was problematic. · the URIs will typically map to a server-side controller and a method name specified by the type of request method. Stuff all your calls into just four methods is not as crazy as it sounds. · Scoping - Path variables look like you’re traversing a hierarchy, and query variables look like you’re passing arguments into an algorithm · Mapping URIs to Controllers - have one controller for each resource is not a rule – can consolidate - route requests to the appropriate controller and action method · Keep URls Consistent - Sometimes it’s tempting to just shorten our URIs. not recommend this as this can cause confusion · Join Naming – for m-m entity relations there may be multiple hierarchy traversal paths · Routing – useful level of indirection for versioning, server backend mocking in development ASPNET WebAPI Considerations ASPNET WebAPI implements a lot (but not all) RESTful API design considerations as part of its infrastructure and via its coding convention. Overview When developing an API there are basically three main steps: 1. Plan out your URIs 2. Setup return values and response codes for your URIs 3. Implement a framework for your API.   Design · Leverage Models MVC folder · Repositories – support IoC for tests, abstraction · Create DTO classes – a level of indirection decouples & allows swap out · Self links can be generated using the UrlHelper · Use IQueryable to support projections across the wire · Models can support restful navigation properties – ICollection<T> · async mechanism for long running ops - return a response with a ticket – the client can then poll or be pushed the final result later. · Design for testability - Test using HttpClient , JQuery ( $.getJSON , $.each) , fiddler, browser debug. Leverage IDependencyResolver – IoC wrapper for mocking · Easy debugging - IE F12 developer tools: Network tab, Request Headers tab     Routing · HTTP request method is matched to the method name. (This rule applies only to GET, POST, PUT, and DELETE requests.) · {id}, if present, is matched to a method parameter named id. · Query parameters are matched to parameter names when possible · Done in config via Routes.MapHttpRoute – similar to MVC routing · Can alternatively: o decorate controller action methods with HttpDelete, HttpGet, HttpHead,HttpOptions, HttpPatch, HttpPost, or HttpPut., + the ActionAttribute o use AcceptVerbsAttribute to support other HTTP verbs: e.g. PATCH, HEAD o use NonActionAttribute to prevent a method from getting invoked as an action · route table Uris can support placeholders (via curly braces{}) – these can support default values and constraints, and optional values · The framework selects the first route in the route table that matches the URI. Response customization · Response code: By default, the Web API framework sets the response status code to 200 (OK). But according to the HTTP/1.1 protocol, when a POST request results in the creation of a resource, the server should reply with status 201 (Created). Non Get methods should return HttpResponseMessage · Location: When the server creates a resource, it should include the URI of the new resource in the Location header of the response. public HttpResponseMessage PostProduct(Product item) {     item = repository.Add(item);     var response = Request.CreateResponse<Product>(HttpStatusCode.Created, item);     string uri = Url.Link("DefaultApi", new { id = item.Id });     response.Headers.Location = new Uri(uri);     return response; } Validation · Decorate Models / DTOs with System.ComponentModel.DataAnnotations properties RequiredAttribute, RangeAttribute. · Check payloads using ModelState.IsValid · Under posting – leave out values in JSON payload à JSON formatter assigns a default value. Use with RequiredAttribute · Over-posting - if model has RO properties à use DTO instead of model · Can hook into pipeline by deriving from ActionFilterAttribute & overriding OnActionExecuting Config · Done in App_Start folder > WebApiConfig.cs – static Register method: HttpConfiguration param: The HttpConfiguration object contains the following members. Member Description DependencyResolver Enables dependency injection for controllers. Filters Action filters – e.g. exception filters. Formatters Media-type formatters. by default contains JsonFormatter, XmlFormatter IncludeErrorDetailPolicy Specifies whether the server should include error details, such as exception messages and stack traces, in HTTP response messages. Initializer A function that performs final initialization of the HttpConfiguration. MessageHandlers HTTP message handlers - plug into pipeline ParameterBindingRules A collection of rules for binding parameters on controller actions. Properties A generic property bag. Routes The collection of routes. Services The collection of services. · Configure JsonFormatter for circular references to support links: PreserveReferencesHandling.Objects Documentation generation · create a help page for a web API, by using the ApiExplorer class. · The ApiExplorer class provides descriptive information about the APIs exposed by a web API as an ApiDescription collection · create the help page as an MVC view public ILookup<string, ApiDescription> GetApis()         {             return _explorer.ApiDescriptions.ToLookup(                 api => api.ActionDescriptor.ControllerDescriptor.ControllerName); · provide documentation for your APIs by implementing the IDocumentationProvider interface. Documentation strings can come from any source that you like – e.g. extract XML comments or define custom attributes to apply to the controller [ApiDoc("Gets a product by ID.")] [ApiParameterDoc("id", "The ID of the product.")] public HttpResponseMessage Get(int id) · GlobalConfiguration.Configuration.Services – add the documentation Provider · To hide an API from the ApiExplorer, add the ApiExplorerSettingsAttribute Plugging into the Message Handler pipeline · Plug into request / response pipeline – derive from DelegatingHandler and override theSendAsync method – e.g. for logging error codes, adding a custom response header · Can be applied globally or to a specific route Exception Handling · Throw HttpResponseException on method failures – specify HttpStatusCode enum value – examine this enum, as its values map well to typical op problems · Exception filters – derive from ExceptionFilterAttribute & override OnException. Apply on Controller or action methods, or add to global HttpConfiguration.Filters collection · HttpError object provides a consistent way to return error information in the HttpResponseException response body. · For model validation, you can pass the model state to CreateErrorResponse, to include the validation errors in the response public HttpResponseMessage PostProduct(Product item) {     if (!ModelState.IsValid)     {         return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState); Cookie Management · Cookie header in request and Set-Cookie headers in a response - Collection of CookieState objects · Specify Expiry, max-age resp.Headers.AddCookies(new CookieHeaderValue[] { cookie }); Internet Media Types, formatters and serialization · Defaults to application/json · Request Accept header and response Content-Type header · determines how Web API serializes and deserializes the HTTP message body. There is built-in support for XML, JSON, and form-urlencoded data · customizable formatters can be inserted into the pipeline · POCO serialization is opt out via JsonIgnoreAttribute, or use DataMemberAttribute for optin · JSON serializer leverages NewtonSoft Json.NET · loosely structured JSON objects are serialzed as JObject which derives from Dynamic · to handle circular references in json: json.SerializerSettings.PreserveReferencesHandling =    PreserveReferencesHandling.All à {"$ref":"1"}. · To preserve object references in XML [DataContract(IsReference=true)] · Content negotiation Accept: Which media types are acceptable for the response, such as “application/json,” “application/xml,” or a custom media type such as "application/vnd.example+xml" Accept-Charset: Which character sets are acceptable, such as UTF-8 or ISO 8859-1. Accept-Encoding: Which content encodings are acceptable, such as gzip. Accept-Language: The preferred natural language, such as “en-us”. o Web API uses the Accept and Accept-Charset headers. (At this time, there is no built-in support for Accept-Encoding or Accept-Language.) · Controller methods can take JSON representations of DTOs as params – auto-deserialization · Typical JQuery GET request: function find() {     var id = $('#prodId').val();     $.getJSON("api/products/" + id,         function (data) {             var str = data.Name + ': $' + data.Price;             $('#product').text(str);         })     .fail(         function (jqXHR, textStatus, err) {             $('#product').text('Error: ' + err);         }); }            · Typical GET response: HTTP/1.1 200 OK Server: ASP.NET Development Server/10.0.0.0 Date: Mon, 18 Jun 2012 04:30:33 GMT X-AspNet-Version: 4.0.30319 Cache-Control: no-cache Pragma: no-cache Expires: -1 Content-Type: application/json; charset=utf-8 Content-Length: 175 Connection: Close [{"Id":1,"Name":"TomatoSoup","Price":1.39,"ActualCost":0.99},{"Id":2,"Name":"Hammer", "Price":16.99,"ActualCost":10.00},{"Id":3,"Name":"Yo yo","Price":6.99,"ActualCost": 2.05}] True OData support · Leverage Query Options $filter, $orderby, $top and $skip to shape the results of controller actions annotated with the [Queryable]attribute. [Queryable]  public IQueryable<Supplier> GetSuppliers()  · Query: ~/Suppliers?$filter=Name eq ‘Microsoft’ · Applies the following selection filter on the server: GetSuppliers().Where(s => s.Name == “Microsoft”)  · Will pass the result to the formatter. · true support for the OData format is still limited - no support for creates, updates, deletes, $metadata and code generation etc · vnext: ability to configure how EditLinks, SelfLinks and Ids are generated Self Hosting no dependency on ASPNET or IIS: using (var server = new HttpSelfHostServer(config)) {     server.OpenAsync().Wait(); Tracing · tracability tools, metrics – e.g. send to nagios · use your choice of tracing/logging library, whether that is ETW,NLog, log4net, or simply System.Diagnostics.Trace. · To collect traces, implement the ITraceWriter interface public class SimpleTracer : ITraceWriter {     public void Trace(HttpRequestMessage request, string category, TraceLevel level,         Action<TraceRecord> traceAction)     {         TraceRecord rec = new TraceRecord(request, category, level);         traceAction(rec);         WriteTrace(rec); · register the service with config · programmatically trace – has helper extension methods: Configuration.Services.GetTraceWriter().Info( · Performance tracing - pipeline writes traces at the beginning and end of an operation - TraceRecord class includes aTimeStamp property, Kind property set to TraceKind.Begin / End Security · Roles class methods: RoleExists, AddUserToRole · WebSecurity class methods: UserExists, .CreateUserAndAccount · Request.IsAuthenticated · Leverage HTTP 401 (Unauthorized) response · [AuthorizeAttribute(Roles="Administrator")] – can be applied to Controller or its action methods · See section in WebApi document on "Claim-based-security for ASP.NET Web APIs using DotNetOpenAuth" – adapt this to STS.--> Web API Host exposes secured Web APIs which can only be accessed by presenting a valid token issued by the trusted issuer. http://zamd.net/2012/05/04/claim-based-security-for-asp-net-web-apis-using-dotnetopenauth/ · Use MVC membership provider infrastructure and add a DelegatingHandler child class to the WebAPI pipeline - http://stackoverflow.com/questions/11535075/asp-net-mvc-4-web-api-authentication-with-membership-provider - this will perform the login actions · Then use AuthorizeAttribute on controllers and methods for role mapping- http://sixgun.wordpress.com/2012/02/29/asp-net-web-api-basic-authentication/ · Alternate option here is to rely on MVC App : http://forums.asp.net/t/1831767.aspx/1

    Read the article

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