Search Results

Search found 23925 results on 957 pages for 'multiple render targets'.

Page 16/957 | < Previous Page | 12 13 14 15 16 17 18 19 20 21 22 23  | Next Page >

  • django: How to make one form from multiple models containing foreignkeys

    - by Tim
    I am trying to make a form on one page that uses multiple models. The models reference each other. I am having trouble getting the form to validate because I cant figure out how to get the id of two of the models used in the form into the form to validate it. I used a hidden key in the template but I cant figure out how to make it work in the views My code is below: views: def the_view(request, a_id,): if request.method == 'POST': b_form= BForm(request.POST) c_form =CForm(request.POST) print "post" if b_form.is_valid() and c_form.is_valid(): print "valid" b_form.save() c_form.save() return HttpResponseRedirect(reverse('myproj.pro.views.this_page')) else: b_form= BForm() c_form = CForm() b_ide = B.objects.get(pk=request.b_id) id_of_a = A.objects.get(pk=a_id) return render_to_response('myproj/a/c.html', {'b_form':b_form, 'c_form':c_form, 'id_of_a':id_of_a, 'b_id':b_ide }) models class A(models.Model): name = models.CharField(max_length=256, null=True, blank=True) classe = models.CharField(max_length=256, null=True, blank=True) def __str__(self): return self.name class B(models.Model): aid = models.ForeignKey(A, null=True, blank=True) number = models.IntegerField(max_length=1000) other_number = models.IntegerField(max_length=1000) class C(models.Model): bid = models.ForeignKey(B, null=False, blank=False) field_name = models.CharField(max_length=15) field_value = models.CharField(max_length=256, null=True, blank=True) forms from mappamundi.mappa.models import A, B, C class BForm(forms.ModelForm): class Meta: model = B exclude = ('aid',) class CForm(forms.ModelForm): class Meta: model = C exclude = ('bid',) B has a foreign key reference to A, C has a foreign key reference to B. Since the models are related, I want to have the forms for them on one page, 1 submit button. Since I need to fill out fields for the forms for B and C & I dont want to select the id of B from a drop down list, I need to somehow get the id of the B form into the form so it will validate. I have a hidden field in the template, I just need to figure how to do it in the views

    Read the article

  • open-iscsi does not login into targets on boot

    - by Creshal
    We have a Debian Lenny server with open-iscsi that's configured to log into a target automatically: hostname:~# grep \\.startup /etc/iscsi/iscsid.conf node.startup = automatic hostname:~# grep \\.startup /etc/iscsi/nodes/iqn..../the.correct.ip.address\,port node.startup = automatic node.conn[0].startup = automatic hostname:~# If I issue a restart of open-iscsi via init.d, it works fine. But if I reboot the machine, iscsi starts, but does not even search for targets. I have to manually restart it before it works. Any ideas how to make it find the target on boot?

    Read the article

  • C++ Multiple inheritance with interfaces?

    - by umanga
    Greetings all, I come from Java background and I am having difficulty with multiple inheritance. I have an interface called IView which has init() method.I want to derive a new class called PlaneViewer implementing above interface and extend another class. (QWidget). My implementation is as: IViwer.h (only Header file , no CPP file) : #ifndef IVIEWER_H_ #define IVIEWER_H_ class IViewer { public: //IViewer(); ///virtual //~IViewer(); virtual void init()=0; }; #endif /* IVIEWER_H_ */ My derived class. PlaneViewer.h #ifndef PLANEVIEWER_H #define PLANEVIEWER_H #include <QtGui/QWidget> #include "ui_planeviewer.h" #include "IViewer.h" class PlaneViewer : public QWidget , public IViewer { Q_OBJECT public: PlaneViewer(QWidget *parent = 0); ~PlaneViewer(); void init(); //do I have to define here also ? private: Ui::PlaneViewerClass ui; }; #endif // PLANEVIEWER_H PlaneViewer.cpp #include "planeviewer.h" PlaneViewer::PlaneViewer(QWidget *parent) : QWidget(parent) { ui.setupUi(this); } PlaneViewer::~PlaneViewer() { } void PlaneViewer::init(){ } My questions are: Is it necessary to declare method init() in PlaneViewer interface also , because it is already defined in IView? 2.I cannot complie above code ,give error : PlaneViewer]+0x28): undefined reference to `typeinfo for IViewer' collect2: ld returned 1 exit status Do I have to have implementation for IView in CPP file?

    Read the article

  • MySql: Query multiple identical dynamic tables.

    - by JYelton
    I have a database with 500+ tables, each with identical structure, that contain historical data from sensors. I am trying to come up with a query that will locate, for example, all instances where sensor n exceeds x. The problem is that the tables are dynamic, the query must be able to dynamically obtain the list of tables. I can query information_schema.tables to get a list of the tables, like so: SELECT table_name FROM information_schema.tables WHERE table_schema = 'database_name'; I can use this to create a loop in the program and then query the database repeatedly, however it seems like there should be a way to have MySql do the multiple table search. I have not been able to make a stored procedure that works, but the examples I can find are generally for searching for a string in any column. I want to specifically find data in a specific column that exists in all tables. I admit I do not understand how to properly use stored procedures nor if they are the appropriate solution to this problem. An example query inside the loop would be: SELECT device_name, sensor_value FROM device_table WHERE sensor_value > 10; Trying the following does not work: SELECT device_name, sensor_value FROM ( SELECT table_name FROM information_schema.tables WHERE table_schema = 'database_name' ) WHERE sensor_value > 10; It results in an error: "Every derived table must have its own alias." The goal is to have a list of all devices that have had a given sensor value occur anywhere in their log (table). Ultimately, should I just loop in my program once I've obtained a list of tables, or is there a query structure that would be more efficient?

    Read the article

  • List goals/targets in GNU make

    - by BitShifter
    I have a fairly large makefile that creates a number of targets on the fly by computing names from variables. (eg foo$(VAR) : $(PREREQS)). Is there any way that gnu make can be convinced to spit out a list of targets after it has expanded these variables?

    Read the article

  • Adding date to multiple fields via datepicker

    - by Andy
    i have a form in drupal with jquery based date module. there are multiple fields with date picker enabled. i want to set the value of all of them (they all have class .date-popup-init) to the value of the first field (#edit-field, the 'from' date) when that field is set. my code so far: <script type="text/javascript"> var DatePicked = function() { var firstdate = $("#edit-field"); var updater = firstdate.datepicker("getDate"); $(".date-popup-init").each(function(){ $(this).datepicker("setDate", updater); }); } $(function() { $("#edit-field").datepicker({ onSelect: DatePicked }); }); </script> this seems to randomly work; it sets the date of some fields to the value of #edit-field, seemingly different fields each time. also, the form adds more datepicker-enabled fields via ajax. is there any way to ensure that all these new fields, when they load, pick up the value of #edit-field as well? disclaimer: last night was my first attempt at javascript of any kind. i have a basic idea now. the above was cobbled through countless google examples.

    Read the article

  • Multiple iSCSI Targets or 1 that's shared?

    - by Joost Verdaasdonk
    On my network I have several types of files I want to save on a SAN like: SQL db's and logs Exchange data Random files Now I'm wondering if I should create one iSCSI Target with a large volume and initiate that from one of the servers. (and share it so other servers can use it too) Or I should create separate Targets to have each server use its own storage. For the record the storage could be separated because the servers aren't using the shared data. For one reason I was thinking of one storage is ease of backup. (but perhaps performance could be a problem?) What would be an advisable configuration for these type of data?

    Read the article

  • Why my autocomplete doesn't whant to be multiple ???

    - by Toni Michel Caubet
    please, give me a hand on this one; i'm trying to use autocomplete so user can enter tags by comma separated, example: 'autocomplete, jquery , next , last' ok, i had the autocomplete working by sending him an $array with all the tags of my website with the previous format aswell, this is my code: <? $a = new etiqueta(0, ''); $b = $a->autocomplete_etiquetas(); mostrar_notificacion('autocomplete_etiquetas_cargado?'); ?> <script type="text/javascript"> function cargar_autocomplete_etiquetas(){ $("#tags").autocomplete({ source: [<? echo $b; ?>] }); } </script> All i want it's user to select a tag, apply the ', ' and the autocomplete to be ready for next tag i'm trying with (i know they are diff id's, also diff inputs): <? $b = new ingrediente(0, ''); $c = $b->autocomplete_ingredientes(); ?> <script type="text/javascript"> function cargar_autocomplete_ingredientes(){ $("#ingredientes").autocomplete({ source: [<? echo $c; ?>], multiple: true, multipleSeparator: ", " }); } </script> But with out success.... 10€ via paypal if answered before 23h (its 21:50 now), it's not much, it's an incentive :P

    Read the article

  • Show symbolic links AND their targets in web directory listing (apache)

    - by Erwan Queffélec
    Listing a directory content with ls -l shows this output: total 12 drwxr-xr-x 3 root root 4096 Dec 11 16:38 2.3 drwxr-xr-x 5 root root 4096 Dec 11 16:38 2.4 drwxr-xr-x 2 root root 4096 Dec 11 16:38 archive lrwxrwxrwx 1 root root 10 Dec 11 16:38 current -> 2.4/2.4.1/ lrwxrwxrwx 1 root root 10 Dec 11 16:38 next -> 2.4/2.4.2/ lrwxrwxrwx 1 root root 10 Dec 11 16:38 previous -> 2.4/2.4.0/ Notice how it shows the symbolic links and their respective targets. I need to know if there is a way of getting the same behaviour in apache directory browsing. If apache is not capable of it as I suspect, is there an application (FLOSS) providing that kind of behaviour ?

    Read the article

  • multiple mysql_real_query() in while loop

    - by Steve
    It seems that when I have one mysql_real_query() function in a continuous while loop, the query will get executed OK. However, if multiple mysql_real_query() are inside the while loop, one right after the other. Depending on the query, sometimes neither the first query nor second query will execute properly. This seems like a threading issue to me. I'm wondering if the mysql c api has a way of dealing with this? Does anyone know how to deal with this? mysql_free_result() doesn't work since I am not even storing the results. //keep polling as long as stop character '-' is not read while(szRxChar != '-') { // Check if a read is outstanding if (HasOverlappedIoCompleted(&ovRead)) { // Issue a serial port read if (!ReadFile(hSerial,&szRxChar,1, &dwBytesRead,&ovRead)) { DWORD dwErr = GetLastError(); if (dwErr!=ERROR_IO_PENDING) return dwErr; } } // Wait 5 seconds for serial input if (!(HasOverlappedIoCompleted(&ovRead))) { WaitForSingleObject(hReadEvent,RESET_TIME); } // Check if serial input has arrived if (GetOverlappedResult(hSerial,&ovRead, &dwBytesRead,FALSE)) { // Wait for the write GetOverlappedResult(hSerial,&ovWrite, &dwBytesWritten,TRUE); //load tagBuffer with byte stream tagBuffer[i] = szRxChar; i++; tagBuffer[i] = 0; //char arrays are \0 terminated //run query with tagBuffer if( strlen(tagBuffer)==PACKET_LENGTH ) { sprintf(query,"insert into scan (rfidnum) values ('"); strcat(query, tagBuffer); strcat(query, "')"); mysql_real_query(&mysql,query,(unsigned int)strlen(query)); i=0; } mysql_real_query(&mysql,"insert into scan (rfidnum) values ('2nd query')",(unsigned int)strlen("insert into scan (rfid) values ('2nd query')")); mysql_free_result(res); } }

    Read the article

  • FineUploader multiple instances and dynamic naming

    - by RichieMN
    I am using FineUploader 4.0.8 within a MVC4 project using the jquery wrapper. Here is an example of my js code that creates a single instance of the fineUploader and is working just fine. At this time, I have the need for more than one instance of fineUploader, but each individual control doesn't know anything about the other and they're rendered as needed on a page (I've seen previous questions using a jQuery .each, which won't work here). Currently, I can't seem to correctly render any upload buttons, probably due to having an ID duplicated or something. See below for how I'm using MVC's Razor to create unique variables and html IDs for that individual instance. Here's my current implementation where I've added the dynamic values (places where you see _@Model.{PropertyName}): // Uploader control setup var [email protected] = $('#[email protected]').fineUploader({ debug: true, template: '[email protected]', button: $("#[email protected]"), request: { endpoint: '@Url.Action("UploadFile", "Survey")', customHeaders: { Accept: 'application/json' }, params: { [email protected]: (function () { return instance; }), [email protected]: (function () { return surveyItemResultId; }), [email protected]: (function () { return itemId; }), [email protected]: (function () { return loopingCounter++; }) } }, validation: { acceptFiles: ['image/*', 'application/xls', 'application/pdf', 'text/csv', 'application/vnd.openxmlformats-officedocument.spreadsheetml.template', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.ms-excel'], allowedExtensions: ['jpeg', 'jpg', 'gif', 'png', 'bmp', 'csv', 'xls', 'xlsx', 'pdf', 'xlt', 'xltx', 'txt'], sizeLimit: 1024 * 1024 * 2.5, // 2.5MB stopOnFirstInvalidFile: false }, failedUploadTextDisplay: { mode: 'custom' }, multiple: true, text: { uploadButton: 'Select your upload file(s)' } }).on('submitted', function (event, id, filename) { $("#modal-overlay").fadeIn(); $("#modal-box").fadeIn(); [email protected]++; $(':input[type=button], :input[type=submit], :input[type=reset]').attr('disabled', 'disabled'); }).on('complete', function (event, id, filename, responseJSON) { [email protected]++; if ([email protected] == [email protected]) { $(':input[type=button], :input[type=submit], :input[type=reset]').removeAttr('disabled'); //$("#overlay").fadeOut(); $("#modal-box").fadeOut(); $("#modal-overlay").fadeOut(); } }).on('error', function (event, id, name, errorReason, xhr) { //$("#overlay").fadeOut(); alert('error: ' + errorReason); $("#modal-box").fadeOut(); $("#modal-overlay").fadeOut(); }); }); Using the same principle as above, I've added this logic to the template too. Here's part of my template: <script type="text/template" id="[email protected]"> <div class="qq-uploader-selector qq-uploader"> <div class="qq-upload-drop-area-selector qq-upload-drop-area qq-hide-dropzone"> <span>Drop files here to upload</span> What I see when I use the above code is only the drag and drop section visible, and no button. There are no js errors either. I do have an example that only has one instance of this control on it and the results are the same visible drag and drop section and no button). Any thought as to what's going on? I'll gladly update the question if you find I'm missing something helpful. Please don't just -1 me if it's something I can easily improve or fix.

    Read the article

  • Using the HTML5 &lt;input type=&quot;file&quot; multiple=&quot;multiple&quot;&gt; Tag in ASP.NET

    - by Rick Strahl
    Per HTML5 spec the <input type="file" /> tag allows for multiple files to be picked from a single File upload button. This is actually a very subtle change that's very useful as it makes it much easier to send multiple files to the server without using complex uploader controls. Please understand though, that even though you can send multiple files using the <input type="file" /> tag, the process of how those files are sent hasn't really changed - there's still no progress information or other hooks that allow you to automatically make for a nicer upload experience without additional libraries or code. For that you will still need some sort of library (I'll post an example in my next blog post using plUpload). All the new features allow for is to make it easier to select multiple images from disk in one operation. Where you might have required many file upload controls before to upload several files, one File control can potentially do the job. How it works To create a file input box that allows with multiple file support you can simply do:<form method="post" enctype="multipart/form-data"> <label>Upload Images:</label> <input type="file" multiple="multiple" name="File1" id="File1" accept="image/*" /> <hr /> <input type="submit" id="btnUpload" value="Upload Images" /> </form> Now when the file open dialog pops up - depending on the browser and whether the browser supports it - you can pick multiple files. Here I'm using Firefox using the thumbnail preview I can easily pick images to upload on a form: Note that I can select multiple images in the dialog all of which get stored in the file textbox. The UI for this can be different in some browsers. For example Chrome displays 3 files selected as text next to the Browse… button when I choose three rather than showing any files in the textbox. Most other browsers display the standard file input box and display the multiple filenames as a comma delimited list in the textbox. Note that you can also specify the accept attribute in the <input> tag, which specifies a mime-type to specify what type of content to allow.Here I'm only allowing images (image/*) and the browser complies by just showing me image files to display. Likewise I could use text/* for all text formats registered on the machine or text/xml to only show XML files (which would include xml,xst,xsd etc.). Capturing Files on the Server with ASP.NET When you upload files to an ASP.NET server there are a couple of things to be aware of. When multiple files are uploaded from a single file control, they are assigned the same name. In other words if I select 3 files to upload on the File1 control shown above I get three file form variables named File1. This means I can't easily retrieve files by their name:HttpPostedFileBase file = Request.Files["File1"]; because there will be multiple files for a given name. The above only selects the first file. Instead you can only reliably retrieve files by their index. Below is an example I use in app to capture a number of images uploaded and store them into a database using a business object and EF 4.2.for (int i = 0; i < Request.Files.Count; i++) { HttpPostedFileBase file = Request.Files[i]; if (file.ContentLength == 0) continue; if (file.ContentLength > App.Configuration.MaxImageUploadSize) { ErrorDisplay.ShowError("File " + file.FileName + " is too large. Max upload size is: " + App.Configuration.MaxImageUploadSize); return View("UploadClassic",model); } var image = new ClassifiedsBusiness.Image(); var ms = new MemoryStream(16498); file.InputStream.CopyTo(ms); image.Entered = DateTime.Now; image.EntryId = model.Entry.Id; image.ContentType = "image/jpeg"; image.ImageData = ms.ToArray(); ms.Seek(0, SeekOrigin.Begin); // resize image if necessary and turn into jpeg Bitmap bmp = Imaging.ResizeImage(ms.ToArray(), App.Configuration.MaxImageWidth, App.Configuration.MaxImageHeight); ms.Close(); ms = new MemoryStream(); bmp.Save(ms,ImageFormat.Jpeg); image.ImageData = ms.ToArray(); bmp.Dispose(); ms.Close(); model.Entry.Images.Add(image); } This works great and also allows you to capture input from multiple input controls if you are dealing with browsers that don't support multiple file selections in the file upload control. The important thing here is that I iterate over the files by index, rather than using a foreach loop over the Request.Files collection. The files collection returns key name strings, rather than the actual files (who thought that was good idea at Microsoft?), and so that isn't going to work since you end up getting multiple keys with the same name. Instead a plain for loop has to be used to loop over all files. Another Option in ASP.NET MVC If you're using ASP.NET MVC you can use the code above as well, but you have yet another option to capture multiple uploaded files by using a parameter for your post action method.public ActionResult Save(HttpPostedFileBase[] file1) { foreach (var file in file1) { if (file.ContentLength < 0) continue; // do something with the file }} Note that in order for this to work you have to specify each posted file variable individually in the parameter list. This works great if you have a single file upload to deal with. You can also pass this in addition to your main model to separate out a ViewModel and a set of uploaded files:public ActionResult Edit(EntryViewModel model,HttpPostedFileBase[] uploadedFile) You can also make the uploaded files part of the ViewModel itself - just make sure you use the appropriate naming for the variable name in the HTML document (since there's Html.FileFor() extension). Browser Support You knew this was coming, right? The feature is really nice, but unfortunately not supported universally yet. Once again Internet Explorer is the problem: No shipping version of Internet Explorer supports multiple file uploads. IE10 supposedly will, but even IE9 does not. All other major browsers - Chrome, Firefox, Safari and Opera - support multi-file uploads in their latest versions. So how can you handle this? If you need to provide multiple file uploads you can simply add multiple file selection boxes and let people either select multiple files with a single upload file box or use multiples. Alternately you can do some browser detection and if IE is used simply show the extra file upload boxes. It's not ideal, but either one of these approaches makes life easier for folks that use a decent browser and leaves you with a functional interface for those that don't. Here's a UI I recently built as an alternate uploader with multiple file upload buttons: I say this is my 'alternate' uploader - for my primary uploader I continue to use an add-in solution. Specifically I use plUpload and I'll discuss how that's implemented in my next post. Although I think that plUpload (and many of the other packaged JavaScript upload solutions) are a better choice especially for large uploads, for simple one file uploads input boxes work well enough. The advantage of this solution is that it's very easy to handle on the server side. Any of the JavaScript controls require special handling for uploads which I'll also discuss in my next post.© Rick Strahl, West Wind Technologies, 2005-2012Posted in HTML5  ASP.NET  MVC   Tweet !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })();

    Read the article

  • Render 2 images that uses different shaders

    - by Code Vader
    Based on the giawa/nehe tutorials, how can I render 2 images with different shaders. I'm pretty new to OpenGl and shaders so I'm not completely sure whats happening in my code, but I think the shaders that is called last overwrites the first one. private static void OnRenderFrame() { // calculate how much time has elapsed since the last frame watch.Stop(); float deltaTime = (float)watch.ElapsedTicks / System.Diagnostics.Stopwatch.Frequency; watch.Restart(); // use the deltaTime to adjust the angle of the cube angle += deltaTime; // set up the OpenGL viewport and clear both the color and depth bits Gl.Viewport(0, 0, width, height); Gl.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); // use our shader program and bind the crate texture Gl.UseProgram(program); //<<<<<<<<<<<< TOP PYRAMID // set the transformation of the top_pyramid program["model_matrix"].SetValue(Matrix4.CreateRotationY(angle * rotate_cube)); program["enable_lighting"].SetValue(lighting); // bind the vertex positions, UV coordinates and element array Gl.BindBufferToShaderAttribute(top_pyramid, program, "vertexPosition"); Gl.BindBufferToShaderAttribute(top_pyramidNormals, program, "vertexNormal"); Gl.BindBufferToShaderAttribute(top_pyramidUV, program, "vertexUV"); Gl.BindBuffer(top_pyramidTrianlges); // draw the textured top_pyramid Gl.DrawElements(BeginMode.Triangles, top_pyramidTrianlges.Count, DrawElementsType.UnsignedInt, IntPtr.Zero); //<<<<<<<<<< CUBE // set the transformation of the cube program["model_matrix"].SetValue(Matrix4.CreateRotationY(angle * rotate_cube)); program["enable_lighting"].SetValue(lighting); // bind the vertex positions, UV coordinates and element array Gl.BindBufferToShaderAttribute(cube, program, "vertexPosition"); Gl.BindBufferToShaderAttribute(cubeNormals, program, "vertexNormal"); Gl.BindBufferToShaderAttribute(cubeUV, program, "vertexUV"); Gl.BindBuffer(cubeQuads); // draw the textured cube Gl.DrawElements(BeginMode.Quads, cubeQuads.Count, DrawElementsType.UnsignedInt, IntPtr.Zero); //<<<<<<<<<<<< BOTTOM PYRAMID // set the transformation of the bottom_pyramid program["model_matrix"].SetValue(Matrix4.CreateRotationY(angle * rotate_cube)); program["enable_lighting"].SetValue(lighting); // bind the vertex positions, UV coordinates and element array Gl.BindBufferToShaderAttribute(bottom_pyramid, program, "vertexPosition"); Gl.BindBufferToShaderAttribute(bottom_pyramidNormals, program, "vertexNormal"); Gl.BindBufferToShaderAttribute(bottom_pyramidUV, program, "vertexUV"); Gl.BindBuffer(bottom_pyramidTrianlges); // draw the textured bottom_pyramid Gl.DrawElements(BeginMode.Triangles, bottom_pyramidTrianlges.Count, DrawElementsType.UnsignedInt, IntPtr.Zero); //<<<<<<<<<<<<< STAR Gl.Disable(EnableCap.DepthTest); Gl.Enable(EnableCap.Blend); Gl.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.One); Gl.BindTexture(starTexture); //calculate the camera position using some fancy polar co-ordinates Vector3 position = 20 * new Vector3(Math.Cos(phi) * Math.Sin(theta), Math.Cos(theta), Math.Sin(phi) * Math.Sin(theta)); Vector3 upVector = ((theta % (Math.PI * 2)) > Math.PI) ? Vector3.Up : Vector3.Down; program_2["view_matrix"].SetValue(Matrix4.LookAt(position, Vector3.Zero, upVector)); // make sure the shader program and texture are being used Gl.UseProgram(program_2); // loop through the stars, drawing each one for (int i = 0; i < stars.Count; i++) { // set the position and color of this star program_2["model_matrix"].SetValue(Matrix4.CreateTranslation(new Vector3(stars[i].dist, 0, 0)) * Matrix4.CreateRotationZ(stars[i].angle)); program_2["color"].SetValue(stars[i].color); Gl.BindBufferToShaderAttribute(star, program_2, "vertexPosition"); Gl.BindBufferToShaderAttribute(starUV, program_2, "vertexUV"); Gl.BindBuffer(starQuads); Gl.DrawElements(BeginMode.Quads, starQuads.Count, DrawElementsType.UnsignedInt, IntPtr.Zero); // update the position of the star stars[i].angle += (float)i / stars.Count * deltaTime * 2 * rotate_stars; stars[i].dist -= 0.2f * deltaTime * rotate_stars; // if we've reached the center then move this star outwards and give it a new color if (stars[i].dist < 0f) { stars[i].dist += 5f; stars[i].color = new Vector3(generator.NextDouble(), generator.NextDouble(), generator.NextDouble()); } } Glut.glutSwapBuffers(); } The same goes for the textures, whichever one I mention last gets applied to both object?

    Read the article

  • Java multiple connections downloading file

    - by weulerjunior
    Hello friends, I was wanting to add multiple connections in the code below to be able to download files faster. Could someone help me? Thanks in advance. public void run() { RandomAccessFile file = null; InputStream stream = null; try { // Open connection to URL. HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // Specify what portion of file to download. connection.setRequestProperty("Range", "bytes=" + downloaded + "-"); // Connect to server. connection.connect(); // Make sure response code is in the 200 range. if (connection.getResponseCode() / 100 != 2) { error(); } // Check for valid content length. int contentLength = connection.getContentLength(); if (contentLength < 1) { error(); } /* Set the size for this download if it hasn't been already set. */ if (size == -1) { size = contentLength; stateChanged(); } // Open file and seek to the end of it. file = new RandomAccessFile("C:\\"+getFileName(url), "rw"); file.seek(downloaded); stream = connection.getInputStream(); while (status == DOWNLOADING) { /* Size buffer according to how much of the file is left to download. */ byte buffer[]; if (size - downloaded > MAX_BUFFER_SIZE) { buffer = new byte[MAX_BUFFER_SIZE]; } else { buffer = new byte[size - downloaded]; } // Read from server into buffer. int read = stream.read(buffer); if (read == -1) { break; } // Write buffer to file. file.write(buffer, 0, read); downloaded += read; stateChanged(); } /* Change status to complete if this point was reached because downloading has finished. */ if (status == DOWNLOADING) { status = COMPLETE; stateChanged(); } } catch (Exception e) { error(); } finally { // Close file. if (file != null) { try { file.close(); } catch (Exception e) { } } // Close connection to server. if (stream != null) { try { stream.close(); } catch (Exception e) { } } } }

    Read the article

  • Multiple Cookie Generation Issue

    - by Shannon
    Hi all, jQuery newbie here. I need to be able to set multiple cookies within the code without have to change out this variable each and every time. Is there any way to make this code generate unique cookies for different pages? As it is now, I'm having to rename that variable for each page that the jQuery animations exist on. (sbbcookiename) Background on the issue: We are having issues with the sliders not autoplaying once one has already been triggered, due to it the cookie having been cached. Thanks for your help. (function(){ jQuery.noConflict(); var _TIMEOUT= 1000, initTimer= 0, sbLoaded= false, _re= null ; initTimer= setTimeout(initSlider, _TIMEOUT); jQuery(document).ready(initSlider); function initSlider(){ if(sbLoaded) return; if (jQuery('#campaign_name').length > 0) { var sbbcookiename = jQuery('#campaign_name').attr('class'); } else { var sbbcookiename = "slider728x90"; } var slideTimeout //timer ,sbTrigger = jQuery('#slidebartrigger') //convenience ,sbFirstSlide = (document.cookie.indexOf(sbbcookiename) == -1) //check cookie for 'already seen today' ; clearTimeout(initTimer); sbLoaded= true; function toggleSlideboxes(){ if(slideTimeout) clearTimeout(slideTimeout); var isDown = sbTrigger.is('.closeSlide'); jQuery('#slidebar')['slide' + (isDown ? 'Up' : 'Down')]((isDown ? 1000 : 1000), function(){ if(sbFirstSlide){ //if 'first time today' then clear for click-to-replay sbTrigger.removeClass('firstSlide'); sbFirstSlide = false; } sbTrigger[(isDown ? 'remove' : 'add') + 'Class']('closeSlide').one('click', toggleSlideboxes); if(!isDown) slideTimeout = setTimeout(toggleSlideboxes, 4000); }); } if(sbFirstSlide){ //not seen yet today so set a cookie for expire tomorrow, then toggle the slide boxes... var oneDay = new Date(); oneDay.setUTCDate(oneDay.getUTCDate()+1); oneDay.setUTCHours(0, 0, 0, 0); //set to literally day-by-day, rather than 24 hours document.cookie=sbbcookiename+"=true;path=/;expires="+oneDay.toUTCString(); toggleSlideboxes(); }else{ //already seen today so show the trigger and set a click event on it... sbTrigger.removeClass('firstSlide').one('click', toggleSlideboxes); } } })();

    Read the article

  • [C++] Multiple inheritance from template class

    - by Tom P.
    Hello, I'm having issues with multiple inheritance from different instantiations of the same template class. Specifically, I'm trying to do this: template <class T> class Base { public: Base() : obj(NULL) { } virtual ~Base() { if( obj != NULL ) delete obj; } template <class T> T* createBase() { obj = new T(); return obj; } protected: T* obj; }; class Something { // ... }; class SomethingElse { // ... }; class Derived : public Base<Something>, public Base<SomethingElse> { }; int main() { Derived* d = new Derived(); Something* smth1 = d->createBase<Something>(); SomethingElse* smth2 = d->createBase<SomethingElse>(); delete d; return 0; } When I try to compile the above code, I get the following errors: 1>[...](41) : error C2440: '=' : cannot convert from 'SomethingElse *' to 'Something *' 1> Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast 1> [...](71) : see reference to function template instantiation 'T *Base<Something>::createBase<SomethingElse>(void)' being compiled 1> with 1> [ 1> T=SomethingElse 1> ] 1>[...](43) : error C2440: 'return' : cannot convert from 'Something *' to 'SomethingElse *' 1> Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast The issue seems to be ambiguity due to member obj being inherited from both Base< Something and Base< SomethingElse , and I can work around it by disambiguating my calls to createBase: Something* smth1 = d->Base<Something>::createBase<Something>(); SomethingElse* smth2 = d->Base<SomethingElse>::createBase<SomethingElse>(); However, this solution is dreadfully impractical, syntactically speaking, and I'd prefer something more elegant. Moreover, I'm puzzled by the first error message. It seems to imply that there is an instantiation createBase< SomethingElse in Base< Something , but how is that even possible? Any information or advice regarding this issue would be much appreciated.

    Read the article

  • [grails] setting cookies when render type is "contentType: text/json"

    - by Robin Jamieson
    Is it possible to set cookies on response when the return render type is set as json? I can set cookies on the response object when returning with a standard render type and later on, I'm able to get it back on the subsequent request. However, if I were to set the cookies while rendering the return values as json, I can't seem to get back the cookie on the next request object. What's happening here? These two actions work as expected with 'basicForm' performing a regular form post to the action, 'withRegularSubmit', when the user clicks submit. // first action set the cookie and second action yields the originally set cookie def regularAction = { // using cookie plugin response.setCookie("username-regular", "regularCookieUser123",604800); return render(view: "basicForm"); } // called by form post def withRegularSubmit = { def myCookie = request.getCookie("username-regular"); // returns the value 'regularCookieUser123' return render(view: "resultView"); } When I switch to setting the cookie just before returning from the response with json, I don't get the cookie back with the post. The request starts by getting an html document that contains a form and when doc load event is fired, the following request is invoked via javascript with jQuery like this: var someUrl = "http://localhost/jsonAction"; $.get(someUrl, function(jsonData) { // do some work with javascript} The controller work: // this action is called initially and returns an html doc with a form. def loadJsonForm = { return render(view: "jsonForm"); } // called via javascript when the document load event is fired def jsonAction = { response.setCookie("username-json", "jsonCookieUser456",604800); // using cookie plugin return render(contentType:'text/json') { 'pair'('myKey': "someValue") }; } // called by form post def withJsonSubmit = { def myCookie = request.getCookie("username-json"); // got null value, expecting: jsonCookieUser456 return render(view: "resultView"); } The data is returned to the server as a result of the user pressing the 'submit' button and not through a script. Prior to the submit of both 'withRegularSubmit' and 'withJsonSubmit', I see the cookies stored in the browser (Firefox) so I know they reached the client.

    Read the article

  • Java multiple class compositing and boiler plate reduction

    - by h2g2java
    We all know why Java does/should not have multiple inheritance. So this is not questioning about what has already been debated till-cows-come-home. This discusses what we would do when we wish to create a class that has the characteristics of two or more other classes. Probably, most of us would do this to "inherit" from three classes. For simplicity, I left out the constructor.: class Car extends Vehicle { final public Transport transport; final public Machine machine; } So that, Car class directly inherits methods and objects of Vehicle class, but would have to refer to transport and machine explicitly to refer to objects instantiated in Transport and Machine. Car car = new Car(); car.drive(); // from Vehicle car.transport.isAmphibious(); // from Transport car.machine.getCO2Footprint(); // from Machine I thought this was a good idea until when I encounter frameworks that require setter and getter methods. For example, the XML <Car amphibious='false' footPrint='1000' model='Fordstatic999'/> would look for the methods setAmphibious(..), setFootPrint(..) and setModel(..). Therefore, I have to project the methods from Transport and Machine classes class Car extends Vehicle { final public Transport transport; final public Machine machine; public void setAmphibious(boolean b){ this.transport.setAmphibious(b); } public void setFootPrint(String fp){ this.machine.setFootPrint(fp); } } This is OK, if there were just a few characteristics. Right now, I am trying to adapt all of SmartGWT into GWT UIBinder, especially those classes that are not a GWT widget. There are lots of characteristics to project. Wouldn't it be nice if there exists some form of annotation framework that is like this: class Car extends Vehicle @projects {Transport @projects{Machine @projects Guzzler}} { /* No need to explicitly instantiate Transport, Machine or Guzzler */ .... } Where, in case of common names of characteristics exist, the characteristics of Machine would take precedence Guzzler's, and Transport's would have precedence over Machine's, and Vehicle's would have precedence over Transport's. The annotation framework would then instantiate Transport, Machine and Guzzler as hidden members of Car and expand to break-out the protected/public characteristics, in the precedence dictated by the @project annotation sequence, into actual source code or into byte-code. Preferably into byte-code. So that the setFootPrint method is found in both Machine and Guzzler, only that of Machine's would be projected. Questions: Don't you think this is a good idea to have such a framework? Does such a framework already exist? Tell me where/what. Is there an eclipse plugin that does it? Is there a proposal or plan anywhere that you know about such an annotation framework? It would be wonderful too, if the annotation/plugin framework lets me specify that boolean, int, or whatever else needs to be converted from String and does the conversion/parsing for me too. Please advise, somebody. I hope wording of my question was clear enough. Thx. Edited: To avoid OO enthusiasts jumping to conclusion, I have renamed the title of this question.

    Read the article

  • Templates, interfaces (multiple inheritance) and static functions (named constructors)

    - by fledgling Cxx user
    Setup I have a graph library where I am trying to decompose things as much as possible, and the cleanest way to describe it that I found is the following: there is a vanilla type node implementing only a list of edges: class node { public: int* edges; int edge_count; }; Then, I would like to be able to add interfaces to this whole mix, like so: template <class T> class node_weight { public: T weight; }; template <class T> class node_position { public: T x; T y; }; and so on. Then, the actual graph class comes in, which is templated on the actual type of node: template <class node_T> class graph { protected: node_T* nodes; public: static graph cartesian(int n, int m) { graph r; r.nodes = new node_T[n * m]; return r; } }; The twist is that it has named constructors which construct some special graphs, like a Cartesian lattice. In this case, I would like to be able to add some extra information into the graph, depending on what interfaces are implemented by node_T. What would be the best way to accomplish this? Possible solution I thought of the following humble solution, through dynamic_cast<>: template <class node_T, class weight_T, class position_T> class graph { protected: node_T* nodes; public: static graph cartesian(int n, int m) { graph r; r.nodes = new node_T[n * m]; if (dynamic_cast<node_weight<weight_T>>(r.nodes[0]) != nullptr) { // do stuff knowing you can add weights } if (dynamic_cast<node_position<positionT>>(r.nodes[0]) != nullptr) { // do stuff knowing you can set position } return r; } }; which would operate on node_T being the following: template <class weight_T, class position_T> class node_weight_position : public node, public node_weight<weight_T>, public node_position<position_T> { // ... }; Questions Is this -- philosophically -- the right way to go? I know people don't look nicely at multiple inheritance, though with "interfaces" like these it should all be fine. There are unfortunately problems with this. From what I know at least, dynamic_cast<> involves quite a bit of run-time overhead. Hence, I run into a problem with what I had solved earlier: writing graph algorithms that require weights independently of whether the actual node_T class has weights or not. The solution with this 'interface' approach would be to write a function: template <class node_T, class weight_T> inline weight_T get_weight(node_T const & n) { if (dynamic_cast<node_weight<weight_T>>(n) != nullptr) { return dynamic_cast<node_weight<weight_T>>(n).weight; } return T(1); } but the issue with it is that it works using run-time information (dynamic_cast), yet in principle I would like to decide it at compile-time and thus make the code more efficient. If there is a different solution that would solve both problems, especially a cleaner and better one than what I have, I would love to hear about it!

    Read the article

  • "undefined reference" error with namespace across multiple files

    - by user1330734
    I've looked at several related posts but no luck with this error. I receive this undefined reference error message below when my namespace exists across multiple files. If I compile only ConsoleTest.cpp with contents of Console.cpp dumped into it the source compiles. I would appreciate any feedback on this issue, thanks in advance. g++ Console.cpp ConsoleTest.cpp -o ConsoleTest.o -Wall /tmp/cc8KfSLh.o: In function `getValueTest()': ConsoleTest.cpp:(.text+0x132): undefined reference to `void Console::getValue<unsigned int>(unsigned int&)' collect2: ld returned 1 exit status Console.h #include <iostream> #include <sstream> #include <string> namespace Console { std::string getLine(); template <typename T> void getValue(T &value); } Console.cpp #include "Console.h" using namespace std; namespace Console { string getLine() { string str; while (true) { cin.clear(); if (cin.eof()) { break; // handle eof (Ctrl-D) gracefully } if (cin.good()) { char next = cin.get(); if (next == '\n') break; str += next; // add character to string } else { cin.clear(); // clear error state string badToken; cin >> badToken; cerr << "Bad input encountered: " << badToken << endl; } } return str; } template <typename T> void getValue(T &value) { string inputStr = Console::getLine(); istringstream strStream(inputStr); strStream >> value; } } ConsoleTest.cpp #include "Console.h" void getLineTest() { std::string str; std::cout << "getLinetest" << std::endl; while (str != "next") { str = Console::getLine(); std::cout << "<string>" << str << "</string>"<< std::endl; } } void getValueTest() { std::cout << "getValueTest" << std::endl; unsigned x = 0; while (x != 12345) { Console::getValue(x); std::cout << "x: " << x << std::endl; } } int main() { getLineTest(); getValueTest(); return 0; }

    Read the article

  • MVC 3 AdditionalMetadata Attribute with ViewBag to Render Dynamic UI

    - by Steve Michelotti
    A few months ago I blogged about using Model metadata to render a dynamic UI in MVC 2. The scenario in the post was that we might have a view model where the questions are conditionally displayed and therefore a dynamic UI is needed. To recap the previous post, the solution was to use a custom attribute called [QuestionId] in conjunction with an “ApplicableQuestions” collection to identify whether each question should be displayed. This allowed me to have a view model that looked like this: 1: [UIHint("ScalarQuestion")] 2: [DisplayName("First Name")] 3: [QuestionId("NB0021")] 4: public string FirstName { get; set; } 5: 6: [UIHint("ScalarQuestion")] 7: [DisplayName("Last Name")] 8: [QuestionId("NB0022")] 9: public string LastName { get; set; } 10: 11: [UIHint("ScalarQuestion")] 12: [QuestionId("NB0023")] 13: public int Age { get; set; } 14: 15: public IEnumerable<string> ApplicableQuestions { get; set; } At the same time, I was able to avoid repetitive IF statements for every single question in my view: 1: <%: Html.EditorFor(m => m.FirstName, new { applicableQuestions = Model.ApplicableQuestions })%> 2: <%: Html.EditorFor(m => m.LastName, new { applicableQuestions = Model.ApplicableQuestions })%> 3: <%: Html.EditorFor(m => m.Age, new { applicableQuestions = Model.ApplicableQuestions })%> by creating an Editor Template called “ScalarQuestion” that encapsulated the IF statement: 1: <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %> 2: <%@ Import Namespace="DynamicQuestions.Models" %> 3: <%@ Import Namespace="System.Linq" %> 4: <% 5: var applicableQuestions = this.ViewData["applicableQuestions"] as IEnumerable<string>; 6: var questionAttr = this.ViewData.ModelMetadata.ContainerType.GetProperty(this.ViewData.ModelMetadata.PropertyName).GetCustomAttributes(typeof(QuestionIdAttribute), true) as QuestionIdAttribute[]; 7: string questionId = null; 8: if (questionAttr.Length > 0) 9: { 10: questionId = questionAttr[0].Id; 11: } 12: if (questionId != null && applicableQuestions.Contains(questionId)) { %> 13: <div> 14: <%: Html.Label("") %> 15: <%: Html.TextBox("", this.Model)%> 16: </div> 17: <% } %> You might want to go back and read the full post in order to get the full context. MVC 3 offers a couple of new features that make this scenario more elegant to implement. The first step is to use the new [AdditionalMetadata] attribute which, so far, appears to be an under appreciated new feature of MVC 3. With this attribute, I don’t need my custom [QuestionId] attribute anymore - now I can just write my view model like this: 1: [UIHint("ScalarQuestion")] 2: [DisplayName("First Name")] 3: [AdditionalMetadata("QuestionId", "NB0021")] 4: public string FirstName { get; set; } 5:   6: [UIHint("ScalarQuestion")] 7: [DisplayName("Last Name")] 8: [AdditionalMetadata("QuestionId", "NB0022")] 9: public string LastName { get; set; } 10:   11: [UIHint("ScalarQuestion")] 12: [AdditionalMetadata("QuestionId", "NB0023")] 13: public int Age { get; set; } Thus far, the documentation seems to be pretty sparse on the AdditionalMetadata attribute. It’s buried in the Other New Features section of the MVC 3 home page and, after showing the attribute on a view model property, it just says, “This metadata is made available to any display or editor template when a product view model is rendered. It is up to you to interpret the metadata information.” But what exactly does it look like for me to “interpret the metadata information”? Well, it turns out it makes the view much easier to work with. Here is the re-implemented ScalarQuestion template updated for MVC 3 and Razor: 1: @{ 2: object questionId; 3: ViewData.ModelMetadata.AdditionalValues.TryGetValue("QuestionId", out questionId); 4: if (ViewBag.applicableQuestions.Contains((string)questionId)) { 5: <div> 6: @Html.LabelFor(m => m) 7: @Html.TextBoxFor(m => m) 8: </div> 9: } 10: } So we’ve gone from 17 lines of code (in the MVC 2 version) to about 7-8 lines of code here. The first thing to notice is that in MVC 3 we now have a property called “AdditionalValues” that hangs off of the ModelMetadata property. This is automatically populated by any [AdditionalMetadata] attributes on the property. There is no more need for me to explicitly write Reflection code to GetCustomAttributes() and then check to see if those attributes were present. I can just call TryGetValue() on the dictionary to see if they were present. Secondly, the “applicableQuestions” anonymous type that I passed in from the calling view – in MVC 3 I now have a dynamic ViewBag property where I can just “dot into” the applicableQuestions with a nicer syntax than dictionary square bracket syntax. And there’s no problems calling the Contains() method on this dynamic object because at runtime the DLR has resolved that it is a generic List<string>. At this point you might be saying that, yes the view got much nicer than the MVC 2 version, but my view model got slightly worse.  In the previous version I had a nice [QuestionId] attribute but now, with the [AdditionalMetadata] attribute, I have to type the string “QuestionId” for every single property and hope that I don’t make a typo. Well, the good news is that it’s easy to create your own attributes that can participate in the metadata’s additional values. The key is that the attribute must implement that IMetadataAware interface and populate the AdditionalValues dictionary in the OnMetadataCreated() method: 1: public class QuestionIdAttribute : Attribute, IMetadataAware 2: { 3: public string Id { get; set; } 4:   5: public QuestionIdAttribute(string id) 6: { 7: this.Id = id; 8: } 9:   10: public void OnMetadataCreated(ModelMetadata metadata) 11: { 12: metadata.AdditionalValues["QuestionId"] = this.Id; 13: } 14: } This now allows me to encapuslate my “QuestionId” string in just one place and get back to my original attribute which can be used like this: [QuestionId(“NB0021”)]. The [AdditionalMetadata] attribute is a powerful and under-appreciated new feature of MVC 3. Combined with the dynamic ViewBag property, you can do some really interesting things with your applications with less code and ceremony.

    Read the article

  • Looking for simple windows scan (multiple pages) to one pdf application?

    - by Troggy
    I would like to find some simple scan software for a windows machine that can scan to pdf, but I would like it to do batch or multiple pages into one big pdf. I saw a couple questions on scan to pdf software, but did not see anything talking about scanning to large multiple page pdf's. EDIT: I am surprised there are not more options out there. Do many of the scanners/all in one devices come with included software that perform this function? EDIT 2: I tried Scan2PDF and it locked up on me multiple times in the middle of the scan job and then gave me non-english error messages. Otherwise, I liked how simple the app was, just select number of pages and hit ok. Any other success stories out there?

    Read the article

  • Microsoft.Build.Engine Error (default targets): Target GetFrameworkPaths: Could not locate the .NET

    - by Mitchan Adams
    I am writing a webservice, that when called should build a C# project. I'm using the framework 2 reference, Microsoft.Buld.Engine and Microsoft.Build.Framework. If you look under the '<Import>' section .csproj file, by default it has: <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> which I then changed to: <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" /> My code to build the csproj is: Engine buildEngine = new Engine(Path.Combine(Environment.GetEnvironmentVariable("SystemRoot"), @"Microsoft.NET\Framework\v2.0.50727")); FileLogger logger = new FileLogger(); logger.Parameters = @"logfile=c:\temp\build.log"; buildEngine.RegisterLogger(logger); bool success = buildEngine.BuildProjectFile([Path_Of_Directory]+ "ProjectName.csproj"); buildEngine.UnregisterAllLoggers(); The success variable returns a false because the build faild. I then check the build.log file and this is the error I recieve: *Build started 3/17/2010 11:16:56 AM. ______________________________ Project "[Path_Of_Directory]\ProjectName.csproj" (default targets): Target GetFrameworkPaths: Could not locate the .NET Framework SDK. The task is looking for the path to the .NET Framework SDK at the location specified in the SDKInstallRootv2.0 value of the registry key HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft.NETFramework. You may be able to solve the problem by doing one of the following: 1.) Install the .NET Framework SDK. 2.) Manually set the above registry key to the correct location. Target* I cant understand why it wont build. Any help will be much appreciated. Thanks

    Read the article

  • Render web page to picture.

    - by Steck
    I have the string with URL. For example "http://google.com". Is there are any way to download and render this page to picture file? ("test.jpg") I tried to use WebBrowser control, to download and render picture, but it only works when WebBrowser placed in displayed form. In other ways it's render only black rectangle. But i want to render picture without any visual effect (creating, activating form etc.)

    Read the article

< Previous Page | 12 13 14 15 16 17 18 19 20 21 22 23  | Next Page >