Search Results

Search found 999 results on 40 pages for 'substring'.

Page 33/40 | < Previous Page | 29 30 31 32 33 34 35 36 37 38 39 40  | Next Page >

  • How to use Caret to tell which line it is in from JTextPane? (Java)

    - by Alex Cheng
    Hi all. Problem: I have CaretListener and DocumentListener listening on a JTextPane. I need an algorithm that is able to tell which line is the caret at in a JTextPane, here's an illustrative example: Result: 3rd line Result: 2nd line Result: 4th line and if the algorithm can tell which line the caret is in the JTextPane, it should be fairly easy to substring whatever that is in between the parentheses as the picture (caret is at character m of metadata): -- This is how I divide the entire text that I retrieved from the JTextPane into sentences: String[] lines = textPane.getText().split("\r?\n|\r", -1); The sentences in the textPane is separated with \n. Problem is, how can I manipulate the caret to let me know at which position and which line it is in? I know the dot of the caret says at which position it is, but I can't tell which line it is at. Assuming if I know which line the caret is, then I can just do lines[<line number>] and manipulate the string from there. In Short: How do I use CaretListener and/or DocumentListener to know which line the caret is currently at, and retrieve the line for further string manipulation? Please help. Thanks. Do let me know if further clarification is needed. Thanks for your time.

    Read the article

  • Hibernate collection mapping Problem

    - by Geln Yang
    Hi, There is a table Item like, code,name 01,parent1 02,parent2 0101,child11 0102,child12 0201,child21 0202,child22 Create a java object and hbm xml to map the table.The Item.parent is a Item whose code is equal to the first two characters of its code : class Item{ String code; String name; Item parent; List<Item> children; .... setter/getter.... } <hibernate-mapping> <class name="Item" table="Item"> <id name="code" length="4" type="string"> <generator class="assigned" /> </id> <property name="name" column="name" length="50" not-null="true" /> <many-to-one name="parent" class="Item" not-found="ignore"> <formula> <![CDATA[ (select i.code,r.name from Item i where (case length(code) when 4 then i.code=SUBSTRING(code,1,2) else false end)) ]]> </formula> </many-to-one> <bag name="children"></bag> </class> </hibernate-mapping> I try to use formula to define the many-to-one relationship,but it doesn't work!Is there something wrong?Or is there other method? Thanks! ps,I use mysql database.

    Read the article

  • Gdata JavaScript Authsub continues redirect

    - by Krustal
    I am using the JavaScript Google Data API and having issues getting the AuthSub script to work correctly. This is my script currently: google.load('gdata', '1'); function getCookie(c_name){ if(document.cookie.length>0){ c_start=document.cookie.indexOf(c_name + "="); if(c_start!=-1){ c_start=c_start + c_name.length+1; c_end=document.cookie.indexOf(";",c_start); if(c_end==-1) c_end=document.cookie.length; return unescape(document.cookie.substring(c_start, c_end)); } } return ""; } function main(){ var scope = 'http://www.google.com/calendar/feeds/'; if(!google.accounts.user.checkLogin(scope)){ google.accounts.user.login(); } else { /* * Retrieve all calendars */ // Create the calendar service object var calendarService = new google.gdata.calendar.CalendarService('GoogleInc-jsguide-1.0'); // The default "allcalendars" feed is used to retrieve a list of all // calendars (primary, secondary and subscribed) of the logged-in user var feedUri = 'http://www.google.com/calendar/feeds/default/allcalendars/full'; // The callback method that will be called when getAllCalendarsFeed() returns feed data var callback = function(result) { // Obtain the array of CalendarEntry var entries = result.feed.entry; //for (var i = 0; i < entries.length; i++) { var calendarEntry = entries[0]; var calendarTitle = calendarEntry.getTitle().getText(); alert('Calendar title = ' + calendarTitle); //} } // Error handler to be invoked when getAllCalendarsFeed() produces an error var handleError = function(error) { alert(error); } // Submit the request using the calendar service object calendarService.getAllCalendarsFeed(feedUri, callback, handleError); } } google.setOnLoadCallback(main); However when I run this the page redirects me to the authentication page. After I authenticate it send me back to my page and then quickly sends me back to the authenticate page again. I've included alerts to check if the token is being set and it doesn't seem to be working. Has anyone has this problem?

    Read the article

  • Hibernate mapping Problem

    - by Geln Yang
    Hi, There is a table Item like, code,name 01,parent1 02,parent2 0101,child11 0102,child12 0201,child21 0202,child22 Create a java object and hbm xml to map the table.The Item.parent is a Item whose code is equal to the first two characters of its code : class Item{ String code; String name; Item parent; List<Item> children; .... setter/getter.... } <hibernate-mapping> <class name="Item" table="Item"> <id name="code" length="4" type="string"> <generator class="assigned" /> </id> <property name="name" column="name" length="50" not-null="true" /> <many-to-one name="parent" class="Item" not-found="ignore"> <formula> <![CDATA[ (select i.code,r.name from Item i where (case length(code) when 4 then i.code=SUBSTRING(code,1,2) else false end)) ]]> </formula> </many-to-one> <bag name="children"></bag> </class> </hibernate-mapping> I try to use formula to define the many-to-one relationship,but it doesn't work!Is there something wrong?Or is there other method? Thanks! ps,I use mysql database.

    Read the article

  • How can I edit an incoming text message (sms) as it arrives in windows mobile 6 using managed code

    - by x86shadow
    I want to make an application for pocket PCs to send and receive Encrypted text messages. I have already made an application that gets special text messages ( starting with !farenc! ) and I know how to Encrypt/Decrypt the messages as well. The problem is that I don't know how to edit a text message after it's arrived (for decryption). See code below for more info. using System; using System.Linq; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using Microsoft.WindowsMobile; using Microsoft.WindowsMobile.PocketOutlook; using Microsoft.WindowsMobile.PocketOutlook.MessageInterception; namespace SMSDECRYPT { public partial class Form1 : Form { MessageInterceptor _SMSCatcher = new MessageInterceptor(InterceptionAction.Notify, true); MessageCondition _SMSFilter = new MessageCondition(); public Form1() { InitializeComponent(); _SMSFilter.Property = MessageProperty.Body; _SMSFilter.ComparisonType = MessagePropertyComparisonType.StartsWith; _SMSFilter.CaseSensitive = true; _SMSFilter.ComparisonValue = "!farenc!"; _SMSCatcher.MessageCondition = _SMSFilter; _SMSCatcher.MessageReceived += new MessageInterceptorEventHandler(_SMSCatcher_MessageReceived); } private void Form1_Load(object sender, EventArgs e) { //... } void _SMSCatcher_MessageReceived(object sender, MessageInterceptorEventArgs e) { SmsMessage mySMS = (SmsMessage)e.Message; string sms = mySMS.Body.ToString(); sms = sms.Substring(8); //Decryption //... //Update the received message and replace it with the decrypted text //!!!HELP!!! } } }

    Read the article

  • Word wrap in multiline textbox after 35 characters

    - by Kanavi
    <asp:TextBox CssClass="txt" ID="TextBox1" runat="server" onkeyup="CountChars(this);" Rows="20" Columns="35" TextMode="MultiLine" Wrap="true"> </asp:TextBox> I need to implement word-wrapping in a multi-line textbox. I cannot allow users to write more then 35 chars a line. I am using the following code, which breaks at precisely the specified character on every line, cutting words in half. Can we fix this so that if there's not enough space left for a word on the current line, we move the whole word to the next line? function CountChars(ID) { var IntermediateText = ''; var FinalText = ''; var SubText = ''; var text = document.getElementById(ID.id).value; var lines = text.split("\n"); for (var i = 0; i < lines.length; i++) { IntermediateText = lines[i]; if (IntermediateText.length <= 50) { if (lines.length - 1 == i) FinalText += IntermediateText; else FinalText += IntermediateText + "\n"; } else { while (IntermediateText.length > 50) { SubText = IntermediateText.substring(0, 50); FinalText += SubText + "\n"; IntermediateText = IntermediateText.replace(SubText, ''); } if (IntermediateText != '') { if (lines.length - 1 == i) FinalText += IntermediateText; else FinalText += IntermediateText + "\n"; } } } document.getElementById(ID.id).value = FinalText; $('#' + ID.id).scrollTop($('#' + ID.id)[0].scrollHeight); } Edit - 1 I have to show total max 35 characters in line without specific word break and need to keep margin of two characters from the right. Again, the restriction should be for 35 characters but need space for total 37 (Just for the Visibility issue.)

    Read the article

  • Self referencing update SQL statement for Informix

    - by CheeseConQueso
    Need some Informix SQL... Courses get a regular grade, but their associated labs get a grade of 'LAB'. I need to update the table so that the lab grade matches the course grade. Also, if there is no corresponding course for a lab, it means the course was canceled. In that case, I want to place a flag value of 'X' for its grade. Example data before update: id yr sess crs_no hrs grd 725 2009 FA COLL101 3.000000000000 C 725 2009 FA ENGL021 3.000000000000 FI 725 2009 FA ENGL021L 1.000000000000 LAB 725 2009 FA ENGL031 3.000000000000 FNI 725 2009 FA ENGL031L 1.000000000000 LAB 725 2009 FA MATH010 3.000000000000 FNI 725 2010 SP AOTE101 3.000000000000 C 725 2010 SP ENGL021L 1.000000000000 LAB 725 2010 SP ENGL031 3.000000000000 FI 725 2010 SP ENGL031L 1.000000000000 LAB 725 2010 SP MATH010 3.000000000000 FNI 726 2010 SP SPAN101 3.000000000000 FN Example data after update: id yr sess crs_no hrs grd 725 2009 FA COLL101 3.000000000000 C 725 2009 FA ENGL021 3.000000000000 FI 725 2009 FA ENGL021L 1.000000000000 FI 725 2009 FA ENGL031 3.000000000000 FNI 725 2009 FA ENGL031L 1.000000000000 FNI 725 2009 FA MATH010 3.000000000000 FNI 725 2010 SP AOTE101 3.000000000000 C 725 2010 SP ENGL021L 1.000000000000 X 725 2010 SP ENGL031 3.000000000000 FI 725 2010 SP ENGL031L 1.000000000000 FI 725 2010 SP MATH010 3.000000000000 FNI 726 2010 SP SPAN101 3.000000000000 FN I worked out a solution for this, but it required a lot of on-the-fly composite foreign keys built from concatenating the id, yr, sess, and substring'd crs_no. My solution is not only overkill, but it has gaps in it and it takes too long to process. I know there is an easier way to do this, but I've gone so far down one road that I am having trouble thinking of a different approach.

    Read the article

  • "A generic error occurred in GDI+" error while showing uploaded images

    - by Prasad
    i am using the following code to show the image that has been saved in my database from my asp.net mvc(C#) application:. public ActionResult GetSiteHeaderLogo() { SiteHeader _siteHeader = new SiteHeader(); Image imgImage = null; long userId = Utility.GetUserIdFromSession(); if (userId > 0) { _siteHeader = this.siteBLL.GetSiteHeaderLogo(userId); if (_siteHeader.Logo != null && _siteHeader.Logo.Length > 0) { byte[] _imageBytes = _siteHeader.Logo; if (_imageBytes != null) { using (System.IO.MemoryStream imageStream = new System.IO.MemoryStream(_imageBytes)) { imgImage = Image.FromStream(imageStream); } } string sFileExtension = _siteHeader.FileName.Substring(_siteHeader.FileName.IndexOf('.') + 1, _siteHeader.FileName.Length - (_siteHeader.FileName.IndexOf('.') + 1)); Response.ContentType = Utility.GetContentTypeByExtension(sFileExtension.ToLower()); Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.BufferOutput = false; if (imgImage != null) { ImageFormat _imageFormat = Utility.GetImageFormat(sFileExtension.ToLower()); imgImage.Save(Response.OutputStream, _imageFormat); imgImage.Dispose(); } } } return new EmptyResult(); } It works fine when i upload original image. But when i upload any downloaded images, it throws the following error: System.Runtime.InteropServices.ExternalException: A generic error occurred in GDI+. System.Runtime.InteropServices.ExternalException: A generic error occurred in GDI+. at System.Drawing.Image.Save(Stream stream, ImageCodecInfo encoder, EncoderParameters encoderParams) at System.Drawing.Image.Save(Stream stream, ImageFormat format) For. Ex: When i upload the original image, it shows as logo in my site and i downloaded that logo from the site and when i re-upload the same downloaded image, it throws the above error. It seems very weird to me and not able to find why its happening. Any ideas on this?

    Read the article

  • Submit to open up a popup window and carry through input data

    - by zac
    Hi, I have a input box on one page that on submit opens a new page with a longer form and the first field is populated with what was entered from the previous pages input box. So on page 1 there is this code: <form action="sign-up.php"> <input type="text" name="email" value="sign up for email" onFocus="clearText(this)" onBlur="clearText(this)" style="float: left;"> <input value='Submit' /> </form> Then on the sign-up page the receiving form grabs the string out of the url //<!-- Begin function getParams() { var idx = document.URL.indexOf('?'); if (idx != -1) { var tempParams = new Object(); var pairs = document.URL.substring(idx+1,document.URL.length).split('&'); for (var i=0; i<pairs.length; i++) { nameVal = pairs[i].split('='); tempParams[nameVal[0]] = nameVal[1]; } return tempParams; } } var params = getParams(); // End --> I would like to keep all of this functionality but it have it occur in a popup. I added this function to the submit: function myPopup() { window.open( "sign-up.php", "myWindow", "status = 1, height = 300, width = 300, resizable = 0" ) and the form becomes <form> <input type="text" name="email" value="sign up for email" onFocus="clearText(this)" onBlur="clearText(this)" style="float: left;"> <input onClick="myPopup()" value='Submit' /> </form> But it no longer appends the input data to the url string. Anyone have any ideas on how I can accomplish this?

    Read the article

  • How should I return different types in a method based on the value of a string in Java?

    - by Siracuse
    I'm new to Java and I have come to having the following problem: I have created several classes which all implement the interface "Parser". I have a JavaParser, PythonParser, CParser and finally a TextParser. I'm trying to write a method so it will take either a File or a String (representing a filename) and return the appropriate parser given the extension of the file. Here is some psuedo-code of what I'm basically attempting to do: public Parser getParser(String filename) { String extension = filename.substring(filename.lastIndexOf(".")); switch(extension) { case "py": return new PythonParser(); case "java": return new JavaParser(); case "c": return new CParser(); default: return new TextParser(); } } In general, is this the right way to handle this situation? Also, how should I handle the fact that Java doesn't allow switching on strings? Should I use the .hashcode() value of the strings? I feel like there is some design pattern or something for handling this but it eludes me. Is this how you would do it?

    Read the article

  • Calling a jQuery method at declaration time, and then onEvent

    - by cesarsalazar
    I've been writing JS (mainly jQuery) for quite a few months now, but today I decided to make my first abstraction as a jQuery method. I already have working code but I feel/know that I'm not doing it the right way, so I come here for some enlightenment. Note: Please do not reply that there's already something out there that does the trick as I already know that. My interest in this matter is rather educational. What my code is intended to do (and does): Limit the characters of a textfield and change the color of the counter when the user is approaching the end. And here's what I have: $(function(){ $('#bio textarea').keyup(function(){ $(this).char_length_validation({ maxlength: 500, warning: 50, validationSelector: '#bio .note' }) }) $('#bio textarea').trigger('keyup'); }) jQuery.fn.char_length_validation = function(opts){ chars_left = opts.maxlength - this.val().length; if(chars_left >= 0){ $(opts.validationSelector + ' .value').text(chars_left); if(chars_left < opts.warning){ $(opts.validationSelector).addClass('invalid'); } else{ $(opts.validationSelector).removeClass('invalid'); } } else{ this.value = this.value.substring(0, opts.maxlength); } } In the HTML: <div id="bio"> <textarea>Some text</textarea> <p class="note> <span class="value">XX</span> <span> characters left</span> </p> </div> Particularly I feel really uncomfortable binding the event each on each keyup instead of binding once and calling a method later. Also, (and hence the title) I need to call the method initially (when the page renders) and then every time the user inputs a character. Thanks in advance for your time :)

    Read the article

  • JavaScript automatically converts some special characters

    - by noplacetoh1de
    I need to extract a HTML-Substring with JS which is position dependent. I store special characters HTML-encoded. For example: HTML <div id="test"><p>l&ouml;sen &amp; gr&uuml;&szlig;en</p></div>? Text lösen & grüßen My problem lies in the JS-part, for example when I try to extract the fragment lö, which has the HTML-dependent starting position of 3 and the end position of 9 inside the <div> block. JS seems to convert some special characters internally so that the count from 3 to 9 is wrongly interpreted as "lösen " and not "l&ouml;". Other special characters like the &amp; are not affected by this. So my question is, if someone knows why JS is behaving in that way? Characters like &auml; or &ouml; are being converted while characters like &amp; or &nbsp; are plain. Is there any possibility to avoid this conversion? I've set up a fiddle to demonstrate this: JSFiddle Thanks for any help! EDIT: Maybe I've explained it a bit confusing, sorry for that. What I want is the HTML: <p>l&ouml;sen &amp; gr&uuml;&szlig;en</p> . Every special character should be unconverted, except the HTML-Tags. Like in the HTML above. But JS converts the &ouml; or &uuml; into ö or ü automatically, what I need to avoid.

    Read the article

  • How can I split a LINESTRING into two LINESTRINGs at a given point?

    - by sabbour
    Hello, I'm trying to write a function that will split a LINESTRING into two LINESTRINGs given the split point. What I'm trying to achieve is a function that given a LINESTRING and a distance, it will return N LINESTRINGS for the original linestring splitted at multiples of that distance. This is what I have so far (I'm using SQL Server Spatial Tools from CodePlex): DECLARE @testLine geography; DECLARE @slicePoint geography; SET @testLine = geography::STGeomFromText('LINESTRING (34.5157942 28.5039665, 34.5157079 28.504725, 34.5156881 28.5049565, 34.5156773 28.505082, 34.5155642 28.5054437, 34.5155498 28.5054899, 34.5154937 28.5058826, 34.5154643 28.5060218, 34.5153968 28.5063415, 34.5153322 28.5065338, 34.5152031 28.5069178, 34.5150603 28.5072288, 34.5148716 28.5075501, 34.5146106 28.5079974, 34.5143617 28.5083813, 34.5141373 28.5086414, 34.5139954 28.5088441, 34.5138874 28.5089983, 34.5138311 28.5091054, 34.5136783 28.5093961, 34.5134336 28.5097531, 34.51325 28.5100794, 34.5130256 28.5105078, 34.5128754 28.5107957, 34.5126258 28.5113222, 34.5123984 28.5117673)', 4326) DECLARE @pointOne geography; declare @result table (segment geography) DECLARE @sliceDistance float DECLARE @nextSliceAt float SET @sliceDistance = 100 -- slice every 100 meters SET @nextSliceAt = @sliceDistance SELECT @pointOne = @testLine.STStartPoint() WHILE(@nextSliceAt < @testLine.STLength()) BEGIN SELECT @slicePoint = dbo.LocateAlongGeog(@testLine,@nextSliceAt) DECLARE @subLineString geography; SET @subLineString = geography::STGeomFromText('LINESTRING (' + dbo.FloatToVarchar(@pointOne.Long) + ' ' + dbo.FloatToVarchar(@pointOne.Lat) + ',' + dbo.FloatToVarchar(@slicePoint.Long) + ' ' + dbo.FloatToVarchar(@slicePoint.Lat) +')', 4326) insert into @result SELECT @subLineString SET @pointOne = @slicePoint set @nextSliceAt = @nextSliceAt + @sliceDistance END SET @subLineString = geography::STGeomFromText('LINESTRING (' + dbo.FloatToVarchar(@pointOne.Long) + ' ' + dbo.FloatToVarchar(@pointOne.Lat) + ',' + dbo.FloatToVarchar(@testLine.STEndPoint().Long) + ' ' + dbo.FloatToVarchar(@testLine.STEndPoint().Lat) +')', 4326) insert into @result SELECT @subLineString select * from @result I know it is not the best looking code, but there is another problem. The above code approximates the resulting LINESTRING because it does not follow the curvature of the original LINESTRING as it only takes into consideration the start and end points when creating the new segment. Is there a way take a substring out of the original LINESTRING given the start and end points?

    Read the article

  • is it better to test if a function is needed inside or outside of it?

    - by b0x0rz
    what is the best practice? call a function then return if you test for something, or test for something then call? i prefer the test inside of function because it makes an easier viewing of what functions are called. for example: protected void Application_BeginRequest(object sender, EventArgs e) { this.FixURLCosmetics(); } and private void FixURLCosmetics() { HttpContext context = HttpContext.Current; if (!context.Request.HttpMethod.ToString().Equals("GET", StringComparison.OrdinalIgnoreCase)) { // if not a GET method cancel url cosmetics return; }; string url = context.Request.RawUrl.ToString(); bool doRedirect = false; // remove > default.aspx if (url.EndsWith("/default.aspx", StringComparison.OrdinalIgnoreCase)) { url = url.Substring(0, url.Length - 12); doRedirect = true; } // remove > www if (url.Contains("//www")) { url = url.Replace("//www", "//"); doRedirect = true; } // redirect if necessary if (doRedirect) { context.Response.Redirect(url); } } is this good: if (!context.Request.HttpMethod.ToString().Equals("GET", StringComparison.OrdinalIgnoreCase)) { // if not a GET method cancel url cosmetics return; }; or should that test be done in Application_BeginRequest? what is better? thnx

    Read the article

  • File.Move, why do i get a FileNotFoundException? The file exist...

    - by acidzombie24
    Its extremely weird since the program is iterating the file! outfolder and infolder are both in H:/ my external HD using windows 7. The idea is to move all folders that only contain files with the extention db and svn-base. When i try to move the folder i get an exception. VS2010 tells me it cant find the folder specified in dir. This code is iterating through dir so how can it not find it! this is weird. string []theExt = new string[] { "db", "svn-base" }; foreach (var dir in Directory.GetDirectories(infolder)) { bool hit = false; if (Directory.GetDirectories(dir).Count() > 0) continue; foreach (var f in Directory.GetFiles(dir)) { var ext = Path.GetExtension(f).Substring(1); if(theExt.Contains(ext) == false) { hit = true; break; } } if (!hit) { var dst = outfolder + "\\" + Path.GetFileName(dir); File.Move(dir, outfolder); //FileNotFoundException: Could not find file dir. } } }

    Read the article

  • Outstanding issues with jQuery.ajax() in IE8?

    - by RyanV
    I am loading feed-items into a ul using this jQuery .ajax() call, which I basically lifted from http://www.makemineatriple.com/2007/10/bbcnewsticker/ var timestamp = true; //set whether timestamp is displayed in $.ajax({ type: "GET", url: "sample-feed.xml", dataType: "xml", success: function(xml) { $(xml).find('item').each(function(){ var title = $(this).find('title').text(); var link = $(this).find('link').text(); if(title.length >=57){ title = title.substring(0,54) + "..."; } var addItem = '<li class="tickerTitle"><a href="'+link+'">'+title+'</a>'; if (Boolean(timestamp)== true){ var time = new Date(Date.parse($(this).find('pubDate').text())); addItem +='<span class="timestamp">' + makestamp(time) +'</span></li>'; } $('ul#news').append(addItem); }); It works in Chrome 4 and Firefox 3.6, but I load it up in IE8 and somehow the ajax call fails. I have tried to use IE8's Developer tools to see where exactly it fails, but I haven't been successful yet. So two questions Is there anything blatantly wrong with my ajax call here that could be preventing me from seeing it in IE where it works in FF/Chrome? Are there any special considerations I have to make for the Internet Explorer family of browsers with regards to this particular jQuery method? I've done some googling on this but nothing obvious is coming up. One other note: I am currently using jQuery 1.3.2 due to some legacy scripts on the same site. I did try loading 1.4.2 and it had the same results on IE8

    Read the article

  • Using hover to swap images, I don't want to swap images if I'm on '.this_page'...

    - by richoid
    When I land on the page, another function (not shown, that works fine) sets the class of the appropriate nav to '.this_page' and then I roll over, and the images swap correctly, but when I hover and leave 'img.this_page' it swaps, the second time I do the hover. I don't want it 'img.this_page' to swap. I tried unbinding mouseout, but on hover apparently it rebinds... so each time you hover, it resets. Page is at http://flourgarden.com/wp/ Here's my function: function hoverNavs() { var baseURL='http://www.flourgarden.com/wp/wp-content/themes/flourgarden/images/nav'; var cache=[]; $j('.lcolumn a img').each(function() { var t = $j(this); var src1 = t.attr('src'); // initial src var newSrc = src1.substring(src1.lastIndexOf('/'), src1.lastIndexOf('.')); // let's get file name without extension i = baseURL+newSrc+'_select.png'; cache.push(i); t.hover(function(){ $j(this).attr('src', baseURL+newSrc+ '_select.' + /[^.]+$/.exec(src1)); //last part is for extension }, function(){ if($j(this).class == "this_page") { $j(this).attr('src', baseURL+newSrc+ '_select.' + /[^.]+$/.exec(src1)); } else { $j(this).attr('src', baseURL+newSrc+ '.' + /[^.]+$/.exec(src1)); } }); }); }

    Read the article

  • Am I encrypting my passwords correctly in ASP.NET

    - by Nick
    I have a security class: public class security { private static string createSalt(int size) { //Generate a random cryptographic number RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); byte[] b = new byte[size]; rng.GetBytes(b); //Convert to Base64 return Convert.ToBase64String(b); } /// <summary> /// Generate a hashed password for comparison or create a new one /// </summary> /// <param name="pwd">Users password</param> /// <returns></returns> public static string createPasswordHash(string pwd) { string salt = "(removed)"; string saltAndPwd = string.Concat(pwd, salt); string hashedPwd = FormsAuthentication.HashPasswordForStoringInConfigFile( saltAndPwd, "sha1"); return hashedPwd; } } This works fine, but I am wondering if it is sufficient enough. Also, is this next block of code better? Overkill? static byte[] encrInitVector = new byte[] { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF }; static string encrKey = "(removed)"; public static string EncryptString(string s) { byte[] key; try { key = Encoding.UTF8.GetBytes(encrKey.Substring(0, 8)); DESCryptoServiceProvider des = new DESCryptoServiceProvider(); byte[] inputByteArray = Encoding.UTF8.GetBytes(s); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(key, encrInitVector), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); return Convert.ToBase64String(ms.ToArray()); } catch (Exception e) { throw e; }

    Read the article

  • Getting "prompt aborted by user" javascript exception

    - by Bhagwat
    I am getting "Components.Exception("prompt aborted by user", Cr.NS_ERROR_NOT_AVAILABLE)" exception when I am using "windows.location.href" in javasacript. My Code is: function checkCookie(){ var value = null; var cookieName='UserDetailsCookie'; value=ReadCookie(cookieName); if(value != null){ var url='<%=request.getContextPath()%>/jsp/admin.jsp'; window.location.href = url; } document.loginForm.userName.focus(); } function ReadCookie(name) { name += '='; var parts = document.cookie.split(/;\s*/); for (var i = 0; i < parts.length; i++) { var part = parts[i]; if (part.indexOf(name) == 0) return part.substring(name.length); } return null; } and I am calling this method on onLoad event of body <body onLoad="javascript:checkCookie();"> In anyone knows why this exception throws please?

    Read the article

  • Is this an acceptable use of "ASCII arithmetic"?

    - by jmgant
    I've got a string value of the form 10123X123456 where 10 is the year, 123 is the day number within the year, and the rest is unique system-generated stuff. Under certain circumstances, I need to add 400 to the day number, so that the number above, for example, would become 10523X123456. My first idea was to substring those three characters, convert them to an integer, add 400 to it, convert them back to a string and then call replace on the original string. That works. But then it occurred to me that the only character I actually need to change is the third one, and that the original value would always be 0-3, so there would never be any "carrying" problems. It further occurred to me that the ASCII code points for the numbers are consecutive, so adding the number 4 to the character "0", for example, would result in "4", and so forth. So that's what I ended up doing. My question is, is there any reason that won't always work? I generally avoid "ASCII arithmetic" on the grounds that it's not cross-platform or internationalization friendly. But it seems reasonable to assume that the code points for numbers will always be sequential, i.e., "4" will always be 1 more than "3". Anybody see any problem with this reasoning? Here's the code. string input = "10123X123456"; input[2] += 4; //Output should be 10523X123456

    Read the article

  • RegEx: difference between "(?:...) and normal parentheses

    - by N0thing
    >>> re.findall(r"(?:do|re|mi)+", "mimi") ['mimi'] >>> re.findall(r"(do|re|mi)+", "mimi") ['mi'] According to my understanding of the definitions, it should produce the same answer. The only difference between (...) and (?:...) should be whether or not we can use back-references later. Am I missing something? (...) Matches whatever regular expression is inside the parentheses, and indicates the start and end of a group; the contents of a group can be retrieved after a match has been performed, and can be matched later in the string with the \number special sequence, described below. To match the literals '(' or ')', use ( or ), or enclose them inside a character class: [(] [)]. (?:...) A non-capturing version of regular parentheses. Matches whatever regular expression is inside the parentheses, but the substring matched by the group cannot be retrieved after performing a match or referenced later in the pattern.

    Read the article

  • Ajax div can't access address bar variable

    - by Elaine Adams
    Can someone please advise me on how my Ajax div can get an address bar variable. The usual way just doesn't work. My address bar currently looks like this: http://localhost/social3/browse/?locationName=Cambridge Usually, I would use a little php and do this: $searchResult = $_POST['locationName']; echo $searchResult; But because I'm in an Ajax div, I can't seem to get to the variable. Do I need to add some JavaScript wizardry to my Ajax coding? (I have little knowledge of this) My Ajax: <script> window.onload = function () { var everyone = document.getElementById('everyone'), searching = document.getElementById('searching'), searchingSubmit = document.getElementById('searchingSubmit'); everyone.onclick = function() { loadXMLDoc('indexEveryone'); everyone.className = 'filterOptionActive'; searching.className = 'filterOption'; } searching.onclick = function() { loadXMLDoc('indexSearching'); searching.className = 'filterOptionActive'; everyone.className = 'filterOption'; } searchingSubmit.onclick = function() { loadXMLDoc('indexSearchingSubmit'); } function loadXMLDoc(pageName) { var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("leftCont").innerHTML=xmlhttp.responseText; } } function get_query(){ var url = location.href; var qs = url.substring(url.indexOf('?') + 1).split('&'); for(var i = 0, result = {}; i < qs.length; i++){ qs[i] = qs[i].split('='); result[qs[i][0]] = decodeURIComponent(qs[i][1]); } return result; } xmlhttp.open("GET","../browse/" + pageName + ".php?user=" + get_query()['user'],true); xmlhttp.send(); } } </script> <!-- ends ajax script -->

    Read the article

  • JQuery: Live <a> tag partially working second time around.

    - by BPotocki
    I have the following jquery code: $("a[id*='Add_']").live('click', function() { //Get parentID to add to. var parentID = $(this).attr('id').substring(4); //Get div. var div = $("#CreateList"); //Ajax call to refresh "CreateList" div with new XML. div.load("/AddUnit?ParentID=" + parentID); }); Basically, contained within the div is a nested unordered list with several "Add_#" links. Clicking the links uses an ajax call to recreate the list with a new node. It clears all the add links, but they are added again by the ajax call. This is why I used the .live method so newly added "Add_#" links still have the binding. This works in most cases. If I click "Add_1", the div refreshes with the new info. If I then click "Add_2", it works again as expected. The problem I'm having happens when I click "Add_1", then the page refreshes (and creates a new "Add_1" link), then I click the re-rendered "Add_1" again. It's the same link, but it was refreshed during the ajax call. When I do that, the javascript function still gets called, but the .load method doesn't work. Any ideas why this might be happening? Thanks.

    Read the article

  • odd behavior with C# ftp client class

    - by geoff
    I found an ftp client class in c# over a year ago and have been using it in a process that uploads files on a nightly basis. A few days ago we started having a problem where it would time out. I'm not well versed in this so I'm not sure why it's doing this. When the program starts uploading a file it checks to see if it's logged in and if not, it calls the login method. In that method is this block of code. if (this.resultCode != 230) { this.sendCommand("PASS " + password); if (!(this.resultCode == 230 || this.resultCode == 202)) { this.cleanup(); throw new FtpException(this.result.Substring(4)); } } On the line that says this.sendCommand("PASS"... it goes into this code. private void sendCommand(String command) { if (this.verboseDebugging) Debug.WriteLine(command, "FtpClient"); Byte[] cmdBytes = Encoding.ASCII.GetBytes((command + "\r\n").ToCharArray()); clientSocket.Send(cmdBytes, cmdBytes.Length, 0); this.readResponse(); } If I let the program run, it times out. However if I step through it into the sendCommand method it executes fine. Does anyone know why it would work fine when I step through it? Nothing on our end has changed and I've been told nothing on the client's end has changed so I'm stumped. Thanks.

    Read the article

  • DotNetOpenAuth getting return_To url as the provider

    - by Jeff
    I have a provider that I'm upgrading from version 2 to version 3. basically a user comes to one of our sites and we say "if you don't have an openID sign up with this one" They click that and are sent to our in house provider what signs them up for an account and has to verify their email address. In the link I send via Email I included the return to url . This way when they click the link to verify their email (sometimes up to a week later) they are sent to our page that knows to send them back to the returnTo to login. I could not find a good way to do this in version 2 so I used a hack. Sadly this hack broke in version 2 so I'm completely stumped as to how to find the login page url that is the return_To Note: I need the full URL not just the domain. old hack: if (ProviderEndpoint.PendingAuthenticationRequest != null) { req = ProviderEndpoint.PendingAuthenticationRequest.ToString(); int startpos = req.LastIndexOf("CheckIdRequest.ReturnTo = '"); startpos += "CheckIdRequest.ReturnTo = '".Length; int endpos = req.LastIndexOf("token=") - startpos-1; if (endpos > 0) { req = req.Substring(startpos, endpos); } else { log.Fatal("Missing token in url" + ProviderEndpoint.PendingAuthenticationRequest.ToString()); return "~/"; } req = req.Replace("&internalLogin=True", ""); req = req.Replace("?internalLogin=True&", "?"); req = req.Replace("?internalLogin=True", ""); }

    Read the article

< Previous Page | 29 30 31 32 33 34 35 36 37 38 39 40  | Next Page >