Search Results

Search found 252 results on 11 pages for 'shorten'.

Page 9/11 | < Previous Page | 5 6 7 8 9 10 11  | Next Page >

  • Yet another "What is this code doing"-type of Perl code

    - by Mike
    I have inherited some code from a guy whose favorite past time was to shorten every line to its absolute minimum (and sometimes only to make it look cool). His code is hard to understand but I managed to understand (and rewrite) most of it. Now I have stumbled on a piece of code which, no matter how hard I try, I cannot understand. my @heads = grep {s/\.txt$//} OSA::Fast::IO::Ls->ls($SysKey,'fo','osr/tiparlo',qr{^\d+\.txt$}) || (); my @selected_heads = (); for my $i (0..1) { $selected_heads[$i] = int rand scalar @heads; for my $j (0..@heads-1) { last if (!grep $j eq $_, @selected_heads[0..$i-1]); $selected_heads[$i] = ($selected_heads[$i] + 1) % @heads; #WTF? } my $head_nr = sprintf "%04d", $i; OSA::Fast::IO::Cp->cp($SysKey,'',"osr/tiparlo/$heads[$selected_heads[$i]].txt","$recdir/heads/$head_nr.txt"); OSA::Fast::IO::Cp->cp($SysKey,'',"osr/tiparlo/$heads[$selected_heads[$i]].cache","$recdir/heads/$head_nr.cache"); } From what I can understand, this is supposed to be some kind of randomizer, but I never saw a more complex way to achieve randomness. Or are my assumptions wrong? At least, that's what this code is supposed to do. Select 2 random files and copy them. === NOTES === The OSA Framework is a Framework of our own. They are named after their UNIX counterparts and do some basic testing so that the application does not need to bother with that.

    Read the article

  • Add Ellipsis to a Path in a WinForms Program without Win32 API call (revisited)

    - by casterle
    I was searching for a way to insert an ellipsis in a C# path, and found an answer here on stackoverflow: http://tinyurl.com/y6rmdfr Using the RTM versions of VS2010 and .Net 4.0, I was unable to get the suggested method to work. I searched the 'Net and found example code that uses the same method, but it failed in the same way. You can see the string I'm trying to shorten in my code below. After calling the MeasureText method, both the input string (OriginalName) and the output string (ellipsisedName) look like this: d:\abcd\efgh\ijkl\mnop\qrst\...\test.txt\0F\GHIJ\KLMN\OPQR\STIV\WXYZ\test.txt Two problems: 1) The resulting string is narfed (the path is truncated as expected, but is followed by what looks like a C-style terminating null and a chunk of the original path). 2) My original string is changed to be identical to the output string. Am I doing something wrong? namespace WindowsFormsApplication2 { public partial class Form1 : Form { public Form1() { InitializeComponent(); string OriginalPath = @"d:\abcd\efgh\ijkl\mnop\qrst\uvwx\yzAB\CDEF\GHIJ\KLMN\OPQR\STIV\WXYZ\test.txt"; string ellipsisedPath = OriginalPath; Size proposedSize = new Size(label1.Width, label1.Height); TextRenderer.MeasureText(ellipsisedPath, label1.Font, proposedSize, TextFormatFlags.ModifyString | TextFormatFlags.PathEllipsis); } } }

    Read the article

  • substitution cypher with different alphabet length

    - by seanizer
    I would like to implement a simple substitution cypher to mask private ids in URLs I know how my IDs will look like (combination of upperchase ascii, digits and underscore), and they will be rather long, as they are composed keys. I would like to use a longer alphabet to shorten the resulting codes (I'd like to use upper and lower case ascii letters, digits and nothing else). So my incoming alphabet would be [A-Z0-9_] (37 chars) and my outgoing alphabet would be [A-Za-z0-9] (62 chars) so a compression of almost 50% would be available. let's say my URLs look like this: /my/page/GFZHFFFZFZTFZTF_24_F34 and I want them to look like this instead: /my/page/Ft32zfegZFV5 Obviously both arrays would be shuffled to bring some random order in. This does not have to be secure. if someone figures it out: fine, but I don't want the scheme to be obvious. My desired solution would be to convert the string to an integer representation of radix 37, convert the radix to 62 and use the second alphabet to write out that number. is there any sample code available that does something similar? Integer.parseInt ( http://java.sun.com/javase/6/docs/api/java/lang/Integer.html#parseInt%28java.lang.String,%20int%29 ) has some similar logic, but it is hard-coded to use standard digit behavior Any hints? I am using java to implement this but code or pseudo-code in any other language is of course also helpful

    Read the article

  • Parameters lost on login form submitted with post in JBoss

    - by Supowski
    My login page contains two forms: one for logging in and one for signing up. Shorten like this: <form name="LoginForm" id="LoginForm" method="post" action="j_security_check" > <input type="text" name="j_username" /> <input type="text" name="j_password" /> <input type="submit" value="Sing In" /> <form> <form name="SignUpForm" id="SignUpForm" method="post" action="/homepage" > <input type="text" name="loginName" /> <input type="password" name="password1" /> <input type="password" name="password2" /> <input type="submit" value="Sing Up" /> <form> I If 'Sing Up', than values of input are lost during processing and not passed into my Servlet. It works fine with GET, but than there is password in URL, so it's not the right solution :) Similar problem has been posted to community.jboss.org, but with no response: http://community.jboss.org/message/7150#7150. I'm using JBoss 4.3eap. Any help?

    Read the article

  • How is this Perl code selecting two different elements from an array?

    - by Mike
    I have inherited some code from a guy whose favorite past time was to shorten every line to its absolute minimum (and sometimes only to make it look cool). His code is hard to understand but I managed to understand (and rewrite) most of it. Now I have stumbled on a piece of code which, no matter how hard I try, I cannot understand. my @heads = grep {s/\.txt$//} OSA::Fast::IO::Ls->ls($SysKey,'fo','osr/tiparlo',qr{^\d+\.txt$}) || (); my @selected_heads = (); for my $i (0..1) { $selected_heads[$i] = int rand scalar @heads; for my $j (0..@heads-1) { last if (!grep $j eq $_, @selected_heads[0..$i-1]); $selected_heads[$i] = ($selected_heads[$i] + 1) % @heads; #WTF? } my $head_nr = sprintf "%04d", $i; OSA::Fast::IO::Cp->cp($SysKey,'',"osr/tiparlo/$heads[$selected_heads[$i]].txt","$recdir/heads/$head_nr.txt"); OSA::Fast::IO::Cp->cp($SysKey,'',"osr/tiparlo/$heads[$selected_heads[$i]].cache","$recdir/heads/$head_nr.cache"); } From what I can understand, this is supposed to be some kind of randomizer, but I never saw a more complex way to achieve randomness. Or are my assumptions wrong? At least, that's what this code is supposed to do. Select 2 random files and copy them. === NOTES === The OSA Framework is a Framework of our own. They are named after their UNIX counterparts and do some basic testing so that the application does not need to bother with that.

    Read the article

  • C: socket connection timeout

    - by The.Anti.9
    I have a simple program to check if a port is open, but I want to shorten the timeout length on the socket connection because the default is far too long. I'm not sure how to do this though. Here's the code: #include <sys/socket.h> #include <sys/time.h> #include <sys/types.h> #include <arpa/inet.h> #include <netinet/in.h> #include <errno.h> #include <fcntl.h> #include <stdio.h> #include <netdb.h> #include <stdlib.h> #include <string.h> #include <unistd.h> int main(int argc, char **argv) { u_short port; /* user specified port number */ char addr[1023]; /* will be a copy of the address entered by u */ struct sockaddr_in address; /* the libc network address data structure */ short int sock = -1; /* file descriptor for the network socket */ if (argc != 3) { fprintf(stderr, "Usage %s <port_num> <address>", argv[0]); return EXIT_FAILURE; } address.sin_addr.s_addr = inet_addr(argv[2]); /* assign the address */ address.sin_port = htons(atoi(argv[2])); /* translate int2port num */ sock = socket(AF_INET, SOCK_STREAM, 0); if (connect(sock,(struct sockaddr *)&address,sizeof(address)) == 0) { printf("%i is open\n", port); } close(sock); return 0; }

    Read the article

  • How to change the width of displayed text nested in a div?

    - by romaintaz
    Hello, Imagine I have the following code (simplified regarding my real context of course): <div id="box" style="width: 120px;" onmouseover="this.style.width='200px'" onmouseout="this.style.width='120px'"> <div>A label</div> <div>Another label</div> <div>Another label, but a longer label</div> </div> What I want to achieve is the following: My div box has a fixed width (120px by default). In this configuration, every label nested in the box must be written in a single line. If the text is too long, then the overflow must be hidden. In my example, the third item will be displayed Another label, but a or Another label, but a .... When the cursor is entering the div box, the width of the box is modified (for example to 200px). In this configuration, the labels that were shorten in the first configuration are now displayed in the whole space. With my code snippet, the third label is displayed in two lines when the box has a 120px, and I do not want that... How can I achieve that? Note that I would be great if the solution works also for IE6! Even if I prefer a pure CSS/HTML solution, (simple) Javascript (and jQuery) is allowed!

    Read the article

  • T-SQL Query, combine columns from multiple rows into single column

    - by Shayne
    I have seeen some examples of what I am trying to do using COALESCE and FOR XML (seems like the better solution). I just can't quite get the syntax right. Here is what I have (I will shorten the fields to only the key ones): Table Fields ------ ------------------------------- Requisition ID, Number IssuedPO ID, Number Job ID, Number Job_Activity ID, JobID (fkey) RequisitionItems ID, RequisitionID(fkey), IssuedPOID(fkey), Job_ActivityID (fkey) I need a query that will list ONE Requisition per line with its associated Jobs and IssuedPOs. (The requisition number start with "R-" and the Job Number start with "J-"). Example: R-123 | "PO1; PO2; PO3" | "J-12345; J-6780" Sure thing Adam! Here is a query that returns multiple rows. I have to use outer joins, since not all Requisitions have RequisitionItems that are assigned to Jobs and/or IssuedPOs (in that case their fkey IDs would just be null of course). SELECT DISTINCT Requisition.Number, IssuedPO.Number, Job.Number FROM Requisition INNER JOIN RequisitionItem on RequisitionItem.RequisitionID = Requisition.ID LEFT OUTER JOIN Job_Activity on RequisitionItem.JobActivityID = Job_Activity.ID LEFT OUTER JOIN Job on Job_Activity.JobID = Job.ID LEFT OUTER JOIN IssuedPO on RequisitionItem.IssuedPOID = IssuedPO.ID

    Read the article

  • an better way to do this code

    - by user295189
    myarray[] = $my[$addintomtarray] //52 elements for ($k=0; $k <= 12; $k++){ echo $myarray[$k].' '; } echo ''; for ($k=13; $k < 26; $k++){ echo $myarray[$k].' '; } echo ''; for ($k=26; $k < 39; $k++){ echo $myarray[$k].' '; } echo ''; for ($k=39; $k <= 51; $k++){ echo $myarray[$k].' '; } how to shorten this array code...all I am doing here is splitting an array of 52 elements into 4 chunck of 13 elements each. In addition I am adding formation with br and space thanks

    Read the article

  • What is jQuery for Document.createElementNS()?

    - by C.W.Holeman II
    What is jQuery for Document.createElementNS()? function emleGraphicToSvg(aGraphicNode) { var lu = function luf(aPrefix){ switch (aPrefix){ case 'xhtml': return 'http://www.w3.org/1999/xhtml'; case 'math': return 'http://www.w3.org/1998/Math/MathML'; case 'svg': return 'http://www.w3.org/2000/svg'; } return ''; }; var svg = document.evaluate("svg:svg", aGraphicNode, lu, XPathResult.FIRST_ORDERED_NODE_TYPE, null). singleNodeValue; $(svg).children().remove(); rect = document.createElementNS(lu('svg'), "rect"); rect.setAttribute("x", "35"); rect.setAttribute("y", "25"); rect.setAttribute("width", "200"); rect.setAttribute("height", "50"); rect.setAttribute("class", "emleGraphicOutline"); svg.appendChild(rect); } The code is a simplified fragment from Emle - Electronic Mathematics Laboratory Equipment JavaScript file emle_lab.js. The Look-Up-Function, luf(), maps a complete reference to a shorten name for the namespace in the XPath string and createElementNS(). The existing svg:svg is located, removed and replaced by a new rectangle.

    Read the article

  • JavaScript doesn't parse when mod-rewrited through a PHP file?

    - by Newbtophp
    If I do the following (this is the actual/direct path to the JavaScript file): <script href="http://localhost/tpl/blue/js/functions.js" type="text/javascript"></script> It works fine, and the JavaScript parses - as its meant too. However I'm wanting to shorten the path to the JavaScript file (aswell as do some caching) which is why I'm rewriting all JavaScript files via .htaccess to cache.php (which handles the caching). The .htaccess contains the following: <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^js/(.+?\.js)$ cache.php?file=$1 [NC] </IfModule> cache.php contains the following PHP code: <?php if (extension_loaded('zlib')) { ob_start('ob_gzhandler'); } $file = basename($_GET['file']); if (file_exists("tpl/blue/js/".$file)) { header("Content-Type: application/javascript"); header('Cache-Control: must-revalidate'); header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 3600) . ' GMT'); echo file_get_contents("tpl/blue/js/".$file); } ?> and I'm calling the JavaScript file like so: <script href="http://localhost/js/functions.js" type="text/javascript"></script> But doing that the JavaScript doesn't parse? (if I call the functions which are within functions.js later on in the page they don't work) - so theirs a problem either with cache.php or the rewrite rule? (because the file by itself works fine). If I access the rewrited file- http://localhost/js/functions.js directly it prints the JavaScript code, as any JavaScript file would - so I'm confused as to what I'm doing wrong... All help is appreciated! :)

    Read the article

  • File name containing more than 16 characters inside parentheses failing

    - by Tom anMoney
    I am generating file names that contain a timestamp in the following format: "base_name (yyyy-mm-dd hhmmss).ext" This seems to cause a problem on Android. Here's my log: /storage/sdcard0/anMoney/transfer/Net worth over time _ Forecast (2012-11-19 110550).pdf E/Gmail (11802): java.io.FileNotFoundException: /storage/sdcard0/myapp/transfer/Net worth over time _ Forecast (2012-11-19 110550).pdf: open failed: ENOENT (No such file or directory) E/Gmail (11802): at libcore.io.IoBridge.open(IoBridge.java:416) E/Gmail (11802): at java.io.FileInputStream.<init>(FileInputStream.java:78) E/Gmail (11802): at java.io.FileInputStream.<init>(FileInputStream.java:105) E/Gmail (11802): at android.content.ContentResolver.openInputStream(ContentResolver.java:445) E/Gmail (11802): at com.google.android.gm.provider.MailEngine.cacheAttachment(MailEngine.java:3054) E/Gmail (11802): at com.google.android.gm.provider.MailEngine.sendOrSaveDraft(MailEngine.java:2746) E/Gmail (11802): at com.google.android.gm.provider.MailProvider.sendOrSaveDraft(MailProvider.java:477) E/Gmail (11802): at com.google.android.gm.provider.MailProvider.insert(MailProvider.java:534) E/Gmail (11802): at android.content.ContentProvider$Transport.insert(ContentProvider.java:201) E/Gmail (11802): at android.content.ContentResolver.insert(ContentResolver.java:864) E/Gmail (11802): at com.google.android.gm.provider.Gmail$MessageModification.sendOrSaveNewMessage(Gmail.java:3576) E/Gmail (11802): at com.google.android.gm.ComposeActivity$SendOrSaveTask$1.onInitializationComplete(ComposeActivity.java:1765) E/Gmail (11802): at com.google.android.gm.provider.MailEngine$5.run(MailEngine.java:1006) E/Gmail (11802): at android.os.Handler.handleCallback(Handler.java:615) E/Gmail (11802): at android.os.Handler.dispatchMessage(Handler.java:92) E/Gmail (11802): at android.os.Looper.loop(Looper.java:137) E/Gmail (11802): at android.os.HandlerThread.run(HandlerThread.java:60) E/Gmail (11802): Caused by: libcore.io.ErrnoException: open failed: ENOENT (No such file or directory) Now, if I trim the file name to have only 16 characters within the parentheses, everything is working as expected. I am able to send the file as a GMail attachment. The following file name is working fine: /storage/sdcard0/myapp/transfer/Net worth over time _ Forecast (2012-11-19 11070).pdf I tried the following troubleshooting: It's not the overall length of the file name, as if I shorten the base name, the same behavior remains It's not GMail, uploading the file to Google Drive fails similarly 16 characters inside the parentheses work, but not 17 It's not the space character inside the parentheses that causes the issue, as I replaced it with a dash and it's the same problem. Anybody has any ideas on what's going on here?

    Read the article

  • How to map string keys to unique integer IDs?

    - by Marek
    I have some data that comes regularily as a dump from a data souce with a string natural key that is long (up to 60 characters) and not relevant to the end user. I am using this key in a url. This makes urls too long and user unfriendly. I would like to transform the string keys into integers with the following requirements: The source dataset will change over time. The ID should be: non negative integer unique and constant even if the set of input keys changes preferrably reversible back to key (not a strong requirement) The database is rebuilt from scratch every time so I can not remember the already assigned IDs and match the new data set to existing IDs and generate sequential IDs for the added keys. There are currently around 30000 distinct keys and the set is constantly growing. How to implement a function that will map string keys to integer IDs? What I have thought about: 1. Built-in string.GetHashCode: ID(key) = Math.Abs(key.GetHashCode()) is not guaranteed to be unique (not reversible) 1.1 "Re-hashing" the built-in GetHashCode until a unique ID is generated to prevent collisions. existing IDs may change if something colliding is added to the beginning of the input data set 2. a perfect hashing function I am not sure if this can generate constant IDs if the set of inputs changes (not reversible) 3. translate to base 36/64/?? does not shorten the long keys enough What are the other options?

    Read the article

  • Check for existing mapping when writing a custom applier in ConfORM

    - by Philip Fourie
    I am writing my first custom column name applier for ConfORM. How do I check if another column has already been map with same mapping name? This is what I have so far: public class MyColumnNameApplier : IPatternApplier<PropertyPath, IPropertyMapper> { public bool Match(PropertyPath subject) { return (subject.LocalMember != null); } public void Apply(PropertyPath subject, IPropertyMapper applyTo) { string shortColumnName = ToOracleName(subject); // How do I check if the short columnName already exist? applyTo.Column(cm => cm.Name(shortColumnName)); } private string ToOracleName(PropertyPath subject) { ... } } } I need to shorten my class property names to less than 30 characters to fit in with Oracle's 30 character limit. Because I am shortening the column names it is possible that I generate the same name for two different properties. I would like to know when a duplicate mapping occurs. If I don't handle this scenario ConfORM/NHibernate allows two different properties to 'share' the same column name - this is obviously creates a problem for me.

    Read the article

  • C++ Little Wonders: The C++11 auto keyword redux

    - by James Michael Hare
    I’ve decided to create a sub-series of my Little Wonders posts to focus on C++.  Just like their C# counterparts, these posts will focus on those features of the C++ language that can help improve code by making it easier to write and maintain.  The index of the C# Little Wonders can be found here. This has been a busy week with a rollout of some new website features here at my work, so I don’t have a big post for this week.  But I wanted to write something up, and since lately I’ve been renewing my C++ skills in a separate project, it seemed like a good opportunity to start a C++ Little Wonders series.  Most of my development work still tends to focus on C#, but it was great to get back into the saddle and renew my C++ knowledge.  Today I’m going to focus on a new feature in C++11 (formerly known as C++0x, which is a major move forward in the C++ language standard).  While this small keyword can seem so trivial, I feel it is a big step forward in improving readability in C++ programs. The auto keyword If you’ve worked on C++ for a long time, you probably have some passing familiarity with the old auto keyword as one of those rarely used C++ keywords that was almost never used because it was the default. That is, in the code below (before C++11): 1: int foo() 2: { 3: // automatic variables (allocated and deallocated on stack) 4: int x; 5: auto int y; 6:  7: // static variables (retain their value across calls) 8: static int z; 9:  10: return 0; 11: } The variable x is assumed to be auto because that is the default, thus it is unnecessary to specify it explicitly as in the declaration of y below that.  Basically, an auto variable is one that is allocated and de-allocated on the stack automatically.  Contrast this to static variables, that are allocated statically and exist across the lifetime of the program. Because auto was so rarely (if ever) used since it is the norm, they decided to remove it for this purpose and give it new meaning in C++11.  The new meaning of auto: implicit typing Now, if your compiler supports C++ 11 (or at least a good subset of C++11 or 0x) you can take advantage of type inference in C++.  For those of you from the C# world, this means that the auto keyword in C++ now behaves a lot like the var keyword in C#! For example, many of us have had to declare those massive type declarations for an iterator before.  Let’s say we have a std::map of std::string to int which will map names to ages: 1: std::map<std::string, int> myMap; And then let’s say we want to find the age of a given person: 1: // Egad that's a long type... 2: std::map<std::string, int>::const_iterator pos = myMap.find(targetName); Notice that big ugly type definition to declare variable pos?  Sure, we could shorten this by creating a typedef of our specific map type if we wanted, but now with the auto keyword there’s no need: 1: // much shorter! 2: auto pos = myMap.find(targetName); The auto now tells the compiler to determine what type pos should be based on what it’s being assigned to.  This is not dynamic typing, it still determines the type as if it were explicitly declared and once declared that type cannot be changed.  That is, this is invalid: 1: // x is type int 2: auto x = 42; 3:  4: // can't assign string to int 5: x = "Hello"; Once the compiler determines x is type int it is exactly as if we typed int x = 42; instead, so don’t' confuse it with dynamic typing, it’s still very type-safe. An interesting feature of the auto keyword is that you can modify the inferred type: 1: // declare method that returns int* 2: int* GetPointer(); 3:  4: // p1 is int*, auto inferred type is int 5: auto *p1 = GetPointer(); 6:  7: // ps is int*, auto inferred type is int* 8: auto p2 = GetPointer(); Notice in both of these cases, p1 and p2 are determined to be int* but in each case the inferred type was different.  because we declared p1 as auto *p1 and GetPointer() returns int*, it inferred the type int was needed to complete the declaration.  In the second case, however, we declared p2 as auto p2 which means the inferred type was int*.  Ultimately, this make p1 and p2 the same type, but which type is inferred makes a difference, if you are chaining multiple inferred declarations together.  In these cases, the inferred type of each must match the first: 1: // Type inferred is int 2: // p1 is int* 3: // p2 is int 4: // p3 is int& 5: auto *p1 = GetPointer(), p2 = 42, &p3 = p2; Note that this works because the inferred type was int, if the inferred type was int* instead: 1: // syntax error, p1 was inferred to be int* so p2 and p3 don't make sense 2: auto p1 = GetPointer(), p2 = 42, &p3 = p2; You could also use const or static to modify the inferred type: 1: // inferred type is an int, theAnswer is a const int 2: const auto theAnswer = 42; 3:  4: // inferred type is double, Pi is a static double 5: static auto Pi = 3.1415927; Thus in the examples above it inferred the types int and double respectively, which were then modified to const and static. Summary The auto keyword has gotten new life in C++11 to allow you to infer the type of a variable from it’s initialization.  This simple little keyword can be used to cut down large declarations for complex types into a much more readable form, where appropriate.   Technorati Tags: C++, C++11, Little Wonders, auto

    Read the article

  • Android - Switching Activities with a Tab Layout

    - by Bill Osuch
    This post is based on the Tab Layout  tutorial on the Android developers site, with some modifications. I wanted to get rid of the icons (they take up too much screen real estate), and modify the fonts on the tabs. First, create a new Android project, with an Activity called TabWidget. Then, create two additional Activities called TabOne and TabTwo. Throw a simple TextView on each one with a message identifying the tab, like this: public class TabTwo extends Activity {  @Override  public void onCreate(Bundle savedInstanceState) {   super.onCreate(savedInstanceState);   TextView tv = new TextView(this);   tv.setText("This is tab 2");   setContentView(tv);  } } And don't forget to add them to your AndroidManifest.xml file: <activity android:name=".TabOne"></activity> <activity android:name=".TabTwo"></activity> Now we'll create the tab layout - open the res/layout/main.xml file and insert the following: <?xml version="1.0" encoding="utf-8"?> <TabHost xmlns:android="http://schemas.android.com/apk/res/android"  android:id="@android:id/tabhost"  android:layout_width="fill_parent"  android:layout_height="fill_parent">  <LinearLayout   android:orientation="vertical"   android:layout_width="fill_parent"   android:layout_height="fill_parent">   <TabWidget    android:id="@android:id/tabs"    android:layout_width="fill_parent"    android:layout_height="wrap_content" />   <FrameLayout    android:id="@android:id/tabcontent"             android:layout_width="fill_parent"    android:layout_height="fill_parent" />  </LinearLayout> </TabHost> Finally, we'll create the code needed to populate the TabHost. Make sure your TabWidget class extends TabActivity rather than Activity, and add code to grab the TabHost and create an Intent to launch a new Activity:    TabHost tabHost = getTabHost();  // The activity TabHost    TabHost.TabSpec spec;  // Reusable TabSpec for each tab    Intent intent;  // Reusable Intent for each tab       // Create an Intent to launch an Activity for the tab (to be reused)    intent = new Intent().setClass(this, TabOne.class); Add the first tab to the layout:    // Initialize a TabSpec for each tab and add it to the TabHost    spec = tabHost.newTabSpec("tabOne");      spec.setContent(intent);     spec.setIndicator("Tab One");     tabHost.addTab(spec); It's pretty tall as-is, so we'll shorten it:   // Squish the tab a little bit horizontally   tabHost.getTabWidget().getChildAt(0).getLayoutParams().height = 40; But the text is a little small, so let's increase the font size:   // Bump the text size up   LinearLayout ll = (LinearLayout) tabHost.getChildAt(0);   android.widget.TabWidget tw = (android.widget.TabWidget) ll.getChildAt(0);   RelativeLayout rllf = (RelativeLayout) tw.getChildAt(0);   TextView lf = (TextView) rllf.getChildAt(1);   lf.setTextSize(20); Do the same for the second tab, and you wind up with this: @Override     public void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.main);                 TabHost tabHost = getTabHost();  // The activity TabHost         TabHost.TabSpec spec;  // Reusable TabSpec for each tab         Intent intent;  // Reusable Intent for each tab            // Create an Intent to launch an Activity for the tab (to be reused)         intent = new Intent().setClass(this, TabOne.class);         // Initialize a TabSpec for each tab and add it to the TabHost         spec = tabHost.newTabSpec("tabOne");           spec.setContent(intent);          spec.setIndicator("Tab One");          tabHost.addTab(spec);         // Squish the tab a little bit horizontally         tabHost.getTabWidget().getChildAt(0).getLayoutParams().height = 40;         // Bump the text size up         LinearLayout ll = (LinearLayout) tabHost.getChildAt(0);         android.widget.TabWidget tw = (android.widget.TabWidget) ll.getChildAt(0);         RelativeLayout rllf = (RelativeLayout) tw.getChildAt(0);         TextView lf = (TextView) rllf.getChildAt(1);         lf.setTextSize(20);            // Do the same for the other tabs         intent = new Intent().setClass(this, TabTwo.class);         spec = tabHost.newTabSpec("tabTwo");          spec.setContent(intent);          spec.setIndicator("Tab Two");         tabHost.addTab(spec);         tabHost.getTabWidget().getChildAt(1).getLayoutParams().height = 40;         RelativeLayout rlrf = (RelativeLayout) tw.getChildAt(1);         TextView rf = (TextView) rlrf.getChildAt(1);         rf.setTextSize(20);            tabHost.setCurrentTab(0);     } Save and fire up the emulator, and you should be able to switch back and forth between your tabs!

    Read the article

  • SSAS Maestro Training in July 2012 #ssasmaestro #ssas

    - by Marco Russo (SQLBI)
    A few hours ago Chris Webb blogged about SSAS Maestro and I’d like to propagate the news, adding also some background info. SSAS Maestro is the premier certification on Analysis Services that selects the best experts in Analysis Services around the world. In 2011 Microsoft organized two rounds of training/exams for SSAS Maestros and up to now only 11 people from the first wave have been announced – around 10% of attendees of the course! In the next few days the new Maestros from the second round should be announced and this long process is caused by many factors that I’m going to explain. First, the course is just a step in the process. Before the course you receive a list of topics to study, including the slides of the course. During the course, students receive a lot of information that might not have been included in the slides and the best part of the course is class interaction. Students are expected to bring their experience to the table and comparing case studies, experiences and having long debates is an important part of the learning process. And it is also a part of the evaluation: good questions might be also more important than good answers! Finally, after the course, students have their homework and this may require one or two months to be completed. After that, a long (very long) evaluation process begins, taking into account homework, labs, participation… And for this reason the final evaluation may arrive months later after the course. We are going to improve and shorten this process with the next courses. The first wave of SSAS Maestro had been made by invitation only and now the program is opening, requiring a fee to participate in order to cover the cost of preparation, training and exam. The number of attendees will be limited and candidates will have to send their CV in order to be admitted to the course. Only experienced Analysis Services developers will be able to participate to this challenging program. So why you should do that? Well, only 10% of students passed the exam until now. So if you need 100% guarantee to pass the exam, you need to study a lot, before, during and after the course. But the course by itself is a precious opportunity to share experience, create networking and learn mission-critical enterprise-level best practices that it’s hard to find written on books. Oh, well, many existing white papers are a required reading *before* the course! The course is now 5 days long, and every day can be *very* long. We’ll have lectures and discussions in the morning and labs in the afternoon/evening. Plus some more lectures in one or two afternoons. A heavy part of the course is about performance optimization, capacity planning, monitoring. This edition will introduce also Tabular models, and don’t expect something you might find in the SSAS Tabular Workshop – only performance, scalability monitoring and optimization will be covered, knowing Analysis Services is a requirement just to be accepted! I and Chris Webb will be the teachers for this edition. The course is expensive. Applying for SSAS Maestro will cost around 7000€ plus taxes (reduced to 5000€ for students of a previous SSAS Maestro edition). And you will be locked in a training room for the large part of the week. So why you should do that? Well, as I said, this is a challenging course. You will not find the time to check your email – the content is just too much interesting to think you can be distracted by something else. Another good reason is that this course will take place in Italy. Well, the course will take place in the brand new Microsoft Innovation Campus, but in general we’ll be able to provide you hints to get great food and, if you are willing to attach one week-end to your trip, there are plenty of places to visit (and I’m not talking about the classic Rome-Florence-Venice) – you might really need to relax after such a week! Finally, the marking process after the course will be faster – we’d like to complete the evaluation within three months after the course, considering that 1-2 months might be required to complete the homework. If at this point you are not scared: registration will open in mid-April, but you can already write to [email protected] sending your CV/resume and a short description of your level of SSAS knowledge and experience. The selection process will start early and you may want to put your admission form on top of the FIFO queue!

    Read the article

  • C#/.NET Little Wonders: Static Char Methods

    - by James Michael Hare
    Once again, in this series of posts I look at the parts of the .NET Framework that may seem trivial, but can help improve your code by making it easier to write and maintain. The index of all my past little wonders posts can be found here. Often times in our code we deal with the bigger classes and types in the BCL, and occasionally forgot that there are some nice methods on the primitive types as well.  Today we will discuss some of the handy static methods that exist on the char (the C# alias of System.Char) type. The Background I was examining a piece of code this week where I saw the following: 1: // need to get the 5th (offset 4) character in upper case 2: var type = symbol.Substring(4, 1).ToUpper(); 3:  4: // test to see if the type is P 5: if (type == "P") 6: { 7: // ... do something with P type... 8: } Is there really any error in this code?  No, but it still struck me wrong because it is allocating two very short-lived throw-away strings, just to store and manipulate a single char: The call to Substring() generates a new string of length 1 The call to ToUpper() generates a new upper-case version of the string from Step 1. In my mind this is similar to using ToUpper() to do a case-insensitive compare: it isn’t wrong, it’s just much heavier than it needs to be (for more info on case-insensitive compares, see #2 in 5 More Little Wonders). One of my favorite books is the C++ Coding Standards: 101 Rules, Guidelines, and Best Practices by Sutter and Alexandrescu.  True, it’s about C++ standards, but there’s also some great general programming advice in there, including two rules I love:         8. Don’t Optimize Prematurely         9. Don’t Pessimize Prematurely We all know what #8 means: don’t optimize when there is no immediate need, especially at the expense of readability and maintainability.  I firmly believe this and in the axiom: it’s easier to make correct code fast than to make fast code correct.  Optimizing code to the point that it becomes difficult to maintain often gains little and often gives you little bang for the buck. But what about #9?  Well, for that they state: “All other things being equal, notably code complexity and readability, certain efficient design patterns and coding idioms should just flow naturally from your fingertips and are no harder to write then the pessimized alternatives. This is not premature optimization; it is avoiding gratuitous pessimization.” Or, if I may paraphrase: “where it doesn’t increase the code complexity and readability, prefer the more efficient option”. The example code above was one of those times I feel where we are violating a tacit C# coding idiom: avoid creating unnecessary temporary strings.  The code creates temporary strings to hold one char, which is just unnecessary.  I think the original coder thought he had to do this because ToUpper() is an instance method on string but not on char.  What he didn’t know, however, is that ToUpper() does exist on char, it’s just a static method instead (though you could write an extension method to make it look instance-ish). This leads me (in a long-winded way) to my Little Wonders for the day… Static Methods of System.Char So let’s look at some of these handy, and often overlooked, static methods on the char type: IsDigit(), IsLetter(), IsLetterOrDigit(), IsPunctuation(), IsWhiteSpace() Methods to tell you whether a char (or position in a string) belongs to a category of characters. IsLower(), IsUpper() Methods that check if a char (or position in a string) is lower or upper case ToLower(), ToUpper() Methods that convert a single char to the lower or upper equivalent. For example, if you wanted to see if a string contained any lower case characters, you could do the following: 1: if (symbol.Any(c => char.IsLower(c))) 2: { 3: // ... 4: } Which, incidentally, we could use a method group to shorten the expression to: 1: if (symbol.Any(char.IsLower)) 2: { 3: // ... 4: } Or, if you wanted to verify that all of the characters in a string are digits: 1: if (symbol.All(char.IsDigit)) 2: { 3: // ... 4: } Also, for the IsXxx() methods, there are overloads that take either a char, or a string and an index, this means that these two calls are logically identical: 1: // check given a character 2: if (char.IsUpper(symbol[0])) { ... } 3:  4: // check given a string and index 5: if (char.IsUpper(symbol, 0)) { ... } Obviously, if you just have a char, then you’d just use the first form.  But if you have a string you can use either form equally well. As a side note, care should be taken when examining all the available static methods on the System.Char type, as some seem to be redundant but actually have very different purposes.  For example, there are IsDigit() and IsNumeric() methods, which sound the same on the surface, but give you different results. IsDigit() returns true if it is a base-10 digit character (‘0’, ‘1’, … ‘9’) where IsNumeric() returns true if it’s any numeric character including the characters for ½, ¼, etc. Summary To come full circle back to our opening example, I would have preferred the code be written like this: 1: // grab 5th char and take upper case version of it 2: var type = char.ToUpper(symbol[4]); 3:  4: if (type == 'P') 5: { 6: // ... do something with P type... 7: } Not only is it just as readable (if not more so), but it performs over 3x faster on my machine:    1,000,000 iterations of char method took: 30 ms, 0.000050 ms/item.    1,000,000 iterations of string method took: 101 ms, 0.000101 ms/item. It’s not only immediately faster because we don’t allocate temporary strings, but as an added bonus there less garbage to collect later as well.  To me this qualifies as a case where we are using a common C# performance idiom (don’t create unnecessary temporary strings) to make our code better. Technorati Tags: C#,CSharp,.NET,Little Wonders,char,string

    Read the article

  • spoj: runlength

    - by user285825
    For RLM problem of SPOJ: This is the problem: "Run-length encoding of a number replaces a run of digits (that is, a sequence of consecutive equivalent digits) with the number of digits followed by the digit itself. For example, 44455 would become 3425 (three fours, two fives). Note that run-length encoding does not necessarily shorten the length of the data: 11 becomes 21, and 42 becomes 1412. If a number has more than nine consecutive digits of the same type, the encoding is done greedily: each run grabs as many digits as it can, so 111111111111111 is encoded as 9161. Implement an integer arithmetic calculator that takes operands and gives results in run-length format. You should support addition, subtraction, multiplication, and division. You won't have to divide by zero or deal with negative numbers. Input/Output The input will consist of several test cases, one per line. For each test case, compute the run-length mathematics expression and output the original expression and the result, as shown in the examples. The (decimal) representation of all operands and results will fit in signed 64-bit integers." These are my testcases: input: 11 + 11 988726 - 978625 12 * 41 1124 / 1112 13 * 33 15 / 16 19222317121013161815142715181017 + 10 10 + 19222317121013161815142715181017 19222317121013161815142715181017 / 19222317121013161815142715181017 19222317121013161815142715181017 / 11 11 / 19222317121013161815142715181017 19222317121013161815142715181017 / 12 12 / 19222317121013161815142715181017 19222317121013161815142715181017 / 141621161816101118141217131817191014 141621161816101118141217131817191014 / 19222317121013161815142715181017 19222317121013161815142715181017 / 141621161816101118141217131817191013 141621161816101118141217131817191013 / 19222317121013161815142715181017 19222317121013161815142715181017 * 11 11 * 19222317121013161815142715181017 19222317121013161815142715181017 * 10 10 * 19222317121013161815142715181017 19222317121013161815142715181017 - 10 19222317121013161815142715181017 - 19222317121013161815142715181017 19222317121013161815142715181017 - 141621161816101118141217131817191014 19222317121013161815142715181017 - 141621161816101118141217131817191013 141621161816101118141217131817191013 + 141621161816101118141217131817191013 141621161816101118141217131817191013 + 141621161816101118141217131817191014 141621161816101118141217131817191014 + 141621161816101118141217131817191013 141621161816101118141217131817191014 + 10 10 + 141621161816101118141217131817191013 141621161816101118141217131817191013 + 11 11 + 141621161816101118141217131817191013 141621161816101118141217131817191013 * 12 12 * 141621161816101118141217131817191013 141621161816101118141217131817191014 - 141621161816101118141217131817191014 141621161816101118141217131817191013 - 141621161816101118141217131817191013 141621161816101118141217131817191013 - 10 141621161816101118141217131817191014 - 11 141621161816101118141217131817191014 - 141621161816101118141217131817191013 141621161816101118141217131817191014 / 141621161816101118141217131817191014 141621161816101118141217131817191014 / 141621161816101118141217131817191013 141621161816101118141217131817191013 / 141621161816101118141217131817191014 141621161816101118141217131817191013 / 141621161816101118141217131817191013 141621161816101118141217131817191014 * 11 11 * 141621161816101118141217131817191014 141621161816101118141217131817191014 / 11 11 / 141621161816101118141217131817191014 10 + 10 10 + 11 10 + 15 15 + 10 11 + 10 11 + 10 10 - 10 15 - 10 10 * 10 10 * 15 15 * 10 10 / 111213 output: 11 + 11 = 12 988726 - 978625 = 919111 12 * 41 = 42 1124 / 1112 = 1112 13 * 33 = 39 15 / 16 = 10 19222317121013161815142715181017 + 10 = 19222317121013161815142715181017 10 + 19222317121013161815142715181017 = 19222317121013161815142715181017 19222317121013161815142715181017 / 19222317121013161815142715181017 = 11 19222317121013161815142715181017 / 11 = 19222317121013161815142715181017 11 / 19222317121013161815142715181017 = 10 19222317121013161815142715181017 / 12 = 141621161816101118141217131817191013 12 / 19222317121013161815142715181017 = 10 19222317121013161815142715181017 / 141621161816101118141217131817191014 = 11 141621161816101118141217131817191014 / 19222317121013161815142715181017 = 10 19222317121013161815142715181017 / 141621161816101118141217131817191013 = 12 141621161816101118141217131817191013 / 19222317121013161815142715181017 = 10 19222317121013161815142715181017 * 11 = 19222317121013161815142715181017 11 * 19222317121013161815142715181017 = 19222317121013161815142715181017 19222317121013161815142715181017 * 10 = 10 10 * 19222317121013161815142715181017 = 10 19222317121013161815142715181017 - 10 = 19222317121013161815142715181017 19222317121013161815142715181017 - 19222317121013161815142715181017 = 10 19222317121013161815142715181017 - 141621161816101118141217131817191014 = 141621161816101118141217131817191013 19222317121013161815142715181017 - 141621161816101118141217131817191013 = 141621161816101118141217131817191014 141621161816101118141217131817191013 + 141621161816101118141217131817191013 = 19222317121013161815142715181016 141621161816101118141217131817191013 + 141621161816101118141217131817191014 = 19222317121013161815142715181017 141621161816101118141217131817191014 + 141621161816101118141217131817191013 = 19222317121013161815142715181017 141621161816101118141217131817191014 + 10 = 141621161816101118141217131817191014 10 + 141621161816101118141217131817191013 = 141621161816101118141217131817191013 141621161816101118141217131817191013 + 11 = 141621161816101118141217131817191014 11 + 141621161816101118141217131817191013 = 141621161816101118141217131817191014 141621161816101118141217131817191013 * 12 = 19222317121013161815142715181016 12 * 141621161816101118141217131817191013 = 19222317121013161815142715181016 141621161816101118141217131817191014 - 141621161816101118141217131817191014 = 10 141621161816101118141217131817191013 - 141621161816101118141217131817191013 = 10 141621161816101118141217131817191013 - 10 = 141621161816101118141217131817191013 141621161816101118141217131817191014 - 11 = 141621161816101118141217131817191013 141621161816101118141217131817191014 - 141621161816101118141217131817191013 = 11 141621161816101118141217131817191014 / 141621161816101118141217131817191014 = 11 141621161816101118141217131817191014 / 141621161816101118141217131817191013 = 11 141621161816101118141217131817191013 / 141621161816101118141217131817191014 = 10 141621161816101118141217131817191013 / 141621161816101118141217131817191013 = 11 141621161816101118141217131817191014 * 11 = 141621161816101118141217131817191014 11 * 141621161816101118141217131817191014 = 141621161816101118141217131817191014 141621161816101118141217131817191014 / 11 = 141621161816101118141217131817191014 11 / 141621161816101118141217131817191014 = 10 10 + 10 = 10 10 + 11 = 11 10 + 15 = 15 15 + 10 = 15 11 + 10 = 11 11 + 10 = 11 10 - 10 = 10 15 - 10 = 15 10 * 10 = 10 10 * 15 = 10 15 * 10 = 10 10 / 111213 = 10 I am getting consistently wrong answer. I generated the above testcases trying to make them as representative as possible (boundary conditions, etc). I am not sure how to test it further. Some guidline would be really appreciated.

    Read the article

  • Dumb IE6 resize behaviour - hope it rings some bells with someone

    - by Ollie2893
    Hi, I'm having no end of fun (sic) with jQuery.tabs. The widget is quite crafty in that it turns basic HTML like so <div> <ul> <li>Tab #1</li> ... </ul> <div for panel #1> </div> <div for panel #2> </div> ... </div> into a cute tabbed dialogue. (It does so by restyling the UL and then toggling the "display" attribute for the panel DIVs to show/not show whatever panel is selected.) Now I found that I can spare myself a lot of trouble in my JS project if I insert a scrollable IFRAME into each panel. One usability problem I'm trying to ameliorate is that when the tabbed panel becomes larger than the browser's window, then the user ends up with too many scrollbars. I am trying to avoid this situation by linking the size of the tabbed panel to that of $(window). That is, I trap and process the resize event on $(window). To make my life bearable, all components are relatively sized. This is also true, in particular, of the IFRAMEs (100% width, 100% height). The only exception are the panel DIVs, which are of fixed height (in px). And this is the only dimension css attribute that I manipulate during my resize action. All of this works a treat in FF and Chrome, but IE6 is doing something rather cute: So long as I do not affect the width of the browser window (but only change its height), only the panel DIV changes in height; the IFRAME contained will not change. As a result of this behaviour, it is not possible to shorten the tabbed panel below the height of the IFRAME. I can lengthen the DIV, yes. But the IFRAME will not fill the panel in that case. All becomes good the moment I make the slightest change to the width of the browser window. In that moment, the IFRAME expands to catch up with the extended DIV or DIV and IFRAME contract in tandem. Bizarre. I inserted useless CSS instructions like "position: relative" and "zoom: 1". Also nudged the display with "display: block". No joy so far. Any ideas? Thanks.

    Read the article

  • Better way to get int from FragmentActivity in a Fragment?

    - by Gimberg
    Hi im trying to get an int from my FragmentActivity and i have a way to do this but the code get very cluttered and long and i did this to shorten the problem and i don't get any errors while in the editor but when i run the app it eminently crashes. Any suggestions? An example of the code that doesn't work MainActivity mainActivity = ((MainActivity)getActivity()); public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.upgrades_fragment, container, false); TextView AirFreshenersCost = (TextView) view.findViewById(R.id.AirFreshenersCost ); if(mainActivity.amountAirFresheners == 5){ AirFreshenersCost.setText("5"); } return view; } LogCat 10-27 22:16:37.333: E/AndroidRuntime(5593): FATAL EXCEPTION: main 10-27 22:16:37.333: E/AndroidRuntime(5593): java.lang.NullPointerException 10-27 22:16:37.333: E/AndroidRuntime(5593): at com.free.dennisg.clickingbad.fragments.UpgradesFragment.onCreateView(UpgradesFragment.java:40) 10-27 22:16:37.333: E/AndroidRuntime(5593): at android.support.v4.app.Fragment.performCreateView(Fragment.java:1478) 10-27 22:16:37.333: E/AndroidRuntime(5593): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:927) 10-27 22:16:37.333: E/AndroidRuntime(5593): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104) 10-27 22:16:37.333: E/AndroidRuntime(5593): at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682) 10-27 22:16:37.333: E/AndroidRuntime(5593): at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1460) 10-27 22:16:37.333: E/AndroidRuntime(5593): at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:472) 10-27 22:16:37.333: E/AndroidRuntime(5593): at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141) 10-27 22:16:37.333: E/AndroidRuntime(5593): at android.support.v4.view.ViewPager.populate(ViewPager.java:1068) 10-27 22:16:37.333: E/AndroidRuntime(5593): at android.support.v4.view.ViewPager.populate(ViewPager.java:914) 10-27 22:16:37.333: E/AndroidRuntime(5593): at android.support.v4.view.ViewPager$3.run(ViewPager.java:244) 10-27 22:16:37.333: E/AndroidRuntime(5593): at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749) 10-27 22:16:37.333: E/AndroidRuntime(5593): at android.view.Choreographer.doCallbacks(Choreographer.java:562) 10-27 22:16:37.333: E/AndroidRuntime(5593): at android.view.Choreographer.doFrame(Choreographer.java:531) 10-27 22:16:37.333: E/AndroidRuntime(5593): at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735) 10-27 22:16:37.333: E/AndroidRuntime(5593): at android.os.Handler.handleCallback(Handler.java:730) 10-27 22:16:37.333: E/AndroidRuntime(5593): at android.os.Handler.dispatchMessage(Handler.java:92) 10-27 22:16:37.333: E/AndroidRuntime(5593): at android.os.Looper.loop(Looper.java:137) 10-27 22:16:37.333: E/AndroidRuntime(5593): at android.app.ActivityThread.main(ActivityThread.java:5289) 10-27 22:16:37.333: E/AndroidRuntime(5593): at java.lang.reflect.Method.invokeNative(Native Method) 10-27 22:16:37.333: E/AndroidRuntime(5593): at java.lang.reflect.Method.invoke(Method.java:525) 10-27 22:16:37.333: E/AndroidRuntime(5593): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739) 10-27 22:16:37.333: E/AndroidRuntime(5593): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:555) 10-27 22:16:37.333: E/AndroidRuntime(5593): at dalvik.system.NativeStart.main(Native Method) An example of the code that work public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.upgrades_fragment, container, false); TextView AirFreshenersCost = (TextView) view.findViewById(R.id.AirFreshenersCost ); if(((MainActivity)getActivity()).amountAirFresheners == 5){ AirFreshenersCost.setText("5"); } return view; }

    Read the article

  • Will this ever result in a stack overflow error?

    - by David
    Will incrementing the instance variables of an object ever lead to a stack overflow error? For example: This method (java) will cause a stack overflow error: class StackOverflow { public static void StackOverflow (int x) { System.out.println (x) ; StackOverflow(x+1) ; } public static void main (String[]arg) { StackOverflow (0) ; } but will this?: (..... is a gap that i've put in to shorten the code. its long enough as it is.) import java.util.*; class Dice { String name ; int x ; int[] sum ; .... public Dice (String name) { this.name = name ; this.x = 0 ; this.sum = new int[7] ; } .... public static void main (String[] arg) { Dice a1 = new Dice ("a1") ; for (int i = 0; i<6000000; i++) { a1.roll () ; printDice(a1) ; } } .... public void roll () { this.x = randNum(1, this.sum.length) ; this.sum[x] ++ ; } public static int randNum (int a, int b) { Random random = new Random() ; int c = (b-a) ; int randomNumber = ((random.nextInt(c)) + a) ; return randomNumber ; } public static void printDice (Dice Dice) { System.out.println (Dice.name) ; System.out.println ("value: "+Dice.x) ; printValues (Dice) ; } public static void printValues (Dice Dice) { for (int i = 0; i<Dice.sum.length; i++) System.out.println ("#of "+i+"'s: "+Dice.sum[i]) ; } } The above doesn't currently cause a stack overflow error but could i get it too if i changed this line in main: for (int i = 0; i<6000000; i++) so that instead of 6 million something sufficiently high were there?

    Read the article

  • jQuery multiple if else Statements

    - by Chris MMgr
    I have a set of images that I am trying to activate (change opacity) based on the position of a user's window. The below code works, but only through a long series of if else statements. Is there a way to shorten the below code? //Function to activate and deactivate the buttons on the side menu function navIndicator() { var winNow = $(window).scrollTop(); var posRoi = $('#roi').offset(); var posRoiNow = posRoi.top; //Activate the propper button corresponding to what section the user is viewing if (winNow == posRoiNow * 0) { $('#homeBut a img.active').stop().animate({ opacity: 1 } { queue: false, duration: 300, easing: "easeOutExpo" }); $('#homeBut').addClass("viewing") } else { $('#homeBut a img.active').stop().animate({ opacity: 0 }, { queue: false, duration: 300, easing: "easeOutExpo" }); $('#homeBut').removeClass("viewing") } if (winNow == posRoiNow) { $('#roiBut a img.active').stop().animate({ opacity: 1 }, { queue: false, duration: 300, easing: "easeOutExpo" }); $('#roiBut').addClass("viewing") } else { $('#roiBut a img.active').stop().animate({ opacity: 0 }, { queue: false, duration: 300, easing: "easeOutExpo" }); $('#roiBut').removeClass("viewing") } if (winNow == posRoiNow * 2) { $('#dmsBut a img.active').stop().animate({ opacity: 1 }, { queue: false, duration: 300, easing: "easeOutExpo" }); $('#dmsBut').addClass("viewing") } else { $('#dmsBut a img.active').stop().animate({ opacity: 0 }, { queue: false, duration: 300, easing: "easeOutExpo" }); $('#dmsBut').removeClass("viewing") } if (winNow == posRoiNow * 3) { $('#techBut a img.active').stop().animate({ opacity: 1 }, { queue: false, duration: 300, easing: "easeOutExpo" }); $('#techBut').addClass("viewing") } else { $('#techBut a img.active').stop().animate({ opacity: 0 }, { queue: false, duration: 300, easing: "easeOutExpo" }); $('#techBut').removeClass("viewing") } if (winNow == posRoiNow * 4) { $('#impBut a img.active').stop().animate({ opacity: 1 }, { queue: false, duration: 300, easing: "easeOutExpo" }); $('#impBut').addClass("viewing") } else { $('#impBut a img.active').stop().animate({ opacity: 0 }, { queue: false, duration: 300, easing: "easeOutExpo" }); $('#impBut').removeClass("viewing") } if (winNow == posRoiNow * 5) { $('#virBut a img.active').stop().animate({ opacity: 1 }, { queue: false, duration: 300, easing: "easeOutExpo" }); $('#virBut').addClass("viewing") } else { $('#virBut a img.active').stop().animate({ opacity: 0 }, { queue: false, duration: 300, easing: "easeOutExpo" }); $('#virBut').removeClass("viewing") } if (winNow == posRoiNow * 6) { $('#biBut a img.active').stop().animate({ opacity: 1 }, { queue: false, duration: 300, easing: "easeOutExpo" }); $('#biBut').addClass("viewing") } else { $('#biBut a img.active').stop().animate({ opacity: 0 }, { queue: false, duration: 300, easing: "easeOutExpo" }); $('#biBut').removeClass("viewing") } if (winNow == posRoiNow * 7) { $('#contBut a img.active').stop().animate({ opacity: 1 }, { queue: false, duration: 300, easing: "easeOutExpo" }); $('#contBut').addClass("viewing") } else { $('#contBut a img.active').stop().animate({ opacity: 0 }, { queue: false, duration: 300, easing: "easeOutExpo" }); $('#contBut').removeClass("viewing") } };

    Read the article

  • Tips on installing Visual Studio 2010 SP1

    - by Jon Galloway
    Visual Studio SP1 went up on MSDN downloads (here) on March 8, and will be released publicly on March 10 here. Release announcements: Soma: Visual Studio 2010 enhancements Jason Zander: Announcing Visual Studio 2010 Service Pack 1 I started on this post with tips on installing VS2010 SP1 when I realized I’ve been writing these up for Visual Studio and .NET framework SP releases for a while (e.g. VS2008 / .NET 3.5 SP1 post, VS2005 SP1 post). Looking back the years of Visual Studio SP installs (and remembering when we’d get up to SP6 for a Visual Studio release), I’m happy to see that it just keeps getting easier. Service Packs are a lot less finicky about requiring beta software to be uninstalled, install more quickly, and are just generally a lot less scary. If I can’t have a jetpack, at least my future provided me faster, easier service packs. Disclaimer: These tips are just general things I've picked up over the years. I don't have any inside knowledge here. If you see anything wrong, be sure to let me know in the comments. You may want to check the readme file before installing - it's short, and it's in that new-fangled HTML format. On with the tips! Before starting, uninstall Visual Studio features you don't use Visual Studio service packs (and other Microsoft service packs as well) install patches for the specific features you’ve got installed. This is a big reason to always do a custom install when you first install Visual Studio, but it’s not difficult to update your existing installation. Here’s the quick way to do that: Tap the windows key and type “add or remove programs” and press enter (or click on the “Add or remove programs” link if you must).   Type “Visual Studio 2010” in the search box in the upper right corner, click on the Visual Studio program (the one with the VS infinity looking logo) and click on Uninstall/Change. Click on Add or Remove Features The next part’s up to you – what features do you actually use? I’ve been doing primarily ASP.NET MVC development in C# lately, so I selected Visual C# and Visual Web Developer. Remember that you can install features later if needed, and can also install the express versions if you want. Selecting everything just because it’s there - or you paid for it – means that you install updates for everything, every time. When you’ve made your changes, click on the Update button to uninstall unused features. Shut down all instances of Visual Studio It probably goes without saying that you should close a program down before installing it, partly to avoid the file-in-use-reboot-after-install horror. Additional "hunch / works on my machine" quality tip: On one computer I saw a note in the setup log about Visual Studio a prompt for user input to close Visual Studio, although I never saw the prompt. Just to  be sure, I'd personally open up Task Manager and kill any devenv.exe processes I saw running, as it couldn't hurt. Use the web installer I use the Web Installers whenever possible. There’s no point in downloading the DVD unless you’re doing multiple installs or won’t have internet access. The DVD IS is 1.5GB, since it needs to be able to service every possible supported installation option on both x86 and x64. The web installer is 776 KB (smaller than calc.exe), so you can start the installation right away. Like other web installers, the real benefit is that it only installs the updates you need (hence the reason for step 1 – uninstalling unused components). Instead of 1.5GB, my download was roughly 530MB. If you’re installing from MSDN (this link takes you right to the Visual Studio installs), select the first one on the list: The first step in the installation process is to analyze the machine configuration and tell you what needs to be installed. Since I've trimmed down my features, that's a pretty short list. The time's not far off where I may not install SQL Server on my dev machines, just using SQL Server Compact - that would shorten the list further. When I hit next, you can see that the download size has shrunk considerably. When I start the install, note that the installation begins while other components are downloading - another benefit of the web install. On my mid-range desktop machine, the install took 25 minutes. What if it takes longer? According to Heath Stewart (Visual Studio installer guru), average SP1 installs take roughly 45 minutes. An installation which takes hours to complete may be a sign of a problem: see his post Visual Studio 2010 Service Pack 1 installing for over 2 hours could be a sign of a problem. Why so long? Yes, even 25 minutes is a while. Heath's got another blog post explaining why the update can take longer than the initial install (see: A patch may take as long or longer to install than the target product) which explains all the additional steps and complexities a patch needs to deal with, as well as some mitigation steps that deployment authors can take to mitigate the impact. Other things to know about Visual Studio 2010 SP1 Installs over Visual Studio 2010 SP1 Beta That's nice. Previous Visual Studio versions did a number of annoying things when you installed SP's over beta's - fail with weird errors, get part way through and tell you needed to cancel and uninstall first, etc. I've installed this on two machines that had random beta stuff installed without tears. That Readme file you didn't read I mentioned the readme file earlier (http://go.microsoft.com/fwlink/?LinkId=210711 ). Some interesting things I picked up in there: 2.1.3. Visual Studio 2010 Service Pack 1 installation may fail when a USB drive or other removeable drive is connected 2.1.4. Visual Studio must be restarted after Visual Studio 2010 SP1 tooling for SQL Server Compact (Compact) 4.0 is installed 2.2.1. If Visual Studio 2010 Service Pack 1 is uninstalled, Visual Studio 2010 must be reinstalled to restore certain components 2.2.2. If Visual Studio 2010 Service Pack 1 is uninstalled, Visual Studio 2010 must be reinstalled before SP1 can be installed again 2.4.3.1. Async CTP If you installed the pre-SP1 version of Async CTP but did not uninstall it before you installed Visual Studio 2010 SP1, then your computer will be in a state in which the version of the C# compiler in the .NET Framework does not match the C# compiler in Visual Studio. To resolve this issue: After you install Visual Studio 2010 SP1, reinstall the SP1 version of the Async CTP from here. Hardware acceleration for Visual Studio is disabled on Windows XP Visual Studio 2010 SP1 disables hardware acceleration when running on Windows XP (only on XP). You can turn it back on in the Visual Studio options, under Environment / General, as shown below. See Jason Zander's post titled Performance Troubleshooting Article and VS2010 SP1 Change.

    Read the article

  • A pseudo-listener for AlwaysOn Availability Groups for SQL Server virtual machines running in Azure

    - by MikeD
    I am involved in a project that is implementing SharePoint 2013 on virtual machines hosted in Azure. The back end data tier consists of two Azure VMs running SQL Server 2012, with the SharePoint databases contained in an AlwaysOn Availability Group. I used this "Tutorial: AlwaysOn Availability Groups in Windows Azure (GUI)" to help me implement this setup.Because Azure DHCP will not assign multiple unique IP addresses to the same VM, having an AG Listener in Azure is not currently supported.  I wanted to figure out another mechanism to support a "pseudo listener" of some sort. First, I created a CNAME (alias) record in the DNS zone with a short TTL (time to live) of 5 minutes (I may yet make this even shorter). The record represents a logical name (let's say the alias is SPSQL) of the server to connect to for the databases in the availability group (AG). When Server1 was hosting the primary replica of the AG, I would set the CNAME of SPSQL to be SERVER1. When the AG failed over to Server1, I wanted to set the CNAME to SERVER2. Seemed simple enough.(It's important to point out that the connection strings for my SharePoint services should use the CNAME alias, and not the actual server name. This whole thing falls apart otherwise.)To accomplish this, I created identical SQL Agent Jobs on Server1 and Server2, with two steps:1. Step 1: Determine if this server is hosting the primary replica.This is a TSQL step using this script:declare @agName sysname = 'AGTest'set nocount on declare @primaryReplica sysnameselect @primaryReplica = agState.primary_replicafrom sys.dm_hadr_availability_group_states agState   join sys.availability_groups ag on agstate.group_id = ag.group_id   where ag.name = @AGname if not exists(   select *    from sys.dm_hadr_availability_group_states agState   join sys.availability_groups ag on agstate.group_id = ag.group_id   where @@Servername = agstate.primary_replica    and ag.name = @AGname)begin   raiserror ('Primary replica of %s is not hosted on %s, it is hosted on %s',17,1,@Agname, @@Servername, @primaryReplica) endThis script determines if the primary replica value of the AG group is the same as the server name, which means that our server is hosting the current AG (you should update the value of the @AgName variable to the name of your AG). If this is true, I want the DNS alias to point to this server. If the current server is not hosting the primary replica, then the script raises an error. Also, if the script can't be executed because it cannot connect to the server, that also will generate an error. For the job step settings, I set the On Failure option to "Quit the job reporting success". The next step in the job will set the DNS alias to this server name, and I only want to do that if I know that it is the current primary replica, otherwise I don't want to do anything. I also include the step output in the job history so I can see the error message.Job Step 2: Update the CNAME entry in DNS with this server's name.I used a PowerShell script to accomplish this:$cname = "SPSQL.contoso.com"$query = "Select * from MicrosoftDNS_CNAMEType"$dns1 = "dc01.contoso.com"$dns2 = "dc02.contoso.com"if ((Test-Connection -ComputerName $dns1 -Count 1 -Quiet) -eq $true){    $dnsServer = $dns1}elseif ((Test-Connection -ComputerName $dns2 -Count 1 -Quiet) -eq $true) {   $dnsServer = $dns2}else{  $msg = "Unable to connect to DNS servers: " + $dns1 + ", " + $dns2   Throw $msg}$record = Get-WmiObject -Namespace "root\microsoftdns" -Query $query -ComputerName $dnsServer  | ? { $_.Ownername -match $cname }$thisServer = [System.Net.Dns]::GetHostEntry("LocalHost").HostName + "."$currentServer = $record.RecordData if ($currentServer -eq $thisServer ) {     $cname + " CNAME is up to date: " + $currentServer}else{    $cname + " CNAME is being updated to " + $thisServer + ". It was " + $currentServer    $record.RecordData = $thisServer    $record.put()}This script does a few things:finds a responsive domain controller (Test-Connection does a ping and returns a Boolean value if you specify the -Quiet parameter)makes a WMI call to the domain controller to get the current CNAME record value (Get-WmiObject)gets the FQDN of this server (GetHostEntry)checks if the CNAME record is correct and updates it if necessary(You should update the values of the variables $cname, $dns1 and $dns2 for your environment.)Since my domain controllers are also hosted in Azure VMs, either one of them could be down at any point in time, so I need to find a DC that is responsive before attempting the DNS call. The other little thing here is that the CNAME record contains the FQDN of a machine, plus it ends with a period. So the comparison of the CNAME record has to take the trailing period into account. When I tested this step, I was getting ACCESS DENIED responses from PowerShell for the Get-WmiObject cmdlet that does a remote lookup on the DC. This occurred because the SQL Agent service account was not a member of the Domain Admins group, so I decided to create a SQL Credential to store the credentials for a domain administrator account and use it as a PowerShell proxy (rather than give the service account Domain Admins membership).In SQL Management Studio, right click on the Credentials node (under the server's Security node), and choose New Credential...Then, under SQL Agent-->Proxies, right click on the PowerShell node and choose New Proxy...Finally, in the job step properties for the PowerShell step, select the new proxy in the Run As drop down.I created this two step Job on both nodes of the Availability Group, but if you had more than two nodes, just create the same job on all the servers. I set the schedule for the job to execute every minute.When the server that is hosting the primary replica is running the job, the job history looks like this:The job history on the secondary server looks like this: When a failover occurs, the SQL Agent job on the new primary replica will detect that the CNAME needs to be updated within a minute. Based on the TTL of the CNAME (which I said at the beginning was 5 minutes), the SharePoint servers will get the new alias within five minutes and should be able to reconnect. I may want to shorten up the TTL to reduce the time it takes for the client connections to use the new alias. Using a DNS CNAME and a SQL Agent Job on all servers hosting AG replicas, I was able to create a pseudo-listener to automatically change the name of the server that was hosting the primary replica, for a scenario where I cannot use a regular AG listener (in this case, because the servers are all hosted in Azure).    

    Read the article

< Previous Page | 5 6 7 8 9 10 11  | Next Page >