Search Results

Search found 4704 results on 189 pages for 'refactoring databases'.

Page 19/189 | < Previous Page | 15 16 17 18 19 20 21 22 23 24 25 26  | Next Page >

  • Replication keeps popping up on SharePoint databases

    - by Ddono25
    My typical discovery scenario: We receive an alert that the transaction log is growing quickly. We are in Simple Recovery so I go to check it out. Log is already sized to 100GB and is at 80% capacity. I run the "Whats using my log files" script from SQL Server Central and see that Replication is enabled on the database. We do not set up replication, and I don't think Replication can be done on SharePoint content db's as Replication is not supported (requires PK on all tables). This has been occurring on random servers (about 5 so far, all within the past three weeks) and it only occurs on Content Databases. sp_removedbreplication does not always work in removing the Replication either. We have found that we need to run the sp_removedbreplication, change all db owners to SA and reset Recovery Mode to Simple to completely eradicate any vestiges of this bug. How would Replication be enabling itself? We have never set up Replication on these servers. There is no evidence of any type of Replication other than the 'log_reuse_wait_desc' from the DMV query and log growth. Any help on this ghost would be appreciated!

    Read the article

  • How do you remove functionality from a program in ruby?

    - by Andrew Grimm
    You have some code you want to remove associated with an obsolete piece of functionality from a ruby project. How do ensure that you get rid of all of the code? Some guidelines that usually help in refactoring ruby apply, but there are added challenges because having code that isn't being called by anything won't break any unit tests.

    Read the article

  • Should I go back and fix work when you learn something new/better?

    - by SnOrfus
    Considering that we're all constantly learning, we've all got to come across a point where we learn something just awesome that improves our code or parts of it significantly. The question is, when you've learned some new technique, strategy or whatever, do your or should you go back to code that you know works, but could be so much better/maintainable/faster/generally improved and implement this new knowledge? I understand the concept of "if it ain't broke, don't fix it" but when does that become losing pride in code you've already written and what does it say for refactoring.

    Read the article

  • What should every developer know about databases?

    - by Aaronaught
    Whether we like it or not, many if not most of us developers either regularly work with databases or may have to work with one someday. And considering the amount of misuse and abuse in the wild, and the volume of database-related questions that come up every day, it's fair to say that there are certain concepts that developers should know - even if they don't design or work with databases today. So: What are the important concepts that developers and other software professionals ought to know about databases? Guidelines for Responses: Keep your list short. One concept per answer is best. Be specific. "Data modelling" may be an important skill, but what does that mean precisely? Explain your rationale. Why is your concept important? Don't just say "use indexes." Don't fall into "best practices." Convince your audience to go learn more. Upvote answers you agree with. Read other people's answers first. One high-ranked answer is a more effective statement than two low-ranked ones. If you have more to add, either add a comment or reference the original. Don't downvote something just because it doesn't apply to you personally. We all work in different domains. The objective here is to provide direction for database novices to gain a well-founded, well-rounded understanding of database design and database-driven development, not to compete for the title of most-important.

    Read the article

  • Can't see *all* databases in a remote SQL Server instance

    - by George
    Yesterday I posted a related question on StackOverflow. This problem involved not being able to see a SQL Server 2008 instance on another PC. I am not sure why adding the port number enabled me to see a SQL Server that I could not otherwise see, since the port number that I specified was, after all, the default port. Now I notice that I have another problem. While I can connect to the remote SQL 2008 Server instance, I cannot see all the databases in the instance. I am trying to connect to the 2008 instance from another PC using SQL Server 2008 Mgt Studio. I am connecting from a Windows 7 Ultimate PC to a Windows XP Pro PC. I suspect that my problem has something to do with not all database in the remote instance having the same version. For example, I "upgraded" a a SL 2005 database to 2008 by doing a backup frm 2005 and importing it into 2008. When I realized that this was not one of the database that I could see from my other PC, I noticed that the compatability level of the imported was still 2005, so I changed it to 2008. Still I could not see the database. I am sure that this is relevant: I just noticed that on my remote server, the sql node instance node, named "sql2008" says "version 10" when I am on the remote serfver, but when I connect to the sql2008 remote instance fron my local PC, the connection is shown locally as being a "SQL Servr version 8.0" instance. I suspect that locally, I am only being shown databases that are somehow in the remote 2008 instance but have not been upgraded. I guess I don't know what constitutes an upgraded database and I don not know who to connect to see all the databases, even if this requires multiple connections from the source PC.

    Read the article

  • Refactoring multiple interfaces to a common interface using MVVM, MEF and Silverlight4

    - by Brian
    I am just learning MVVM with MEF and already see the benefits but I am a little confused about some implementation details. The app I am building has several Models that do the same with with different entities (WCF RIA Services exposing a Entity framework object) and I would like to avoid implementing a similar interface/model for each view I need and the following is what I have come up with though it currently doesn't work. The common interface has a new completed event for each model that implements the base model, this was the easiest way I could implement a common class as the compiler did not like casting from a child to the base type. The code as it currently sits compiles and runs but the is a null IModel being passed into the [ImportingConstructor] for the FaqViewModel class. I have a common interface (simplified for posting) defined as follows, this should look familiar to those who have seen Shawn Wildermuth's RIAXboxGames sample. public interface IModel { void GetItemsAsync(); event EventHandler<EntityResultsArgs<faq>> GetFaqsComplete; } A base method that implements the interface public class ModelBase : IModel { public virtual void GetItemsAsync() { } public virtual event EventHandler<EntityResultsArgs<faq>> GetFaqsComplete; protected void PerformQuery<T>(EntityQuery<T> qry, EventHandler<EntityResultsArgs<T>> evt) where T : Entity { Context.Load(qry, r => { if (evt == null) return; try { if (r.HasError) { evt(this, new EntityResultsArgs<T>(r.Error)); } else if (r.Entities.Count() > 0) { evt(this, new EntityResultsArgs<T>(r.Entities)); } } catch (Exception ex) { evt(this, new EntityResultsArgs<T>(ex)); } }, null); } private DomainContext _domainContext; protected DomainContext Context { get { if (_domainContext == null) { _domainContext = new DomainContext(); _domainContext.PropertyChanged += DomainContext_PropertyChanged; } return _domainContext; } } void DomainContext_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { switch (e.PropertyName) { case "IsLoading": AppMessages.IsBusyMessage.Send(_domainContext.IsLoading); break; case "IsSubmitting": AppMessages.IsBusyMessage.Send(_domainContext.IsSubmitting); break; } } } A model that implements the base model [Export(ViewModelTypes.FaqViewModel, typeof(IModel))] public class FaqModel : ModelBase { public override void GetItemsAsync() { PerformQuery(Context.GetFaqsQuery(), GetFaqsComplete); } public override event EventHandler<EntityResultsArgs<faq>> GetFaqsComplete; } A view model [PartCreationPolicy(CreationPolicy.NonShared)] [Export(ViewModelTypes.FaqViewModel)] public class FaqViewModel : MyViewModelBase { private readonly IModel _model; [ImportingConstructor] public FaqViewModel(IModel model) { _model = model; _model.GetFaqsComplete += Model_GetFaqsComplete; _model.GetItemsAsync(); // Load FAQS on creation } private IEnumerable<faq> _faqs; public IEnumerable<faq> Faqs { get { return _faqs; } private set { if (value == _faqs) return; _faqs = value; RaisePropertyChanged("Faqs"); } } private faq _currentFaq; public faq CurrentFaq { get { return _currentFaq; } set { if (value == _currentFaq) return; _currentFaq = value; RaisePropertyChanged("CurrentFaq"); } } public void GetFaqsAsync() { _model.GetItemsAsync(); } void Model_GetFaqsComplete(object sender, EntityResultsArgs<faq> e) { if (e.Error != null) { ErrorMessage = e.Error.Message; } else { Faqs = e.Results; } } } And then finally the Silverlight view itself public partial class FrequentlyAskedQuestions { public FrequentlyAskedQuestions() { InitializeComponent(); if (!ViewModelBase.IsInDesignModeStatic) { // Use MEF To load the View Model CompositionInitializer.SatisfyImports(this); } } [Import(ViewModelTypes.FaqViewModel)] public object ViewModel { set { DataContext = value; } } }

    Read the article

  • Refactoring Bloated ViewModel

    - by Holy Christ
    Hi, I am writing a PRISM/MVVM/WPF application. It's a LOB application, so there are a lot of complicated rules. I've noticed the View Model is starting to get bloated. There are two main issues. One is that to maintain MVVM, I'm doing a lot of things that feel hacky like adding a bunch of properties to my VM. The view binds to those properties to keep track of what feels like view specific information. For example, a boolean keeping track of the status of a long running process in the VM, so the view can disable some of its controls while the long running process is working. I've read that this issue could be solved with Attached Behaviors. I'll look more into that. In the example MVVM apps you see online, this isn't a big deal because they are over-simplified. The other issue is the number of commands in my VM. Right now there are four commands. I'm defining the commands in the VM using Josh Smith's RelayCommand (basically the DelegateCommand in PRISM) so all the business logic lives in the VM. I considered moving each command into separate unit of works. I'm not sure the best way to do this. Which patterns are you guys using to keep your VMs clean? I can already feel someone responding with "your view and VM is too complicated, you should break them into many view/VMs". It is certainly not too complicated from a Ux perspective - there are 2 buttons, a combobox, and a listbox. Also, from a logical perspective, it is one cohesive domain. Having said that, I'm very interested in hearing how others are dealing with this type of issue. Thanks for your input.

    Read the article

  • ruby on rails, searchlogic and refactoring

    - by JohnMerlino
    Hey all, I'mt not too familiar with searchlogic plugin for rails (I did view the railscasts but wasn't helpful in relation to the specific code below). Can anyone briefly describe how it is being used in the three methods below? Thanks for any response. def extract_order @order_by = if params[:order].present? field = params[:order].gsub(".", "_") field = field.starts_with?('-') ? 'descend_by_'+field[1..-1] : 'ascend_by_'+field field.to_sym else # Workaround 'searchlogic'.to_sym end end def find_resources @search_conditions = params[:search_conditions] || {} # See http://www.binarylogic.com/2008/11/30/searchlogic-1-5-7-complex-searching-no-longer-a-problem/ @resources = @resource_model.send(@order_by).searchlogic(:conditions => @search_conditions) end def apply_filters f = filter_by f.each do |filter_field| filter_constraints = params[filter_field.to_sym] if filter_constraints.present? # Apply searchlogic's scope @resources.send(filter_field,filter_constraints) end end end

    Read the article

  • Refactoring ADO.NET - SqlTransaction vs. TransactionScope

    - by marc_s
    I have "inherited" a little C# method that creates an ADO.NET SqlCommand object and loops over a list of items to be saved to the database (SQL Server 2005). Right now, the traditional SqlConnection/SqlCommand approach is used, and to make sure everything works, the two steps (delete old entries, then insert new ones) are wrapped into an ADO.NET SqlTransaction. using (SqlConnection _con = new SqlConnection(_connectionString)) { using (SqlTransaction _tran = _con.BeginTransaction()) { try { SqlCommand _deleteOld = new SqlCommand(......., _con); _deleteOld.Transaction = _tran; _deleteOld.Parameters.AddWithValue("@ID", 5); _con.Open(); _deleteOld.ExecuteNonQuery(); SqlCommand _insertCmd = new SqlCommand(......, _con); _insertCmd.Transaction = _tran; // add parameters to _insertCmd foreach (Item item in listOfItem) { _insertCmd.ExecuteNonQuery(); } _tran.Commit(); _con.Close(); } catch (Exception ex) { // log exception _tran.Rollback(); throw; } } } Now, I've been reading a lot about the .NET TransactionScope class lately, and I was wondering, what's the preferred approach here? Would I gain anything (readibility, speed, reliability) by switching to using using (TransactionScope _scope = new TransactionScope()) { using (SqlConnection _con = new SqlConnection(_connectionString)) { .... } _scope.Complete(); } What you would prefer, and why? Marc

    Read the article

  • Accessing Oracle 6i and 9i/10g Databases using C#

    - by Mike M
    Hi all, I am making two build files using NAnt. The first aims to automatically compile Oracle 6i forms and reports and the second aims to compile Oracle 9i/10g forms and reports. Within the NAnt task is a C# script which prompts the developer for database credentials (username, password, database) in order to compile the forms and reports. I want to then run these credentials against the relevant database to ensure the credentials entered are correct and, if they are not, prompt the user to re-enter their credentials. My script currently looks as follows: class GetInput { public static void ScriptMain(Project project) { Console.Clear(); Console.WriteLine("==================================================================="); Console.WriteLine("Welcome to the Compile and Deploy Oracle Forms and Reports Facility"); Console.WriteLine("==================================================================="); Console.WriteLine(); Console.WriteLine("Please enter the acronym of the project to work on from the following list:"); Console.WriteLine(); Console.WriteLine("--------"); Console.WriteLine("- BCS"); Console.WriteLine("- COPEN"); Console.WriteLine("- FCDD"); Console.WriteLine("--------"); Console.WriteLine(); Console.Write("Selection: "); project.Properties["project.type"] = Console.ReadLine(); Console.WriteLine(); Console.Write("Please enter username: "); string username = Console.ReadLine(); project.Properties["username"] = username; string password = ReturnPassword(); project.Properties["password"] = password Console.WriteLine(); Console.Write("Please enter database: "); string database = Console.ReadLine(); project.Properties["database"] = database Console.WriteLine(); //Call method to verify user credentials Console.WriteLine(); Console.WriteLine("Compiling files..."; } public static string ReturnPassword() { Console.Write("Please enter password: "); string password = ""; ConsoleKeyInfo nextKey = Console.ReadKey(true); while (nextKey.Key != ConsoleKey.Enter) { if (nextKey.Key == ConsoleKey.Backspace) { if (password.Length > 0) { password = password.Substring(0, password.Length - 1); Console.Write(nextKey.KeyChar); Console.Write(" "); Console.Write(nextKey.KeyChar); } } else { password += nextKey.KeyChar; Console.Write("*"); } nextKey = Console.ReadKey(true); } return password; } } Having done a bit of research, I find that you can connect to Oracle databases using the System.Data.OracleClient namespace clicky. However, as mentioned in the link, Microsoft is discontinuing support for this so it is not a desireable solution. I have also fonud that Oracle provides its own classes for connecting to Oracle databases clicky. However, this only seems to support connecting to Oracle 9 or newer databases (clicky) so it is not feasible solution as I also need to connect to Oracle 6i databases. I could achieve this by calling a bat script from within the C# script, but I would much prefer to have a single build file for simplicity. Ideally, I would like to run a series of commands such as is contained in the following .bat script: rem -- Set Database SID -- set ORACLE_SID=%DBSID% sqlplus -s %nameofuser%/%password%@%dbsid% set cmdsep on set cmdsep '"'; --" set term on set echo off set heading off select '========================================' || CHR(10) || 'Have checked and found both Password and ' || chr(10) || 'Database Identifier are valid, continuing ...' || CHR(10) || '========================================' from dual; exit; This requires me to set the environment variable of ORACLE_SID and then run sqlplus in silent mode (-s) followed by a series of sql set commands (set x), the actual select statement and an exit command. Can I achieve this within a c# script without calling a bat script, or am I forced to call a bat script? Thanks in advance!

    Read the article

  • Code refactoring homework?

    - by Hira
    This is the code that I have to refactor for my homework: if (state == TEXAS) { rate = TX_RATE; amt = base * TX_RATE; calc = 2 * basis(amt) + extra(amt) * 1.05; } else if ((state == OHIO) || (state == MAINE)) { rate = (state == OHIO) ? OH_RATE : MN_RATE; amt = base * rate; calc = 2 * basis(amt) + extra(amt) * 1.05; if (state == OHIO) points = 2; } else { rate = 1; amt = base; calc = 2 * basis(amt) + extra(amt) * 1.05; } I have done something like this if (state == TEXAS) { rate = TX_RATE; calculation(rate); } else if ((state == OHIO) || (state == MAINE)) { rate = (state == OHIO) ? OH_RATE : MN_RATE; calculation(rate); if (state == OHIO) points = 2; } else { rate = 1; calculation(rate); } function calculation(rate) { amt = base * rate; calc = 2 * basis(amt) + extra(amt) * 1.05; } How could I have done better? Edit i have done code edit amt = base * rate;

    Read the article

  • Refactoring a C# derived class with method dependancies

    - by drelihan
    Hi Folks, I want to get your opinion on this. I have a class which is derived from a base class. I don't have control over the code in the base class and it is critical to the system that I derive from it. In my class I inherite two methods that are critical to the system and are used in pretty much every function, many times. I intend to refactor this derived class and extract some classes from it - this won't be a problem. What I'm not sure about is, is it worth extracting class if I have to constantly make call backs to my main class to access the two methods (or public wrappers to the methods)??? Thanks

    Read the article

  • C#: AutoFixture refactoring

    - by Thomas Jaskula
    Hello, I started to use AutoFixture http://autofixture.codeplex.com/ as my unit tests was bloated with a lot of data setup. I was spending more time on seting up the data than to write my unit test. Here's an example of how my initial unit test looks like (example taken from cargo application sample from DDD blue book) [Test] public void should_create_instance_with_correct_ctor_parameters() { var carrierMovements = new List<CarrierMovement>(); var deparureUnLocode1 = new UnLocode("AB44D"); var departureLocation1 = new Location(deparureUnLocode1, "HAMBOURG"); var arrivalUnLocode1 = new UnLocode("XX44D"); var arrivalLocation1 = new Location(arrivalUnLocode1, "TUNIS"); var departureDate1 = new DateTime(2010, 3, 15); var arrivalDate1 = new DateTime(2010, 5, 12); var carrierMovement1 = new CarrierMovement(departureLocation1, arrivalLocation1, departureDate1, arrivalDate1); var deparureUnLocode2 = new UnLocode("CXRET"); var departureLocation2 = new Location(deparureUnLocode2, "GDANSK"); var arrivalUnLocode2 = new UnLocode("ZEZD4"); var arrivalLocation2 = new Location(arrivalUnLocode2, "LE HAVRE"); var departureDate2 = new DateTime(2010, 3, 18); var arrivalDate2 = new DateTime(2010, 3, 31); var carrierMovement2 = new CarrierMovement(departureLocation2, arrivalLocation2, departureDate2, arrivalDate2); carrierMovements.Add(carrierMovement1); carrierMovements.Add(carrierMovement2); new Schedule(carrierMovements).ShouldNotBeNull(); } Here's how I tried to refactor it with AutoFixture [Test] public void should_create_instance_with_correct_ctor_parameters_AutoFixture() { var fixture = new Fixture(); fixture.Register(() => new UnLocode(UnLocodeString())); var departureLoc = fixture.CreateAnonymous<Location>(); var arrivalLoc = fixture.CreateAnonymous<Location>(); var departureDateTime = fixture.CreateAnonymous<DateTime>(); var arrivalDateTime = fixture.CreateAnonymous<DateTime>(); fixture.Register<Location, Location, DateTime, DateTime, CarrierMovement>( (departure, arrival, departureTime, arrivalTime) => new CarrierMovement(departureLoc, arrivalLoc, departureDateTime, arrivalDateTime)); var carrierMovements = fixture.CreateMany<CarrierMovement>(50).ToList(); fixture.Register<List<CarrierMovement>, Schedule>((carrierM) => new Schedule(carrierMovements)); var schedule = fixture.CreateAnonymous<Schedule>(); schedule.ShouldNotBeNull(); } private static string UnLocodeString() { var stringBuilder = new StringBuilder(); for (int i = 0; i < 5; i++) stringBuilder.Append(GetRandomUpperCaseCharacter(i)); return stringBuilder.ToString(); } private static char GetRandomUpperCaseCharacter(int seed) { return ((char)((short)'A' + new Random(seed).Next(26))); } I would like to know if there's better way to refactor it. Would like to do it shorter and easier than that. Thanks in advance for your help.

    Read the article

  • AutoFixture refactoring

    - by Thomas Jaskula
    I started to use AutoFixture http://autofixture.codeplex.com/ as my unit tests was bloated with a lot of data setup. I was spending more time on seting up the data than to write my unit test. Here's an example of how my initial unit test looks like (example taken from cargo application sample from DDD blue book) [Test] public void should_create_instance_with_correct_ctor_parameters() { var carrierMovements = new List<CarrierMovement>(); var deparureUnLocode1 = new UnLocode("AB44D"); var departureLocation1 = new Location(deparureUnLocode1, "HAMBOURG"); var arrivalUnLocode1 = new UnLocode("XX44D"); var arrivalLocation1 = new Location(arrivalUnLocode1, "TUNIS"); var departureDate1 = new DateTime(2010, 3, 15); var arrivalDate1 = new DateTime(2010, 5, 12); var carrierMovement1 = new CarrierMovement(departureLocation1, arrivalLocation1, departureDate1, arrivalDate1); var deparureUnLocode2 = new UnLocode("CXRET"); var departureLocation2 = new Location(deparureUnLocode2, "GDANSK"); var arrivalUnLocode2 = new UnLocode("ZEZD4"); var arrivalLocation2 = new Location(arrivalUnLocode2, "LE HAVRE"); var departureDate2 = new DateTime(2010, 3, 18); var arrivalDate2 = new DateTime(2010, 3, 31); var carrierMovement2 = new CarrierMovement(departureLocation2, arrivalLocation2, departureDate2, arrivalDate2); carrierMovements.Add(carrierMovement1); carrierMovements.Add(carrierMovement2); new Schedule(carrierMovements).ShouldNotBeNull(); } Here's how I tried to refactor it with AutoFixture [Test] public void should_create_instance_with_correct_ctor_parameters_AutoFixture() { var fixture = new Fixture(); fixture.Register(() => new UnLocode(UnLocodeString())); var departureLoc = fixture.CreateAnonymous<Location>(); var arrivalLoc = fixture.CreateAnonymous<Location>(); var departureDateTime = fixture.CreateAnonymous<DateTime>(); var arrivalDateTime = fixture.CreateAnonymous<DateTime>(); fixture.Register<Location, Location, DateTime, DateTime, CarrierMovement>( (departure, arrival, departureTime, arrivalTime) => new CarrierMovement(departureLoc, arrivalLoc, departureDateTime, arrivalDateTime)); var carrierMovements = fixture.CreateMany<CarrierMovement>(50).ToList(); fixture.Register<List<CarrierMovement>, Schedule>((carrierM) => new Schedule(carrierMovements)); var schedule = fixture.CreateAnonymous<Schedule>(); schedule.ShouldNotBeNull(); } private static string UnLocodeString() { var stringBuilder = new StringBuilder(); for (int i = 0; i < 5; i++) stringBuilder.Append(GetRandomUpperCaseCharacter(i)); return stringBuilder.ToString(); } private static char GetRandomUpperCaseCharacter(int seed) { return ((char)((short)'A' + new Random(seed).Next(26))); } I would like to know if there's better way to refactor it. Would like to do it shorter and easier than that.

    Read the article

  • How to Extract Properties for Refactoring

    - by Ngu Soon Hui
    I have this property public List<PointK> LineList {get;set;} Where PointK consists of the following structure: string Mark{get;set;} double X{get;set;} doible Y{get;set;} Now, I have the following code: private static Dictionary<string , double > GetY(List<PointK> points) { var invertedDictResult = new Dictionary<string, double>(); foreach (var point in points) { if (!invertedDictResult.ContainsKey(point.Mark)) { invertedDictResult.Add(point .Mark, Math.Round(point.Y, 4)); } } return invertedDictResult; } private static Dictionary<string , double > GetX(List<PointK> points) { var invertedDictResult = new Dictionary<string, double>(); foreach (var point in points) { if (!invertedDictResult.ContainsKey(point.Mark)) { invertedDictResult.Add(point .Mark, Math.Round(point.X, 4)); } } return invertedDictResult; } How to restructure the above code?

    Read the article

  • JavaScript regex refactoring

    - by JamesBrownIsDead
    I'm performing this on a string: var poo = poo .replace(/[%][<]/g, "'<") .replace(/[>][%]/g, ">'") .replace(/[%]\s*[+]/g, "'+") .replace(/[+]\s*[%]/g, "+'"); Given the similar if these statements, can these regexs be comebined somehow?

    Read the article

  • Refactoring a javascript array rotate function

    - by ideotop
    I wrote a rotate function, but I'm not satisfied with it: var pixels=['011','110','000']; var result=new Array(); result=['000','000','000']; for ( y=0; y<(pixels.length); y++ ){ for ( x=0; x<(pixels.length); x++ ){ var newx=0,newy=0; if ( clock ){ if ( x< r.x && y< r.y ) {newx=x+2;newy=y ;}//top left if ( x==r.x && y< r.y ) {newx=x+1;newy=y+1;}//top if ( x> r.x && y< r.y ) {newx=x ;newy=y+2;}//top right if ( x< r.x && y==r.y ) {newx=x+1;newy=y-1;}//left if ( x==r.x && y==r.y ) {newx=x ;newy=y ;}//center if ( x> r.x && y==r.y ) {newx=x-1;newy=y+1;}//right if ( x< r.x && y> r.y ) {newx=x ;newy=y-2;}//bottom left if ( x==r.x && y> r.y ) {newx=x-1;newy=y-1;}//bottom if ( x> r.x && y> r.y ) {newx=x-2;newy=y ;}//bottom right } else { if ( x< r.x && y< r.y ) {newx=x ;newy=y+2;}//top left if ( x==r.x && y< r.y ) {newx=x-1;newy=y+1;}//top if ( x> r.x && y< r.y ) {newx=x-2;newy=y ;}//top right if ( x< r.x && y==r.y ) {newx=x+1;newy=y+1;}//left if ( x==r.x && y==r.y ) {newx=x ;newy=y ;}//center if ( x> r.x && y==r.y ) {newx=x-1;newy=y-1;}//right if ( x< r.x && y> r.y ) {newx=x+2;newy=y ;}//bottom left if ( x==r.x && y> r.y ) {newx=x+1;newy=y-1;}//bottom if ( x> r.x && y> r.y ) {newx=x ;newy=y-2;}//bottom right } //inject(result,newx,newy,pixels[y][x]) } } does someone now how to write a cleaner code for this rotate (clock and counter-clock) function ?

    Read the article

  • Help me refactoring this nasty Ruby if/else statement

    - by Suborx
    Hello, so I have this big method in my application for newsletter distribution. Method is for updating rayons and i need to assigned user to rayon. I have relation n:n through table colporteur_in_rayons witch have attributes since_date and _until_date. I am junior programmer and i know this code is pretty dummy :) I appreciated every suggestion. def update rayon = Rayon.find(params[:id]) if rayon.update_attributes(params[:rayon]) if params[:user_id] != "" unless rayon.users.empty? unless rayon.users.last.id.eql?(params[:user_id]) rayon.colporteur_in_rayons.last.update_attributes(:until_date = Time.now) Rayon.assign_user(rayon.id,params[:user_id]) flash[:success] = "Rayon #{rayon.name} has been succesuly assigned to #{rayon.actual_user.name}." return redirect_to rayons_path end else Rayon.assign_user(rayon.id,params[:user_id]) flash[:success] = "Rayon #{rayon.name} has been successfully assigned to #{rayon.actual_user.name}." return redirect_to rayons_path end end flash[:success] = "Rayon has been successfully updated." return redirect_to rayons_path else flash[:error] = "Rayon has not been updated." return redirect_to :back end end

    Read the article

  • Java: JPA classes, refactoring from Date to DateTime

    - by bguiz
    With a table created using this SQL Create Table X ( ID varchar(4) Not Null, XDATE date ); and an entity class defined like so @Entity @Table(name = "X") public class X implements Serializable { @Id @Basic(optional = false) @Column(name = "ID", nullable = false, length = 4) private String id; @Column(name = "XDATE") @Temporal(TemporalType.DATE) private Date xDate; //java.util.Date ... } With the above, I can use JPA to achieve object relational mapping. However, the xDate attribute can only store dates, e.g. dd/MM/yyyy. How do I refactor the above to store a full date object using just one field, i.e. dd/MM/yyyy HH24:mm?

    Read the article

  • Refactoring a leaf class to a base class, and keeping it also a interface implementation

    - by elcuco
    I am trying to refactor a working code. The code basically derives an interface class into a working implementation, and I want to use this implementation outside the original project as a standalone class. However, I do not want to create a fork, and I want the original project to be able to take out their implementation, and use mine. The problem is that the hierarchy structure is very different and I am not sure if this would work. I also cannot use the original base class in my project, since in reality it's quite entangled in the project (too many classes, includes) and I need to take care of only a subdomain of the problems the original project is. I wrote this code to test an idea how to implement this, and while it's working, I am not sure I like it: #include <iostream> // Original code is: // IBase -> Derived1 // I need to refactor Derive2 to be both indipendet class // and programmers should also be able to use the interface class // Derived2 -> MyClass + IBase // MyClass class IBase { public: virtual void printMsg() = 0; }; /////////////////////////////////////////////////// class Derived1 : public IBase { public: virtual void printMsg(){ std::cout << "Hello from Derived 1" << std::endl; } }; ////////////////////////////////////////////////// class MyClass { public: virtual void printMsg(){ std::cout << "Hello from MyClass" << std::endl; } }; class Derived2: public IBase, public MyClass{ virtual void printMsg(){ MyClass::printMsg(); } }; class Derived3: public MyClass, public IBase{ virtual void printMsg(){ MyClass::printMsg(); } }; int main() { IBase *o1 = new Derived1(); IBase *o2 = new Derived2(); IBase *o3 = new Derived3(); MyClass *o4 = new MyClass(); o1->printMsg(); o2->printMsg(); o3->printMsg(); o4->printMsg(); return 0; } The output is working as expected (tested using gcc and clang, 2 different C++ implementations so I think I am safe here): [elcuco@pinky ~/src/googlecode/qtedit4/tools/qtsourceview/qate/tests] ./test1 Hello from Derived 1 Hello from MyClass Hello from MyClass Hello from MyClass [elcuco@pinky ~/src/googlecode/qtedit4/tools/qtsourceview/qate/tests] ./test1.clang Hello from Derived 1 Hello from MyClass Hello from MyClass Hello from MyClass The question is My original code was: class Derived3: public MyClass, public IBase{ virtual void IBase::printMsg(){ MyClass::printMsg(); } }; Which is what I want to express, but this does not compile. I must admit I do not fully understand why this code work, as I expect that the new method Derived3::printMsg() will be an implementation of MyClass::printMsg() and not IBase::printMsg() (even tough this is what I do want). How does the compiler chooses which method to re-implement, when two "sister classes" have the same virtual function name? If anyone has a better way of implementing this, I would like to know as well :)

    Read the article

  • Refactoring or Rewriting Monolithic PHP Spaghetti Codebase

    - by nategood
    I've inherited a really poorly designed PHP spaghetti code project. It's been gaining a good bit of traffic recently and is starting to have performance issues on top of the poor monolithic code base. Its maxing out performance on a chunky 16GB dedicated machine when it really shouldn't be. I'm planning on doing some performance tweaks right off the bat to help the performance issue, but this still won't really help the horrible code base. The team is small but expecting to grow very soon. I've read Joel's article on the troubles of doing a complete rewrite and see the concerns. But how bad does the code base have to be before you consider a rewrite? There is PHP handling logic interjected into what one would usually consider a "view". Even worse, in some places SQL statements are in these same files! The only real separation of presentation and logic are a few PHP scripts that serve as function libraries. These scripts do most of the ORM stuff... if you can even call it that. Trying to slowly refractor this seems like a nightmare. Open to your thoughts and opinions... however not interested in hearing, "Run away, Run away!".

    Read the article

  • Refactoring routes - serving different layouts

    - by dmclark
    As a Rails NOOB, I started with a routes.rb of: ActionController::Routing::Routes.draw do |map| map.resources :events map.connect 'affiliates/list', :controller => "affiliates", :action => "list" map.connect 'affiliates/regenerate_thumb/:id', :controller => "affiliates", :action => "regenerate_thumb" map.connect 'affiliates/state/:id.:format', :controller => "affiliates", :action => "find_by_state" map.connect 'affiliates/getfeed', :controller => "affiliates", :action => "feed" map.resources :affiliates, :has_many => :events map.connect ":controller/:action" map.connect '', :controller => "affiliates" map.connect ":controller/:action/:id" map.connect ":controller/:action/:id/:format" end and i'm trying to tighten it up. and I've gotten as far as: ActionController::Routing::Routes.draw do |map| map.resources :events, :only => "index" map.resources :affiliates do |affiliates| affiliates.resources :has_many => :events affiliates.resources :collection => { :list => :get, :regenerate_thumb => "regenerate_thumb" } end # map.connect 'affiliates/regenerate_thumb/:id', :controller => "affiliates", :action => "regenerate_thumb" map.connect 'affiliates/state/:id.:format', :controller => "affiliates", :action => "find_by_state" map.connect 'affiliates/getfeed', :controller => "affiliates", :action => "feed" map.root :affiliates end what is confusing to me is routes vs parameters.. For example, I realized that the only difference between list and index is HOW it is rendered, rather than WHAT is rendered. Having a different action (as I do now) feels wrong but I can't figure out he right way. Thanks

    Read the article

< Previous Page | 15 16 17 18 19 20 21 22 23 24 25 26  | Next Page >