Search Results

Search found 23 results on 1 pages for 'delimit'.

Page 1/1 | 1 

  • SQL Server: How do I delimit this data?

    - by codingguy3000
    declare @mydata nvarchar(4000) set @mydata = '36|0, 77|5, 132|61' I have this data that I need to get into a table. So for Row1 columnA would be 36 and columnB would be 0. For Row2 columnA would be 77 and columnB would be 5 etc. What is the best way to do this? Thanks

    Read the article

  • Triple Quotes? How do I delimit a databound Javascript string parameter in ASP.NET?

    - by David HAust
    How do I delimit a Javascript databound string parameter in an anchor OnClick event? I have an anchor tag in an ASP.NET Repeater control. The OnClick event of the anchor contains a call to a Javascript function. The Javascript funciton takes a string for it's input parameter. The string parameter is populated with a databound value from the Repeater. I need the 'double quotes' for the Container.DataItem. I need the 'single quotes' for the OnClick. And I still need one more delimiter (triple quotes?) for the input string parameter of the Javascript function call. Since I can't use 'single quotes' again, how do I ensure the Javascript function knows the input parameter is a string and not an integer? Without the extra quotes around the input string parameter, the Javascript function thinks I'm passing in an integer. Cheers in advance for any knowledge you can drop. The anchor: <a id="aShowHide" onclick='ToggleDisplay(<%# DataBinder.Eval(Container.DataItem, "JobCode") %>);' >Show/Hide</a> and here is the Javascript: <script language="JavaScript" type="text/javascript">/* Shows/Hides the Jobs Div */ function ToggleDisplay(jobCode) { /* Each div has it's ID set dynamically ('d' plus the JobCode) */ var elem = document.getElementById('d' + jobCode); if (elem) { if (elem.style.display != 'block') { elem.style.display = 'block'; elem.style.visibility = 'visible'; } else { elem.style.display = 'none'; elem.style.visibility = 'hidden'; } } }</script>

    Read the article

  • Mod Rewirte Question.

    - by delimit
    I cant seem to get Example 1 to turn into Example 2 using mod rewrite. Can someone help me out? Example 1 http://www.example.com/info/index.php?uid=123 Example 2 http://www.example.com/123 Mod rewrite code. Options +FollowSymLinks Options -Indexes RewriteEngine on RewriteBase /info RewriteCond %{HTTP_HOST} ^example\.com$ [NC] RewriteRule ^(.*)$ http://www.example.com/info/$1 [R=301,L] RewriteRule ^([^/]*)$ /info/index.php?uid=$1 [L]

    Read the article

  • Thoughts on my new template language/HTML generator?

    - by Ralph
    I guess I should have pre-faced this with: Yes, I know there is no need for a new templating language, but I want to make a new one anyway, because I'm a fool. That aside, how can I improve my language: Let's start with an example: using "html5" using "extratags" html { head { title "Ordering Notice" jsinclude "jquery.js" } body { h1 "Ordering Notice" p "Dear @name," p "Thanks for placing your order with @company. It's scheduled to ship on {@ship_date|dateformat}." p "Here are the items you've ordered:" table { tr { th "name" th "price" } for(@item in @item_list) { tr { td @item.name td @item.price } } } if(@ordered_warranty) p "Your warranty information will be included in the packaging." p(class="footer") { "Sincerely," br @company } } } The "using" keyword indicates which tags to use. "html5" might include all the html5 standard tags, but your tags names wouldn't have to be based on their HTML counter-parts at all if you didn't want to. The "extratags" library for example might add an extra tag, called "jsinclude" which gets replaced with something like <script type="text/javascript" src="@content"></script> Tags can be optionally be followed by an opening brace. They will automatically be closed at the closing brace. If no brace is used, they will be closed after taking one element. Variables are prefixed with the @ symbol. They may be used inside double-quoted strings. I think I'll use single-quotes to indicate "no variable substitution" like PHP does. Filter functions can be applied to variables like @variable|filter. Arguments can be passed to the filter @variable|filter:@arg1,arg2="y" Attributes can be passed to tags by including them in (), like p(class="classname"). You will also be able to include partial templates like: for(@item in @item_list) include("item_partial", item=@item) Something like that I'm thinking. The first argument will be the name of the template file, and subsequent ones will be named arguments where @item gets the variable name "item" inside that template. I also want to have a collection version like RoR has, so you don't even have to write the loop. Thoughts on this and exact syntax would be helpful :) Some questions: Which symbol should I use to prefix variables? @ (like Razor), $ (like PHP), or something else? Should the @ symbol be necessary in "for" and "if" statements? It's kind of implied that those are variables. Tags and controls (like if,for) presently have the exact same syntax. Should I do something to differentiate the two? If so, what? This would make it more clear that the "tag" isn't behaving like just a normal tag that will get replaced with content, but controls the flow. Also, it would allow name-reuse. Do you like the attribute syntax? (round brackets) How should I do template inheritance/layouts? In Django, the first line of the file has to include the layout file, and then you delimit blocks of code which get stuffed into that layout. In CakePHP, it's kind of backwards, you specify the layout in the controller.view function, the layout gets a special $content_for_layout variable, and then the entire template gets stuffed into that, and you don't need to delimit any blocks of code. I guess Django's is a little more powerful because you can have multiple code blocks, but it makes your templates more verbose... trying to decide what approach to take Filtered variables inside quotes: "xxx {@var|filter} yyy" "xxx @{var|filter} yyy" "xxx @var|filter yyy" i.e, @ inside, @ outside, or no braces at all. I think no-braces might cause problems, especially when you try adding arguments, like @var|filter:arg="x", then the quotes would get confused. But perhaps a braceless version could work for when there are no quotes...? Still, which option for braces, first or second? I think the first one might be better because then we're consistent... the @ is always nudged up against the variable. I'll add more questions in a few minutes, once I get some feedback.

    Read the article

  • How to use symbols/punctuation characters in discriminated unions

    - by user343550
    I'm trying to create a discriminated union for part of speech tags and other labels returned by a natural language parser. It's common to use either strings or enums for these in C#/Java, but discriminated unions seem more appropriate in F# because these are distinct, read-only values. In the language reference, I found that this symbol ``...`` can be used to delimit keywords/reserved words. This works for type ArgumentType = | A0 // subject | A1 // indirect object | A2 // direct object | A3 // | A4 // | A5 // | AA // | ``AM-ADV`` However, the tags contain symbols like $, e.g. type PosTag = | CC // Coordinating conjunction | CD // Cardinal Number | DT // Determiner | EX // Existential there | FW // Foreign Word | IN // Preposision or subordinating conjunction | JJ // Adjective | JJR // Adjective, comparative | JJS // Adjective, superlative | LS // List Item Marker | MD // Modal | NN // Noun, singular or mass | NNP // Proper Noun, singular | NNPS // Proper Noun, plural | NNS // Noun, plural | PDT // Predeterminer | POS // Possessive Ending | PRP // Personal Pronoun | PRP$ //$ Possessive Pronoun | RB // Adverb | RBR // Adverb, comparative | RBS // Adverb, superlative | RP // Particle | SYM // Symbol | TO // to | UH // Interjection | VB // Verb, base form | VBD // Verb, past tense | VBG // Verb, gerund or persent participle | VBN // Verb, past participle | VBP // Verb, non-3rd person singular present | VBZ // Verb, 3rd person singular present | WDT // Wh-determiner | WP // Wh-pronoun | WP$ //$ Possessive wh-pronoun | WRB // Wh-adverb | ``#`` | ``$`` | ``''`` | ``(`` | ``)`` | ``,`` | ``.`` | ``:`` | `` //not sure how to escape/delimit this ``...`` isn't working for WP$ or symbols like ( Also, I have the interesting problem that the parser returns `` as a meaningful symbol, so I need to escape it as well. Is there some other way to do this, or is this just not possible with a discriminated union? Right now I'm getting errors like Invalid namespace, module, type or union case name Discriminated union cases and exception labels must be uppercase identifiers I suppose I could somehow override toString for these goofy cases and replace the symbols with some alphanumeric equivalent?

    Read the article

  • Extracting a number from a 1-word string

    - by Kyle
    In this program I am trying to make, I have an expression (such as "I=23mm", or "H=4V") and I am trying to extract the 23 (or the 4) out of it, so that I can turn it into an integer. The problem I keep running into is that since the expression I am trying to take the numbers out of is 1 word, I cannot use split() or anything. One example I saw but wouldnt work was - I="I=2.7A" [int(s) for s in I.split() if s.isdigit()] This wouldnt work because it only takes the numbers are are delimited by spaces. If there was a number in the word int078vert, it wouldnt extract it. Also, mine doesnt have spaces to delimit. I tried one that looked like this, re.findall("\d+.\d+", "Amps= 1.4 I") but it didnt work either, because the number that is being passed is not always 2 digits. It could be something like 5, or something like 13.6. What code do I need to write so that if I pass a string, such as I="I=2.4A" or I="A=3V" So that I can extract only the number out of this string? (and do operations on it)? There are no spaces or other constant chars that I can delimit by.

    Read the article

  • Software Architecture: Unit of Work design pattern discussion

    - by santiagobasulto
    Hey everybody. According Martin Fowler's Unit of Work description: "Maintains a list of objects that are affected by a business transaction and coordinates the writing out of changes and resolution of concurrency problems." Avoiding very small calls to the database, which ends up being very slow I'm wondering. If we just delimit it to database transaction management, won't prepare statements help with this?

    Read the article

  • Ubuntu 13.10 install ISO crashes on VirtualBox Mac 4.3

    - by John Allsup
    Does anybody know what to do about this? Machine is a 2008 Core 2 Duo iMac with 4GB RAM. (And 64bit Debian 7 boots OK, but I've not tried installing under the latest version of VirtualBox as I have just upgraded VBox today.) VirtualBox 4.3, upon trying to boot a machine with the Ubuntu 13.10 (64bit) iso (with the VM configured for Ubuntu 64bit) crashes, with the following information: Failed to open a session for the virtual machine Ubuntu64. The VM session was aborted. Result Code: NS_ERROR_FAILURE (0x80004005) Component: SessionMachine Interface: ISession {12f4dcdb-12b2-4ec1-b7cd-ddd9f6c5bf4d} === Head of crash dump is below Process: VirtualBoxVM [716] Path: /Applications/VirtualBox.app/Contents/MacOS/VirtualBoxVM Identifier: VirtualBoxVM Version: ??? (???) Code Type: X86 (Native) Parent Process: VBoxSVC [644] Date/Time: 2013-10-17 22:58:23.679 +0100 OS Version: Mac OS X 10.6.8 (10K549) Report Version: 6 Exception Type: EXC_BAD_ACCESS (SIGBUS) Exception Codes: KERN_PROTECTION_FAILURE at 0x0000000000000040 Crashed Thread: 0 Dispatch queue: com.apple.main-thread Thread 0 Crashed: Dispatch queue: com.apple.main-thread 0 com.apple.CoreFoundation 0x92a25c03 CFSetApplyFunction + 83 1 com.apple.framework.IOKit 0x95557ad4 __IOHIDManagerInitialEnumCallback + 69 2 com.apple.CoreFoundation 0x92a2442b __CFRunLoopDoSources0 + 1563 3 com.apple.CoreFoundation 0x92a21eef __CFRunLoopRun + 1071 4 com.apple.CoreFoundation 0x92a213c4 CFRunLoopRunSpecific + 452 5 com.apple.CoreFoundation 0x92a211f1 CFRunLoopRunInMode + 97 6 com.apple.HIToolbox 0x98eb5e04 RunCurrentEventLoopInMode + 392 7 com.apple.HIToolbox 0x98eb5af5 ReceiveNextEventCommon + 158 8 com.apple.HIToolbox 0x98eb5a3e BlockUntilNextEventMatchingListInMode + 81 9 com.apple.AppKit 0x9971b595 _DPSNextEvent + 847 10 com.apple.AppKit 0x9971add6 -[NSApplication nextEventMatchingMask:untilDate:inMode:dequeue:] + 156 11 com.apple.AppKit 0x996dd1f3 -[NSApplication run] + 821 12 QtGuiVBox 0x019f19e1 QEventDispatcherMac::processEvents(QFlags<QEventLoop::ProcessEventsFlag>) + 1505 13 QtCoreVBox 0x018083b1 QEventLoop::processEvents(QFlags<QEventLoop::ProcessEventsFlag>) + 65 14 QtCoreVBox 0x018086fa QEventLoop::exec(QFlags<QEventLoop::ProcessEventsFlag>) + 170 15 QtGuiVBox 0x01eea9e5 QDialog::exec() + 261 16 VirtualBox.dylib 0x011234b8 TrustedMain + 1108104 17 VirtualBox.dylib 0x01126d68 TrustedMain + 1122616 18 VirtualBox.dylib 0x010fac19 TrustedMain + 942057 19 VirtualBox.dylib 0x010f9b3d TrustedMain + 937741 20 VirtualBox.dylib 0x010f81dd TrustedMain + 931245 21 VirtualBox.dylib 0x010f85b8 TrustedMain + 932232 22 VirtualBox.dylib 0x0109d4f8 TrustedMain + 559304 23 VirtualBox.dylib 0x0101521e TrustedMain + 1518 24 ...virtualbox.app.VirtualBoxVM 0x00002e7e start + 2766 25 ...virtualbox.app.VirtualBoxVM 0x000024b5 start + 261 26 ...virtualbox.app.VirtualBoxVM 0x000023e5 start + 53 ==== And please somebody fix the code so that you can just delimit large blocks of code at the start and the end without indenting every line manually by 4 spaces.

    Read the article

  • Space a valid delimiter for email addresses in email header?

    - by semanticalo
    Is it syntactically correct to delimit multiple email recipients in the "To" header of an email with spaces only or do I need to use another delimiter (a semicolon or the like)? Example (MIME data reads as follows): Date: Mon, 04 Oct 2010 06:14:16 +0200 From: [email protected] To: [email protected] [email protected] [email protected] Subject: Test Subject The above will be processed by many email processing applications, but I need to know whether it's correct according to standard (RFC). Unfortunately I didn't find anything useful on the internet so far. Thanks a million for your help!

    Read the article

  • Detecting regular expression in content during parse

    - by sonofdelphi
    I am writing a parser for C. I was just running it with some other language files (for fun, to see the extent C-likeness). It breaks down if the code being parsed contains regular expressions... Case 1: For example, while parsing the JavaScript code snippet, var phone="(304)434-5454" phone=phone.replace(/[\(\)-]/g, "") //Returns "3044345454" (removes "(", ")", and "-") The '(', '[' etc get matched as starters of new scopes, which may never be closed. Case 2: And, for the Perl code snippet, # Replace backslashes with two forward slashes # Any character can be used to delimit the regex $FILE_PATH =~ s@\\@//@g; The // gets matched as a comment... How can I detect a regular expression within the content text of a "C-like" program-file?

    Read the article

  • Python - network buffer handling question...

    - by Patrick Moriarty
    Hi, I want to design a game server in python. The game will mostly just be passing small packets filled with ints, strings, and bytes stuffed into one message. As I'm using a different language to write the game, a normal packet would be sent like so: Writebyte(buffer, 5); // Delimit type of message Writestring(buffer, "Hello"); Sendmessage(buffer, socket); As you can see, it writes the bytes to the buffer, and sends the buffer. Is there any way to read something like this in python? I am aware of the struct module, and I've used it to pack things, but I've never used it to actually read something with mixed types stuck into one message. Thanks for the help.

    Read the article

  • PL/SQL embedded insert into table that may not exist

    - by Richard
    Hi, I much prefer using this 'embedded' style inserts in a pl/sql block (opposed to the execute immediate style dynamic sql - where you have to delimit quotes etc). -- a contrived example PROCEDURE CreateReport( customer IN VARCHAR2, reportdate IN DATE ) BEGIN -- drop table, create table with explicit column list CreateReportTableForCustomer; INSERT INTO TEMP_TABLE VALUES ( customer, reportdate ); END; / The problem here is that oracle checks if 'temp_table' exists and that it has the correct number of colunms and throws a compile error if it doesn't exist. So I was wondering if theres any way round that?! Essentially I want to use a placeholder for the table name to trick oracle into not checking if the table exists.

    Read the article

  • See former key sequences in vim

    - by Vasiliy Sharapov
    Sometimes I share screen shots and clips of vim usage with others. It would be nice to expand on the part of the status bar highlighted in this picture: I would like some way to make previous key sequences visible as well, such as: y2w jj f[ p 2d - You can see the key sequences leading up to the current one. I'll elaborate on my wish list at the bottom. Is something like this is available as a plugin or vim script? The sheer number of scripts available on vim online makes this hard to find by keyword. Some features I would hope for (but seem improbable): Delimit key sequences with a non-keyboard character instead of space, and a different one for the current command, so y2w jj f[ p 2d might become y2w¦jj¦f[¦p » 2d Replace keys that have a letter alternative with the alternative, such as the right arrow key - ^[[C with the equivalent l. Edit: To clarify, the right arrow key is a valid key in vim, but has no character to represent it, the l key preforms the same function and could/should substitute it. Have previous keystrokes run all the way to the beginning of the line (instead of just one or two), and just have vim's command prompt overwrite it when necessary. Replace some keystrokes with a more elegant alternative, for example hhhhh with 5h or more impressively d2f) with d% (in the appropriate situation).

    Read the article

  • How to import this data set into excel? (column headings on each row delimited by a colon)

    - by Anonymous
    I'm trying to import the following data set into Excel. I've had no luck with the text import wizard. I'd like Excel to make id, name, street, etc the column names and insert each record onto a new row. , id: sdfg:435-345, name: Some Name, type: , street: Address Line 1, Some Place, postalcode: DN2 5FF, city: Cityhere, telephoneNumber: 01234 567890, mobileNumber: 01234 567890, faxNumber: /, url: http://www.website.co.uk, email: [email protected], remark: , geocode: 526.2456;-0.8520, category: some, more, info , id: sdfg:435-345f, name: Some Name, type: , street: Address Line 1, Some Place, postalcode: DN2 5FF, city: Cityhere, telephoneNumber: 01234 567890, mobileNumber: 01234 567890, faxNumber: /, url: http://www.website.co.uk, email: [email protected], remark: , geocode: 526.2456;-0.8520, category: some, more, info Is there any easy way to do this with Excel? I'm struggling to think of a way to convert this to a conventional CSV easily. As far as I can think, I'd have to remove the labels from each line, enclose each line in quotes, then delimit them with commas. Obviously that's made a little more difficult to script though seeing as some fields (address, for instance) contain comma-delimited data. I'm not good with regex at all. What's the best way to tackle this?

    Read the article

  • Creating my first F# program in my new &ldquo;Expert F# Book&rdquo;

    - by MarkPearl
    So I have a brief hour or so that I can dedicate today to reading my F# book. It’s a public holiday and my wife’s birthday and I have a ton of assignments for UNISA that I need to complete – but I just had to try something in F#. So I read chapter 1 – pretty much an introduction to the rest of the book – it looks good so far. Then I get to chapter 2, called “Getting Started with F# and .NET”. Great, there is a code sample on the first page of the chapter. So I open up VS2010 and create a new F# console project and type in the code which was meant to analyze a string for duplicate words… #light let wordCount text = let words = Split [' '] text let wordset = Set.ofList words let nWords = words.Length let nDups = words.Length - wordSet.Count (nWords, nDups) let showWordCount text = let nWords,nDups = wordCount text printfn "--> %d words in text" nWords printfn "--> %d duplicate words" nDups   So… bad start - VS does not like the “Split” method. It gives me an error message “The value constructor ‘Split’ is not defined”. It also doesn’t like wordSet.Count telling me that the “namespace or module ‘wordSet’ is not defined”. ??? So a bit of googling and it turns out that there was a bit of shuffling of libraries between the CTP of F# and the Beta 2 of F#. To have access to the Split function you need to download the F# PowerPack and hen reference it in your code… I download and install the powerpack and then add the reference to FSharp.Core and FSharp.PowerPack in my project. Still no luck! Some more googling and I get the suggestions I got were something like this…#r "FSharp.PowerPack.dll";; #r "FSharp.PowerPack.Compatibility.dll";; So I add the code above to the top of my Program.fs file and still no joy… I now get an error message saying… Error    1    #r directives may only occur in F# script files (extensions .fsx or .fsscript). Either move this code to a script file, add a '-r' compiler option for this reference or delimit the directive with '#if INTERACTIVE'/'#endif'. So what does that mean? If I put the code straight into the F# interactive it works – but I want to be able to use it in a project. The C# equivalent I would think would be the “Using” keyword. The #r doesn’t seem like it should be in the FSharp code. So I try what the compiler suggests by doing the following…#if INTERACTIVE #r "FSharp.PowerPack.dll";; #r "FSharp.PowerPack.Compatibility.dll";; #endif No luck, the Split method is still not recognized. So wait a second, it mentioned something about FSharp.PowerPack.Compatibility.dll – I haven’t added this as a reference to my project so I add it and remove the two lines of #r code. Partial success – the Split method is now recognized and not underlined, but wordSet.Count is still not working. I look at my code again and it was a case error – the original wordset was mistyped comapred to the wordSet. Some case correction and the compiler is no longer complaining. So the code now seems to work… listed below…#light let wordCount text = let words = String.split [' '] text let wordSet = Set.ofList words let nWords = words.Length let nDups = words.Length - wordSet.Count (nWords, nDups) let showWordCount text = let nWords,nDups = wordCount text printfn "--> %d words in text" nWords printfn "--> %d duplicate words" nDups  So recap – if I wanted to use the interactive compiler then I need to put the #r code. In my mind this is the equivalent of me adding the the references to my project. If however I want to use the powerpack in a project – I just need to make sure that the correct references are there. I feel like a noob once again!

    Read the article

  • Reading CSV files in numpy where delimiter is ","

    - by monch1962
    Hello all, I've got a CSV file with a format that looks like this: "FieldName1", "FieldName2", "FieldName3", "FieldName4" "04/13/2010 14:45:07.008", "7.59484916392", "10", "6.552373" "04/13/2010 14:45:22.010", "6.55478493312", "9", "3.5378543" ... Note that there are double quote characters at the start and end of each line in the CSV file, and the "," string is used to delimit fields within each line. When I try to read this into numpy via: import numpy as np data = np.genfromtxt(csvfile, dtype=None, delimiter=',', names=True) all the data gets read in as string values, surrounded by double-quote characters. Not unreasonable, but not much use to me as I then have to go back and convert every column to its correct type When I use delimiter='","' instead, everything works as I'd like, except for the 1st and last fields. As the start of line and end of line characters are a single double-quote character, this isn't seen as a valid delimiter for the 1st and last fields, so they get read in as e.g. "04/13/2010 14:45:07.008 and 6.552373" - note the leading and trailing double-quote characters respectively. Because of these redundant characters, numpy assumes the 1st and last fields are both String types; I don't want that to be the case Is there a way of instructing numpy to read in files formatted in this fashion as I'd like, without having to go back and "fix" the structure of the numpy array after the initial read?

    Read the article

  • Escape whitespace in paths using nautilus script

    - by Tommy Brunn
    I didn't think this would be as tricky as it turned out to be, but here I am. I'm trying to write a Nautilus script in Python to upload one or more images to Imgur just by selecting and right clicking them. It works well enough with both single images and multiple images - as long as they don't contain any whitespace. In fact, you can upload a single image containing whitespace, just not multiple ones. The problem is that NAUTILUS_SCRIPT_SELECTED_FILE_PATHS returns all the selected files and directories as a space separated string. So for example, it could look like this: print os.environment['NAUTILUS_SCRIPT_SELECTED_FILE_PATHS'] /home/nevon/Desktop/test image.png /home/nevon/Desktop/test.jpg What I need is a way to -either in bash or Python- escape the spaces in the path - but not the spaces that delimit different items. Either that, or a way to put quotation marks around each item. The ultimate solution would be if I could do that in bash and then send the items as separate arguments to my python script. Something like: python uploader.py /home/nevon/Desktop/test\ image.png /home/nevon/Desktop/test.jpg I've tried RTFM'ing, but there doesn't seem to be a lot of good solutions for this. At least not that I've found. Any ideas?

    Read the article

  • Saving multiple items per single database cell...

    - by eugeneK
    Hi, i have a countries list. Each user can check multiple countries. Once saved, this "user country list" will be used to get whether other users fit into countries certain user chose. Question is what would be the most efficient approach to this problem... I have one, one to save user selection as delimited list like Canada,USA,France ... in single varchar(max) field but problem with it would be that once user from Germany enters page i perform this check on. To search for Germany i would be needed to get all items and un-delimit each field to check against value or to use sql 'like' which again is pretty damn slow.. If you have better solution or some tips i would be glad to hear. Just to make sure, many users will have their own selections of countries from which and only they want to have users to land on their page. While millions of users will reach those pages. So the faster approach will be the better. technology, MSSQL and ASP.NET thanks

    Read the article

  • Splitting 25mb .txt file into smaller files using text delimiter

    - by user574141
    Regards, SO I am new to python and Perl. I have been trying to solve a simple problem and getting tied in knots with syntax. I hope someone has the time and patience to help. I have a 25mb file in ".txt" format which contains news-wire articles going back to 1970. Each news story is concatenated to the next, with only the "Copyright" statement to delimit. Each news story starts with "Item XX of XXX DOCUMENTS". There are certain metadata that are repeated throughout, I will use these for tagging later on. I wish to split this 25mb file into separate .txt files, each containing one news story (i.e. the text between "DOCUMENTS" and "Copyright", saving each with a different name (obviously). I am trying to 1 ) open the file... 2) iterate over lines in the file checking for the eof delimiter, and if it is not present writing the line to a list 3)write that list to a seperate small file. I'm having big problems with changing filenames using the counter, and how do I make Python start from where I left off, is the "seek" function appropriate? so far I have been trying this approach, completely unsuccessfully: myfile = open ("myfile.txt", 'r') filenumber = 0 for line in myfile.readline(): filenumber += 1 w=0 while myfile.readline() != '\s+DOCUMENTS\s*\n' ### read my line into a list mysmallfile()['w'] = [myfile.readline()] w += 1 output = open('C:\\Users\\dunner7\\Documents\###how do I change the filename each iteration???', 'w') output.writelines(mysmallfile) ###go back to start. Thank you for your time and patience. RD

    Read the article

  • RIF PRD: Presentation syntax issues

    - by Charles Young
    Over Christmas I got to play a bit with the W3C RIF PRD and came across a few issues which I thought I would record for posterity. Specifically, I was working on a grammar for the presentation syntax using a GLR grammar parser tool (I was using the current CTP of ‘M’ (MGrammer) and Intellipad – I do so hope the MS guys don’t kill off M and Intellipad now they have dropped the other parts of SQL Server Modelling). I realise that the presentation syntax is non-normative and that any issues with it do not therefore compromise the standard. However, presentation syntax is useful in its own right, and it would be great to iron out any issues in a future revision of the standard. The main issues are actually not to do with the grammar at all, but rather with the ‘running example’ in the RIF PRD recommendation. I started with the code provided in Example 9.1. There are several discrepancies when compared with the EBNF rules documented in the standard. Broadly the problems can be categorised as follows: ·      Parenthesis mismatch – the wrong number of parentheses are used in various places. For example, in GoldRule, the RHS of the rule (the ‘Then’) is nested in the LHS (‘the If’). In NewCustomerAndWidgetRule, the RHS is orphaned from the LHS. Together with additional incorrect parenthesis, this leads to orphanage of UnknownStatusRule from the entire Document. ·      Invalid use of parenthesis in ‘Forall’ constructs. Parenthesis should not be used to enclose formulae. Removal of the invalid parenthesis gave me a feeling of inconsistency when comparing formulae in Forall to formulae in If. The use of parenthesis is not actually inconsistent in these two context, but in an If construct it ‘feels’ as if you are enclosing formulae in parenthesis in a LISP-like fashion. In reality, the parenthesis is simply being used to group subordinate syntax elements. The fact that an If construct can contain only a single formula as an immediate child adds to this feeling of inconsistency. ·      Invalid representation of compact URIs (CURIEs) in the context of Frame productions. In several places the URIs are not qualified with a namespace prefix (‘ex1:’). This conflicts with the definition of CURIEs in the RIF Datatypes and Built-Ins 1.0 document. Here are the productions: CURIE          ::= PNAME_LN                  | PNAME_NS PNAME_LN       ::= PNAME_NS PN_LOCAL PNAME_NS       ::= PN_PREFIX? ':' PN_LOCAL       ::= ( PN_CHARS_U | [0-9] ) ((PN_CHARS|'.')* PN_CHARS)? PN_CHARS       ::= PN_CHARS_U                  | '-' | [0-9] | #x00B7                  | [#x0300-#x036F] | [#x203F-#x2040] PN_CHARS_U     ::= PN_CHARS_BASE                  | '_' PN_CHARS_BASE ::= [A-Z] | [a-z] | [#x00C0-#x00D6] | [#x00D8-#x00F6]                  | [#x00F8-#x02FF] | [#x0370-#x037D] | [#x037F-#x1FFF]                  | [#x200C-#x200D] | [#x2070-#x218F] | [#x2C00-#x2FEF]                  | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD]                  | [#x10000-#xEFFFF] PN_PREFIX      ::= PN_CHARS_BASE ((PN_CHARS|'.')* PN_CHARS)? The more I look at CURIEs, the more my head hurts! The RIF specification allows prefixes and colons without local names, which surprised me. However, the CURIE Syntax 1.0 working group note specifically states that this form is supported…and then promptly provides a syntactic definition that seems to preclude it! However, on (much) deeper inspection, it appears that ‘ex1:’ (for example) is allowed, but would really represent a ‘fragment’ of the ‘reference’, rather than a prefix! Ouch! This is so completely ambiguous that it surely calls into question the whole CURIE specification.   In any case, RIF does not allow local names without a prefix. ·      Missing ‘External’ specifiers for built-in functions and predicates.  The EBNF specification enforces this for terms within frames, but does not appear to enforce (what I believe is) the correct use of External on built-in predicates. In any case, the running example only specifies ‘External’ once on the predicate in UnknownStatusRule. External() is required in several other places. ·      The List used on the LHS of UnknownStatusRule is comma-delimited. This is not supported by the EBNF definition. Similarly, the argument list of pred:list-contains is illegally comma-delimited. ·      Unnecessary use of conjunction around a single formula in DiscountRule. This is strictly legal in the EBNF, but redundant.   All the above issues concern the presentation syntax used in the running example. There are a few minor issues with the grammar itself. Note that Michael Kiefer stated in his paper “Rule Interchange Format: The Framework” that: “The presentation syntax of RIF … is an abstract syntax and, as such, it omits certain details that might be important for unambiguous parsing.” ·      The grammar cannot differentiate unambiguously between strategies and priorities on groups. A processor is forced to resolve this by detecting the use of IRIs and integers. This could easily be fixed in the grammar.   ·      The grammar cannot unambiguously parse the ‘->’ operator in frames. Specifically, ‘-’ characters are allowed in PN_LOCAL names and hence a parser cannot determine if ‘status->’ is (‘status’ ‘->’) or (‘status-’ ‘>’).   One way to fix this is to amend the PN_LOCAL production as follows: PN_LOCAL ::= ( PN_CHARS_U | [0-9] ) ((PN_CHARS|'.')* ((PN_CHARS)-('-')))? However, unilaterally changing the definition of this production, which is defined in the SPARQL Query Language for RDF specification, makes me uncomfortable. ·      I assume that the presentation syntax is case-sensitive. I couldn’t find this stated anywhere in the documentation, but function/predicate names do appear to be documented as being case-sensitive. ·      The EBNF does not specify whitespace handling. A couple of productions (RULE and ACTION_BLOCK) are crafted to enforce the use of whitespace. This is not necessary. It seems inconsistent with the rest of the specification and can cause parsing issues. In addition, the Const production exhibits whitespaces issues. The intention may have been to disallow the use of whitespace around ‘^^’, but any direct implementation of the EBNF will probably allow whitespace between ‘^^’ and the SYMSPACE. Of course, I am being a little nit-picking about all this. On the whole, the EBNF translated very smoothly and directly to ‘M’ (MGrammar) and proved to be fairly complete. I have encountered far worse issues when translating other EBNF specifications into usable grammars.   I can’t imagine there would be any difficulty in implementing the same grammar in Antlr, COCO/R, gppg, XText, Bison, etc. A general observation, which repeats a point made above, is that the use of parenthesis in the presentation syntax can feel inconsistent and un-intuitive.   It isn’t actually inconsistent, but I think the presentation syntax could be improved by adopting braces, rather than parenthesis, to delimit subordinate syntax elements in a similar way to so many programming languages. The familiarity of braces would communicate the structure of the syntax more clearly to people like me.  If braces were adopted, parentheses could be retained around ‘var (frame | ‘new()’) constructs in action blocks. This use of parenthesis feels very LISP-like, and I think that this is my issue. It’s as if the presentation syntax represents the deformed love-child of LISP and C. In some places (specifically, action blocks), parenthesis is used in a LISP-like fashion. In other places it is used like braces in C. I find this quite confusing. Here is a corrected version of the running example (Example 9.1) in compliant presentation syntax: Document(    Prefix( ex1 <http://example.com/2009/prd2> )    (* ex1:CheckoutRuleset *)  Group rif:forwardChaining (     (* ex1:GoldRule *)    Group 10 (      Forall ?customer such that And(?customer # ex1:Customer                                     ?customer[ex1:status->"Silver"])        (Forall ?shoppingCart such that ?customer[ex1:shoppingCart->?shoppingCart]           (If Exists ?value (And(?shoppingCart[ex1:value->?value]                                  External(pred:numeric-greater-than-or-equal(?value 2000))))            Then Do(Modify(?customer[ex1:status->"Gold"])))))      (* ex1:DiscountRule *)    Group (      Forall ?customer such that ?customer # ex1:Customer        (If Or( ?customer[ex1:status->"Silver"]                ?customer[ex1:status->"Gold"])         Then Do ((?s ?customer[ex1:shoppingCart-> ?s])                  (?v ?s[ex1:value->?v])                  Modify(?s [ex1:value->External(func:numeric-multiply (?v 0.95))]))))      (* ex1:NewCustomerAndWidgetRule *)    Group (      Forall ?customer such that And(?customer # ex1:Customer                                     ?customer[ex1:status->"New"] )        (If Exists ?shoppingCart ?item                   (And(?customer[ex1:shoppingCart->?shoppingCart]                        ?shoppingCart[ex1:containsItem->?item]                        ?item # ex1:Widget ) )         Then Do( (?s ?customer[ex1:shoppingCart->?s])                  (?val ?s[ex1:value->?val])                  (?voucher ?customer[ex1:voucher->?voucher])                  Retract(?customer[ex1:voucher->?voucher])                  Retract(?voucher)                  Modify(?s[ex1:value->External(func:numeric-multiply(?val 0.90))]))))      (* ex1:UnknownStatusRule *)    Group (      Forall ?customer such that ?customer # ex1:Customer        (If Not(Exists ?status                       (And(?customer[ex1:status->?status]                            External(pred:list-contains(List("New" "Bronze" "Silver" "Gold") ?status)) )))         Then Do( Execute(act:print(External(func:concat("New customer: " ?customer))))                  Assert(?customer[ex1:status->"New"]))))  ) )   I hope that helps someone out there :-)

    Read the article

  • Developing Schema Compare for Oracle (Part 1)

    - by Simon Cooper
    SQL Compare is one of Red Gate's most successful SQL Server tools; it allows developers and DBAs to compare and synchronize the contents of their databases. Although similar tools exist for Oracle, they are quite noticeably lacking in the usability and stability that SQL Compare is known for in the SQL Server world. We could see a real need for a usable schema comparison tools for Oracle, and so the Schema Compare for Oracle project was born. Over the next few weeks, as we come up to release of v1, I'll be doing a series of posts on the development of Schema Compare for Oracle. For the first post, I thought I would start with the main pitfalls that we stumbled across when developing the product, especially from a SQL Server background. 1. Schemas and Databases The most obvious difference is that the concept of a 'database' is quite different between Oracle and SQL Server. On SQL Server, one server instance has multiple databases, each with separate schemas. There is typically little communication between separate databases, and most databases are no more than about 1000-2000 objects. This means SQL Compare can register an entire database in a reasonable amount of time, and cross-database dependencies probably won't be an issue. It is a quite different scene under Oracle, however. The terms 'database' and 'instance' are used interchangeably, (although technically 'database' refers to the datafiles on disk, and 'instance' the running Oracle process that reads & writes to the database), and a database is a single conceptual entity. This immediately presents problems, as it is infeasible to register an entire database as we do in SQL Compare; in my Oracle install, using the standard recommended options, there are 63975 system objects. If we tried to register all those, not only would it take hours, but the client would probably run out of memory before we finished. As a result, we had to allow people to specify what schemas they wanted to register. This decision had quite a few knock-on effects for the design, which I will cover in a future post. 2. Connecting to Oracle The next obvious difference is in actually connecting to Oracle – in SQL Server, you can specify a server and database, and off you go. On Oracle things are slightly more complicated. SIDs, Service Names, and TNS A database (the files on disk) must have a unique identifier for the databases on the system, called the SID. It also has a global database name, which consists of a name (which doesn't have to match the SID) and a domain. Alternatively, you can identify a database using a service name, which normally has a 1-to-1 relationship with instances, but may not if, for example, using RAC (Real Application Clusters) for redundancy and failover. You specify the computer and instance you want to connect to using TNS (Transparent Network Substrate). The user-visible parts are a config file (tnsnames.ora) on the client machine that specifies how to connect to an instance. For example, the entry for one of my test instances is: SC_11GDB1 = (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = simonctest)(PORT = 1521)) ) (CONNECT_DATA = (SID = 11gR1db1) ) ) This gives the hostname, port, and SID of the instance I want to connect to, and associates it with a name (SC_11GDB1). The tnsnames syntax also allows you to specify failover, multiple descriptions and address lists, and client load balancing. You can then specify this TNS identifier as the data source in a connection string. Although using ODP.NET (the .NET dlls provided by Oracle) was fine for internal prototype builds, once we released the EAP we discovered that this simply wasn't an acceptable solution for installs on other people's machines. Due to .NET assembly strong naming, users had to have installed on their machines the exact same version of the ODP.NET dlls as we had on our build server. We couldn't ship the ODP.NET dlls with our installer as the Oracle license agreement prohibited this, and we didn't want to force users to install another Oracle client just so they can run our program. To be able to list the TNS entries in the connection dialog, we also had to locate and parse the tnsnames.ora file, which was complicated by users with several Oracle client installs and intricate TNS entries. After much swearing at our computers, we eventually decided to use a third party Oracle connection library from Devart that we could ship with our program; this could use whatever client version was installed, parse the TNS entries for us, and also had the nice feature of being able to connect to an Oracle server without having any client installed at all. Unfortunately, their current license agreement prevents us from shipping an Oracle SDK, but that's a bridge we'll cross when we get to it. 3. Running synchronization scripts The most important difference is that in Oracle, DDL is non-transactional; you cannot rollback DDL statements like you can on SQL Server. Although we considered various solutions to this, including using the flashback archive or recycle bin, or generating an undo script, no reliable method of completely undoing a half-executed sync script has yet been found; so in this case we simply have to trust that the DBA or developer will check and verify the script before running it. However, before we got to that stage, we had to get the scripts to run in the first place... To run a synchronization script from SQL Compare we essentially pass the script over to the SqlCommand.ExecuteNonQuery method. However, when we tried to do the same for an OracleConnection we got a very strange error – 'ORA-00911: invalid character', even when running the most basic CREATE TABLE command. After much hair-pulling and Googling, we discovered that Oracle has got some very strange behaviour with semicolons at the end of statements. To understand what's going on, we need to take a quick foray into SQL and PL/SQL. PL/SQL is not T-SQL In SQL Server, T-SQL is the language used to interface with the database. It has DDL, DML, control flow, and many other nice features (like Turing-completeness) that you can mix and match in the same script. In Oracle, DDL SQL and PL/SQL are two completely separate languages, with different syntax, different datatypes and different execution engines within the instance. Oracle SQL is much more like 'pure' ANSI SQL, with no state, no control flow, and only the basic DML commands. PL/SQL is the Turing-complete language, but can only do DML and DCL (i.e. BEGIN TRANSATION commands). Any DDL or SQL commands that aren't recognised by the PL/SQL engine have to be passed back to the SQL engine via an EXECUTE IMMEDIATE command. In PL/SQL, a semicolons is a valid token used to delimit the end of a statement. In SQL, a semicolon is not a valid token (even though the Oracle documentation gives them at the end of the syntax diagrams) . When you execute the command CREATE TABLE table1 (COL1 NUMBER); in SQL*Plus the semicolon on the end is a command to SQL*Plus to execute the preceding statement on the server; it strips off the semicolon before passing it on. SQL Developer does a similar thing. When executing a PL/SQL block, however, the syntax is like so: BEGIN INSERT INTO table1 VALUES (1); INSERT INTO table1 VALUES (2); END; / In this case, the semicolon is accepted by the PL/SQL engine as a statement delimiter, and instead the / is the command to SQL*Plus to execute the current block. This explains the ORA-00911 error we got when trying to run the CREATE TABLE command – the server is complaining about the semicolon on the end. This also means that there is no SQL syntax to execute more than one DDL command in the same OracleCommand. Therefore, we would have to do a round-trip to the server for every command we want to execute. Obviously, this would cause lots of network traffic and be very slow on slow or congested networks. Our first attempt at a solution was to wrap every SQL statement (without semicolon) inside an EXECUTE IMMEDIATE command in a PL/SQL block and pass that to the server to execute. One downside of this solution is that we get no feedback as to how the script execution is going; we're currently evaluating better solutions to this thorny issue. Next up: Dependencies; how we solved the problem of being unable to register the entire database, and the knock-on effects to the whole product.

    Read the article

  • ASP.NET MVC Checkbox Group

    - by Greg Ogle
    I am trying to formulate a work-around for the lack of a "checkbox group" in ASP.NET MVC. The typical way to implement this is to have check boxes of the same name, each with the value it represents. <input type="checkbox" name="n" value=1 /> <input type="checkbox" name="n" value=2 /> <input type="checkbox" name="n" value=3 /> When submitted, it will comma delimit all values to the request item "n".. so Request["n"] == "1,2,3" if all three are checked when submitted. In ASP.NET MVC, you can have a parameter of n as an array to accept this post. public ActionResult ActionName( int[] n ) { ... } All of the above works fine. The problem I have is that when validation fails, the check boxes are not restored to their checked state. Any suggestions. Problem Code: (I started with the default asp.net mvc project) Controller public class HomeController : Controller { public ActionResult Index() { var t = getTestModel("First"); return View(t); } [AcceptVerbs(HttpVerbs.Post)] public ActionResult Index(TestModelView t) { if(String.IsNullOrEmpty( t.TextBoxValue)) ModelState.AddModelError("TextBoxValue", "TextBoxValue required."); var newView = getTestModel("Next"); return View(newView); } private TestModelView getTestModel(string prefix) { var t = new TestModelView(); t.Checkboxes = new List<CheckboxInfo>() { new CheckboxInfo(){Text = prefix + "1", Value="1", IsChecked=false}, new CheckboxInfo(){Text = prefix + "2", Value="2", IsChecked=false} }; return t; } } public class TestModelView { public string TextBoxValue { get; set; } public List<CheckboxInfo> Checkboxes { get; set; } } public class CheckboxInfo { public string Text { get; set; } public string Value { get; set; } public bool IsChecked { get; set; } } } ASPX <% using( Html.BeginForm() ){ %> <p><%= Html.ValidationSummary() %></p> <p><%= Html.TextBox("TextBoxValue")%></p> <p><% int i = 0; foreach (var cb in Model.Checkboxes) { %> <input type="checkbox" name="Checkboxes[<%=i%>]" value="<%= Html.Encode(cb.Value) %>" <%=cb.IsChecked ? "checked=\"checked\"" : String.Empty %> /><%= Html.Encode(cb.Text)%><br /> <% i++; } %></p> <p><input type="submit" value="submit" /></p> <% } %> Working Code Controller [AcceptVerbs(HttpVerbs.Post)] public ActionResult Index(TestModelView t) { if(String.IsNullOrEmpty( t.TextBoxValue)) { ModelState.AddModelError("TextBoxValue", "TextBoxValue required."); return View(t); } var newView = getTestModel("Next"); return View(newView); } ASPX int i = 0; foreach (var cb in Model.Checkboxes) { %> <input type="checkbox" name="Checkboxes[<%=i%>].IsChecked" <%=cb.IsChecked ? "checked=\"checked\"" : String.Empty %> value="true" /> <input type="hidden" name="Checkboxes[<%=i%>].IsChecked" value="false" /> <input type="hidden" name="Checkboxes[<%=i%>].Value" value="<%= cb.Value %>" /> <input type="hidden" name="Checkboxes[<%=i%>].Text" value="<%= cb.Text %>" /> <%= Html.Encode(cb.Text)%><br /> <% i++; } %></p> <p><input type="submit" value="submit" /></p> Of course something similar could be done with Html Helpers, but this works.

    Read the article

1