Daily Archives

Articles indexed Saturday September 15 2012

Page 7/13 | < Previous Page | 3 4 5 6 7 8 9 10 11 12 13  | Next Page >

  • How to save data of two for loops in one array?

    - by Homer_Simpson
    I have two for loops and I wanna save that data in one array. The first for loop will create 5 rectangles in the array. After that, the second for loop will create 5 rectangles and add them to the array. But something doesn't work. I get that "Index was outside the bounds of the array" error message in the last line of the code and I don't know what to change. int framewidth = texture.Width / sourceRects.Length; int frameheight = texture.Height; private void vorrück(Rectangle[] sourceRects, int framewidth, int frameheight) { int doublelenght = sourceRects.Length * 2; for (int i = 0; i < sourceRects.Length; i++) sourceRects[i] = new Rectangle(i * framewidth, 0, framewidth, frameheight); for (int normallenght = sourceRects.Length; normallenght < doublelenght; normallenght++) sourceRects[normallenght] = new Rectangle((sourceRects.Length - 1 - normallenght) * framewidth, 0, framewidth, frameheight); }

    Read the article

  • Erro while join table in SQL

    - by Color Shadow
    I have two tables that have relationship with UserName field. Based on UserName column, I want to get ID from CarReserve table. Here is my SQL statement: SELECT CarReserve.ID FROM CarReserve INNER JOIN aspnet_Users ON CarReserve.UserName = aspnet_Users.UserName WHERE UserName = @UserName Unfortunately, I am getting this warning: Ambiguous column name "UserName" Can anyone here tell me what is wrong with my statement?

    Read the article

  • Mysql Query is not working, why?

    - by Furkan Kadioglu
    Im using this example: www.jtable.org Now i download to jtable php version. And i edited script. Jtable simple version is working but my edition is doesnt working. I can do list, but i cant do add a row; this codes having problem. But php doesnt giving any error. else if($_GET["action"] == "create") { //Insert record into database $result = mysql_query("INSERT INTO veriler(bolge, sehir, firma, adres, tel, web) VALUES('" . $_POST["bolge"] . "', '" . $_POST["sehir"] . "', '" . $_POST["firma"] . "', '" . $_POST["adres"] . "', '" . $_POST["tel"] . "', '" . $_POST["web"] . "'"); //Get last inserted record (to return to jTable) $result = mysql_query("SELECT * FROM veriler WHERE id = LAST_INSERT_ID();"); $row = mysql_fetch_array($result); //Return result to jTable $jTableResult = array(); $jTableResult['Result'] = "OK"; $jTableResult['Record'] = $row; print json_encode($jTableResult); } if you doesnt understand, please ask me question. Where is the problem?

    Read the article

  • Insert not working

    - by user1642318
    I've searched evreywhere and tried all suggestions but still no luck when running the following code. Note that some code is commented out. Thats just me trying different things. SqlConnection connection = new SqlConnection("Data Source=URB900-PC\SQLEXPRESS;Initial Catalog=usersSQL;Integrated Security=True"); string password = PasswordTextBox.Text; string email = EmailTextBox.Text; string firstname = FirstNameTextBox.Text; string lastname = SurnameTextBox.Text; //command.Parameters.AddWithValue("@UserName", username); //command.Parameters.AddWithValue("@Password", password); //command.Parameters.AddWithValue("@Email", email); //command.Parameters.AddWithValue("@FirstName", firstname); //command.Parameters.AddWithValue("@LastName", lastname); command.Parameters.Add("@UserName", SqlDbType.VarChar); command.Parameters["@UserName"].Value = username; command.Parameters.Add("@Password", SqlDbType.VarChar); command.Parameters["@Password"].Value = password; command.Parameters.Add("@Email", SqlDbType.VarChar); command.Parameters["@Email"].Value = email; command.Parameters.Add("@FirstName", SqlDbType.VarChar); command.Parameters["@FirstName"].Value = firstname; command.Parameters.Add("@LasttName", SqlDbType.VarChar); command.Parameters["@LasttName"].Value = lastname; SqlCommand command2 = new SqlCommand("INSERT INTO users (UserName, Password, UserEmail, FirstName, LastName)" + "values (@UserName, @Password, @Email, @FirstName, @LastName)", connection); connection.Open(); command2.ExecuteNonQuery(); //command2.ExecuteScalar(); connection.Close(); When I run this, fill in the textboxes and hit the button I get...... Must declare the scalar variable "@UserName". Any help would be greatly appreciated. Thanks.

    Read the article

  • c# - sqllite dosnt save data i inserted

    - by samy
    I'm messing around with SQL lite and learning it. I got a table called People, I got some method that connect to the database and do some stuff, like show all the info. Now I'm trying to insert some data and here it get wierd for me. I have this method: private void ExecuteQuery(string txtQuery) { SetConnection(); sql_con.Open(); sql_cmd = sql_con.CreateCommand(); sql_cmd.CommandText = txtQuery; sql_cmd.ExecuteNonQuery(); sql_con.Close(); } and to see all the data I've got this method: private void LoadData() { SetConnection(); sql_con.Open(); sql_cmd = sql_con.CreateCommand(); string CommandText = "SELECT * FROM People"; DB = new SQLiteDataAdapter(CommandText, sql_con); DS.Reset(); DB.Fill(DS); DT = DS.Tables[0]; dataGridView1.DataSource = DT; sql_con.Close(); } When I inset some data and right afther it I call the LoadData(), I can see all the changes I made. After I close the program, and then open it agian and call LoadData(), I don't see the new info that I inserted before. I got some data that I used SQL lite GUI app to insert, and I can see that data every time I call the LoadData() method, but not mine. Do I need to do somthing else to make sure SQL lite saves all the data?

    Read the article

  • Call the method of base Class which was over ridden

    - by Abhijith Venkata
    I have illustrated my question in this example class Car { public void start(){ System.out.println("Car Started!!!"); } } class Mercedes extends Car { public void start(){ System.out.println("Mercedes Started!!!"); } } Now, in my main program, I write Mercedes m = new Mercedes(); m.start(); It prints: Mercedes Started!!! How do I call the start() method of Car class using the same object so that the output can be Car Started!!!. Edit: Actually It was asked in an interview I attended. I gave the super keyword answer. But the interviewer denied it. He said he'd give me a hint and said Virtual Function. I have no idea how to use that hint.

    Read the article

  • How to use Google Drive api in Android?

    - by Sajid Shaikh
    I Want to implement Google Drive api in my application but how to implement it in Android, I searched lot for sample code or way to implement in android & finally i came back with question on Stackoverflow. I am hoping that developer who implemented Google drive api in their application they will share there knowledge with us. So please android developer help me with step by step process & sample code. Thanks for reading my question patiently.

    Read the article

  • populate CoreData data model from JSON files prior to app start

    - by johannes_d
    I am creating an iPad App that displays data I got from an API in JSON format. My Core Data model has several entities(Countries, Events, Talks, ...). For each entity I have one .json file that contains all instances of the entity and its attributes as well as its relationships. I would like to populate my Core Data data model with these entities before the start of the App (otherwise it takes about 15 minutes for the iPad to create all the instances of the entities from the several JSON files using factory methods). I am currently importing the data into CoreData like this: -(void)fetchDataIntoDocument:(UIManagedDocument *)document { dispatch_queue_t dataQ = dispatch_queue_create("Data import", NULL); dispatch_async(dataQ, ^{ //Fetching data from application bundle NSURL *tedxgroupsurl = [[NSBundle mainBundle] URLForResource:@"contries" withExtension:@"json"]; NSURL *tedxeventsurl = [[NSBundle mainBundle] URLForResource:@"events" withExtension:@"json"]; //converting the JSON files to NSDictionaries NSError *error = nil; NSDictionary *countries = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfURL:countriesurl] options:kNilOptions error:&error]; countries = [countries objectForKey:@"countries"]; NSDictionary *events = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfURL:eventsurl] options:kNilOptions error:&error]; events = [events objectForKey:@"events"]; //creating entities using factory methods in NSManagedObject Subclasses (Country / Event) [document.managedObjectContext performBlock:^{ NSLog(@"creating countries"); for (NSDictionary *country in countries) { [Country countryWithCountryInfo:country inManagedObjectContext:document.managedObjectContext]; //creating Country entities } NSLog(@"creating events"); for (NSDictionary *event in events) { [Event eventWithEventInfo:event inManagedObjectContext:document.managedObjectContext]; // creating Event entities } NSLog(@"done creating, saving document"); [document saveToURL:document.fileURL forSaveOperation:UIDocumentSaveForOverwriting completionHandler:NULL]; }]; }); dispatch_release(dataQ); } This combines the different JSON files into one UIManagedDocument which i can then perform fetchRequests on to populate tableViews, mapView, etc. I'm looking for a way to create this document outside my application & add it to the mainBundle. Then I could copy it once to the apps DocumentsDirectory and be able I use it (instead of creating the Document within the app from the original JSON files). Any help is appreciated!

    Read the article

  • Select rows where column LIKE dictionary word

    - by Gerve
    I have 2 tables: Dictionary - Contains roughly 36,000 words CREATE TABLE IF NOT EXISTS `dictionary` ( `word` varchar(255) NOT NULL, PRIMARY KEY (`word`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; Datas - Contains roughly 100,000 rows CREATE TABLE IF NOT EXISTS `datas` ( `ID` int(11) NOT NULL AUTO_INCREMENT, `hash` varchar(32) NOT NULL, `data` varchar(255) NOT NULL, `length` int(11) NOT NULL, `time` int(11) NOT NULL, PRIMARY KEY (`ID`), UNIQUE KEY `hash` (`hash`), KEY `data` (`data`), KEY `length` (`length`), KEY `time` (`time`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=105316 ; I would like to somehow select all the rows from datas where the column data contains 1 or more words. I understand this is a big ask, it would need to match all of these rows together in every combination possible, so it needs the best optimization. I have tried the below query, but it just hangs for ages: SELECT `datas`.*, `dictionary`.`word` FROM `datas`, `dictionary` WHERE `datas`.`data` LIKE CONCAT('%', `dictionary`.`word`, '%') AND LENGTH(`dictionary`.`word`) > 3 ORDER BY `length` ASC LIMIT 15 I have also tried something similar to the above with a left join, and on clause that specified the like statement.

    Read the article

  • HTML5 web storage: can different websites overwrite each other’s data on a user’s computer?

    - by Deepak Mahalingam
    I have a few questions regarding the concept of HTML5 storage. I went through the w3c specification, books and tutorials on the same, but still I am a bit unclear about certain concepts: Assume that I access Website A. Some JavaScript runs in my browser that sets a key value pair, say ('username','deepak'). Then I access Website B which also adds a key,value pair in the localstorage as ('username','mahalingam'). How will they both be differentiated? Will Website B override the value set by website A in my localstorage? How can we ensure that a website would not erase all of my localstorage?

    Read the article

  • CSS navigation submenu and seperator

    - by Xenioz
    I have created a navigation bar that is centered with CSS which works. Each li item is separated with a border which is a background image. When hovering on the nav items, the separator disappears because the hover changes the background (I guess) but I wonder how I can fix this, padding or margin can't work because it will just shift the li element. Second problem is that the sub menu items aren't displaying correctly and I have no idea why... Demonstration: http://jsfiddle.net/Xenios/tfbhh/9/embedded/result/ The code: http://jsfiddle.net/Xenios/tfbhh/9/ I'm trying to get this to work for almost a week, and I'm quite tired of it, so I'm looking here for support.

    Read the article

  • Set @Html.RadioButtonFor as Checked by default

    - by minchiya
    I am not able to set the default radio button to "Checked" ! I am using @Html.RadioButtonFor : <div id="private-user"> @Html.RadioButtonFor(m => m.UserType, "type1", new { @class="type-radio" , **@Checked="checked"** }) 1 </div> <div id="proff-user"> @Html.RadioButtonFor(m => m.UserType, "type2", new { @class="type-radio" }) 2 </div> Is it possible to set a radio button as cheched using @Html.RadioButtonFor ? Thx

    Read the article

  • nhibernate fatal error

    - by Afif Lamloumi
    i have an error ( System.InvalidCastException: Unable to cast object of type 'AccountProxy' to type 'System.String'.) when i did this code i mapped the tables( Account,AccountString,EventData,...) of the the database opengts ( open source) i have this error when i called a function from EventData.cs IQuery query = session.CreateQuery("FROM Eventdata"); IList pets = query.List(); return pets; the Stack Trace: [InvalidCastException: Impossible d'effectuer un cast d'un objet de type 'AccountProxy' en type 'System.String'.] (Object , Object[] , SetterCallback ) +431 NHibernate.Bytecode.Lightweight.AccessOptimizer.SetPropertyValues(Object target, Object[] values) +20 NHibernate.Tuple.Component.PocoComponentTuplizer.SetPropertyValues(Object component, Object[] values) +49 NHibernate.Type.ComponentType.SetPropertyValues(Object component, Object[] values, EntityMode entityMode) +34 NHibernate.Type.ComponentType.ResolveIdentifier(Object value, ISessionImplementor session, Object owner) +150 NHibernate.Type.ComponentType.NullSafeGet(IDataReader rs, String[] names, ISessionImplementor session, Object owner) +42 NHibernate.Loader.Loader.GetKeyFromResultSet(Int32 i, IEntityPersister persister, Object id, IDataReader rs, ISessionImplementor session) +93 NHibernate.Loader.Loader.GetRowFromResultSet(IDataReader resultSet, ISessionImplementor session, QueryParameters queryParameters, LockMode[] lockModeArray, EntityKey optionalObjectKey, IList hydratedObjects, EntityKey[] keys, Boolean returnProxies) +92 NHibernate.Loader.Loader.DoQuery(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies) +675 NHibernate.Loader.Loader.DoQueryAndInitializeNonLazyCollections(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies) +129 NHibernate.Loader.Loader.DoList(ISessionImplementor session, QueryParameters queryParameters) +116 [GenericADOException: could not execute query [ select eventdata0_.deviceID as deviceID5_, eventdata0_.timestamp as timestamp5_, eventdata0_.statusCode as statusCode5_, eventdata0_.accountID as accountID5_, eventdata0_.latitude as latitude5_, eventdata0_.longitude as longitude5_, eventdata0_.gpsAge as gpsAge5_, eventdata0_.speedKPH as speedKPH5_, eventdata0_.heading as heading5_, eventdata0_.altitude as altitude5_, eventdata0_.transportID as transpo11_5_, eventdata0_.inputMask as inputMask5_, eventdata0_.outputMask as outputMask5_, eventdata0_.address as address5_, eventdata0_.DataSource as DataSource5_, eventdata0_.rawdata as rawdata5_, eventdata0_.distanceKM as distanceKM5_, eventdata0_.odometerKM as odometerKM5_, eventdata0_.geozoneIndex as geozone19_5_, eventdata0_.geozoneID as geozoneID5_, eventdata0_.creationTime as creatio21_5_ from eventdata eventdata0_ ] [SQL: select eventdata0_.deviceID as deviceID5_, eventdata0_.timestamp as timestamp5_, eventdata0_.statusCode as statusCode5_, eventdata0_.accountID as accountID5_, eventdata0_.latitude as latitude5_, eventdata0_.longitude as longitude5_, eventdata0_.gpsAge as gpsAge5_, eventdata0_.speedKPH as speedKPH5_, eventdata0_.heading as heading5_, eventdata0_.altitude as altitude5_, eventdata0_.transportID as transpo11_5_, eventdata0_.inputMask as inputMask5_, eventdata0_.outputMask as outputMask5_, eventdata0_.address as address5_, eventdata0_.DataSource as DataSource5_, eventdata0_.rawdata as rawdata5_, eventdata0_.distanceKM as distanceKM5_, eventdata0_.odometerKM as odometerKM5_, eventdata0_.geozoneIndex as geozone19_5_, eventdata0_.geozoneID as geozoneID5_, eventdata0_.creationTime as creatio21_5_ from eventdata eventdata0_]] NHibernate.Loader.Loader.DoList(ISessionImplementor session, QueryParameters queryParameters) +213 NHibernate.Loader.Loader.ListIgnoreQueryCache(ISessionImplementor session, QueryParameters queryParameters) +18 NHibernate.Loader.Loader.List(ISessionImplementor session, QueryParameters queryParameters, ISet`1 querySpaces, IType[] resultTypes) +79 NHibernate.Hql.Ast.ANTLR.Loader.QueryLoader.List(ISessionImplementor session, QueryParameters queryParameters) +51 NHibernate.Hql.Ast.ANTLR.QueryTranslatorImpl.List(ISessionImplementor session, QueryParameters queryParameters) +231 NHibernate.Engine.Query.HQLQueryPlan.PerformList(QueryParameters queryParameters, ISessionImplementor session, IList results) +369 NHibernate.Impl.SessionImpl.List(String query, QueryParameters queryParameters, IList results) +317 NHibernate.Impl.SessionImpl.List(String query, QueryParameters parameters) +282 NHibernate.Impl.QueryImpl.List() +163 DATA1.EventdataExtensions.GetEventdata() in C:\Users\HP\Desktop\our_project\DATA1\Queries\Eventdata.cs:33 MvcApplication7.Controllers.HistoriqueController.Index() in C:\Users\HP\Desktop\our_project\MvcApplication7\Controllers\HistoriqueController.cs:17 lambda_method(Closure , ControllerBase , Object[] ) +62 System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +17 System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +208 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27 System.Web.Mvc.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12() +55 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +263 System.Web.Mvc.<>c__DisplayClass17.<InvokeActionMethodWithFilters>b__14() +19 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +191 System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +343 System.Web.Mvc.Controller.ExecuteCore() +116 System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +97 System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +10 System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +37 System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +21 System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +12 System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62 System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +50 System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7 System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22 System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +60 System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8841105 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184 Any suggestions? how can correct this error Data entity class (outtake from comment): public class MyClass { public virtual string DeviceID { get; set; } public virtual int Timestamp { get; set; } public virtual string Account { get; set; } public virtual int StatusCode { get; set; } public virtual double Latitude { get; set; } public virtual double Longitude { get; set; } public virtual int GpsAge { get; set; } public virtual double SpeedKPH { get; set; } public virtual double Heading { get; set; } public override bool Equals(object obj) { return true; } public override int GetHashCode() { return 0; } }

    Read the article

  • Inserting contact with android and querying the result uri returns no entries

    - by th0m4d
    Im developing an application which is dealing with the android contacts API. I implemented methods to insert, update and query contacts. So far everything worked (writing and reading contacts). At one point in my project Im experiencing a strange behaviour. I insert a contact using batch mode. I receive the URI to the RawContact. I do this in a background thread. // use batchmode for contact insertion ArrayList ops = new ArrayList(); int rawContactInsertIndex = ops.size(); // create rawContact ops.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI) .withValue(RawContacts.ACCOUNT_TYPE, ConstantsContract.ACCOUNT_TYPE) .withValue(RawContacts.ACCOUNT_NAME, accountName).build()); ops.add(createInsertOperation().withValueBackReference(Data.RAW_CONTACT_ID, rawContactInsertIndex) .withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE) .withValue(StructuredName.DISPLAY_NAME, displayName).withValue(StructuredName.GIVEN_NAME, firstName) .withValue(StructuredName.FAMILY_NAME, lastName).build()); //other data values... ContentProviderResult[] results = context.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops); if (results.length 0) { result = results[0]; } Then i request and store the lookup uri RawContacts.getContactLookupUri(this.getContentResolver(), myContantRawContactUri); I am able to query the contact using the rawContactUri directly after inserting it (in the same thread). The lookup uri returns null. Uri rawContactUri = appUser.getRawContactUri(ctx); if (rawContactUri == null) { return null; } String lastPathSegment = rawContactUri.getLastPathSegment(); long rawContactId = Long.decode(lastPathSegment); if (rawContactUri != null) { contact = readContactWithID(rawContactId, ContactsContract.Data.RAW_CONTACT_ID); In a different place in the project I want to query the contact i inserted by the stored lookup uri or raw contact uri. Both return no rows from the content provider. I tried it in the main thread and in another background thread. ctx.getContentResolver().query(ContactsContract.Data.CONTENT_URI, null, ContactsContract.Data.RAW_CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?", new String[] { contactID + "", ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE }, null); My first thought was that it could be related to the context.getContentResolver(). But the android documentation states, that the ContentResolver objects scope is the application's package, so you have on ContentResolver for the whole app. Am I right? What am I doing wrong? Why does the same rawContactUri return the contact at one place and does not on another place? And why do I get a lookup uri from a raw contact, which is not working at all?

    Read the article

  • Images to video - converting to IplImage makes video blue

    - by user891908
    I want to create a video from images using opencv. The strange problem is that if i will write image (bmp) to disk and then load (cv.LoadImage) it it renders fine, but when i try to load image from StringIO and convert it to IplImage, it turns video to blue. Heres the code: import StringIO output = StringIO.StringIO() FOREGROUND = (0, 0, 0) TEXT = 'MY TEXT' font_path = 'arial.ttf' font = ImageFont.truetype(font_path, 18, encoding='unic') text = TEXT.decode('utf-8') (width, height) = font.getsize(text) # Create with background with place for text w,h=(600,600) contentimage=Image.open('0.jpg') background=Image.open('background.bmp') x, y = contentimage.size # put content onto background background.paste(contentimage,(((w-x)/2),0)) draw = ImageDraw.Draw(background) draw.text((0,0), text, font=font, fill=FOREGROUND) pi = background pi.save(output, "bmp") #pi.show() #shows image in full color output.seek(0) pi= Image.open(output) print pi, pi.format, "%dx%d" % pi.size, pi.mode cv_im = cv.CreateImageHeader(pi.size, cv.IPL_DEPTH_8U, 3) cv.SetData(cv_im, pi.tostring()) print pi.size, cv.GetSize(cv_im) w = cv.CreateVideoWriter("2.avi", cv.CV_FOURCC('M','J','P','G'), 1,(cv.GetSize(cv_im)[0],cv.GetSize(cv_im)[1]), is_color=1) for i in range(1,5): cv.WriteFrame(w, cv_im) del w

    Read the article

  • Multiplying two matrices from two text files with unknown dimensions

    - by wes schwertner
    This is my first post here. I've been working on this c++ question for a while now and have gotten nowhere. Maybe you guys can give me some hints to get me started. My program has to read two .txt files each containing one matrix. Then it has to multiply them and output it to another .txt file. My confusion here though is how the .txt files are setup and how to get the dimensions. Here is an example of matrix 1.txt. #ivalue #jvalue value 1 1 1.0 2 2 1 The dimension of the matrix is 2x2. 1.0 0 0 1 Before I can start multiplying these matrices I need to get the i and j value from the text file. The only way I have found out to do this is int main() { ifstream file("a.txt"); int numcol; float col; for(int x=0; x<3;x++) { file>>col; cout<<col; if(x==1) //grabs the number of columns numcol=col; } cout<<numcol; } The problem is I don't know how to get to the second line to read the number of rows. And on top of that I don't think this will give me accurate results for other matrices files. Let me know if anything is unclear. UPDATE Thanks! I got getline to work correctly. But now I am running into another problem. In matrix B it is setup like: #ivalue #jvalue Value 1 1 0.1 1 2 0.2 2 1 0.3 2 2 0.4 I need to let the program know that it needs to go down 4 lines, maybe even more (The matrices dimensions are unknown. My matrix B example is a 2x2, but it could be a 20x20). I have a while(!file.eof()) loop my program to let it loop until the end of file. I know I need a dynamic array for multiplying, but would I need one here also? #include <iostream> #include <fstream> using namespace std; int main() { ifstream file("a.txt"); //reads matrix A while(!file.eof()) { int temp; int numcol; string numrow; float row; float col; for(int x=0; x<3;x++) { file>>col; if(x==1) { numcol=col; //number of columns } } string test; getline(file, test); //next line to get rows for(int x=0; x<3; x++) { file>>test; if(x==1) { numrow=test; //sets number of rows } } cout<<numrow; cout<<numcol<<endl; } ifstream file1("b.txt"); //reads matrix 2 while(!file1.eof()) { int temp1; int numcol1; string numrow1; float row1; float col1; for(int x=0; x<2;x++) { file1>>col1; if(x==1) numcol1=col1; //sets number of columns } string test1; getline(file1, test1); //In matrix B there are four rows. getline(file1, test1); //These getlines go down a row. getline(file1, test1); //Need help here. for(int x=0; x<2; x++) { file1>>test1; if(x==1) numrow1=test1; } cout<<numrow1; cout<<numcol1<<endl; } }

    Read the article

  • Is my code a correct implementation of insertion sort?

    - by user1657171
    This code sorts correctly. Is this an insertion sort? import java.util.Scanner; public class InsertionSort { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter the number of elements: "); int count; count = sc.nextInt(); int[] a = new int[count]; System.out.println("Enter elements: "); for(int i = 0 ; i<count;i++){ a[i] = sc.nextInt(); } int j,temp; System.out.println("aftr insertion sort :"); for(int i = 1 ; i<count;i++){ j=i; while(j>0 && a[j-1] > a[j] ){ temp = a[j]; a[j] = a[j-1]; a[j-1] = temp; j--; } } for(int i = 0 ; i<count;i++){ System.out.print(a[i]+" "); } } }

    Read the article

  • Using only alphanumeric characters(a-z) inside toCharArray

    - by Aaron
    Below you will find me using toCharArray in order to send a string to array. I then MOVE the value of the letter using a for statement... for(i = 0; i < letter.length; i++){ letter[i] += (shiftCode); System.out.print(letter[i]); } However, when I use shiftCode to move the value such as... a shifted by -1; I get a symbol @. Is there a way to send the string to shiftCode or tell shiftCode to ONLY use letters? I need it to see my text, like "aaron", and when I use the for statement iterate through a-z only and ignore all symbols and numbers. I THINK it is as simple as... letter=codeWord.toCharArray(a,z); But trying different forms of that and googling it didn't give me any results. Perhaps it has to do with regex or something? Below you will find a complete copy of my program; it works exactly how I want it to do; but it iterates through letters and symbols. I also tried finding instructions online for toCharArray but if there exists any arguments I can't locate them. My program... import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /* * Aaron L. Jones * CS219 * AaronJonesProg3 * * This program is designed to - * Work as a Ceasar Cipher */ /** * * Aaron Jones */ public class AaronJonesProg3 { static String codeWord; static int shiftCode; static int i; static char[] letter; /** * @param args the command line arguments */ public static void main(String[] args) throws IOException { // Instantiating that Buffer Class // We are going to use this to read data from the user; in buffer // For performance related reasons BufferedReader reader; // Building the reader variable here // Just a basic input buffer (Holds things for us) reader = new BufferedReader(new InputStreamReader(System.in)); // Java speaks to us here / We get it to query our user System.out.print("Please enter text to encrypt: "); // Try to get their input here try { // Get their codeword using the reader codeWord = reader.readLine(); // Make that input upper case codeWord = codeWord.toUpperCase(); // Cut the white space out codeWord = codeWord.replaceAll("\\s",""); // Make it all a character array letter = codeWord.toCharArray(); } // If they messed up the input we let them know here and end the prog. catch(Throwable t) { System.out.println(t.toString()); System.out.println("You broke it. But you impressed me because" + "I don't know how you did it!"); } // Java Speaks / Lets get their desired shift value System.out.print("Please enter the shift value: "); // Try for their input try { // We get their number here shiftCode = Integer.parseInt(reader.readLine()); } // Again; if the user broke it. We let them know. catch(java.lang.NumberFormatException ioe) { System.out.println(ioe.toString()); System.out.println("How did you break this? Use a number next time!"); } for(i = 0; i < letter.length; i++){ letter[i] += (shiftCode); System.out.print(letter[i]); } System.out.println(); /**************************************************************** **************************************************************** ***************************************************************/ // Java speaks to us here / We get it to query our user System.out.print("Please enter text to decrypt: "); // Try to get their input here try { // Get their codeword using the reader codeWord = reader.readLine(); // Make that input upper case codeWord = codeWord.toUpperCase(); // Cut the white space out codeWord = codeWord.replaceAll("\\s",""); // Make it all a character array letter = codeWord.toCharArray(); } // If they messed up the input we let them know here and end the prog. catch(Throwable t) { System.out.println(t.toString()); System.out.println("You broke it. But you impressed me because" + "I don't know how you did it!"); } // Java Speaks / Lets get their desired shift value System.out.print("Please enter the shift value: "); // Try for their input try { // We get their number here shiftCode = Integer.parseInt(reader.readLine()); } // Again; if the user broke it. We let them know. catch(java.lang.NumberFormatException ioe) { System.out.println(ioe.toString()); System.out.println("How did you break this? Use a number next time!"); } for(i = 0; i < letter.length; i++){ letter[i] += (shiftCode); System.out.print(letter[i]); } System.out.println(); } }

    Read the article

  • Phone-book Database Help - Python

    - by IDOntWantThat
    I'm new to programming and have an assignment I've been working at for awhile. I understand defining functions and a lot of the basics but I'm kind of running into a brick wall at this point. I'm trying to figure this one out and don't really understand how the 'class' feature works yet. I'd appreciate any help with this one; also any help with some python resources that have can dummy down how/why classes are used. You've been going to work on a database project at work for sometime now. Your boss encourages you to program the database in Python. You disagree, arguing that Python is not a database language but your boss persists by providing the source code below for a sample telephone database. He asks you to do two things: Evaluate the existing source code and extend it to make it useful for managers in the firm. (You do not need a GUI interface, just work on the database aspects: data entry and retrieval - of course you must get the program to run or properly work He wants you to critically evaluate Python as a database tool. Import the sample code below into the Python IDLE and enhance it, run it and debug it. Add features to make this a more realistic database tool by providing for easy data entry and retrieval. import shelve import string UNKNOWN = 0 HOME = 1 WORK = 2 FAX = 3 CELL = 4 class phoneentry: def __init__(self, name = 'Unknown', number = 'Unknown', type = UNKNOWN): self.name = name self.number = number self.type = type # create string representation def __repr__(self): return('%s:%d' % ( self.name, self.type )) # fuzzy compare or two items def __cmp__(self, that): this = string.lower(str(self)) that = string.lower(that) if string.find(this, that) >= 0: return(0) return(cmp(this, that)) def showtype(self): if self.type == UNKNOWN: return('Unknown') if self.type == HOME: return('Home') if self.type == WORK: return('Work') if self.type == FAX: return('Fax') if self.type == CELL: return('Cellular') class phonedb: def __init__(self, dbname = 'phonedata'): self.dbname = dbname; self.shelve = shelve.open(self.dbname); def __del__(self): self.shelve.close() self.shelve = None def add(self, name, number, type = HOME): e = phoneentry(name, number, type) self.shelve[str(e)] = e def lookup(self, string): list = [] for key in self.shelve.keys(): e = self.shelve[key] if cmp(e, string) == 0: list.append(e) return(list) # if not being loaded as a module, run a small test if __name__ == '__main__': foo = phonedb() foo.add('Sean Reifschneider', '970-555-1111', HOME) foo.add('Sean Reifschneider', '970-555-2222', CELL) foo.add('Evelyn Mitchell', '970-555-1111', HOME) print 'First lookup:' for entry in foo.lookup('reifsch'): print '%-40s %s (%s)' % ( entry.name, entry.number, entry.showtype() ) print print 'Second lookup:' for entry in foo.lookup('e'): print '%-40s %s (%s)' % ( entry.name, entry.number, entry.showtype() ) I'm not sure if I'm on the right track but here is what I have so far: def openPB(): foo = phonedb() print 'Please select an option:' print '1 - Lookup' print '2 - Add' print '3 - Delete' print '4 - Quit' entry=int(raw_input('>> ')) if entry==1: namelookup=raw_input('Please enter a name: ') for entry in foo.lookup(namelookup): print '%-40s %s (%s)' % (entry.name, entry.number, entry.showtype() ) elif entry==2: name=raw_input('Name: ') number=raw_input('Number: ') showtype=input('Type (UNKNOWN, HOME, WORK, FAX, CELL): \n>> ') for entry in foo.add(name, number, showtype): #Trying to figure out this part print '%-40s %s (%s)'% (entry.name, entry.number, entry.showtype() ) elif entry==3: delname=raw_input('Please enter a name to delete: ') # #Trying to figure out this part print "Contact '%s' has been deleted" (delname) elif entry==4: print "Phone book is now closed" quit else: print "Your entry was not recognized." openPB() openPB()

    Read the article

  • Find the minimum gap between two numbers in an AVL tree

    - by user1656647
    I have a data structures homework, that in addition to the regular AVL tree functions, I have to add a function that returns the minimum gap between any two numbers in the AVL tree (the nodes in the AVL actually represent numbers.) Lets say we have the numbers (as nodes) 1 5 12 20 23 21 in the AVL tree, the function should return the minimum gap between any two numbers. In this situation it should return "1" which is |20-21| or |21-20|. It should be done in O(1). Tried to think alot about it, and I know there is a trick but just couldn't find it, I have spent hours on this. There was another task which is to find the maximum gap, which is easy, it is the difference between the minimal and maximal number.

    Read the article

  • FOSUserBundle override mapping to remove need for username

    - by musoNic80
    I want to remove the need for a username in the FOSUserBundle. My users will login using an email address only and I've added real name fields as part of the user entity. I realised that I needed to redo the entire mapping as described here. I think I've done it correctly but when I try to submit the registration form I get the error: "Only field names mapped by Doctrine can be validated for uniqueness." The strange thing is that I haven't tried to assert a unique constraint to anything in the user entity. Here is my full user entity file: <?php // src/MyApp/UserBundle/Entity/User.php namespace MyApp\UserBundle\Entity; use FOS\UserBundle\Model\User as BaseUser; use Doctrine\ORM\Mapping as ORM; use Symfony\Component\Validator\Constraints as Assert; /** * @ORM\Entity * @ORM\Table(name="depbook_user") */ class User extends BaseUser { /** * @ORM\Id * @ORM\Column(type="integer") * @ORM\GeneratedValue(strategy="AUTO") */ protected $id; /** * @ORM\Column(type="string", length=255) * * @Assert\NotBlank(message="Please enter your first name.", groups={"Registration", "Profile"}) * @Assert\MaxLength(limit="255", message="The name is too long.", groups={"Registration", "Profile"}) */ protected $firstName; /** * @ORM\Column(type="string", length=255) * * @Assert\NotBlank(message="Please enter your last name.", groups={"Registration", "Profile"}) * @Assert\MaxLength(limit="255", message="The name is too long.", groups={"Registration", "Profile"}) */ protected $lastName; /** * @ORM\Column(type="string", length=255) * * @Assert\NotBlank(message="Please enter your email address.", groups={"Registration", "Profile"}) * @Assert\MaxLength(limit="255", message="The name is too long.", groups={"Registration", "Profile"}) * @Assert\Email(groups={"Registration"}) */ protected $email; /** * @ORM\Column(type="string", length=255, name="email_canonical", unique=true) */ protected $emailCanonical; /** * @ORM\Column(type="boolean") */ protected $enabled; /** * @ORM\Column(type="string") */ protected $salt; /** * @ORM\Column(type="string") */ protected $password; /** * @ORM\Column(type="datetime", nullable=true, name="last_login") */ protected $lastLogin; /** * @ORM\Column(type="boolean") */ protected $locked; /** * @ORM\Column(type="boolean") */ protected $expired; /** * @ORM\Column(type="datetime", nullable=true, name="expires_at") */ protected $expiresAt; /** * @ORM\Column(type="string", nullable=true, name="confirmation_token") */ protected $confirmationToken; /** * @ORM\Column(type="datetime", nullable=true, name="password_requested_at") */ protected $passwordRequestedAt; /** * @ORM\Column(type="array") */ protected $roles; /** * @ORM\Column(type="boolean", name="credentials_expired") */ protected $credentialsExpired; /** * @ORM\Column(type="datetime", nullable=true, name="credentials_expired_at") */ protected $credentialsExpiredAt; public function __construct() { parent::__construct(); // your own logic } /** * @return string */ public function getFirstName() { return $this->firstName; } /** * @return string */ public function getLastName() { return $this->lastName; } /** * Sets the first name. * * @param string $firstname * * @return User */ public function setFirstName($firstname) { $this->firstName = $firstname; return $this; } /** * Sets the last name. * * @param string $lastname * * @return User */ public function setLastName($lastname) { $this->lastName = $lastname; return $this; } } I've seen various suggestions about this but none of the suggestions seem to work for me. The FOSUserBundle docs are very sparse about what must be a very common request.

    Read the article

  • How do I find the list of functions executed to build a page?

    - by ashy_32bit
    I want the list of all functions executed to a certain point in code, somehow like debug_backtrace() but including functions not in the exact thread that leads to where debug_backtrace() is called. e.g : a(); function a() { b(); c(); d(); } function b() { } function c() { } function d() { print all_trace(); } would produce : a(), b(), c(), d() and not a(), d() like debug_backtrace() would

    Read the article

  • Flash As3 Loader Problem

    - by Hadar
    Hi iam trying to load a few external jpegs in As3. It works fine locally in Flash, but it dosen't work at all ion my server. My app also loads a youtube video simultaneously. function drawResult(index,videoID,song_title,thumbnail:String=null) { var theClip:resultRowClip=new resultRowClip (); _clip.addChild(theClip); myArray[index] = new Array(videoID,theClip); theClip.y=0+(43*(index-1)); theClip.rowText.text = song_title; theClip.rowBack.visible = false; if (thumbnail != ""){ theClip.tHolder.visible=true; loadImage(thumbnail,index); } } function loadImage(url:String,index):void { //this.myClip.myText.text += "load image"; // Set properties on my Loader object var imageLoader:Loader = new Loader(); imageLoader.load(new URLRequest(url)); imageLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, function (evt:Event){imageLoaded(evt,index)}); } function imageLoaded(evt,id):void { //this.myClip.myText.text += "id : evt : " + evt.status; // Load Image var image:Bitmap = new Bitmap(evt.target.content.bitmapData); myArray[id][1].tHolder.addChild(image); myArray[id][1].tHolder.width=myArray[id][1].tHolder.width*0.35; myArray[id][1].tHolder.height=myArray[id][1].tHolder.height*0.35; } Does anyone knows what the problem is ? ** I added two Evenet listeners from io Error : imageLoader.addEventListener(IOErrorEvent.IO_ERROR,ioErrorHandler); imageLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR,ioErrorHandler); This is the function for handling the errors : private function ioErrorHandler(event:IOErrorEvent):void { this.myClip.myText.text +=("ioErrorHandler: " + event); } anyway, I got no errors... I also tried to move the listeners before imageLoader.load but it's still the same...no errors and no data loaded.. I change my code to patrikS suggestion : function loadImage(url:String,index):void { //this.myClip.myText.text += "load image"; // Set properties on my Loader object //if (index != 1) return; var imageLoader:Loader = new Loader(); imageLoader.name = index.toString(); //myArray[index][1].addChild(imageLoader); //imageLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, function (evt:Event){imageLoaded(evt,index)}); imageLoader.contentLoaderInfo.addEventListener(Event.COMPLETE,completeHandler); imageLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR,ioErrorHandler); imageLoader.load(new URLRequest(url)); } My current completeHandler function(tnx patrikS ) : private function completeHandler(evt:Event):void{ //this.myClip.myText.text += "id : evt : " + evt.status; // Load Image trace("evt target loader name : "+ evt.target.loader.name ); evt.target.removeEventListener(Event.COMPLETE, completeHandler ); var image:Bitmap = new Bitmap(evt.target.content.bitmapData); myArray[evt.target.loader.name][1].tHolder.addChild(image); myArray[evt.target.loader.name][1].tHolder.width=myArray[evt.target.loader.name][1].tHolder.width*0.35; myArray[evt.target.loader.name][1].tHolder.height=myArray[evt.target.loader.name][1].tHolder.height*0.35; //trace (hadar.y + "Y / X" + hadar.x); } It still work only on flash IDE and dosent work on any browser...

    Read the article

  • Cleaning your BizTalk Build Server

    - by Michael Stephenson
    Just a little note for myself this one.At one of my customers where it is still BizTalk 2006 one of the build servers is intermittently getting issues so I wanted to run a script periodically to clean things up a little.  The below script is an example of how you can stop cruise control and all of the biztalk services, then clean the biztalk databases and reset the backup process and then click everything off again.This should keep the server a little cleaner and reduce the number of builds that occasionally fail for adhoc environmental issues.REM Server Clean ScriptREM =================== REM This script is ran to move the build server back to a clean state echo Stop Cruise Controlnet stop CCService echo Stop IISiisreset /stop echo Stop BizTalk Servicesnet stop BTSSvc$<Name of BizTalk Host><Repeat for other BizTalk services> echo Stop SSOnet stop ENTSSO echo Stop SQL Job Agentnet stop SQLSERVERAGENT echo Clean Message Boxsqlcmd -E -d BizTalkMsgBoxDB -Q "Exec bts_CleanupMsgbox"sqlcmd -E -d BizTalkMsgBoxDB -Q "Exec bts_PurgeSubscriptions"  echo Clean Tracking Databasesqlcmd -E -d BizTalkDTADb -Q "Exec dtasp_CleanHMData" echo Reset TDDS Stream Statussqlcmd -E -d BizTalkDTADb -Q "Update TDDS_StreamStatus Set lastSeqNum = 0" echo Force Full Backupsqlcmd -E -d BizTalkMgmtDB -Q "Exec sp_ForceFullBackup" echo Clean Backup Directorydel E:\BtsBackups\*.* /q  echo Start SSOnet start ENTSSO echo Start SQL Job Agentnet start SQLSERVERAGENT echo Start BizTalk Servicesnet start BTSSvc$<Name of BizTalk Host><Repeat for other BizTalk services> echo Start IISiisreset /start echo Start Cruise Controlnet start CCService

    Read the article

  • VS2010 crashes when opening a vsp generated using VS 2012

    - by Tarun Arora
    I recently profiled some web applications using Visual Studio 2012, a vsp (Visual Studio Profile) file was generated as a result of the profiling session. I could successfully open the vsp file in Visual Studio 2012 as expected but when I tried to open the vsp file in Visual Studio 2010 the VS2010 IDE crashed. As a responsible citizen I raised bug # 762202 on Microsoft Connect site using the Microsoft Visual Studio 2012 Feedback Client. Note – In case you didn’t already know, VSP generated in Visual Studio 2012 is not backward compatible. Please refer below for the steps to reproduce the issue and the resolution of the connect bug. 1. Behaviour and Steps to Reproduce the Issue Description I have generated a vsp file by using the Visual Studio 2012 Standalone profiler. When I try and open the vsp file in Visual Studio 2010 the IDE crashes. I understand that a vsp generated by using VS 2012 cannot be opened in VS 2010, but the IDE crashing is not the behaviour I would expect to see. Steps to Reproduce the Issue 1. Pick up the Stand lone profiler from the VS 2012 installation media. The folder has both x 64 and x86 installer, since the machine I am using is x64 bit. I have installed the x64 version of the standalone profiler. 2. I have configured the system path by setting the 'environment variable' path to where the profiler is installed. In my case this is, C:\Program Files (x86)\Microsoft Visual Studio 11.0\Team Tools\Performance Tools 3. Created a new environment variable _NT_SYMBOL_PATH and set its value to CACHE*C:\SYMBOLSCACHE;SRV*C:\SYMBOLSCACHE*HTTP://MSDL.MICROSOFT.COM/DOWNLOAD/SYMBOLS;\\FOO\BUILD1234 4. Open up CMD as an administrator and run 'VSPerfASPNETCmd /tip http://localhost:56180/ /o:C:\Temp\SampleEISK.vsp' 5. This generates the following message on the cmd       Microsoft (R) VSPerf ASP.NET Command, Version 11.0.0.0     Copyright (C) Microsoft Corporation. All rights reserved.     Configuring and attaching to ASP.NET process. Please wait.     Setting up profiling environment.     Starting monitor.     Launching ASP.NET service.     Attaching Monitor to process.     Launching Internet Explorer.     The profiler is attached to ASP.net. Please run your application scenario now.     Press Enter to stop data collection...   6. I perform certain actions and then I come back to the cmd and hit enter to shut down the profiling. Once I do this, the following message is written to the cmd, Press Enter to stop data collection... Profiling now shut down. Report file "C:\Temp\SampleEISK.vsp" was generated. Running VsPerfReport, packing symbols into the .VSP. Shutting down profiling and restarting ASP.NET. Please wait. Restarting w3wp.exe.   7. I look in the C:\Temp folder and I can see the SampleEISK.vsp file generated. I can successfully open this file in Visual Studio 2012. 8. When I am trying to open the vsp file in VS 2010 the VS 2010 IDE crashes. Kaboooom! What I would expect to happen I expect to receive a message "VS 2010 does not support the vsp file generated by VS 2012". What actually happened The VS 2010 IDE crashed 2. Resolution This is a valid bug! However, there isn’t much value in releasing a hotfix for this issue. Refer below to the resolution provided by the Visual Studio Profiler Team.  Thank you for taking the time to report this issue. We completely agree that Visual Studio 2010 should not crash. However in this particular case this is not a bug we are going to retroactively release a fix to 2010 for at this point. Given that a fix would not unblock the scenario of opening a 2012 created file on Visual Studio 2010, and there is not an active update channel for Visual Studio 2010 other than manually locating and installing hot fixes, we will not be fixing this particular issue. Best Regards, Visual Studio Profiler Team   Though it would be great to improve the behaviour however, this is not a defect that would stop you from progressing in any way. It’s important to note however that VSP files generated by Visual Studio 2012 are not backward compatible so you should refrain from opening these files in Visual Studio 2010.

    Read the article

< Previous Page | 3 4 5 6 7 8 9 10 11 12 13  | Next Page >