Search Results

Search found 4955 results on 199 pages for 'range'.

Page 67/199 | < Previous Page | 63 64 65 66 67 68 69 70 71 72 73 74  | Next Page >

  • Why does VBA Find loop fail when called from Evaluate?

    - by Abiel
    I am having some problems running a find loop inside of a subroutine when the routine is called using the Application.Evaluate or ActiveSheet.Evaluate method. For example, in the code below, I define a subroutine FindSub() which searches the sheet for a string "xxx". The routine CallSub() calls the FindSub() routine using both a standard Call statement and Evaluate. When I run Call FindSub, everything will work as expected: each matching address gets printed out to the immediate window and we get a final message "Finished up" when the code is done. However, when I do Application.Evaluate "FindSub()", only the address of the first match gets printed out, and we never reach the "Finished up" message. In other words, an error is encountered after the Cells.FindNext line as the loop tries to evaluate whether it should continue, and program execution stops without any runtime error being printed. I would expect both Call FindSub and Application.Evaluate "FindSub()" to yield the same results in this case. Can someone explain why they do not, and if possible, a way to fix this? Thanks. Note: In this example I obviously do not need to use Evaluate. This version is simplified to just focus on the particular problem I am having in a more complex situation. Sub CallSub() Call FindSub Application.Evaluate "FindSub()" End Sub Sub FindSub() Dim rngFoundCell As Range Dim rngFirstCell As Range Set rngFoundCell = Cells.Find(What:="xxx", after:=ActiveCell, LookIn:=xlValues, _ LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _ MatchCase:=False, SearchFormat:=False) If Not rngFoundCell Is Nothing Then Set rngFirstCell = rngFoundCell Do Debug.Print rngFoundCell.Address Set rngFoundCell = Cells.FindNext(after:=rngFoundCell) Loop Until (rngFoundCell Is Nothing) Or (rngFoundCell.Address = rngFirstCell.Address) End If Debug.Print "Finished up" End Sub

    Read the article

  • Convert string to decimal retaining the exact input format

    - by Brett
    Hi All, I'm sure this is a piece of cake but I'm really struggling with something that seems trivial. I need to check the inputted text of a textbox on the form submit and check to see if it's within a desired range (I've tried a Range Validator but it doesn't work for some reason so I'm trying to do this server-side). What I want to do is: Get the value inputted (eg. 0.02), replace the commas and periods, convert that to a decimal (or double or equivalent) and check to see if it's between 0.10 and 35000.00. Here's what I have so far: string s = txtTransactionValue.Text.Replace(",", string.Empty).Replace(".", string.Empty); decimal transactionValue = Decimal.Parse(s); if (transactionValue >= 0.10M && transactionValue <= 35000.00M) // do something If I pass 0.02 into the above, transactionValue is 2. I want to retain the value as 0.02 (ie. do no format changes to it - 100.00 is 100.00, 999.99 is 999.99) Any ideas? Thanks in advance, Brett

    Read the article

  • SQL deadlock on delete then bulk insert

    - by StarLite
    I have an issue with a deadlock in SQL Server that I haven't been able to resolve. Basically I have a large number of concurrent connections (from many machines) that are executing transactions where they first delete a range of entries and then re-insert entries within the same range with a bulk insert. Essentially, the transaction looks like this BEGIN TRANSACTION T1 DELETE FROM [TableName] WITH( XLOCK HOLDLOCK ) WHERE [Id]=@Id AND [SubId]=@SubId INSERT BULK [TableName] ( [Id] Int , [SubId] Int , [Text] VarChar(max) COLLATE SQL_Latin1_General_CP1_CI_AS ) WITH(CHECK_CONSTRAINTS, FIRE_TRIGGERS) COMMIT TRANSACTION T1 The bulk insert only inserts items matching the Id and SubId of the deletion in the same transaction. Furthermore, these Id and SubId entries should never overlap. When I have enough concurrent transaction of this form, I start to see a significant number of deadlocks between these statements. I added the locking hints XLOCK HOLDLOCK to attempt to deal with the issue, but they don't seem to be helpling. The canonical deadlock graph for this error shows: Connection 1: Holds RangeX-X on PK_TableName Holds IX Page lock on the table Requesting X Page lock on the table Connection 2: Holds IX Page lock on the table Requests RangeX-X lock on the table What do I need to do in order to ensure that these deadlocks don't occur. I have been doing some reading on the RangeX-X locks and I'm not sure I fully understand what is going on with these. Do I have any options short of locking the entire table here?

    Read the article

  • Changing Positions of the Chart When Creating Multiple Charts Automatically via Vbasic in Excel 2007

    - by McVey
    I am creating a new chart for each row of data in an Excel spreadsheet. I have the Vbasic working properly, but I want to change the position of the chart on the sheet that is added for each row. Below is my code, what do I need to do to change the position of the chart on the page automatically? Ideally, I would like it to be in the upper left hand corner of each sheet. Sub DrawCharts() Dim Ws As Worksheet Dim NewWs As Worksheet Dim cht As Chart Dim LastRow As Long Dim CurrRow As Long Set Ws = ThisWorkbook.Worksheets("Sheet1") LastRow = Ws.Range("A65536").End(xlUp).Row For CurrRow = 2 To LastRow Set NewWs = ThisWorkbook.Worksheets.Add NewWs.Name = Ws.Range("A" & CurrRow).Value Set cht = ThisWorkbook.Charts.Add With cht .ChartType = xl3DColumnClustered .SeriesCollection.NewSeries .SeriesCollection(1).Values = "=" & Ws.Name & "!R" & CurrRow & "C3:R" & CurrRow & "C8" .SeriesCollection(1).Name = "=" & Ws.Name & "!R" & CurrRow & "C2" .SeriesCollection(1).XValues = "Sheet1!R1C3:R1C8" .Axes(xlValue).MinimumScale = 0 .Axes(xlValue).MaximumScale = 1 .Axes(xlValue).MajorUnit = 0.2 .SetElement (msoElementDataLabelShow) .SetElement (msoElementLegendNone) .Location Where:=xlLocationAsObject, Name:=NewWs.Name End With Next CurrRow End Sub Any help is appreciated.

    Read the article

  • How to implement Excel Solver functionality in C#?

    - by Vic
    Hi, I have an application in C#, I need to do some optimization calculations, like Excel Solver Add-in does, one option is certainly to write my own solver implementation, but I'm kind of short of time, so I'm looking into libraries that already exist that can help me with this. I've been trying the Microsoft Solver Foundation, which seems pretty neat and cool, the problem is that it doesn't seem to work with the kind of calculations that I need to do. At the end of this question I'm adding the information about the calculations I need to perform and optimize. So basically my question is if any of you know of any other library that I can use for this purpose, or any tutorial that can help to do my own solver, or any idea that gives me a lead to solve this issue. Thanks. Additional Info: This is the data I need to calculate: I have 7 variables, lets call them var1, var2,...,var7 The constraints for these variables are: All of them need to be 0 <= varn <= 0.5 (where n is the number of the variable) The sum of all the variables should be equal to 1 The objective is to maximize the target formula, which in Excel looks like this: (MMULT(TRANSPOSE(L26:L32),M14:M20)) / (SQRT(MMULT(MMULT(TRANSPOSE(L26:L32),M4:S10),L26:L32))) The range that you see in this formula, L26:L32, is actually the range with the variables from above, var1, var2,..., varn. M14:M20 and M4:S10 are ranges with data that I get from different sources, there are more likely decimal values. As I said before, I was using Microsoft Solver Foundation, I modeled pretty much everything with it, I created functions that handle the operations of the target formula, but when I tried to solve the model it always fail, I think it is because of the complexity of the operations. In any case, I just wanted to show these data so you can have an idea about the kind of calculations that I need to implement.

    Read the article

  • Why does jQuery.ajax() add a parameter to the url?

    - by FK82
    Hi, I have a data fetching method that uses jQuery.ajax() to fetch xml files. /* */data: function() { /* debug */try { var url = arguments[0] ; var type = arguments[1] ; var scope = arguments[2] ; var callback = arguments[3] ; var self = this ; if(this.cache[url]) { callback(this.cache[url]) ; } else if(!this.cache[url]) { $.ajax({ type: "GET" , url: url , dataType: type , cache: false , success: function(data) { if(type == "text/xml") { var myJson = AUX.json ; var jsonString = myJson.build(data,scope,null) ; var jsonObject = $.parseJSON(jsonString) ; self.cache[url] = jsonObject ; callback(url) ; } else if(type == "json") { self.cache[url] = data ; callback(url) ; } } , error: function() { throw "Ajax call failed." ; } }) ; } /* debug */} catch(e) { /* debug */ alert("- caller: signTutor.data\n- " + e) ; /* debug */} } , My problem is: jQuery somehow adds a parameter (?_=1272708280072) to the url if there are escaped (hexadecimal notation) or unescaped utf-8 characters outside of the ASCII range -- i believe -- in the file name. It all works well if the file name does not contain characters in that range. Type is set to xml so there should not be a confusion of types. Headers of the xml files are also set adequately. I can see from the console that jQuery throws an error, but I'm not sure as to where the problem really is. Probably a problem with file name formatting, but I did not find any resources on the web as to AJAX file name specifications. Any ideas? Thanks for you help!

    Read the article

  • Converting a PHP associative array to a JSON associative array

    - by Extrakun
    I am converting a look-up table in PHP which looks like this to JavaScript using json_encode: AbilitiesLookup Object ( [abilities:private] => Array ( [1] => Ability_MeleeAttack Object ( [abilityid:protected] => [range:protected] => 1 [name:protected] => MeleeAttack [ability_identifier:protected] => MeleeAttack [aoe_row:protected] => 1 [aoe_col:protected] => 1 [aoe_shape:protected] => [cooldown:protected] => 0 [focusCost:protected] => 0 [possibleFactions:protected] => 2 [abilityDesc:protected] => Basic Attack ) .....snipped... And in JSON, it is: {"1":{"name":"MeleeAttack","fof":"2","range":"1","aoe":[null,"1","1"],"fp":"0","image":"dummy.jpg"},.... The problem is I get a JS object, not an array, and the identifier is a number. I see 2 ways around this problem - either find a way to access the JSON using a number (which I do not know how) or make it such that json_encode (or some other custom encoding functions) can give a JavaScript associative array. (Yes, I am rather lacking in my JavaScript department). Note: The JSON output doesn't match the array - this is because I do a manual json encoding for each element in the subscript, before pushing it onto an array (with the index as the key), then using json_encode on it. To be clear, the number are not sequential because it's an associative array (which is why the JSON output is not an array).

    Read the article

  • Find max integer size that a floating point type can handle without loss of precision

    - by Checkers
    Double has range more than a 64-bit integer, but its precision is less dues to its representation (since double is 64-bit as well, it can't fit more actual values). So, when representing larger integers, you start to lose precision in the integer part. #include <boost/cstdint.hpp> #include <limits> template<typename T, typename TFloat> void maxint_to_double() { T i = std::numeric_limits<T>::max(); TFloat d = i; std::cout << std::fixed << i << std::endl << d << std::endl; } int main() { maxint_to_double<int, double>(); maxint_to_double<boost::intmax_t, double>(); maxint_to_double<int, float>(); return 0; } This prints: 2147483647 2147483647.000000 9223372036854775807 9223372036854775800.000000 2147483647 2147483648.000000 Note how max int can fit into a double without loss of precision and boost::intmax_t (64-bit in this case) cannot. float can't even hold an int. Now, the question: is there a way in C++ to check if the entire range of a given integer type can fit into a loating point type without loss of precision? Preferably, it would be a compile-time check that can be used in a static assertion, and would not involve enumerating the constants the compiler should know or can compute.

    Read the article

  • UnicodeDecodeError on attempt to save file through django default filebased backend

    - by Ivan Kuznetsov
    When i attempt to add a file with russian symbols in name to the model instance through default instance.file_field.save method, i get an UnicodeDecodeError (ascii decoding error, not in range (128) from the storage backend (stacktrace ended on os.exist). If i write this file through default python file open/write all goes right. All filenames in utf-8. I get this error only on testing Gentoo, on my Ubuntu workstation all works fine. class Article(models.Model): file = models.FileField(null=True, blank=True, max_length = 300, upload_to='articles_files/%Y/%m/%d/') Traceback: File "/usr/lib/python2.6/site-packages/django/core/handlers/base.py" in get_response 100. response = callback(request, *callback_args, **callback_kwargs) File "/usr/lib/python2.6/site-packages/django/contrib/auth/decorators.py" in _wrapped_view 24. return view_func(request, *args, **kwargs) File "/var/www/localhost/help/wiki/views.py" in edit_article 338. new_article.file.save(fp, fi, save=True) File "/usr/lib/python2.6/site-packages/django/db/models/fields/files.py" in save 92. self.name = self.storage.save(name, content) File "/usr/lib/python2.6/site-packages/django/core/files/storage.py" in save 47. name = self.get_available_name(name) File "/usr/lib/python2.6/site-packages/django/core/files/storage.py" in get_available_name 73. while self.exists(name): File "/usr/lib/python2.6/site-packages/django/core/files/storage.py" in exists 196. return os.path.exists(self.path(name)) File "/usr/lib/python2.6/genericpath.py" in exists 18. st = os.stat(path) Exception Type: UnicodeEncodeError at /edit/ Exception Value: ('ascii', u'/var/www/localhost/help/i/articles_files/2010/03/17/\u041f\u0440\u0438\u0432\u0435\u0442', 52, 58, 'ordinal not in range(128)')

    Read the article

  • Reading UTF-8 XML and writing it to a file with Python

    - by Harri
    I'm trying to parse UTF-8 XML file and save some parts of it to another file. Problem is, that this is my first Python script ever and I'm totally confused about the character encoding problems I'm finding. My script fails immediately when it tries to write non-ascii character to a file, but it can print it to command prompt (at least in some level) Here's the XML (from the parts that matter at least, it's a *.resx file which contains UI strings) <?xml version="1.0" encoding="utf-8"?> <root> <resheader name="foo"> <value>bar</value> </resheader> <data name="lorem" xml:space="preserve"> <value>ipsum öä</value> </data> </root> And here's my python script from xml.dom.minidom import parse names = [] values = [] def getStrings(path): dom = parse(path) data = dom.getElementsByTagName("data") for i in range(len(data)): name = data[i].getAttribute("name") names.append(name) value = data[i].getElementsByTagName("value") values.append(value[0].firstChild.nodeValue.encode("utf-8")) def writeToFile(): with open("uiStrings-fi.py", "w") as f: for i in range(len(names)): line = names[i] + '="'+ values[i] + '"' #varName='varValue' f.write(line) f.write("\n") getStrings("ResourceFile.fi-FI.resx") writeToFile() And here's the traceback: Traceback (most recent call last): File "GenerateLanguageFiles.py", line 24, in writeToFile() File "GenerateLanguageFiles.py", line 19, in writeToFile line = names[i] + '="'+ values[i] + '"' #varName='varValue' UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 2: ordinal not in ran ge(128) How should I fix my script so it would read and write UTF-8 characters properly? The files I'm trying to generate would be used in test automation with Robots Framework.

    Read the article

  • Python Locking Implementation (with threading module)

    - by Matty
    This is probably a rudimentary question, but I'm new to threaded programming in Python and am not entirely sure what the correct practice is. Should I be creating a single lock object (either globally or being passed around) and using that everywhere that I need to do locking? Or, should I be creating multiple lock instances in each of the classes where I will be employing them. Take these 2 rudimentary code samples, which direction is best to go? The main difference being that a single lock instance is used in both class A and B in the second, while multiple instances are used in the first. Sample 1 class A(): def __init__(self, theList): self.theList = theList self.lock = threading.Lock() def poll(self): while True: # do some stuff that eventually needs to work with theList self.lock.acquire() try: self.theList.append(something) finally: self.lock.release() class B(threading.Thread): def __init__(self,theList): self.theList = theList self.lock = threading.Lock() self.start() def run(self): while True: # do some stuff that eventually needs to work with theList self.lock.acquire() try: self.theList.remove(something) finally: self.lock.release() if __name__ == "__main__": aList = [] for x in range(10): B(aList) A(aList).poll() Sample 2 class A(): def __init__(self, theList,lock): self.theList = theList self.lock = lock def poll(self): while True: # do some stuff that eventually needs to work with theList self.lock.acquire() try: self.theList.append(something) finally: self.lock.release() class B(threading.Thread): def __init__(self,theList,lock): self.theList = theList self.lock = lock self.start() def run(self): while True: # do some stuff that eventually needs to work with theList self.lock.acquire() try: self.theList.remove(something) finally: self.lock.release() if __name__ == "__main__": lock = threading.Lock() aList = [] for x in range(10): B(aList,lock) A(aList,lock).poll()

    Read the article

  • Java error on bilinear interpolation of 16 bit data

    - by Jon
    I'm having an issue using bilinear interpolation for 16 bit data. I have two images, origImage and displayImage. I want to use AffineTransformOp to filter origImage through an AffineTransform into displayImage which is the size of the display area. origImage is of type BufferedImage.TYPE_USHORT_GRAY and has a raster of type sun.awt.image.ShortInterleavedRaster. Here is the code I have right now displayImage = new BufferedImage(getWidth(), getHeight(), origImage.getType()); try { op = new AffineTransformOp(atx, AffineTransformOp.TYPE_BILINEAR); op.filter(origImage, displayImage); } catch (Exception e) { e.printStackTrace(); } In order to show the error I have created 2 gradient images. One has values in the 15 bit range (max of 32767) and one in the 16 bit range (max of 65535). Below are the two images 15 bit image 16 bit image These two images were created in identical fashions and should look identical, but notice the line across the middle of the 16 bit image. At first I thought that this was an overflow problem however, it is weird that it's manifesting itself in the center of the gradient instead of at the end where the pixel values are higher. Also, if it was an overflow issue than I would suspect that the 15 bit image would have been affected as well. Any help on this would be greatly appreciated.

    Read the article

  • why isn't my validator working?

    - by Lina
    hi, can anybody tell me why is the following code not working? <script type="text/javascript" src="../../Scripts/jquery.js"></script> <script type="text/javascript" src="../../Scripts/jquery.validate.js"></script> <script type="text/javascript"> $(function() { // validate contact form on keyup and submit $("#myform").validate({ //set the rules for the fild names rules: { hour: { required: true, minlength: 2, range:[0,23] }, minute: { required: true, minlength: 2, range:[0,60] }, }, //set messages to appear inline messages: { hour: "Please enter a valid hour", minute: "Please enter a valid minute" } }); }); </script> <style type="text/css"> .error { color: red; font: 12pt verdana; padding-left: 10px } </style> <form id="myform" method="" action=""> <input id="hour" type="text" name="hour" style="width:30px; text-align:center;"></input> : <input id="minute" type="text" name="minute" style="width:30px; text-align:center;"></input> <br/> <input type="submit" value="Validate!" /> </form> thanks a million in advance, Lina

    Read the article

  • Problem on "Finding cursor position" function

    - by sanceray3
    Hi all, Few days ago, I have found a solution to obtain the cursor position on a div with contentedit="true". I use the solution defined on this web site : Finding cursor position in a contenteditable div function getCursorPos() { var cursorPos; if (window.getSelection) { var selObj = window.getSelection(); var selRange = selObj.getRangeAt(0); cursorPos = findNode(selObj.anchorNode.parentNode.childNodes, selObj.anchorNode) + selObj.anchorOffset; /* FIXME the following works wrong in Opera when the document is longer than 32767 chars */ } else if (document.selection) { var range = document.selection.createRange(); var bookmark = range.getBookmark(); /* FIXME the following works wrong when the document is longer than 65535 chars */ cursorPos = bookmark.charCodeAt(2) - 11; /* Undocumented function [3] */ } return cursorPos; } function findNode(list, node) { for (var i = 0; i < list.length; i++) { if (list[i] == node) { return i; } } return -1; } It functions well, but when I use html tags inside the div the pointer doesnt show the correct position. For example if I try to find cursor position on the <strong>cat</strong> is black, the function doesn't return me the good position. But if I try on the cat is black, it functions. Any ideas how to get the position with html tags ? Thanks for your help.

    Read the article

  • Outlook 2010 Retrieving and restricting appointments programmatically causing recurrences to be incl

    - by Mike Dearing
    I wrote a winforms app that uses Microsoft.Office.Interop.Outlook to retrieve and restrict appointments based upon the date range entered by a user. This worked fine with Outlook 2007 installed, however now that some users have updated to Outlook 2010 the appointment retrieval is pulling back incorrect appointments along with the correct ones falling within the specified date range. The additional incorrect appointments being retrieved always appear to be recurring appointments. I was wondering if this is a known bug and if so what exactly is happening that is causing these additional recurring appointments to come in? I'd rather not have to throw in a workaround where I step through the items after they have been restricted and remove the extra ones, when this functionality works fine with 2007. Note: I've not recompiled or updated any code when experiencing this issue, just running the old program. This is the spot in my code where appointments are being restricted. This is similar to the way advised in the following msdn link: http://msdn.microsoft.com/en-us/library/bb611267.aspx Microsoft.Office.Interop.Outlook.Items outlookItems = outlookMapiFolder.Items.Restrict( "[Start] >= '" + outlookImport.startDay.ToString("g") + "' AND [Start] <= '" + outlookImport.endDay.ToString("g") + "'"); outlookItems.Sort("[Start]", Type.Missing); outlookItems.IncludeRecurrences = true;

    Read the article

  • How to select a rectangle from List<Rectangle[]> with Linq

    - by dboarman
    I have a list of DrawObject[]. Each DrawObject has a Rectangle property. Here is my event: List<Canvas.DrawObject[]> matrix; void Control_MouseMove ( object sender, MouseEventArgs e ) { IEnumerable<Canvas.DrawObject> tile = Enumerable.Range( 0, matrix.Capacity - 1) .Where(row => Enumerable.Range(0, matrix[row].Length -1) .Where(column => this[column, row].Rectangle.Contains(e.Location))) .????; } I am not sure exactly what my final select command should be in place of the "????". Also, I was getting an error: cannot convert IEnumerable to bool. I've read several questions about performing a linq query on a list of arrays, but I can't quite get what is going wrong with this. Any help? Edit Apologies for not being clear in my intentions with the implementation. I intend to select the DrawObject that currently contains the mouse location.

    Read the article

  • Having trouble animating Line in D3.js using and array of objects as data

    - by user1731245
    I can't seem to get an animated transition between line graphs when I pass in a new set of data. I am using an array of objects as data like this: [{ clicks: 40 installs: 10 time: "1349474400000" },{ clicks: 61 installs: 3 time: "1349478000000" }]; I am using this code to setup my ranges / axis's var xRange = d3.time.scale().range([0, w]), yRange = d3.scale.linear().range([h , 0]), xAxis = d3.svg.axis().scale(xRange).tickSize(-h).ticks(6).tickSubdivide(false), yAxis = d3.svg.axis().scale(yRange).ticks(5).tickSize(-w).orient("left"); var clicksLine = d3.svg.line() .interpolate("cardinal") .x(function(d){return xRange(d.time)}) .y(function(d){return yRange(d.clicks)}); var clickPath; function drawGraphs(data) { clickPath = svg.append("g") .append("path") .data([data]) .attr("class", "clicks") .attr("d", clicksLine); } function updateGraphs(data) { svg.select('path.clicks') .data([data]) .attr("d", clicksLine) .transition() .duration(500) .ease("linear") } I have tried just about everything to be able to pass in new data and see an animation between graph's. Not sure what I am missing? does it have something to do with using an array of objects instead of just a flat array of numbers as data?

    Read the article

  • Is it possible to alternate between two types in an XML Schema

    - by lief79
    I'm wondering if I am missing something obvious. I have a list of numbers, possibly including ranges (think of the print page option of a print dialog). Ideally I'd like to have the final XML output look like this, with page and pageRange in an order. <pages> <page> 1</page> <pageRange><start>3</start><end>6</end></pageRange> <page> 34</page> </pages> What would I have to put into a schema to allow this? From what I saw: Sequence with multiple page and page Range allowed doesn't permit alternation. Choice only allows one or the other. I tried messing with all, but I wasn't getting it to validate properly. My short term solution is to have a sequence of ranges, and to force single numbers into the range, but it seems potentially cumbersome. So am I missing something?

    Read the article

  • What is the name of this geometrical function?

    - by Spike
    In a two dimentional integer space, you have two points, A and B. This function returns an enumeration of the points in the quadrilateral subset bounded by A and B. A = {1,1} B = {2,3} Fn(A,B) = {{1,1},{1,2},{1,3},{2,1},{2,2},{2,3}} I can implement it in a few lines of LINQ. private void UnknownFunction(Point to, Point from, List<Point> list) { var vectorX = Enumerable.Range(Math.Min(to.X, from.X), Math.Abs(to.X - from.Y) + 1); var vectorY = Enumerable.Range(Math.Min(to.Y, from.Y), Math.Abs(to.Y - from.Y) + 1); foreach (var x in vectorX) foreach (var y in vectorY) list.Add(new Point(x, y)); } I'm fairly sure that this is a standard mathematical operation, but I can't think what it is. Feel free to tell me that it's one line of code in your language of choice. Or to give me a cunning implementation with lambdas or some such. But mostly I just want to know what it's called. It's driving me nuts. It feels a little like a convolution, but it's been too long since I was at school for me to be sure.

    Read the article

  • Merge Word Documents (Office Interop & .NET), Keeping Formatting

    - by mbmccormick
    I'm having some difficulty merging multiple word documents together using Microsoft Office Interop Assemblies (Office 2007) and ASP.NET 3.5. I'm able to merge the documents, but some of my formatting is missing (namely the fonts and images). My current merge code is shown below. private void CombineDocuments() { object wdPageBreak = 7; object wdStory = 6; object oMissing = System.Reflection.Missing.Value; object oFalse = false; object oTrue = true; string fileDirectory = @"C:\documents\"; Microsoft.Office.Interop.Word.Application WordApp = new Microsoft.Office.Interop.Word.Application(); Microsoft.Office.Interop.Word.Document wDoc = WordApp.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing); string[] wordFiles = Directory.GetFiles(fileDirectory, "*.doc"); for (int i = 0; i < wordFiles.Length; i++) { string file = wordFiles[i]; wDoc.Application.Selection.Range.InsertFile(file, ref oMissing, ref oMissing, ref oMissing, ref oFalse); wDoc.Application.Selection.Range.InsertBreak(ref wdPageBreak); wDoc.Application.Selection.EndKey(ref wdStory, ref oMissing); } string combineDocName = Path.Combine(fileDirectory, "Merged Document.doc"); if (File.Exists(combineDocName)) File.Delete(combineDocName); object combineDocNameObj = combineDocName; wDoc.SaveAs(ref combineDocNameObj, ref m_WordDocumentType, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); } I don't care necessarily how this is accomplished. It could output via PDF if it had to. I just want the formatting to carry over. Any help or hints that you could provide me with would be appreciated! Thanks!

    Read the article

  • When developing a Microsoft Office Add-In (for Word), is it possible to store hidden metadata inform

    - by leftend
    I am trying to store metadata (basically a unique id) along with each cell of a table in a Word document. Currently, for the add-in I'm developing, I am querying the database, and building a table inside the Word document using the data that is retrieved. I want to be able to save any of the user's edits to the document, and persist it back to the database. My initial thought was to store a unique id along with each cell in the table so that I would be able to tell which records to update. I would also like to store some sort of "isChanged" flag within each cell so that I could tell which cells were changed. I found that I could add the needed information into the "ID" property of the cell - however, that information was not retained if the user saved the document, closed it, and re-opened it. I then tried storing the data by adding a data to the "Fields" collection - but that did not work and threw a runtime error. Here is the code that I tried: object t1 = Word.WdFieldType.wdFieldEmpty; object val = "myValue: " + counter; object preserveFormatting = true; tbl.Cell(i, j).Range.Fields.Add(tbl.Cell(i, j).Range, ref t1, ref val, ref preserveFormatting); This compiles fine, but throws this runtime error "This command is not available". So, is this possible at all? Or am I headed in the wrong direction? Thanks in advance.

    Read the article

  • Dragging a copy of all selected elements from a select box--possible?

    - by Sean
    I have a picklist web interface: a pair of select elements with a pair of buttons (a left-pointing arrow and a right-pointing arrow) between them. Users can move items between the two columns by, eg, selecting one of options in the left column and clicking on the right-pointing arrow. Now I have an enhancement request: someone wants to be able to drag-and-drop items between the two columns instead of clicking a button. The problem with my initial two-select-box setup is that as soon as I click one of the highlighted options to initiate a drag, all of the other selected options are deselected. Using jQuery, I've attached mousedown event handlers to both the select boxes and each individual option that just call preventDefault() on the event object, but this isn't sufficient. On Firefox 3 the clicked-on option loses focus immediately, but all other options are still deseleted, and on IE6 (which I regrettably still have to support) it makes no difference at all. So I thought I could maybe create a reasonable facsimile of a select box using list elements or divs or something. I can create something reasonable-looking that works on Firefox, but on IE6, if I shift-click on an element of my pseudo-select object (in order to select a range of options), IE selects all of the text between where I click and the last place I clicked. Again, I've attached preventDefault-ing mousedown, mouseup, and click handlers to all of the elements involved, but it doesn't help. I've even tried overlaying transparent divs over both my original select boxes and my pseudo-select objects, thinking to intercept mouse clicks and manage the selections manually, but I can't make it work on IE. If I use a select box, I can't prevent clicks from changing the selection, and if I use text that just looks like a select element, I can't prevent it from selecting a range of text on a shift-click. Is there some general solution, or am I just out of luck?

    Read the article

  • Can this code be further optimized??

    - by kaki
    i understand that the code given below will not be compltely understood unless i explain my whole of previous and next lines of code. But this is part of the code which is causing so much of delay in my project and want to optimize this. i want to know which code part is faulty and how could this be replaced. i guess,few can say that use of this function is heavy compared and other ligher method are available to do this work please help, thanks in advance for i in range(len(lists)): save=database_index[lists[i]] #print save #if save[1]!='text0194'and save[1]!='text0526': using_data[save[0]]=save p=os.path.join("c:/begpython/wavnk/",str(str(str(save[1]).replace('phone','text'))+'.pm')) x1=open(p , 'r') x2=open(p ,'r') for i in range(6): x1.readline() x2.readline() gen = (float(line.partition(' ')[0]) for line in x1) r= min(enumerate(gen), key=lambda x: abs(x[1] - float(save[4]))) #print r[0] a1=linecache.getline(str(str(p).replace('.pm','.mcep')), (r[0]+1)) #print a1 p1=str(str(a1).rstrip('\n')).split(' ') #print p1 join_cost_index_end[save[0]]=p1 #print join_cost_index_end gen = (float(line.partition(' ')[0]) for line in x2) r= min(enumerate(gen), key=lambda x: abs(x[1] - float(save[3]))) #print r[0] a2=linecache.getline(str(str(p).replace('.pm','.mcep')), (r[0]+1)) #print a2 p2=str(str(a2).rstrip('\n')).split(' ') #print p2 join_cost_index_strt[save[0]]=p2 #print join_cost_index_strt j=j+1 #print j #print join_cost_index_end #print join_cost_index_strt enter code here here my database_index has about 2,50,000 entries`

    Read the article

  • how do i keep form data after submitting the form using javascript?

    - by Lina
    When i submit this form, the values just disappears from the textboxes. I like them to stay printed in the textboxes. How do i do that? <form id="myform" method="get" action="" onSubmit="hello();"> <input id="hour" type="text" name="hour" style="width:30px; text-align:center;" /> : <input id="minute" type="text" name="minute" style="width:30px; text-align:center;" /> <br/> <input type="submit" value="Validate!" /> </form> <style type="text/css"> .error { color: red; font: 10pt verdana; padding-left: 10px } </style> <script type="text/javascript"> function hello(){ var hour = $("#hour").html(); alert(hour); } $(function() { // validate contact form on keyup and submit $("#myform").validate({ //set the rules for the fild names rules: { hour: { required: true, minlength: 1, maxlength: 2, range:[0,23] }, minute: { required: true, minlength: 1, maxlength: 2, range:[0,60] }, }, //set messages to appear inline messages: { hour: "Please enter a valid hour", minute: "Please enter a valid minute" } }); }); </script>

    Read the article

  • How do I read binary C++ protobuf data using Python protobuf?

    - by nbolton
    The Python version of Google protobuf gives us only: SerializeAsString() Where as the C++ version gives us both: SerializeToArray(...) SerializeAsString() We're writing to our C++ file in binary format, and we'd like to keep it this way. That said, is there a way of reading the binary data into Python and parsing it as if it were a string? Is this the correct way of doing it? binary = get_binary_data() binary_size = get_binary_size() string = None for i in range(len(binary_size)): string += i message = new MyMessage() message.ParseFromString(string) Update: Here's a new example, and a problem: message_length = 512 file = open('foobars.bin', 'rb') eof = False while not eof: data = file.read(message_length) eof = not data if not eof: foo_bar = FooBar() foo_bar.ParseFromString(data) When we get to the foo_bar.ParseFromString(data) line, I get this error: Exception Type: DecodeError Exception Value: Too many bytes when decoding varint. Update 2: It turns out, that the padding on the binary data was throwing protobuf off; too many bytes were being sent in, as the message suggests (in this case it was referring to the padding). This padding comes from using the C++ protobuf function, SerializeToArray on a fixed-length buffer. To eliminate this, I have used this temproary code: message_length = 512 file = open('foobars.bin', 'rb') eof = False while not eof: data = file.read(message_length) eof = not data string = '' for i in range(0, len(data)): byte = data[i] if byte != '\xcc': # yuck! string += data[i] if not eof: foo_bar = FooBar() foo_bar.ParseFromString(string) There is a design flaw here I think. I will re-implement my C++ code so that it writes variable length arrays to the binary file. As advised by the protobuf documentation, I will prefix each message with it's binary size so that I know how much to read when I'm opening the file with Python.

    Read the article

< Previous Page | 63 64 65 66 67 68 69 70 71 72 73 74  | Next Page >