Search Results

Search found 6569 results on 263 pages for 'specification pattern'.

Page 86/263 | < Previous Page | 82 83 84 85 86 87 88 89 90 91 92 93  | Next Page >

  • Dynamically specify and change a Silverlight DataGrid's columns during runtime (MVVM)

    - by Biggert
    What's the best method of dynamically specifying DataGrid columns in the Silverlight DataGrid control at runtime following the MVVM pattern? What I'd like to do would be bind the "DataGrid.Columns" property to a property in my ViewModel so that, if the user adds/removes columns, I simply update the ViewModel property and the DataGrid would change. Problem is, the "DataGrid.Columns" property can't be bound to (I don't think). Because this property isn't available nor is the DataGrid control itself available at the ViewModel level, my current approach is to step outside of the MVVM pattern for this particular implementation and capture certain events in View's code-behind using MVVM Light's Messenger class and then talk directly with the DataGrid control to achieve this capability. I know this is a general statement to this approach without details but is there an easier way... or maybe not so much easier, but a better way that adheres to the MVVM pattern a little better? It's driving me crazy that the DataGrid control's Columns property can't be bound... seems like such a simple thing. FYI - Before it's suggested to use AutoGenerateColumns = True, the class being bound for each item in the collection that's bound to DataGrid.ItemsSource does not have individual properties to identify what is bound to the columns... it's a collection property that contains the columns in order to keep them completely dynamic so that particular path is out. Also, handling the AutoGeneratingColumns and using e.Cancel to show/hide columns is also iffy for this same reason (I think).

    Read the article

  • Scaling gwt's "Contacts" (sample project) AppController with MVP

    - by brad
    I'm just learning GWT so I'm still trying to sort out all of its quirks and features. I'm reading through the example they give illustrating the MVP pattern, and I pretty much get it, except I'm wondering about one thing. The AppController they use implements the ValueChangeHandler interface and the onValueChange method is triggered when history changes. My problem is with this onValueChange in the AppController (i've included it below for anyone who hasn't seen the sample project). It's doing a string comparison on the history token sent in and instantiating the appropriate presenter to handle the action. This is all fine and dandy for the sample app with 3 actions, but how would one scale this to a real app with many more actions? Sticking to this pattern would lead to a pretty large/ugly else if, but I'm still too new to GWT (and java) to infer a better pattern for larger apps. Any help is greatly appreciated! public class AppController implements Presenter, ValueChangeHandler<String> { ... public void onValueChange(ValueChangeEvent<String> event) { String token = event.getValue(); if (token != null) { Presenter presenter = null; if (token.equals("list")) { presenter = new ContactsPresenter(rpcService, eventBus, new ContactsView()); } else if (token.equals("add")) { presenter = new EditContactPresenter(rpcService, eventBus, new EditContactView()); } else if (token.equals("edit")) { presenter = new EditContactPresenter(rpcService, eventBus, new EditContactView()); } if (presenter != null) { presenter.go(container); } } } }

    Read the article

  • codingbat wordEnds using regex

    - by polygenelubricants
    I'm trying to solve wordEnds from codingbat.com using regex. This is the simplest as I can make it with my current knowledge of regex: public String wordEnds(String str, String word) { return str.replaceAll( String.format( ".*?(?=%s)(?<=(.|^))%1$s(?=(.|$))|.+", java.util.regex.Pattern.quote(word) ), "$1$2" ); } String.format is used to inject word into the pattern for both readability and convenience (it's injected twice). Pattern.quote isn't necessary to pass their tests, but I think it's required for a proper regex-based solution. The regex has two major parts: If after matching as few characters as possible ".*?", word can still be found "(?=%s)", then lookbehind to capture any character immediately preceding it "(?<=(.|^))", match word "%1$s" and lookforward to capture any character following it "(?=(.|$))". The initial "if" test ensures that the atomic lookbehind captures only if there's a word Using lookahead to capture the following character doesn't consume it, so it can be used as part of further matching Otherwise match what's left "|.+" Groups 1 and 2 would capture empty strings I think this works in all cases, but it's obviously quite complex. I'm just wondering if others can suggest a simpler regex to do this. Note: I'm not looking for a solution using indexOf and a loop. I want a regex-based replaceAll solution. I also need a working solution that I can just copy-paste into codingbat and passes.

    Read the article

  • What are common anti-patterns when using VBA

    - by Ahmad
    I have being coding a lot in VBA lately (maintenance and new code), specifically with regards to Excel automation etc. = macros. Typically most of this has revolved around copy/paste, send some emails, import some files etc. but eventually just ends up as a Big ball of mud As a person who values clean code, I find it very difficult to produce 'decent' code when using VBA. I think that in most cases, this is a direct result of the macro-recorder. Very helpful to get you started, but most times, there are one too many lines of code that achieve the end result. Edit: The code from the macro-recorder is used as a base to get started, but is not used in its entirety in the end result I have already created a common addin that has my commonly used subroutines and some utility classes in an early attempt to enforce some DRYness - so this I think is a step in the right direction. But I feel as if it's a constant square peg, round hole situation. The wiki has an extensive list of common anti-patterns and what scared me the most was how many I have implemented in one way or another. The question Now considering, that my mindset is OO design, what some common anti-patterns and the possible solutions when designing a solution (think of this - how would designing a solution using Excel and VBA be different from say a .net/java/php/.../ etc solution) ; and when doing common tasks like copying data, emailing, data importing, file operations... etc An anti-pattern as defined by Wikipedia is: In software engineering, an anti-pattern (or antipattern) is a pattern that may be commonly used but is ineffective and/or counterproductive in practice

    Read the article

  • After Filter redirects to login.jsp, proper servlet doesnt get called

    - by gnomeguru
    My simple project structure is shown in this link. I am using Eclipse and Tomcat 6. There is login.jsp which submits its form to login_servlet. The login_servlet sets a session variable and then redirects to home.jsp. The home.jsp file has links to the 4 JSP files under a directory called /sam. In web.xml I have given the url-pattern as /sam/* for the LogFiler filter. The LogFilter just reads the session variable and does doChain(request,resposne) if valid, else it redirects to /login.jsp. RequestDispatcher rd = request.getRequestDispatcher("/login.jsp"); rd.forward(request,response); Basically I don't want anyone to access files inside /sam directory directly. Now let's say, I try to directly access a file inside /sam directory, the filter kicks in and the redirection to login.jsp works and even the broswers contents are that of login.jsp, but the url in the browser doesn't change. When I enter details and press submit, instead of sending the data to login_servlet, it sends it to sam/login_servlet and then tomcat tells me there is no such servlet here! Obviously there isn't. My doubt is why is it sending it so sam/login_servlet instead of /login_servlet which is usually what it does when I start running the login.jsp on my own. One more thing, is there a way I can apply the servlet to ONLY .jsp files inside /sam diectory? I tried giving the url-pattern like /sam/*.jsp, but Tomcat was refusing to accept that url-pattern.

    Read the article

  • Java NIO (Netty): How does Encryption or GZIPping work in theory (with filters)

    - by Tom
    Hello Experts, i would be very thankfull if you can explain to me, how in theory the "Interceptor/Filter" Pattern in ByteStreams (over Sockets/Channels) work (in Asynchronous IO with netty) in regard to encryption or compression of data. Given I have a Filter that does GZIPPING. How is this internally implemented? Does the Filter "collect" so many bytes form the channel, that this is a usefull number of bytes that can then be en/decoded? What is in general the minimal "blocksize(data to encode/decode in a chunk)" of socket based gzipping? Does this "blocksize" have to be negotiated in advance between server and client? What happens if the client does not send enough data to "fill" the blocksize (due to a network conquestion) but does not close the connection. Does this mean the other side will simply wait until it gets enough bytes to decode or until a timeout occoures...How is the Filter pattern the applied? The compression filter will de/compress the blocksize of bytes and then store them again in the same buffer would (in the case of netty) i normally be using the ChannelHanlderContext to pass the de/encoded data to the next filter?... Any explanations/links/tutorials (for beginners;-) will be very much appreciated to help me understand how for example encryption/compressing are implemented in socket based communication with filters/interceptor pattern. thank you very much tom

    Read the article

  • Excel 2003 VBA - Method to duplicate this code that select and colors rows

    - by Justin
    so this is a fragment of a procedure that exports a dataset from access to excel Dim rs As Recordset Dim intMaxCol As Integer Dim intMaxRow As Integer Dim objxls As Excel.Application Dim objWkb As Excel.Workbook Dim objSht As Excel.Worksheet Set rs = CurrentDb.OpenRecordset("qryOutput", dbOpenSnapshot) intMaxCol = rs.Fields.Count If rs.RecordCount > 0 Then rs.MoveLast: rs.MoveFirst intMaxRow = rs.RecordCount Set objxls = New Excel.Application objxls.Visible = True With objxls Set objWkb = .Workbooks.Add Set objSht = objWkb.Worksheets(1) With objSht On Error Resume Next .Range(.Cells(1, 1), .Cells(intMaxRow, intMaxCol)).CopyFromRecordset rs .Name = conSHT_NAME .Cells.WrapText = False .Cells.EntireColumn.AutoFit .Cells.RowHeight = 17 .Cells.Select With Selection.Font .Name = "Calibri" .Size = 10 End With .Rows("1:1").Select With Selection .Insert Shift:=xlDown End With .Rows("1:1").Interior.ColorIndex = 15 .Rows("1:1").RowHeight = 30 .Rows("2:2").Select With Selection.Interior .ColorIndex = 40 .Pattern = xlSolid End With .Rows("4:4").Select With Selection.Interior .ColorIndex = 40 .Pattern = xlSolid End With .Rows("6:6").Select With Selection.Interior .ColorIndex = 40 .Pattern = xlSolid End With .Rows("1:1").Select With Selection.Borders(xlEdgeBottom) .LineStyle = xlContinuous .Weight = xlMedium .ColorIndex = xlAutomatic End With End With End With End If Set objSht = Nothing Set objWkb = Nothing Set objxls = Nothing Set rs = Nothing Set DB = Nothing End Sub see where I am looking at coloring the rows. I wanted to select and fill (with any color) every other row, kinda like some of those access reports. I can do it manually coding each and every row, but two problems: 1) its a pain 2) i don't know what the record count is before hand. How can I make the code more efficient in this respect while incorporating the recordcount to know how many rows to "loop through" EDIT: Another question I have is with the selection methods I am using in the module, is there a better excel syntax instead of these with selections.... .Cells.Select With Selection.Font .Name = "Calibri" .Size = 10 End With is the only way i figure out how to accomplish this piece, but literally every other time I run this code, it fails. It says there is no object and points to the .font ....every other time? is this because the code is poor, or that I am not closing the xls app in the code? if so how do i do that? Thanks as always!

    Read the article

  • Graph limitations - Should I use Decorator?

    - by Nick Wiggill
    I have a functional AdjacencyListGraph class that adheres to a defined interface GraphStructure. In order to layer limitations on this (eg. acyclic, non-null, unique vertex data etc.), I can see two possible routes, each making use of the GraphStructure interface: Create a single class ("ControlledGraph") that has a set of bitflags specifying various possible limitations. Handle all limitations in this class. Update the class if new limitation requirements become apparent. Use the decorator pattern (DI, essentially) to create a separate class implementation for each individual limitation that a client class may wish to use. The benefit here is that we are adhering to the Single Responsibility Principle. I would lean toward the latter, but by Jove!, I hate the decorator Pattern. It is the epitome of clutter, IMO. Truthfully it all depends on how many decorators might be applied in the worst case -- in mine so far, the count is seven (the number of discrete limitations I've recognised at this stage). The other problem with decorator is that I'm going to have to do interface method wrapping in every... single... decorator class. Bah. Which would you go for, if either? Or, if you can suggest some more elegant solution, that would be welcome. EDIT: It occurs to me that using the proposed ControlledGraph class with the strategy pattern may help here... some sort of template method / functors setup, with individual bits applying separate controls in the various graph-canonical interface methods. Or am I losing the plot?

    Read the article

  • Why is Swing Parser's handleText not handling nested tags?

    - by Jim P
    I need to transform some HTML text that has nested tags to decorate 'matches' with a css attribute to highlight it (like firefox search). I can't just do a simple replace (think if user searched for "img" for example), so I'm trying to just do the replace within the body text (not on tag attributes). I have a pretty straightforward HTML parser that I think should do this: final Pattern pat = Pattern.compile(srch, Pattern.CASE_INSENSITIVE); Matcher m = pat.matcher(output); if (m.find()) { final StringBuffer ret = new StringBuffer(output.length()+100); lastPos=0; try { new ParserDelegator().parse(new StringReader(output.toString()), new HTMLEditorKit.ParserCallback () { public void handleText(char[] data, int pos) { ret.append(output.subSequence(lastPos, pos)); Matcher m = pat.matcher(new String(data)); ret.append(m.replaceAll("<span class=\"search\">$0</span>")); lastPos=pos+data.length; } }, false); ret.append(output.subSequence(lastPos, output.length())); return ret; } catch (Exception e) { return output; } } return output; My problem is, when I debug this, the handleText is getting called with text that includes tags! It's like it's only going one level deep. Anyone know why? Is there some simple thing I need to do to HTMLParser (haven't used it much) to enable 'proper' behavior of nested tags? PS - I figured it out myself - see answer below. Short answer is, it works fine if you pass it HTML, not pre-escaped HTML. Doh! Hope this helps someone else. <span>example with <a href="#">nested</a> <p>more nesting</p> </span> <!-- all this gets thrown together -->

    Read the article

  • shell scripting: search/replace & check file exist

    - by johndashen
    I have a perl script (or any executable) E which will take a file foo.xml and write a file foo.txt. I use a Beowulf cluster to run E for a large number of XML files, but I'd like to write a simple job server script in shell (bash) which doesn't overwrite existing txt files. I'm currently doing something like #!/bin/sh PATTERN="[A-Z]*0[1-2][a-j]"; # this matches foo in all cases todo=`ls *.xml | grep $PATTERN -o`; isdone=`ls *.txt | grep $PATTERN -o`; whatsleft=todo - isdone; # what's the unix magic? #tack on the .xml prefix with sed or something #and then call the job server; jobserve E "$whatsleft"; and then I don't know how to get the difference between $todo and $isdone. I'd prefer using sort/uniq to something like a for loop with grep inside, but I'm not sure how to do it (pipes? temporary files?) As a bonus question, is there a way to do lookahead search in bash grep? To clarify: so the simplest way to do what i'm asking is (in pseudocode) for i in `/bin/ls *.xml` do replace xml suffix with txt if [that file exists] add to whatsleft list end done

    Read the article

  • Spring security with GAE

    - by xybrek
    I'm trying to implement Spring security for my GAE application however I'm getting this error: No bean named 'springSecurityFilterChain' is defined I added this configuration on my application web.xml: <filter> <filter-name>springSecurityFilterChain</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> </filter> <filter-mapping> <filter-name>springSecurityFilterChain</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> And in the servlet-context: <!-- Configure security --> <security:http auto-config="true"> <security:intercept-url pattern="/**" access="ROLE_USER" /> </security:http> <security:authentication-manager alias="authenticationManager"> <security:authentication-provider> <security:user-service> <security:user name="jimi" password="jimi" authorities="ROLE_USER, ROLE_ADMIN" /> <security:user name="bob" password="bob" authorities="ROLE_USER" /> </security:user-service> </security:authentication-provider> </security:authentication-manager> What could be causing the error?

    Read the article

  • MVVM: Thin ViewModels and Rich Models

    - by Dan Bryant
    I'm continuing to struggle with the MVVM pattern and, in attempting to create a practical design for a small/medium project, have run into a number of challenges. One of these challenges is figuring out how to get the benefits of decoupling with this pattern without creating a lot of repetitive, hard-to-maintain code. My current strategy has been to create 'rich' Model classes. They are fully aware that they will be consumed by an MVVM pattern and implement INotifyPropertyChanged, allow their collections to be observed and remain cognizant that they may always be under observation. My ViewModel classes tend to be thin, only exposing properties when data actually needs to be transformed, with the bulk of their code being RelayCommand handlers. Views happily bind to either ViewModels or Models directly, depending on whether any data transformation is required. I use AOP (via Postsharp) to ease the pain of INotifyPropertyChanged, making it easy to make all of my Model classes 'rich' in this way. Are there significant disadvantages to using this approach? Can I assume that the ViewModel and View are so tightly coupled that if I need new data transformation for the View, I can simply add it to the ViewModel as needed?

    Read the article

  • preg_match_all and newlines inside quotes

    - by David
    Another noob regex problem/question. I'm probably doing something silly so I thought I'd exploit the general ingenuity of the SO regulars ;) Trying to match newlines but only if they occur within either double quotes or single quotes. I also want to catch strings that are between quotes but contain no newlines. Okay so there's what i got, with output. Below that, will be the output I would like to get. Any help would be greatly appreciated! :) I use Regex Coach to help me create my patterns, being a novice and all. According to RC, The pattern I supply does match all occurances within the data, but in my PHP, it skips over the multi-line part. I have tried with the 'm' pattern modifier already, to no avail. Contents of $CompressedData: <?php $Var = "test"; $Var2 = "test2"; $Var3 = "blah blah blah blah blah blah blah blah blah"; $Var4 = "hello"; ?> Pattern / Code: preg_match_all('!(\'|")(\b.*\b\n*)*(\'|")!', $CompressedData, $Matches); Current print_r output of $Matches: Array ( [0] => Array ( [0] => "test" [1] => "test2" [2] => "hello" ) ... } DESIRED print_r output of $Matches: Array ( [0] => Array ( [0] => "test" [1] => "test2" [2] => "blah blah blah blah blah blah blah blah blah" [3] => "hello" ) ... }

    Read the article

  • Spring security and authentication provider

    - by Pascal
    I'm trying to implement Spring 3 Security in a project, but I can not get rid of the following error: org.springframework.beans.factory.BeanCreationException: Error creating bean with name '_authenticationManager': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: No authentication providers were found in the application context This seems weird, as I did provide an authentication provider! I've added these lines to web. <filter> <filter-name>springSecurityFilterChain</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> </filter> <filter-mapping> <filter-name>springSecurityFilterChain</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> And this is my applicationContext-security.xml: <http auto-config="false"> <intercept-url pattern="/**" access="ROLE_USER" /> <http-basic /> </http> <authentication-manager alias="authenticationManager"> <authentication-provider> <user-service> <user name="jimi" password="jimispassword" authorities="ROLE_USER, ROLE_ADMIN"/> <user name="bob" password="bobspassword" authorities="ROLE_USER"/> </user-service> </authentication-provider> </authentication-manager> Google couldn't help me much further, nor could the official documentation.

    Read the article

  • PHP str_replace and preg_replace work on one server but not another

    - by retailevolved
    I have a simple function on a php page that takes a url such as: http://myurl.com/mypage.html?param1=value1 and converts it to: http://myurl.com/searchpage.html?param1=value1 All it does it swap out the page.html portion. To do this, I use the following: $currentUrl = $this-getCurrentUrl(); // Grabs the current url, i.e 'http://myurl.com/mypage.html?param1=value1' // Derive a search pattern from the current url $pattern = "/" . str_replace(array("/", ".", "-"), array("\\/", "\\.", "\\-"), $currentUrl) . "/"; // get rid of the 'mypage.html' $newUrl = preg_replace($pattern, 'http://myurl.com/', $currentUrl); // replace the question mark with the correct page $newUrl = str_replace("/?", "/searchpage.html?", $newUrl); The above code is not the exact code but is a good representation. It works beautifully on one server, but when I push to production, the preg_replace does not work. I originally attempted to use str_replace. It also works on my local development machine, but not on the production server. I have confirmed that the URL variables are coming in correctly. Any ideas?

    Read the article

  • Whats the wrong with this code?

    - by girinie
    Hi in this code first I am downloading a web-page source code then I am storing the code in text file. Again I am reading that file and matching with the regex to search a specific string. There is no compiler error. Exception in thread "main" java.lang.NoClassDefFoundError: java/lang/CharSequence Can anybody tell me Where I am wrong. import java.io.*; import java.net.*; import java.lang.*; import java.util.regex.Matcher; import java.util.regex.Pattern; public class WebDownload { public void getWebsite() { try{ URL url=new URL("www.gmail.com");// any URL can be given URLConnection urlc=url.openConnection(); BufferedInputStream buffer=new BufferedInputStream(urlc.getInputStream()); StringBuffer builder=new StringBuffer(); int byteRead; FileOutputStream fout; StringBuffer contentBuf = new StringBuffer(); while((byteRead=buffer.read()) !=-1) { builder.append((char)byteRead); fout = new FileOutputStream ("myfile3.txt"); new PrintStream(fout).println (builder.toString()); fout.close(); } BufferedReader in = new BufferedReader(new FileReader("myfile3.txt")); String buf = null; while ((buf = in.readLine()) != null) { contentBuf.append(buf);contentBuf.append("\n"); } in.close(); Pattern p = Pattern.compile("<div class=\"summarycount\">([^<]*)</div>"); Matcher matcher = p.matcher(contentBuf); if(matcher.find()) { System.out.println(matcher.group(1)); } else System.out.println("could not find"); } catch(MalformedURLException ex) { ex.printStackTrace(); } catch(IOException ex){ ex.printStackTrace(); } } public static void main(String [] args) { WebDownload web=new WebDownload(); web.getWebsite(); } }

    Read the article

  • Can the Singleton be replaced by Factory?

    - by lostiniceland
    Hello Everyone There are already quite some posts about the Singleton-Pattern around, but I would like to start another one on this topic since I would like to know if the Factory-Pattern would be the right approach to remove this "anti-pattern". In the past I used the singleton quite a lot, also did my fellow collegues since it is so easy to use. For example, the Eclipse IDE or better its workbench-model makes heavy usage of singletons as well. It was due to some posts about E4 (the next big Eclipse version) that made me start to rethink the singleton. The bottom line was that due to this singletons the dependecies in Eclipse 3.x are tightly coupled. Lets assume I want to get rid of all singletons completely and instead use factories. My thoughts were as follows: hide complexity less coupling I have control over how many instances are created (just store the reference I a private field of the factory) mock the factory for testing (with Dependency Injection) when it is behind an interface In some cases the factories can make more than one singleton obsolete (depending on business logic/component composition) Does this make sense? If not, please give good reasons for why you think so. An alternative solution is also appreciated. Thanks Marc

    Read the article

  • Static files in (Java) App Engine not accessible.

    - by fiXedd
    The example documentation says that you simply need to place your files in war/ (or a subdirectory) and they should be accessible from the host (as long as they aren't JSPs or in WEB-INF). For example, if you place foo.css in war/ then you should be able to access it at http://localhost:8080/foo.css. However, this isn't working for me at all. NONE of my static files are accessible. The docs on appengine-web.xml say that you can also specifically denote certain types as static. I've tried this as well and it makes no difference. Am I missing something obvious? UPDATE: Turns out one of the mappings in my web.xml was a little too aggressive. The following was the culprit: <servlet> <servlet-name>Main</servlet-name> <servlet-class>MainServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Main</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> It seems that it was grabbing everything that wasn't grabbed be one of the other rules, which I don't understand because there was no * on the end of the url-pattern. It also seems to be directly contradictory to the documentation that says: Note: Static files, files that are served verbatim to users such as images, CSS or JavaScript, are handled separately from paths mentioned in the deployment descriptor. A request for a URL path that matches a path to a file in the WAR that's considered a static file will serve the file, regardless of servlet and filter mappings in the deployment descriptor. You can exclude files from those treated as static files using the appengine-web.xml file. So, how can I have a rule that matches the base of my domain (eg. http://www.example.com/) and still allows the static files to filter through?

    Read the article

  • How does this RegEx for parsing emails work in PHP?

    - by George Edison
    Okay, I have the following PHP code to extract an email address of the following two forms: Random Stranger <[email protected]> [email protected] Here is the PHP code: // The first example $sender = "Random Stranger <[email protected]>"; $pattern = '/([\w_-]*@[\w-\.]*)|.*<([\w_-]*@[\w-\.]*)>/'; preg_match($pattern,$sender,$matches,PREG_OFFSET_CAPTURE); echo "<pre>"; print_r($matches); echo "</pre><hr>"; // The second example $sender = "[email protected]"; preg_match($pattern,$sender,$matches,PREG_OFFSET_CAPTURE); echo "<pre>"; print_r($matches); echo "</pre>"; My question is... what is in $matches? It seems to be a strange collection of arrays. Which index holds the match from the parenthesis? How can I be sure I'm getting the email address and only the email address? Update: Here is the output: Array ( [0] => Array ( [0] => Random Stranger [1] => 0 ) [1] => Array ( [0] => [1] => -1 ) [2] => Array ( [0] => [email protected] [1] => 5 ) ) Array ( [0] => Array ( [0] => [email protected] [1] => 0 ) [1] => Array ( [0] => [email protected] [1] => 0 ) )

    Read the article

  • List files with two dots in their names using java regular expressions

    - by Nivas
    I was trying to match files in a directory that had two dots in their name, something like theme.default.properties I thought the pattern .\\..\\.. should be the required pattern [. matches any character and \. matches a dot] but it matches both oneTwo.txt and theme.default.properties I tried the following: [resources/themes has two files oneTwo.txt and theme.default.properties] 1. public static void loadThemes() { File themeDirectory = new File("resources/themes"); if(themeDirectory.exists()) { File[] themeFiles = themeDirectory.listFiles(); for(File themeFile : themeFiles) { if(themeFile.getName().matches(".\\..\\..")); { System.out.println(themeFile.getName()); } } } } This prints nothing and the following File[] themeFiles = themeDirectory.listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return name.matches(".\\..\\.."); } }); for (File file : themeFiles) { System.out.println(file.getName()); } prints both oneTwo.txt theme.default.properties I am unable to find why these two give different results and which pattern I should be using to match two dots... Can someone help?

    Read the article

  • php cURL. preg_match , extract text from xhtml

    - by Michael
    I'm trying to extract the price from the bellow html page/link using php cURL and preg_match . Basically I'm expecting for this code to output 4,550 but for some reasons I get Notice: Undefined offset: 1 in C:\wamp\www\test.php on line 22 I think that the pattern is correct because if I put the html itself in a variable and escape the "" it works ! . Also if I output (echo $result;) it displays the html properly grabbed from foxtons website so I just can't figure it out why the whole thing doesn't work . I need to make this work and also I would appreciate if you would tell me why is that notice generated and why my current script doesn't work. $url = "http://www.foxtons.co.uk/search?bedrooms_from=0&property_id=727717"; $ch = curl_init($url); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1); $result = curl_exec($ch); curl_exec($ch); curl_close($ch); $result2 = str_replace('"', '\"', $result); $tagname1= ");<\/script "; $tagname2= "<\/noscript per month<\/a"; $pattern = "/$tagname1(.*?)$tagname2/"; preg_match($pattern, $result, $matches); $prices = $matches[1]; print_r($prices); ?

    Read the article

  • Creating a web application that can be extended by plugins/modules

    - by Adam Pope
    I'm currently involved with developing a C# CMS-like web application which will be used to standardise our development of websites. From the outset, the idea has been to keep the core as simple as possible to avoid the complexity and menu/option overload that blights many CMS systems. This simple core is now complete and working very well. We envisisaged that the system would be able to accept plugins or modules which would extend the core functionality to suit a given projects needs. These would also be re-usable across projects. For example, a basic catalogue and shopping basket might be needed. All the code for such extensions should be in seperate assemblies. They should be able to provide their own admin interfaces and front-end code from this library. The system should search for available plugins and give the admin user the option to enable/disable the feature. (This is all very much like WordPress plugins) It is crucial that we attack this problem in the correct way, so I'm trying to perform as much due dilligence as possible before jumping in. I am aware of the Plugin Pattern (http://msdn.microsoft.com/en-us/library/ms972962.aspx) and have read some articles on it's use. It seems reasonable but I'm not convinced it's necessarily the correct/best technique for this situation. It seems more suited to processing applications (image/audio manipulation, maths etc). Are there any other options for achieving this kind of UI extensibility functionality? Or is the plugin pattern the way to go? I'd also be interested if anybody has links to articles that explain using the plugin pattern for this purpose?

    Read the article

  • compare two text files using linq?

    - by bala3569
    I have 4 text files in one folder and a pattern.txt to compare these text files..In pattern.txt i have insert update delete drop I need to compare this text file with those four text files and if these patterns matches any line in that text files i have to write those lines in another log file...i had read those files using linq..i need to compare those files and write in a text file with line number..here is my code var foldercontent = Directory.GetFiles(pathA) .Select(filename => File.ReadAllText(filename)) .Aggregate(new StringBuilder(), (sb, s) => sb.Append(s).Append(Environment.NewLine), sb => sb.ToString()); var pattern = File.ReadAllLines(pathB).Aggregate(new StringBuilder(), (sb, s) => sb.Append(s).Append(Environment.NewLine), sb => sb.ToString()); using (var dest = File.AppendText(Path.Combine(_logFolderPath, "log.txt"))) { //dest.WriteLine("LineNo : " + counter.ToString() + " : " + "" + line); } EDIT I have already used c# to compare two text files but i need this in linq while ((line = file.ReadLine()) != null) { if (line.IndexOf(line2, StringComparison.CurrentCultureIgnoreCase) != -1) { dest.WriteLine("LineNo : " + counter.ToString() + " : " + " " + line.TrimStart()); } counter++; } file.BaseStream.Seek(0, SeekOrigin.Begin); counter = 1;

    Read the article

  • The best way to write a jQuery plugin - If there is such a way?

    - by Nick Lowman
    There are quite a few ways to write plugins i.e. here's a nice example and what I've seen quite a lot of lately is the following code pattern and it's used by Doug Neiner here; (function($){ $.formatLink = function(el, options){ var base = this; base.$el = $(el); base.el = el; base.$el.data("formatLink", base); base.init = function(){ base.options = $.extend({}, $.formatLink.defaultOptions, options); //code here } base.init(); }; $.formatLink.defaultOptions = { }; $.fn.formatLink = function(options){ return this.each(function(){ (new $.formatLink(this, options)); }); }; })(jQuery); So, can anyone tell me the benefits of using the pattern above rather than the one below. I can't see the point in calling the $.extend function for every element in the jQuery stack (above), where the example below only does this once and then works on the stack. To test it I created two plugins, using both patterns, which applied styles to about 5000 li elements and the code below took about 1 second whereas the pattern above took about 1.3 seconds. (function($){ $.fn.formatLink = function(options){ var options = $.extend({}, $.fn.formatLink.defaultOptions, options || {}); return this.each(function(){ //code here }); }); $.fn.formatLink.defaultOptions ={} })(jQuery);

    Read the article

  • What is better: Developing a Web project in MVC or N -Tier Architecture?

    - by Starx
    I have asked a similar question before and got an convincing answer as well? http://stackoverflow.com/questions/2843311/what-is-difference-of-developing-a-website-in-mvc-and-3-tier-or-n-tier-architectu Due to the conclusion of this question I started developing projects in N-tier Architecture. Just about an hour ago, I asked another question, about what is the best design pattern to create interface? There the most voted answer is suggesting me to use MVC architecture. http://stackoverflow.com/questions/2930300/what-is-the-best-desing-pattern-to-design-the-interface-of-an-webpage Now I am confused, First post suggested me that both are similar, just a difference that in N-tier, the tier are physically and logically separated and one layer has access to the one above and below it but not all the layers. I think ASP.net used 3 Tier architecture while developing applications or Web applications. Where as frameworks like Zend, Symphony they use MVC. I just want to stick to a pattern that is best suitable for WebProject Development? May be this is a very silly confusion? But if someone could clear this confusion, that would be very greatful?

    Read the article

< Previous Page | 82 83 84 85 86 87 88 89 90 91 92 93  | Next Page >