Search Results

Search found 1725 results on 69 pages for 'equation solving'.

Page 64/69 | < Previous Page | 60 61 62 63 64 65 66 67 68 69  | Next Page >

  • Hadoop in a RESTful Java Web Application - Conflicting URI templates

    - by user1231583
    I have a small Java Web Application in which I am using Jersey 1.12 and the Hadoop 1.0.0 JAR file (hadoop-core-1.0.0.jar). When I deploy my application to my JBoss 5.0 server, the log file records the following error: SEVERE: Conflicting URI templates. The URI template / for root resource class org.apache.hadoop.hdfs.server.namenode.web.resources.NamenodeWebHdfsMethods and the URI template / transform to the same regular expression (/.*)? To make sure my code is not the problem, I have created a fresh web application that contains nothing but the Jersey and Hadoop JAR files along with a small stub. My web.xml is as follows: <?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <servlet> <servlet-name>ServletAdaptor</servlet-name> <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet- class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>ServletAdaptor</servlet-name> <url-pattern>/mytest/*</url-pattern> </servlet-mapping> <session-config> <session-timeout> 30 </session-timeout> </session-config> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app> My simple RESTful stub is as follows: import javax.ws.rs.core.Context; import javax.ws.rs.core.UriInfo; import javax.ws.rs.Path; @Path("/mytest") public class MyRest { @Context private UriInfo context; public MyRest() { } } In my regular application, when I remove the Hadoop JAR files (and the code that is using Hadoop), everything works as I would expect. The deployment is successful and the remaining RESTful services work. I have also tried the Hadoop 1.0.1 JAR files and have had the same problems with the conflicting URL template in the NamenodeWebHdfsMethods class. Any suggestions or tips in solving this problem would be greatly appreciated.

    Read the article

  • Why do some questions get closed for no reason? [closed]

    - by IVlad
    Recently there was a question asking about generating all subsets of a set using a stack and a queue, which was closed (and now deleted it seems) as not a real question for no good reason, since it didn't fit into any of these conditions: It's difficult to tell what is being asked here. No, it was clear what was being asked. This question is ambiguous, vague, incomplete, or rhetorical and cannot be reasonably answered in its current form. Not ambiguous, not vague, not incomplete, definitely not rhetorical and could easily be answered if one knew the solution. Now, the exact same thing has happened with this question: http://stackoverflow.com/questions/2791982/a-shortest-path-problem-with-superheroes-and-intergalactic-journeys/2793746#2793746 I am interested in hearing a logical argument for why that question is either ambiguous, vague, incomplete, rhetorical or cannot reasonably be answered in its current form. It seems that (the same bunch of) people like to close questions that they think are homework questions, especially when they think people want to be served the solution on a platter, which is also not the case: Any suggestions or ideas of how this problem might be solved would be most welcomed. Most of the time the people asking these questions are very reasonable and appreciate even the most vague idea, yet their question is closed. Let's go further and assume that it IS a homework problem. So what? When I registered here I didn't see any rule that said not to post homework problems, nor do I see such a rule now. What is wrong with posting homework problems that makes people hunt them down with a passion to close them without even reading the entire question body? This site is full of questions asked by people who get paid to know the things they are asking, yet their questions are considered fine. How is solving someone's homework problem worse? In some places (like where I live), computer science is a mandatory high school subject, and not everyone is interested in it. How is helping at least those people worse than doing someone's JOB? Not answering homework questions is fine and it's everyone's choice, but I consider closing them to be an act of power abuse, selfishness, and an insult to the fellow community members who are also interested in a solution or want feedback on their proposed solution. So my questions are: - Why do questions like the above get closed for reasons that do not apply? Why do you close them? Why don't you? - Why doesn't a vote to reopen a question reopen it automatically? Needing 5 votes for a reopen takes too long, and it's not fair because one reopen vote basically cancels out a close vote, making it 4 close votes (or 5 to 1, which is the same as only 4 people wanting to close the question), which isn't enough to close the question. I think a question should only be closed when CloseVotes - ReopenVotes >= 5. I'm hoping this will stay up, but I realize it probably won't. In either case, I think this is worth saying and discussing, since it IS community-related.

    Read the article

  • Please help with iPhone Memory & Images, memory usage crashing app

    - by Andrew Gray
    I have an issue with memory usage relating to images and I've searched the docs and watched the videos from cs193p and the iphone dev site on memory mgmt and performance. I've searched online and posted on forums, but I still can't figure it out. The app uses core data and simply lets the user associate text with a picture and stores the list of items in a table view that lets you add and delete items. Clicking on a row shows the image and related text. that's it. Everything runs fine on the simulator and on the device as well. I ran the analyzer and it looked good, so i then starting looking at performance. I ran leaks and everything looked good. My issue is when running Object Allocations as every time i select a row and the view with the image is shown, the live bytes jumps up a few MB and never goes down and my app eventually crashes due to memory usage. Sorting the live bytes column, i see 2 2.72MB mallocs (5.45Mb total), 14 CFDatas (3.58MB total), 1 2.74MB malloc and everything else is real small. the problem is all the related info in instruments is really technical and all the problem solving examples i've seen are just missing a release and nothing complicated. Instruments shows Core Data as the responsible library for all but one (libsqlite3.dylib the other) with [NSSQLCore _prepareResultsFromResultSet:usingFetchPlan:withMatchingRows:] as the caller for all but one (fetchResultSetReallocCurrentRow the other) and im just not sure how to track down what the problem is. i've looked at the stack traces and opened the last instance of my code and found 2 culprits (below). I havent been able to get any responses at all on this, so if anyone has any tips or pointers, I'd really appreciate it!!!! //this is from view controller that shows the title and image - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; self.title = item.title; self.itemTitleTextField.text = item.title; if ([item.notes length] == 0) { self.itemNotesTextView.hidden = YES; } else { self.itemNotesTextView.text = item.notes; } //this is the line instruments points to UIImage *image = item.photo.image; itemPhoto.image = image; } - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { if (editingStyle == UITableViewCellEditingStyleDelete) { // Delete the managed object for the given index path NSManagedObjectContext *context = [fetchedResultsController managedObjectContext]; [context deleteObject:[fetchedResultsController objectAtIndexPath:indexPath]]; // Save the context. NSError *error = nil; if (![context save:&error]) //this is the line instruments points to { NSLog(@"Unresolved error %@, %@", error, [error userInfo]); exit(-1); } } }

    Read the article

  • Estimating the boundary of arbitrarily distributed data

    - by Dave
    I have two dimensional discrete spatial data. I would like to make an approximation of the spatial boundaries of this data so that I can produce a plot with another dataset on top of it. Ideally, this would be an ordered set of (x,y) points that matplotlib can plot with the plt.Polygon() patch. My initial attempt is very inelegant: I place a fine grid over the data, and where data is found in a cell, a square matplotlib patch is created of that cell. The resolution of the boundary thus depends on the sampling frequency of the grid. Here is an example, where the grey region are the cells containing data, black where no data exists. OK, problem solved - why am I still here? Well.... I'd like a more "elegant" solution, or at least one that is faster (ie. I don't want to get on with "real" work, I'd like to have some fun with this!). The best way I can think of is a ray-tracing approach - eg: from xmin to xmax, at y=ymin, check if data boundary crossed in intervals dx y=ymin+dy, do 1 do 1-2, but now sample in y An alternative is defining a centre, and sampling in r-theta space - ie radial spokes in dtheta increments. Both would produce a set of (x,y) points, but then how do I order/link neighbouring points them to create the boundary? A nearest neighbour approach is not appropriate as, for example (to borrow from Geography), an isthmus (think of Panama connecting N&S America) could then close off and isolate regions. This also might not deal very well with the holes seen in the data, which I would like to represent as a different plt.Polygon. The solution perhaps comes from solving an area maximisation problem. For a set of points defining the data limits, what is the maximum contiguous area contained within those points To form the enclosed area, what are the neighbouring points for the nth point? How will the holes be treated in this scheme - is this erring into topology now? Apologies, much of this is me thinking out loud. I'd be grateful for some hints, suggestions or solutions. I suspect this is an oft-studied problem with many solution techniques, but I'm looking for something simple to code and quick to run... I guess everyone is, really! Cheers, David

    Read the article

  • How to maxmise the largest contiguous block of memory in the Large Object Heap

    - by Unsliced
    The situation is that I am making a WCF call to a remote server which is returns an XML document as a string. Most of the time this return value is a few K, sometimes a few dozen K, very occasionally a few hundred K, but very rarely it could be several megabytes (first problem is that there is no way for me to know). It's these rare occasions that are causing grief. I get a stack trace that starts: System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown. at System.Xml.BufferBuilder.AddBuffer() at System.Xml.BufferBuilder.AppendHelper(Char* pSource, Int32 count) at System.Xml.BufferBuilder.Append(Char[] value, Int32 start, Int32 count) at System.Xml.XmlTextReaderImpl.ParseText() at System.Xml.XmlTextReaderImpl.ParseElementContent() at System.Xml.XmlTextReaderImpl.Read() at System.Xml.XmlTextReader.Read() at System.Xml.XmlReader.ReadElementString() at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderMDRQuery.Read2_getMarketDataResponse() at Microsoft.Xml.Serialization.GeneratedAssembly.ArrayOfObjectSerializer2.Deserialize(XmlSerializationReader reader) at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, XmlDeserializationEvents events) at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle) at System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, Boolean asyncCall) at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters) I've read around and it is because the Large Object Heap is just getting too fragmented, so even preceding the call with a quick check to StringBuilder.EnsureCapacity just causes the OutOfMemoryException to be thrown earlier (and because I'm guessing at what's needed, it might not actually need that much so my check is causing more problems than it is solving). Some opinions are that there's not much I can do about it. Some of the questions I've asked myself: Use less memory - have you checked for leaks? Yes. The memory usage goes up and down, but there's no fundamental growth that guarantees this to happen. Some of the times it fails, it succeeded at that stage previously. Transfer smaller amounts Not an option, this is a third party web service over which I have no control (or at least it would take a long time to resolve, in the meantime I still have a problem) Can you do something to the LOH to make it less likely to fail? ... now this is most fruitful course. It's a 32-bit process (it has to be for various political, technical and boring reasons) but there's normally hundreds of meg free (multiples of the largest amount for which we've seen failures). Can we monitor the LOH? Using perfmon I can track the size of the heaps, but I don't think there's a way to monitor the largest available contiguous block of memory. Question is: any advice or suggestions for things to try?

    Read the article

  • Trying to integrate CakePHP and jQuery

    - by user198003
    Trying to integrate CakePHP and jQuery, using next example http://bakery.cakephp.org/articles/view/dynamic-select-boxes-with-ajax-jquery What I want is to when user change first option element, to automaticly fill second select option box with proper values. But, nothing happens, if you can help me why. So, there is a Invoice add form (add.ctp), with next code... <?php echo $form->create('Invoice');?> <?php echo $javascript->link('jquery.js'); $category = array('1' => 'First', '4' => 'Fourth', '7' => 'Seventh'); echo $form->input('client_id', array('options' => $category, 'empty' => 'Choose:')); echo $form->select('clientBank_id', array("Choose category first"), null, null, false); ?> <script> $("#InvoiceClientId").change(function () { $.post('/invoices/listTitleByCategory/' + $(this).val(), function(data) { $("#InvoiceClientBankId").empty().append(data); }, 'html'); }) </script> Also, there is controller (invoices_controller.php): <?php var $name = 'Invoices'; var $helpers = array('Html', 'Form', 'Time', 'Number', 'Javascript'); var $paginate = array('order' => array('Invoice.pinned DESC', 'Invoice.invoiceNumber')); var $components = array('RequestHandler'); function beforeRender(){ // prevent useless warnings for Ajax if($this->RequestHandler->isAjax()){ Configure::write('debug', 0); } } // etc... function listTitleByCategory($category = "") { $this->layout = 'ajax'; $this->beforeRender(); $this->autoRender = false; $data = $this->Invoice->Client->find('list'); echo "<option value=0>just for testing...</option>"; foreach($data as $key => $val) { echo "<option value=$key>$val</option>"; } } ?> Please, if you can help me solving this. Thank you in advance!

    Read the article

  • How can I group an array of rectangles into "Islands" of connected regions?

    - by Eric
    The problem I have an array of java.awt.Rectangles. For those who are not familiar with this class, the important piece of information is that they provide an .intersects(Rectangle b) function. I would like to write a function that takes this array of Rectangles, and breaks it up into groups of connected rectangles. Lets say for example, that these are my rectangles (constructor takes the arguments x, y, width,height): Rectangle[] rects = new Rectangle[] { new Rectangle(0, 0, 4, 2), //A new Rectangle(1, 1, 2, 4), //B new Rectangle(0, 4, 8, 2), //C new Rectangle(6, 0, 2, 2) //D } A quick drawing shows that A intersects B and B intersects C. D intersects nothing. A tediously drawn piece of ascii art does the job too: +-------+ +---+ ¦A+---+ ¦ ¦ D ¦ +-+---+-+ +---+ ¦ B ¦ +-+---+---------+ ¦ +---+ C ¦ +---------------+ Therefore, the output of my function should be: new Rectangle[][]{ new Rectangle[] {A,B,C}, new Rectangle[] {D} } The failed code This was my attempt at solving the problem: public List<Rectangle> getIntersections(ArrayList<Rectangle> list, Rectangle r) { List<Rectangle> intersections = new ArrayList<Rectangle>(); for(Rectangle rect : list) { if(r.intersects(rect)) { list.remove(rect); intersections.add(rect); intersections.addAll(getIntersections(list, rect)); } } return intersections; } public List<List<Rectangle>> mergeIntersectingRects(Rectangle... rectArray) { List<Rectangle> allRects = new ArrayList<Rectangle>(rectArray); List<List<Rectangle>> groups = new ArrayList<ArrayList<Rectangle>>(); for(Rectangle rect : allRects) { allRects.remove(rect); ArrayList<Rectangle> group = getIntersections(allRects, rect); group.add(rect); groups.add(group); } return groups; } Unfortunately, there seems to be an infinite recursion loop going on here. My uneducated guess would be that java does not like me doing this: for(Rectangle rect : allRects) { allRects.remove(rect); //... } Can anyone shed some light on the issue?

    Read the article

  • why java application not working after applying "web look and feel" theme?

    - by Vasu
    I have developed "Employee Management System" java project .For improving the ui appearance i have integrated "web look and feel" into my application.Theme is applied correctly. But here the problem arises: At first i have runned the java application without connecting to oracle data base,application have runned and worked perfectly. But when i connected the application to oracle database and runned again the application is taking more time to open and getting strucked. Code: For applying theme try { WebLookAndFeel.install(); }catch(Exception ex){ ex.printStackTrace(); } Code for Connecting DataBase: if (con == null) { File sd = new File(""); File in = new File(sd.getAbsolutePath() + File.separator + "conf.properties"); File dir = new File(sd.getAbsolutePath() + File.separator + "conf.properties"); if (!dir.exists()) { // dir.mkdir(); dir.createNewFile(); Properties pro = new Properties(); pro.load(new FileInputStream(in)); pro.setProperty("driverclass", "oracle.jdbc.driver.OracleDriver"); pro.setProperty("url", "jdbc:oracle:thin:@192.168.1.1:1521:main"); pro.setProperty("username", "gb16"); pro.setProperty("passwd", "gb16"); try { FileOutputStream out = new FileOutputStream(in); pro.store(out, "Human Management System initialization properties"); out.flush(); out.close();} catch(Exception e) { e.printStackTrace(); } } else { // System.out.println("Already exists "); } Properties pro = new Properties(); pro.load(new FileInputStream(in)); Class.forName(pro.getProperty("driverclass")); con = DriverManager.getConnection(pro.getProperty("url"), pro.getProperty("username"), pro.getProperty("passwd")); st = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); } else { return con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE); } without the theme the application with connected to database working correctly. Please help me in solving this issue. Thanks in advance..

    Read the article

  • Combined sign in and registration page?

    - by Ryan
    This is somewhat against rails convention but I am trying to have one controller that manages both user session authentication and user registration. I am having troubles figuring out how to go about this. So far I am merging the User Controller and the Sessions Controller and having the 'new' method deliver both a new usersession and a new user instance. With the new routes in rails 3 though, I am having trouble figuring out how to generate forms for these items. Below is the code: user_controller.rb class UserController < ApplicationController def new @user_session = UserSession.new @user = User.new end def create_user @user = User.new(params[:user]) if @user.save flash[:notice] = "Account Successfully Registered" redirect_back_or_default signup_path else render :action => new end end def create_session @user_session = UserSession.new(params[:user_session]) if @user_session.save flash[:notice] = "Login successful!" redirect_back_or_default login_path else render :action => new end end end views/user/new.html.erb <div id="login_section"> <% form_for @user_session do |f| -%> <%= f.label :email_address, "Email Address" %> <%= f.text_field :email %> <%= f.label :password, "Password" %> <%= f.text_field :password %> <%= f.submit "Login", :disable_with => 'Logining...' %> <% end -%> </div> <div id="registration_section"> <% form_for @user do |f| -%> <%= f.label :email_address, "Email Address" %> <%= f.text_field :email %> <%= f.label :password, "Password" %> <%= f.text_field :password %> <%= f.label :password_confirmation, "Password Confirmation" %> <%= f.text_field :password_confirmation %> <%= f.submit "Register", :disable_with => 'Logining...' %> <% end -%> </div> I imagine I will need to use :url = something for those forms, but I am unsure how to specify. Within routes.rb I have yet to specify either Usersor UserSessions as resources (not convinced that this is the best way to do it... but I could be). I would like, however, the registration and login on the same page and have implemented this by doing the following: routes.rb match 'signup' => 'user#new' match 'login' => 'user#new' What's the best way to go about solving this?

    Read the article

  • Dynamically find other hosts in a LAN in Java

    - by Federico Cristina
    A while ago I developed a little LAN chat app. in Java which allows chatting with other hosts, send images, etc. Although it was created just for fun, now it's being used where I work. Currently, there is no "chat server" on the app. where each client registers, updates it's status, etc. (I liked the idea of symmetric design and not depending on a server running on some other machine). Instead, each host is a client/server which has a hosts.properties file with the hostname of the other hosts, and - for instance - broadcasts to each one of them when sending a massive message/image/whatever. In the beginning there were just a couple of hosts, so this hosts.properties file wasn't an issue. But as the amount of users increased, the need of updating that file was a bit daunting. So now I've decided to get rid of it, and each time the app. starts, dynammically find the other active hosts. However, I cannot find the correct way of implement this. I've tried starting different threads, each one of them searching for other hosts in a known range of IP addresses. Something like this (simplified for the sake of readability): /** HostsLocator */ public static void searchForHosts(boolean waitToEnd) { for (int i=0; i < MAX_IP; i+= MAX_IP / threads) { HostsLocator detector = new HostsLocator(i, i+(MAX_IP / threads - 1)); // range: from - to new Thread(detector).start(); } } public void run() { for (int i=from; i<=to; i++) findHosts( maskAddress + Integer.toString(i) ); } public static boolean findHosts(String IP) { InetAddress address = InetAddress.getByName(IP); if ( address.isReachable(CONNECTION_TIME_OUT) ) // host found! } However: With a single thread and a low value in CONNECTION_TIME_OUT (500ms) I get wrong Host Not Found status for for hosts actually active. With a high value in CONNECTION_TIME_OUT (5000ms) and only one single thread takes forever to end With several threads I've also found problems similar like the first one, due to collisions. So... I guess there's a better way of solving this problem but I couldn't find it. Any advice? Thanks!

    Read the article

  • Help with bugs in a C code

    - by Yanki Twizzy
    This C code is giving me some unpredictable results. The program is meant to collect 6 nos and print out the max, position of the max no and the average. It's supposed to have only 3 functions - input, max_avr_pos and output for doing what the code is supposed to do but I am getting unpredictable results. Please what could be the problem #include <stdio.h> #include <stdlib.h> #include <conio.h> void input_vals(int arrnum[]); void max_ave_val(int arrnum1[],double *average,int *maxval,int *position); void print_output(double *average1,int *maxval1,int *position1); int main(void) { int arrnum[6],maxval2,position2; double average2; input_vals(arrnum); max_ave_val(arrnum,&average2,&maxval2,&position2); print_output(&average2,&maxval2,&position2); _getche(); return 0; } void input_vals(int arrnum[]) { int count; printf("\n Please enter six numbers\n"); for(count=0;count<6;count++) { scanf("%d",&arrnum[count]); } } void max_ave_val(int arrnum1[],double *average,int *maxval,int *position) { int total=0; int cnt,cnt1,cnt2,limit,maxval2,post; limit=6; /* finding the max value*/ for(cnt=0;cnt<limit-1;cnt++) for(cnt1=limit-1;cnt1>cnt;--cnt1) { if(arrnum1[cnt1-1]>arrnum1[cnt1]) { maxval2=arrnum1[cnt-1]; post=(cnt-1)+1; } else { maxval2=arrnum1[cnt1]; post=cnt1+1; } } *maxval=maxval2; *position=post; /* solving for total */ for(cnt2=0;cnt2<limit;cnt2++); { total=total+arrnum1[cnt2]; } *average=total/limit; } void print_output(double *average1,int *maxval1,int *position1) { printf("\n value of the highest of the numbers is %d\n",*maxval1); printf("\n the average of all the numbers is %g\n",*average1); printf("\n the postion of the highest number in the list is %d\n",*position1); }

    Read the article

  • How to discover classes with [Authorize] attributes using Reflection in C#? (or How to build Dynamic

    - by Pretzel
    Maybe I should back-up and widen the scope before diving into the title question... I'm currently writing a web app in ASP.NET MVC 1.0 (although I do have MVC 2.0 installed on my PC, so I'm not exactly restricted to 1.0) -- I've started with the standard MVC project which has your basic "Welcome to ASP.NET MVC" and shows both the [Home] tab and [About] tab in the upper-right corner. Pretty standard, right? I've added 4 new Controller classes, let's call them "Astronomer", "Biologist", "Chemist", and "Physicist". Attached to each new controller class is the [Authorize] attribute. For example, for the BiologistController.cs [Authorize(Roles = "Biologist,Admin")] public class BiologistController : Controller { public ActionResult Index() { return View(); } } These [Authorize] tags naturally limit which user can access different controllers depending on Roles, but I want to dynamically build a Menu at the top of my website in the Site.Master Page based on the Roles the user is a part of. So for example, if JoeUser was a member of Roles "Astronomer" and "Physicist", the navigation menu would say: [Home] [Astronomer] [Physicist] [About] And naturally, it would not list links to "Biologist" or "Chemist" controller Index page. Or if "JohnAdmin" was a member of Role "Admin", links to all 4 controllers would show up in the navigation bar. Ok, you prolly get the idea... Starting with the answer from this StackOverflow topic about Dynamic Menu building in ASP.NET, I'm trying to understand how I would fully implement this. (I'm a newbie and need a little more guidance, so please bare with me.) The answer proposes Extending the Controller class (call it "ExtController") and then have each new WhateverController inherit from ExtController. My conclusion is that I would need to use Reflection in this ExtController Constructor to determine which Classes and Methods have [Authorize] attributes attached to them to determine the Roles. Then using a Static Dictionary, store the Roles and Controllers/Methods in key-value pairs. I imagine it something like this: public class ExtController : Controller { protected static Dictionary<Type,List<string>> ControllerRolesDictionary; protected override void OnActionExecuted(ActionExecutedContext filterContext) { // build list of menu items based on user's permissions, and add it to ViewData IEnumerable<MenuItem> menu = BuildMenu(); ViewData["Menu"] = menu; } private IEnumerable<MenuItem> BuildMenu() { // Code to build a menu SomeRoleProvider rp = new SomeRoleProvider(); foreach (var role in rp.GetRolesForUser(HttpContext.User.Identity.Name)) { } } public ExtController() { // Use this.GetType() to determine if this Controller is already in the Dictionary if (!ControllerRolesDictionary.ContainsKey(this.GetType())) { // If not, use Reflection to add List of Roles to Dictionary // associating with Controller } } } Is this doable? If so, how do I perform Reflection in the ExtController constructor to discover the [Authorize] attribute and related Roles (if any) ALSO! Feel free to go out-of-scope on this question and suggest an alternate way of solving this "Dynamic Site.Master Menu based on Roles" problem. I'm the first to admit that this may not be the best approach.

    Read the article

  • Makefile issue with compiling a C++ program

    - by Steve
    I recently got MySQL compiled and working on Cygwin, and got a simple test example from online to verify that it worked. The test example compiled and ran successfully. However, when incorporating MySQL in a hobby project of mine it isn't compiling which I believe is due to how the Makefile is setup, I have no experience with Makefiles and after reading tutorials about them, I have a better grasp but still can't get it working correctly. When I try and compile my hobby project I recieve errors such as: Obj/Database.o:Database.cpp:(.text+0x492): undefined reference to `_mysql_insert_id' Obj/Database.o:Database.cpp:(.text+0x4c1): undefined reference to `_mysql_affected_rows' collect2: ld returned 1 exit status make[1]: *** [build] Error 1 make: *** [all] Error 2 Here is my Makefile, it worked with compiling and building the source before I attempted to put in MySQL support into the project. The LIBMYSQL paths are correct, verified by 'mysql_config'. COMPILER = g++ WARNING1 = -Wall -Werror -Wformat-security -Winline -Wshadow -Wpointer-arith WARNING2 = -Wcast-align -Wcast-qual -Wredundant-decls LIBMYSQL = -I/usr/local/include/mysql -L/usr/local/lib/mysql -lmysqlclient DEBUGGER = -g3 OPTIMISE = -O C_FLAGS = $(OPTIMISE) $(DEBUGGER) $(WARNING1) $(WARNING2) -export-dynamic $(LIBMYSQL) L_FLAGS = -lz -lm -lpthread -lcrypt $(LIBMYSQL) OBJ_DIR = Obj/ SRC_DIR = Source/ MUD_EXE = project MUD_DIR = TestP/ LOG_DIR = $(MUD_DIR)Files/Logs/ ECHOCMD = echo -e L_GREEN = \e[1;32m L_WHITE = \e[1;37m L_BLUE = \e[1;34m L_RED = \e[1;31m L_NRM = \e[0;00m DATE = `date +%d-%m-%Y` FILES = $(wildcard $(SRC_DIR)*.cpp) C_FILES = $(sort $(FILES)) O_FILES = $(patsubst $(SRC_DIR)%.cpp, $(OBJ_DIR)%.o, $(C_FILES)) all: @$(ECHOCMD) " Compiling $(L_RED)$(MUD_EXE)$(L_NRM)."; @$(MAKE) -s build build: $(O_FILES) @rm -f $(MUD_EXE) $(COMPILER) -o $(MUD_EXE) $(L_FLAGS) $(O_FILES) @echo " Finished Compiling $(MUD_EXE)."; @chmod g+w $(MUD_EXE) @chmod a+x $(MUD_EXE) @chmod g+w $(O_FILES) $(OBJ_DIR)%.o: $(SRC_DIR)%.cpp @echo " Compiling $@"; $(COMPILER) -c $(C_FLAGS) $< -o $@ .cpp.o: $(COMPILER) -c $(C_FLAGS) $< clean: @echo " Complete compile on $(MUD_EXE)."; @rm -f $(OBJ_DIR)*.o $(MUD_EXE) @$(MAKE) -s build I like the functionality of the Makefile, instead of spitting out all the arguments etc, it just spits out the "Compiling [Filename]" etc. If I add -c to the L_FLAGS then it compiles (I think) but instead spits out stuff like: g++: Obj/Database.o: linker input file unused because linking not done After a full day of trying and research on google, I'm no closer to solving my problem, so I come to you guys to see if you can explain to me why all this is happening and if possible, steps to solve. Regards, Steve

    Read the article

  • SVG via dynamic XML+XSL

    - by Daniel
    This is a bit of a vague notion which I have been running over in my head, and which I am very curious if there is an elegant method of solving. Perhaps it should be taken as a thought experiment. Imagine you have an XML schema with a corresponding XSL transform, which renders the XML as SVG in the browser. The XSL generates SVG with appropriate Javascript handlers that, ultimately, implement editing-like functionality such that properties of the objects or their locations on the SVG canvas can be edited by the user. For instance, an element can be dragged from one location to another. Now, this isn't particularly difficult - the drag/drop example is simply a matter of changing the (x,y) coordinates of the SVG object, or a resize operation would be a simple matter of changing its width or height. But is there an elegant way to have Javascript work on the DOM of the source XML document instead of the rendered SVG? Why, you ask? Well, imagine you have very complex XSL transforms, where the modification of one property results in complex changes to the SVG. You want to maintain simplicity in your Javascript code, but also a simple way to persist the modified XML back to the server. Some possibilities of how this may function: After modification of the source DOM, simply re-run the XSL transform and replace the original. Downside: brute force, potentially expensive operation. Create id/class naming conventions in the source and target XML/SVG so elements can be related back to each other, and do an XSL transform on only a subset of the new DOM. In other words, modify temporary DOM, apply XSL to it, remove changed elements from SVG, and insert the new one. Downside: May not be possible to apply XSL to temporary in-browser DOMs(?). Also, perhaps a bit convoluted or ugly to maintain. I think that it may be possible to come up with a framework that handles the second scenario, but the challenge would be making it lightweight and not heavily tied to the actual XML schema. Any ideas or other possibilities? Or is there maybe an existing method of doing this which I'm not aware of? UPDATE: To clarify, as I mentioned in a comment below, this aids in separating the draw code from the edit code. For a more concrete example of how this is useful, imagine an element which determines how it is drawn dependent on the value of a property of an adjacent element. It's better to condense that logic directly in the draw code instead of also duplicating it in the edit code.

    Read the article

  • Calculate minimum moves to solve a puzzle

    - by Luke
    I'm in the process of creating a game where the user will be presented with 2 sets of colored tiles. In order to ensure that the puzzle is solvable, I start with one set, copy it to a second set, then swap tiles from one set to another. Currently, (and this is where my issue lies) the number of swaps is determined by the level the user is playing - 1 swap for level 1, 2 swaps for level 2, etc. This same number of swaps is used as a goal in the game. The user must complete the puzzle by swapping a tile from one set to the other to make the 2 sets match (by color). The order of the tiles in the (user) solved puzzle doesn't matter as long as the 2 sets match. The problem I have is that as the number of swaps I used to generate the puzzle approaches the number of tiles in each set, the puzzle becomes easier to solve. Basically, you can just drag from one set in whatever order you need for the second set and solve the puzzle with plenty of moves left. What I am looking to do is after I finish building the puzzle, calculate the minimum number of moves required to solve the puzzle. Again, this is almost always less than the number of swaps used to create the puzzle, especially as the number of swaps approaches the number of tiles in each set. My goal is to calculate the best case scenario and then give the user a "fudge factor" (i.e. 1.2 times the minimum number of moves). Solving the puzzle in under this number of moves will result in passing the level. A little background as to how I currently have the game configured: Levels 1 to 10: 9 tiles in each set. 5 different color tiles. Levels 11 to 20: 12 tiles in each set. 7 different color tiles. Levels 21 to 25: 15 tiles in each set. 10 different color tiles. Swapping within a set is not allowed. For each level, there will be at least 2 tiles of a given color (one for each set in the solved puzzle). Is there any type of algorithm anyone could recommend to calculate the minimum number of moves to solve a given puzzle?

    Read the article

  • Model Binding with Parent/Child Relationship

    - by user296297
    I'm sure this has been answered before, but I've spent the last three hours looking for an acceptable solution and have been unable to find anything, so I apologize for what I'm sure is a repeat. I have two domain objects, Player and Position. Player's have a Position. My domain objects are POCOs tied to my database with NHibernate. I have an Add action that takes a Player, so I'm using the built in model binding. On my view I have a drop down list that lets a user select the Position for the Player. The value of the drop down list is the Id of the position. Everything gets populated correctly except that my Position object fails validation (ModelState.IsValid) because at the point of model binding it only has an Id and none of it's other required attributes. What is the preferred solution for solving this with ASP.NET MVC 2? Solutions I've tried... Fetch the Position from the database based on the Id before ModelState.IsValid is called in the Add action of my controller. I can't get the model to run the validation again, so ModelState.IsValid always returns false. Create a custom ModelBinder that inherits from the default binder and fetch the Position from the database after the base binder is called. The ModelBinder seems to be doing the validation so if I use anything from the default binder I'm hosed. Which means I have to completely roll my own binder and grab every value from the form...this seems really wrong and inefficient for such a common use-case. Solutions I think might work, I just can't figure out how to do... Turn off the validation for the Position class when used in Player. Write a custom ModelBinder leverages the default binder for most of the property binding, but lets me get the Position from the database BEFORE the default binder runs validation. So, how do the rest of you solve this? Thanks, Dan P.S. In my opinion having a PositionId on Player just for this case is not a good solution. There has to be solvable in a more elegant fashion.

    Read the article

  • C++ SQLDriverConnect API

    - by harshalkreddy
    Hi, I am using visual studio 2008 and sql server 2008 for developing application(SQL server is in my system). I need to fetch some fields from the database. I am using the SQLDriverConnect API to connect to the database. If I use the "SQL_DRIVER_PROMPT" I will get pop window to select the data source. I don't want this window to appear. As per my understanding this window will appear if we provide insufficient information in the connection string. I think I have provided all the information. I am trying to connect with windows authentication. I tried different options but still no luck. Please help me in solving this problem. Below is the code that I am using: //******************************************************************************** // SQLDriverConnect_ref.cpp // compile with: odbc32.lib user32.lib #include <windows.h> #include <sqlext.h> int main() { SQLHENV henv; SQLHDBC hdbc; SQLHSTMT hstmt; SQLRETURN retcode; SQLWCHAR OutConnStr[255]; SQLSMALLINT OutConnStrLen; SQLCHAR ConnStrIn[255] = "DRIVER={SQL Server};SERVER=(local);DSN=MyDSN;DATABASE=MyDatabase;Trusted_Connection=yes;"; //SQLWCHAR *ConntStr =(SQLWCHAR *) "DRIVER={SQL Server};DSN=MyDSN;"; HWND desktopHandle = GetDesktopWindow(); // desktop's window handle // Allocate environment handle retcode = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv); // Set the ODBC version environment attribute if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO) { retcode = SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION, (SQLPOINTER*)SQL_OV_ODBC3, 0); // Allocate connection handle if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO) { retcode = SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc); // Set login timeout to 5 seconds if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO) { SQLSetConnectAttr(hdbc, SQL_LOGIN_TIMEOUT, (SQLPOINTER)5, 0); retcode = SQLDriverConnect( // SQL_NULL_HDBC hdbc, desktopHandle, (SQLWCHAR *)ConnStrIn, SQL_NTS, OutConnStr, 255, &OutConnStrLen, SQL_DRIVER_NOPROMPT); // Allocate statement handle if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO) { retcode = SQLAllocHandle(SQL_HANDLE_STMT, hdbc, &hstmt); // Process data if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO) { SQLFreeHandle(SQL_HANDLE_STMT, hstmt); } SQLDisconnect(hdbc); } SQLFreeHandle(SQL_HANDLE_DBC, hdbc); } } SQLFreeHandle(SQL_HANDLE_ENV, henv); } } //******************************************************************************** Thanks in advance, Harsha

    Read the article

  • How to handle very frequent updates to a Lucene index

    - by fsm
    I am trying to prototype an indexing/search application which uses very volatile indexing data sources (forums, social networks etc), here are some of the performance requirements, Very fast turn-around time (by this I mean that any new data (such as a new message on a forum) should be available in the search results very soon (less than a minute)) I need to discard old documents on a fairly regular basis to ensure that the search results are not dated. Last but not least, the search application needs to be responsive. (latency on the order of 100 milliseconds, and should support at least 10 qps) All of the requirements I have currently can be met w/o using Lucene (and that would let me satisfy all 1,2 and 3), but I am anticipating other requirements in the future (like search relevance etc) which Lucene makes easier to implement. However, since Lucene is designed for use cases far more complex than the one I'm currently working on, I'm having a hard time satisfying my performance requirements. Here are some questions, a. I read that the optimize() method in the IndexWriter class is expensive, and should not be used by applications that do frequent updates, what are the alternatives? b. In order to do incremental updates, I need to keep committing new data, and also keep refreshing the index reader to make sure it has the new data available. These are going to affect 1 and 3 above. Should I try duplicate indices? What are some common approaches to solving this problem? c. I know that Lucene provides a delete method, which lets you delete all documents that match a certain query, in my case, I need to delete all documents which are older than a certain age, now one option is to add a date field to every document and use that to delete documents later. Is it possible to do range queries on document ids (I can create my own id field since I think that the one created by lucene keeps changing) to delete documents? Is it any faster than comparing dates represented as strings? I know these are very open questions, so I am not looking for a detailed answer, I will try to treat all of your answers as suggestions and use them to inform my design. Thanks! Please let me know if you need any other information.

    Read the article

  • Webservice for uploading data: security considerations

    - by Philip Daubmeier
    Hi everyone! Im not sure about what authentification method I should use for my webservice. I've searched on SO, and found nothing that helped me. Preliminary Im building an application that uploads data from a local database to a server (running my webservice), where all records are merged and stored in a central database. I am currently binary serializing a DataTable, that holds a small fragment of the local database, where all uninteresting stuff is already filtered out. The byte[] (serialized DataTable), together with the userid and a hash of the users password is then uploaded to the webservice via SOAP. The application together with the webservice already work exactly like intended. The Problem The issue I am thinking about is now: What is if someone just sniffs the network traffic, 'steals' the users id and password hash to send his own SOAP message with modified data that corrupts my database? Options The approaches to solving that problem, I already thought of, are: Using ssl + certificates for establishing the connection: I dont really want to use ssl, I would prefer a simpler solution. After all, every information that is transfered to the webservice can be seen on the website later on. What I want to say is: there is no secret/financial/business-critical information, that has to be hidden. I think ssl would be sort of an overkill for that task. Encrypting the byte[]: I think that would be a performance killer, considering that the goal of the excercise was simply to authenticate the user. Hashing the users password together with the data: I kind of like the idea: Creating a checksum from the data, concatenating that checksum with the password-hash and hashing this whole thing again. That would assure the data was sent from this specific user, and the data wasnt modified. The actual question So, what do you think is the best approach in terms of meeting the following requirements? Rather simple solution (As it doesnt have to be super secure; no secret/business-critical information transfered) Easily implementable retrospectively (Dont want to write it all again :) ) Doesnt impact to much on performance What do you think of my prefered solution, the last one in the list above? Is there any alternative solution I didnt mention, that would fit better? You dont have to answer every question in detail. Just push me in the right direction. I very much appreciate every well-grounded opinion. Thanks in advance!

    Read the article

  • Java exercise - display table with 2d array

    - by TheHacker66
    I'm struggling to finish a java exercise, it involves using 2d arrays to dinamically create and display a table based on a command line parameter. Example: java table 5 +-+-+-+-+-+ |1|2|3|4|5| +-+-+-+-+-+ |2|3|4|5|1| +-+-+-+-+-+ |3|4|5|1|2| +-+-+-+-+-+ |4|5|1|2|3| +-+-+-+-+-+ |5|1|2|3|4| +-+-+-+-+-+ What i have done so far: public static void main(String[] args) { int num = Integer.parseInt(args[0]); String[][] table = new String[num*2+1][num]; int[] numbers = new int[num]; int temp = 0; for(int i=0; i<numbers.length; i++) numbers[i] = i+1; // wrong for(int i=0; i<table.length; i++){ for(int j=0; j<num;j++){ if(i%2!=0){ temp=numbers[0]; for(int k=1; k<numbers.length; k++){ numbers[k-1]=numbers[k]; } numbers[numbers.length-1]=temp; for(int l=0; l<numbers.length; l++){ table[i][j] = "|"+numbers[l]; } } else table[i][j] = "+-"; } } for(int i=0; i<table.length; i++){ for(int j=0; j<num; j++) System.out.print(table[i][j]); if(i%2==0) System.out.print("+"); else System.out.print("|"); System.out.println();} } This doesn't work, since it prints 1|2|3|4 in every row, which isn't what i need. I found the issue, and it's because the first for loop changes the array order more times than needed and basically it returns as it was at the beginning. I know that probably there's a way to achieve this by writing more code, but i always tend to nest as much as possible to "optimize" the code while i write it, so that's why i tried solving this exercise by using less variables and loops as possible. Thanks in advance for your help!

    Read the article

  • I always get stuck here... Divs not behaving properly (alignment issues)

    - by user345501
    Hi, I don't know why, after encountering this problem dozens of times, the answer always seems different and I can't seem to work my way through the problem-solving process, but here I am again with misaligned divs. I've got 3rows encasing columns. each row is to have (at least) 3 columns (and probably some nested divs down the line, but I'm not even there yet). I'm trying to make a fluid chunk in the center ultimately, with pretty corners. However, my top row is already showing signs of misbehaving. .O Please help with my silly questions! Cheers and thanks in advance! <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> </head> <style type="text/css"> #wrap { margin:auto; width:80%; height:75%; border: solid #066 1px;} #row1 { width:100%; height:10%; background:#F20; } #r1c1 { float:left; width:05%;} #r1c2 { float:left; width:80%} #r1c3 { clear:both; width:05%; } #row2 { float:none; width:100%; background:#0C6; } #r2c1 {} #r2c2 {} #r2c3 {} #row3 { width:100%; height:15%; background:#00F; clear:both; } #r3c1 {} #r3c2 {} #r3c3 {} </style> <body> <div id="wrap"> <div id="row1"> <div id="r1c1">LEFT</div> <div id="r1c2">CENT</div> <div id="r1c3">RIGHT</div> </div> <div id="row2"> MIDDLE </div> <div id="row3"> BOTTOM </div> </div> </body> </html>

    Read the article

  • Programmatically triggering events in Javascript for IE using jQuery

    - by Dan Herbert
    When an Event is triggered by a user in IE, it is set to the window.event object. The only way to see what triggered the event is by accessing the window.event object (as far as I know) This causes a problem in ASP.NET validators if an event is triggered programmatically, like when triggering an event through jQuery. In this case, the window.event object stores the last user-triggered event. When the onchange event is fired programmatically for a text box that has an ASP.NET validator attached to it, the validation breaks because it is looking at the element that fired last event, which is not the element the validator is for. Does anyone know a way around this? It seems like a problem that is solvable, but from looking online, most people just find ways to ignore the problem instead of solving it. To explain what I'm doing specifically: I'm using a jQuery time picker plugin on a text box that also has 2 ASP.NET validators associated with it. When the time is changed, I'm using an update panel to post back to the server to do some things dynamically, so I need the onchange event to fire in order to trigger the postback for that text box. The jQuery time picker operates by creating a hidden unordered list that is made visible when the text box is clicked. When one of the list items is clicked, the "change" event is fired programmatically for the text box through jQuery's change() method. Because the trigger for the event was a list item, IE sees the list item as the source of the event, not the text box, like it should. I'm not too concerned with this ASP.NET validator working as soon as the text box is changed, I just need the "change" event to be processed so my postback event is called for the text box. The problem is that the validator throws an exception in IE which stops any event from being triggered. Firefox (and I assume other browsers) don't have this issue. Only IE due to the different event model. Has anyone encountered this and seen how to fix it? I've found this problem reported several other places, but they offer no solutions: jQuery's forum, with the jQuery UI Datepicker and an ASP.NET Validator ASP.NET forums, bug with ValidatorOnChange() function

    Read the article

  • c++ recursion with arrays

    - by Sam
    I have this project that I'm working on for a class, and I'm not looking for the answer, but maybe just a few tips since I don't feel like I'm using true recursion. The problem involves solving the game of Hi Q or "peg solitaire" where you want the end result to be one peg remaining (it's played with a triangular board and one space is open at the start.) I've represented the board with a simple array, each index being a spot and having a value of 1 if it has a peg, and 0 if it doesn't and also the set of valid moves with a 2 dimensional array that is 36, 3 (each move set contains 3 numbers; the peg you're moving, the peg it hops over, and the destination index.) So my problem is that in my recursive function, I'm using a lot of iteration to determine things like which space is open (or has a value of 0) and which move to use based on which space is open by looping through the arrays. Secondly, I don't understand how you would then backtrack with recursion, in the event that an incorrect move was made and you wanted to take that move back in order to choose a different one. This is what I have so far; the "a" array represents the board, the "b" array represents the moves, and the "c" array was my idea of a reminder as to which moves I used already. The functions used are helper functions that basically just loop through the arrays to find an empty space and corresponding move. : void solveGame(int a[15], int b[36][3], int c[15][3]){ int empSpace; int moveIndex; int count = 0; if(pegCount(a) < 2){ return; } else{ empSpace = findEmpty(a); moveIndex = chooseMove( a, b, empSpace); a[b[moveIndex][0]] = 0; a[b[moveIndex][1]] = 0; a[b[moveIndex][2]] = 1; c[count][0] = b[moveIndex][0]; c[count][1] = b[moveIndex][1]; c[count][2] = b[moveIndex][2]; solveGame(a,b,c); } }

    Read the article

  • Representation of a DateTime as the local to remote user

    - by TwoSecondsBefore
    Hello! I was confused in the problem of time zones. I am writing a web application that will contain some news with dates of publication, and I want the client to see the date of publication of the news in the form of corresponding local time. However, I do not know in which time zone the client is located. I have three questions. I have to ask just in case: does DateTimeOffset.UtcNow always returns the correct UTC date and time, regardless of whether the server is dependent on daylight savings time? For example, if the first time I get the value of this property for two minutes before daylight savings time (or before the transition from daylight saving time back) and the second time in 2 minutes after the transfer, whether the value of properties in all cases differ by only 4 minutes? Or here require any further logic? (Question #1) Please see the following example and tell me what you think. I posted the news on the site. I assume that DateTimeOffset.UtcNow takes into account the time zone of the server and the daylight savings time, and so I immediately get the correct UTC server time when pressing the button "Submit". I write this value to a MS SQL database in the field of type datetime2(0). Then the user opens a page with news and no matter how long after publication. This may occur even after many years. I did not ask him to enter his time zone. Instead, I get the offset of his current local time from UTC using the javascript function following way: function GetUserTimezoneOffset() { var offset = new Date().getTimezoneOffset(); return offset; } Next I make the calculation of the date and time of publication, which will show the user: public static DateTime Get_Publication_Date_In_User_Local_DateTime( DateTime Publication_Utc_Date_Time_From_DataBase, int User_Time_Zone_Offset_Returned_by_Javascript) { int userTimezoneOffset = User_Time_Zone_Offset_Returned_by_Javascript; // For // example Javascript returns a value equal to -300, which means the // current user's time differs from UTC to 300 minutes. Ie offset // is UTC +6. In this case, it may be the time zone UTC +5 which // currently operates summer time or UTC +6 which currently operates the // standard time. // Right? (Question #2) DateTimeOffset utcPublicationDateTime = new DateTimeOffset(Publication_Utc_Date_Time_From_DataBase, new TimeSpan(0)); // get an instance of type DateTimeOffset for the // date and time of publication for further calculations DateTimeOffset publication_DateTime_In_User_Local_DateTime = utcPublicationDateTime.ToOffset(new TimeSpan(0, - userTimezoneOffset, 0)); return publication_DateTime_In_User_Local_DateTime.DateTime;// return to user } Is the value obtained correct? Is this the right approach to solving this problem? (Question #3)

    Read the article

  • Big O Complexity of a method

    - by timeNomad
    I have this method: public static int what(String str, char start, char end) { int count=0; for(int i=0;i<str.length(); i++) { if(str.charAt(i) == start) { for(int j=i+1;j<str.length(); j++) { if(str.charAt(j) == end) count++; } } } return count; } What I need to find is: 1) What is it doing? Answer: counting the total number of end occurrences after EACH (or is it? Not specified in the assignment, point 3 depends on this) start. 2) What is its complexity? Answer: the first loops iterates over the string completely, so it's at least O(n), the second loop executes only if start char is found and even then partially (index at which start was found + 1). Although, big O is all about worst case no? So in the worst case, start is the 1st char & the inner iteration iterates over the string n-1 times, the -1 is a constant so it's n. But, the inner loop won't be executed every outer iteration pass, statistically, but since big O is about worst case, is it correct to say the complexity of it is O(n^2)? Ignoring any constants and the fact that in 99.99% of times the inner loop won't execute every outer loop pass. 3) Rewrite it so that complexity is lower. What I'm not sure of is whether start occurs at most once or more, if once at most, then method can be rewritten using one loop (having a flag indicating whether start has been encountered and from there on incrementing count at each end occurrence), yielding a complexity of O(n). In case though, that start can appear multiple times, which most likely it is, because assignment is of a Java course and I don't think they would make such ambiguity. Solving, in this case, is not possible using one loop... WAIT! Yes it is..! Just have a variable, say, inc to be incremented each time start is encountered & used to increment count each time end is encountered after the 1st start was found: inc = 0, count = 0 if (current char == start) inc++ if (inc > 0 && current char == end) count += inc This would also yield a complexity of O(n)? Because there is only 1 loop. Yes I realize I wrote a lot hehe, but what I also realized is that I understand a lot better by forming my thoughts into words...

    Read the article

< Previous Page | 60 61 62 63 64 65 66 67 68 69  | Next Page >