Search Results

Search found 5942 results on 238 pages for 'total starnger'.

Page 232/238 | < Previous Page | 228 229 230 231 232 233 234 235 236 237 238  | Next Page >

  • Fetching value from collection

    - by user334119
    public string GetProductVariantImageUrl(ShoppingCartItem shoppingCartItem) { string pictureUrl = String.Empty; ProductVariant productVariant = shoppingCartItem.ProductVariant; ProductVariantAttributeValueCollection pvaValues = shoppingCartItem.Attributes; [here the count comes 0]{case1} } public string GetAttributeDescription(ShoppingCartItem shoppingCartItem) { string result = string.Empty; ProductVariant productVariant = shoppingCartItem.ProductVariant; if (productVariant != null) { ProductVariantAttributeValueCollection pvaValues = shoppingCartItem.Attributes;[here count is 1] } } WHY am i not able to get count as 1 for the case1. /// <summary> /// Represents a shopping cart item /// </summary> public class ShoppingCartItem : BaseEntity { #region Fields private ProductVariant _cachedProductVariant; private ProductVariantAttributeValueCollection _cachedPvaValues; #endregion #region Ctor /// <summary> /// Creates a new instance of the shopping cart class /// </summary> public ShoppingCartItem() { } #endregion #region Properties /// <summary> /// Gets or sets the shopping cart item identifier /// </summary> public int ShoppingCartItemID { get; set; } /// <summary> /// Gets or sets the shopping cart type identifier /// </summary> public int ShoppingCartTypeID { get; set; } /// <summary> /// Gets or sets the customer session identifier /// </summary> public Guid CustomerSessionGUID { get; set; } /// <summary> /// Gets or sets the product variant identifier /// </summary> public int ProductVariantID { get; set; } /// <summary> /// Gets or sets the product variant attribute identifiers /// </summary> public List<int> AttributeIDs { get; set; } /// <summary> /// Gets or sets the text option /// </summary> public string TextOption { get; set; } /// <summary> /// Gets or sets the quantity /// </summary> public int Quantity { get; set; } /// <summary> /// Gets or sets the date and time of instance creation /// </summary> public DateTime CreatedOn { get; set; } /// <summary> /// Gets or sets the date and time of instance update /// </summary> public DateTime UpdatedOn { get; set; } #endregion #region Custom Properties /// <summary> /// Gets the log type /// </summary> public ShoppingCartTypeEnum ShoppingCartType { get { return (ShoppingCartTypeEnum)ShoppingCartTypeID; } } /// <summary> /// Gets the product variant /// </summary> public ProductVariant ProductVariant { get { if (_cachedProductVariant == null) { _cachedProductVariant = ProductManager.GetProductVariantByID(ProductVariantID); } return _cachedProductVariant; } } /// <summary> /// Gets the product variant attribute values /// </summary> public ProductVariantAttributeValueCollection Attributes { get { if (_cachedPvaValues == null) { ProductVariantAttributeValueCollection pvaValues = new ProductVariantAttributeValueCollection(); foreach (int attributeID in this.AttributeIDs) { ProductVariantAttributeValue pvaValue = ProductAttributeManager.GetProductVariantAttributeValueByID(attributeID); if (pvaValue != null) pvaValues.Add(pvaValue); } _cachedPvaValues = pvaValues; } return _cachedPvaValues; } } /// <summary> /// Gets the total weight /// </summary> public decimal TotalWeigth { get { decimal totalWeigth = decimal.Zero; ProductVariant productVariant = ProductVariant; if (productVariant != null) { decimal attributesTotalWeight = decimal.Zero; foreach (ProductVariantAttributeValue pvaValue in this.Attributes) { attributesTotalWeight += pvaValue.WeightAdjustment; } decimal unitWeight = productVariant.Weight + attributesTotalWeight; totalWeigth = unitWeight * Quantity; } return totalWeigth; } } /// <summary> /// Gets a value indicating whether the shopping cart item is free shipping /// </summary> public bool IsFreeShipping { get { ProductVariant productVariant = this.ProductVariant; if (productVariant != null) return productVariant.IsFreeShipping; return true; } }

    Read the article

  • How to filter Backbone.js Collection and Rerender App View?

    - by Jeremy H.
    Is is a total Backbone.js noob question. I am working off of the ToDo Backbone.js example trying to build out a fairly simple single app interface. While the todo project is more about user input, this app is more about filtering the data based on the user options (click events). I am completely new to Backbone.js and Mongoose and have been unable to find a good example of what I am trying to do. I have been able to get my api to pull the data from the MongoDB collection and drop it into the Backbone.js collection which renders it in the app. What I cannot for the life of me figure out how to do is filter that data and re-render the app view. I am trying to filter by the "type" field in the document. Here is my script: (I am totally aware of some major refactoring needed, I am just rapid prototyping a concept.) $(function() { window.Job = Backbone.Model.extend({ idAttribute: "_id", defaults: function() { return { attachments: false } } }); window.JobsList = Backbone.Collection.extend({ model: Job, url: '/api/jobs', leads: function() { return this.filter(function(job){ return job.get('type') == "Lead"; }); } }); window.Jobs = new JobsList; window.JobView = Backbone.View.extend({ tagName: "div", className: "item", template: _.template($('#item-template').html()), initialize: function() { this.model.bind('change', this.render, this); this.model.bind('destroy', this.remove, this); }, render: function() { $(this.el).html(this.template(this.model.toJSON())); this.setText(); return this; }, setText: function() { var month=new Array(); month[0]="Jan"; month[1]="Feb"; month[2]="Mar"; month[3]="Apr"; month[4]="May"; month[5]="Jun"; month[6]="Jul"; month[7]="Aug"; month[8]="Sep"; month[9]="Oct"; month[10]="Nov"; month[11]="Dec"; var title = this.model.get('title'); var description = this.model.get('description'); var datemonth = this.model.get('datem'); var dateday = this.model.get('dated'); var jobtype = this.model.get('type'); var jobstatus = this.model.get('status'); var amount = this.model.get('amount'); var paymentstatus = this.model.get('paymentstatus') var type = this.$('.status .jobtype'); var status = this.$('.status .jobstatus'); this.$('.title a').text(title); this.$('.description').text(description); this.$('.date .month').text(month[datemonth]); this.$('.date .day').text(dateday); type.text(jobtype); status.text(jobstatus); if(amount > 0) this.$('.paymentamount').text(amount) if(paymentstatus) this.$('.paymentstatus').text(paymentstatus) if(jobstatus === 'New') { status.addClass('new'); } else if (jobstatus === 'Past Due') { status.addClass('pastdue') }; if(jobtype === 'Lead') { type.addClass('lead'); } else if (jobtype === '') { type.addClass(''); }; }, remove: function() { $(this.el).remove(); }, clear: function() { this.model.destroy(); } }); window.AppView = Backbone.View.extend({ el: $("#main"), events: { "click #leads .highlight" : "filterLeads" }, initialize: function() { Jobs.bind('add', this.addOne, this); Jobs.bind('reset', this.addAll, this); Jobs.bind('all', this.render, this); Jobs.fetch(); }, addOne: function(job) { var view = new JobView({model: job}); this.$("#activitystream").append(view.render().el); }, addAll: function() { Jobs.each(this.addOne); }, filterLeads: function() { // left here, this event fires but i need to figure out how to filter the activity list. } }); window.App = new AppView; });

    Read the article

  • New hire expectations... (Am I being unreasonable?)

    - by user295841
    I work for a very small custom software shop. We currently consist me and my boss. My boss is an old FoxPro DOS developer and OOP makes him uncomfortable. He is planning on taking a back seat in the next few years to hopefully enjoy a “partial retirement”. I will be taking over the day to day operations and we are now desperately looking for more help. We tried Monster.com, Dice.com, and others a few years ago when we started our search. We had no success. We have tried outsourcing overseas (total disaster), hiring kids right out of college (mostly a disaster but that’s where I came from), interns (good for them, not so good for us) and hiring laid off “experienced” developers (there was a reason they were laid off). I have heard hiring practices discussed on podcasts, blogs, etc... and have tried a few. The “Fizz Buzz” test was a good one. One kid looked physically ill before he finally gave up. I think my problem is that I have grown so much as a developer since I started here that I now have a high standard. I hear/read very intelligent people podcasts and blogs and I know that there are lots of people out there that can do the job. I don’t want to settle for less than a “good” developer. Perhaps my expectations are unreasonable. I expect any good developer (entry level or experienced) to be billable (at least paying their own wage) in under one month. I expect any good developer to be able to be productive (at least dangerous) in any language or technology with only a few days of research/training. I expect any good developer to be able to take a project from initial customer request to completion with little or no help from others. Am I being unreasonable? What constitutes a valuable developer? What should be expected of an entry level developer? What should be expected of an experienced developer? I realize that everyone is different but there has to be some sort of expectations standard, right? I have been giving the test project below to potential canidates to weed them out. Good idea? Too much? Too little? Please let me know what you think. Thanks. Project ID: T00001 Description: Order Entry System Deadline: 1 Week Scope The scope of this project is to develop a fully function order entry system. Screen/Form design must be user friendly and promote efficient data entry and modification. User experience (Navigation, Screen/Form layouts, Look and Feel…) is at the developer’s discretion. System may be developed using any technologies that conform to the technical and system requirements. Deliverables Complete source code Database setup instructions (Scripts or restorable backup) Application installation instructions (Installer or installation procedure) Any necessary documentation Technical Requirements Server Platform – Windows XP / Windows Server 2003 / SBS Client Platform – Windows XP Web Browser (If applicable) – IE 8 Database – At developer’s discretion (Must be a relational SQL database.) Language – At developer’s discretion All data must be normalized. (+) All data must maintain referential integrity. (++) All data must be indexed for optimal performance. System must handle concurrency. System Requirements Customer Maintenance Customer records must have unique ID. Customer data will include Name, Address, Phone, etc. User must be able to perform all CRUD (Create, Read, Update, and Delete) operations on the Customer table. User must be able to enter a specific Customer ID to edit. User must be able to pull up a sortable/queryable search grid/utility to find a customer to edit. Validation must be performed prior to database commit. Customer record cannot be deleted if the customer has an order in the system. (++) Inventory Maintenance Part records must have unique ID. Part data will include Description, Price, UOM (Unit of Measure), etc. User must be able to perform all CRUD operations on the part table. User must be able to enter a specific Part ID to edit. User must be able to pull up a sortable/queryable search grid/utility to find a part to edit. Validation must be performed prior to database commit. Part record cannot be deleted if the part has been used in an order. (++) Order Entry Order records must have a unique auto-incrementing key (Order Number). Order data must be split into a header/detail structure. (+) Order can contain an infinite number of detail records. Order header data will include Order Number, Customer ID (++), Order Date, Order Status (Open/Closed), etc. Order detail data will include Part Number (++), Quantity, Price, etc. User must be able to perform all CRUD operations on the order tables. User must be able to enter a specific Order Number to edit. User must be able to pull up a sortable/queryable search grid/utility to find an order to edit. User must be able to print an order form from within the order entry form. Validation must be performed prior to database commit. Reports Customer Listing – All Customers in the system. Inventory Listing – All parts in the system. Open Order Listing – All open orders in system. Customer Order Listing – All orders for specific customer. All reports must include sorts and filter functions where applicable. Ex. Customer Listing by range of Customer IDs. Open Order Listing by date range.

    Read the article

  • What's wrong with Bundler working with RubyGems to push a Git repo to Heroku?

    - by stanigator
    I've made sure that all the files are in the root of the repository as recommended in this discussion. However, as I follow the instructions in this section of the book, I can't get through the section without the problems. What do you think is happening with my system that's causing the error? I have no clue at the moment of what the problem means despite reading the following in the log. Thanks in advance for your help! stanley@ubuntu:~/rails_sample/first_app$ git push heroku master Warning: Permanently added the RSA host key for IP address '50.19.85.156' to the list of known hosts. Counting objects: 96, done. Compressing objects: 100% (79/79), done. Writing objects: 100% (96/96), 28.81 KiB, done. Total 96 (delta 22), reused 0 (delta 0) -----> Heroku receiving push -----> Ruby/Rails app detected -----> Installing dependencies using Bundler version 1.2.0.pre Running: bundle install --without development:test --path vendor/bundle --binstubs bin/ --deployment Fetching gem metadata from https://rubygems.org/....... Installing rake (0.9.2.2) Installing i18n (0.6.0) Installing multi_json (1.3.5) Installing activesupport (3.2.3) Installing builder (3.0.0) Installing activemodel (3.2.3) Installing erubis (2.7.0) Installing journey (1.0.3) Installing rack (1.4.1) Installing rack-cache (1.2) Installing rack-test (0.6.1) Installing hike (1.2.1) Installing tilt (1.3.3) Installing sprockets (2.1.3) Installing actionpack (3.2.3) Installing mime-types (1.18) Installing polyglot (0.3.3) Installing treetop (1.4.10) Installing mail (2.4.4) Installing actionmailer (3.2.3) Installing arel (3.0.2) Installing tzinfo (0.3.33) Installing activerecord (3.2.3) Installing activeresource (3.2.3) Installing coffee-script-source (1.3.3) Installing execjs (1.3.2) Installing coffee-script (2.2.0) Installing rack-ssl (1.3.2) Installing json (1.7.3) with native extensions Installing rdoc (3.12) Installing thor (0.14.6) Installing railties (3.2.3) Installing coffee-rails (3.2.2) Installing jquery-rails (2.0.2) Using bundler (1.2.0.pre) Installing rails (3.2.3) Installing sass (3.1.18) Installing sass-rails (3.2.5) Installing sqlite3 (1.3.6) with native extensions Gem::Installer::ExtensionBuildError: ERROR: Failed to build gem native extension. /usr/local/bin/ruby extconf.rb checking for sqlite3.h... no sqlite3.h is missing. Try 'port install sqlite3 +universal' or 'yum install sqlite-devel' and check your shared library search path (the location where your sqlite3 shared library is located). *** extconf.rb failed *** Could not create Makefile due to some reason, probably lack of necessary libraries and/or headers. Check the mkmf.log file for more details. You may need configuration options. Provided configuration options: --with-opt-dir --without-opt-dir --with-opt-include --without-opt-include=${opt-dir}/include --with-opt-lib --without-opt-lib=${opt-dir}/lib --with-make-prog --without-make-prog --srcdir=. --curdir --ruby=/usr/local/bin/ruby --with-sqlite3-dir --without-sqlite3-dir --with-sqlite3-include --without-sqlite3-include=${sqlite3-dir}/include --with-sqlite3-lib --without-sqlite3-lib=${sqlite3-dir}/lib --enable-local --disable-local Gem files will remain installed in /tmp/build_3tplrxvj7qa81/vendor/bundle/ruby/1.9.1/gems/sqlite3-1.3.6 for inspection. Results logged to /tmp/build_3tplrxvj7qa81/vendor/bundle/ruby/1.9.1/gems/sqlite3-1.3.6/ext/sqlite3/gem_make.out An error occurred while installing sqlite3 (1.3.6), and Bundler cannot continue. Make sure that `gem install sqlite3 -v '1.3.6'` succeeds before bundling. ! ! Failed to install gems via Bundler. ! ! Heroku push rejected, failed to compile Ruby/rails app To [email protected]:growing-mountain-2788.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to '[email protected]:growing-mountain-2788.git' ------Gemfile------------------------ As requested, here's the auto-generated gemfile: source 'https://rubygems.org' gem 'rails', '3.2.3' # Bundle edge Rails instead: # gem 'rails', :git => 'git://github.com/rails/rails.git' gem 'sqlite3' gem 'json' # Gems used only for assets and not required # in production environments by default. group :assets do gem 'sass-rails', '~> 3.2.3' gem 'coffee-rails', '~> 3.2.1' # See https://github.com/sstephenson/execjs#readme for more supported runtimes # gem 'therubyracer', :platform => :ruby gem 'uglifier', '>= 1.0.3' end gem 'jquery-rails' # To use ActiveModel has_secure_password # gem 'bcrypt-ruby', '~> 3.0.0' # To use Jbuilder templates for JSON # gem 'jbuilder' # Use unicorn as the app server # gem 'unicorn' # Deploy with Capistrano # gem 'capistrano' # To use debugger # gem 'ruby-debug'

    Read the article

  • Watching setTimeout loops so that only one is running at a time.

    - by DA
    I'm creating a content rotator in jQuery. 5 items total. Item 1 fades in, pauses 10 seconds, fades out, then item 2 fades in. Repeat. Simple enough. Using setTimeout I can call a set of functions that create a loop and will repeat the process indefinitely. I now want to add the ability to interrupt this rotator at any time by clicking on a navigation element to jump directly to one of the content items. I originally started going down the path of pinging a variable constantly (say every half second) that would check to see if a navigation element was clicked and, if so, abandon the loop, then restart the loop based on the item that was clicked. The challenge I ran into was how to actually ping a variable via a timer. The solution is to dive into JavaScript closures...which are a little over my head but definitely something I need to delve into more. However, in the process of that, I came up with an alternative option that actually seems to be better performance-wise (theoretically, at least). I have a sample running here: http://jsbin.com/uxupi/14 (It's using console.log so have fireBug running) Sample script: $(document).ready(function(){ var loopCount = 0; $('p#hello').click(function(){ loopCount++; doThatThing(loopCount); }) function doThatOtherThing(currentLoopCount) { console.log('doThatOtherThing-'+currentLoopCount); if(currentLoopCount==loopCount){ setTimeout(function(){doThatThing(currentLoopCount)},5000) } } function doThatThing(currentLoopCount) { console.log('doThatThing-'+currentLoopCount); if(currentLoopCount==loopCount){ setTimeout(function(){doThatOtherThing(currentLoopCount)},5000); } } }) The logic being that every click of the trigger element will kick off the loop passing into itself a variable equal to the current value of the global variable. That variable gets passed back and forth between the functions in the loop. Each click of the trigger also increments the global variable so that subsequent calls of the loop have a unique local variable. Then, within the loop, before the next step of each loop is called, it checks to see if the variable it has still matches the global variable. If not, it knows that a new loop has already been activated so it just ends the existing loop. Thoughts on this? Valid solution? Better options? Caveats? Dangers? UPDATE: I'm using John's suggestion below via the clearTimeout option. However, I can't quite get it to work. The logic is as such: var slideNumber = 0; var timeout = null; function startLoop(slideNumber) { ...do stuff here to set up the slide based on slideNumber... slideFadeIn() } function continueCheck(){ if (timeout != null) { // cancel the scheduled task. clearTimeout(timeout); timeout = null; return false; }else{ return true; } }; function slideFadeIn() { if (continueCheck){ // a new loop hasn't been called yet so proceed... // fade in the LI $currentListItem.fadeIn(fade, function() { if(multipleFeatures){ timeout = setTimeout(slideFadeOut,display); } }); }; function slideFadeOut() { if (continueLoop){ // a new loop hasn't been called yet so proceed... slideNumber=slideNumber+1; if(slideNumber==features.length) { slideNumber = 0; }; timeout = setTimeout(function(){startLoop(slideNumber)},100); }; startLoop(slideNumber); The above kicks of the looping. I then have navigation items that, when clicked, I want the above loop to stop, then restart with a new beginning slide: $(myNav).click(function(){ clearTimeout(timeout); timeout = null; startLoop(thisItem); }) If I comment out 'startLoop...' from the click event, it, indeed, stops the initial loop. However, if I leave that last line in, it doesn't actually stop the initial loop. Why? What happens is that both loops seem to run in parallel for a period. So, when I click my navigation, clearTimeout is called, which clears it.

    Read the article

  • Sending the files (At least 11 files) from folder through web service to android app.

    - by Shashank_Itmaster
    Hello All, I stuck in middle of this situation,Please help me out. My question is that I want to send files (Total 11 PDF Files) to android app using web service. I tried it with below code.Main Class from which web service is created public class MultipleFilesImpl implements MultipleFiles { public FileData[] sendPDFs() { FileData fileData = null; // List<FileData> filesDetails = new ArrayList<FileData>(); File fileFolder = new File( "C:/eclipse/workspace/AIPWebService/src/pdfs/"); // File fileTwo = new File( // "C:/eclipse/workspace/AIPWebService/src/simple.pdf"); File sendFiles[] = fileFolder.listFiles(); // sendFiles[0] = fileOne; // sendFiles[1] = fileTwo; DataHandler handler = null; char[] readLine = null; byte[] data = null; int offset = 0; int numRead = 0; InputStream stream = null; FileOutputStream outputStream = null; FileData[] filesData = null; try { System.out.println("Web Service Called Successfully"); for (int i = 0; i < sendFiles.length; i++) { handler = new DataHandler(new FileDataSource(sendFiles[i])); fileData = new FileData(); data = new byte[(int) sendFiles[i].length()]; stream = handler.getInputStream(); while (offset < data.length && (numRead = stream.read(data, offset, data.length - offset)) >= 0) { offset += numRead; } readLine = Base64Coder.encode(data); offset = 0; numRead = 0; System.out.println("'Reading File............................"); System.out.println("\n"); System.out.println(readLine); System.out.println("Data Reading Successful"); fileData.setFileName(sendFiles[i].getName()); fileData.setFileData(String.valueOf(readLine)); readLine = null; System.out.println("Data from bean " + fileData.getFileData()); outputStream = new FileOutputStream("D:/" + sendFiles[i].getName()); outputStream.write(Base64Coder.decode(fileData.getFileData())); outputStream.flush(); outputStream.close(); stream.close(); // FileData fileDetails = new FileData(); // fileDetails = fileData; // filesDetails.add(fileData); filesData = new FileData[(int) sendFiles[i].length()]; } // return fileData; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return filesData; } } Also The Interface MultipleFiles:- public interface MultipleFiles extends Remote { public FileData[] sendPDFs() throws FileNotFoundException, IOException, Exception; } Here I am sending an array of bean "File Data",having properties viz. FileData & FileName. FileData- contains file data in encoded. FileName- encoded file name. The Bean:- (FileData) public class FileData { private String fileName; private String fileData; public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public String getFileData() { return fileData; } public void setFileData(String string) { this.fileData = string; } } The android DDMS gives out of memory exception when tried below code & when i tried to send two files then only first file is created. public class PDFActivity extends Activity { private final String METHOD_NAME = "sendPDFs"; private final String NAMESPACE = "http://webservice.uks.com/"; private final String SOAP_ACTION = NAMESPACE + METHOD_NAME; private final String URL = "http://192.168.1.123:8080/AIPWebService/services/MultipleFilesImpl"; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); TextView textViewOne = (TextView) findViewById(R.id.textViewOne); try { SoapObject soapObject = new SoapObject(NAMESPACE, METHOD_NAME); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope( SoapEnvelope.VER11); envelope.setOutputSoapObject(soapObject); textViewOne.setText("Web Service Started"); AndroidHttpTransport httpTransport = new AndroidHttpTransport(URL); httpTransport.call(SOAP_ACTION, envelope); // SoapObject result = (SoapObject) envelope.getResponse(); Object result = envelope.getResponse(); Log.i("Result", result.toString()); // String fileName = result.getProperty("fileName").toString(); // String fileData = result.getProperty("fileData").toString(); // Log.i("File Name", fileName); // Log.i("File Data", fileData); // File pdfFile = new File(fileName); // FileOutputStream outputStream = // openFileOutput(pdfFile.toString(), // MODE_PRIVATE); // outputStream.write(Base64Coder.decode(fileData)); Log.i("File", "File Created"); // textViewTwo.setText(result); // Object result = envelope.getResponse(); // FileOutputStream outputStream = openFileOutput(name, mode) } catch (Exception e) { e.printStackTrace(); } } } Please help with some explanation or changes in my code. Thanks in Advance.

    Read the article

  • sequential mandelbrot image creation

    - by visanio_learner
    can anyone tell me what is wrong in this code? i am getting an error in the main function, when i am calling the 'file_write' method function inside the main function, it says 'y' is not declared in this scope, but actually it was an argument that i have passed it in the method function earlier. is it a serious error? #include <stdio.h> #include <stdlib.h> #include <time.h> unsigned int width = 1500; unsigned int height = 1500; unsigned int max_iterations = 30000; unsigned int **color = NULL; double threshold = 4; double min_re = -2.0; double max_re = 1.0; double min_im = -1.2; double max_im = min_im+(max_re-min_re)*height/width; double x_factor = (max_re-min_re)/(width-1); double y_factor = (max_im-min_im)/(height-1); int file_write(int x, int y, double min_re, double max_im, double x_factor, double y_factor) { FILE *fractal = fopen("mandelbrot_imageSequential.ppm","w+"); if(fractal != NULL) { fprintf(fractal,"P6\n"); fprintf(fractal,"# %s\n", "Mandelbrot_imageSequential.ppm"); fprintf(fractal,"%d %d\n", height, width); fprintf(fractal,"255\n"); unsigned int R = 0, G = 0, B = 0; for(unsigned y = 0; y < height; ++y) { double c_im = max_im - y*y_factor; for(unsigned x = 0; x < width; ++x) { double c_re = min_re + x*x_factor; double Z_re = c_re, Z_im = c_im; bool image_inside = true; R = 0, G = 0, B = 0; for(unsigned n=0; n<max_iterations; ++n) { double Z_re2 = Z_re*Z_re, Z_im2 = Z_im*Z_im; if(Z_re2 + Z_im2 > threshold) { image_inside = false; G = n; if(G == 10) { G = 25, R = 10, B = 5; } break; } Z_im = 2 * Z_re * Z_im + c_im; Z_re = Z_re2 - Z_im2 + c_re; } if(image_inside) { putc(R, fractal); putc(G, fractal); putc(B, fractal); } else { putc(R, fractal); putc(G, fractal); putc(B, fractal); } } } fclose(fractal); return 0; } } int main(int argc, char *argv[]) { if(argc != 9) { printf("There is an error in the input given.\n"); return 0; } else { height = atoi(argv[1]); width = atoi(argv[2]); max_iterations = atoi(argv[3]); min_re = atof(argv[4]); max_re = atof(argv[5]); min_im = atof(argv[6]); max_im = atof(argv[7]); threshold = atoi(argv[8]); } color = (unsigned int**)malloc(height*sizeof(unsigned int*)); printf("height = %d\twidth = %d\tmaximum_iterations = %d\tminimum_x-value = %.2f\tmaximum_x-value = %.2f\tminimum_y-value = %.2f\tmaximum_y-value = %.2f\tthreshold_value = %.2f\t\n",height,width,max_iterations,min_re,max_re,min_im,max_im,threshold); int x; for(x = 0; x < height; x++) { color[x] = (unsigned int*)malloc(width*sizeof(unsigned int)); } time_t ts,te; time(&ts); file_write(x,y,min_re,max_im,x_factor,y_factor); time(&te); double diff = difftime(te,ts); printf("Total Time elapsed: %f\n",diff); for(x = 0; x < height; x++) { free(color[x]); } free(color); return 0; }

    Read the article

  • Fetch a specific tag from Rally in order to compute a value in another field

    - by 4jas
    I'm extremely new to Rally development so my question may sound dumb (but couldn't find how to do it from rally's help or from previous posts here) :) I've started from the rally freeform grid example - my purpose is to implement a Business Value calculator: I fill the score field with a 5-digit figure where each number is a score in the 1-5 range. Then I compute a business value as the result of a calculation, where each number is weighted by a preset weight. I can sort my stories by Business Value to help me prioritize my backlog: that's the first step, and it works. Now what I want to do is to make my freeform grid editable: I am extracting each of my digits as a separate column, but those columns are display-only. How can I turn them into something editable? What I want to do of course is update back the score field based on the values input in each custom column. Here's an example: I have a record with score "15254", which means Business Value criteria 1 scores 1 out of 5, Business Value criteria 2 scores 5 out of 5, and so on... In the end my Business Value is computed as "1*1 + 5*2 + 2*3 + 5*4 + 4*5 = 57". So far this is the part that works. Now let's say I found that the third criteria should not score 2 but 3, I want to be able to edit the value in the corresponding column and have my score field updated to "15354", and my Business Value to display 60 instead of 57. Here is my current code, I'll be really grateful if you can help me with turning that grid into something editable :) <!--Include SDK--> <script type="text/javascript" src="https://rally1.rallydev.com/apps/2.0p2/sdk-debug.js"></script> <!--App code--> <script type="text/javascript"> Rally.onReady(function() { Ext.define('BVApp', { extend: 'Rally.app.App', componentCls: 'app', launch: function() { Ext.create('Rally.data.WsapiDataStore', { model: 'UserStory', autoLoad: true, listeners: { load: this._onDataLoaded, scope: this } }); }, _onDataLoaded: function(store, data) { var records = []; var li_score; var li_bv1, li_bv2, li_bv3, li_bv4, li_bv5, li_bvtotal; var weights = new Array(1, 2, 3, 4, 5); Ext.Array.each(data, function(record) { //Let's fetch score and compute the business values... li_score = record.get('Score'); if (li_score) { li_bv1 = li_score.toString().substring(0,1); li_bv2 = li_score.toString().substring(1,2); li_bv3 = li_score.toString().substring(2,3); li_bv4 = li_score.toString().substring(3,4); li_bv5 = li_score.toString().substring(4,5); li_bvtotal = li_bv1*weights[0] + li_bv2*weights[1] + li_bv3*weights[2] + li_bv4*weights[3] + li_bv5*weights[4]; } records.push({ FormattedID: record.get('FormattedID'), ref: record.get('_ref'), Name: record.get('Name'), Score: record.get('Score'), Bv1: li_bv1, Bv2: li_bv2, Bv3: li_bv3, Bv4: li_bv4, Bv5: li_bv5, BvTotal: li_bvtotal }); }); this.add({ xtype: 'rallygrid', store: Ext.create('Rally.data.custom.Store', { data: records, pageSize: 5 }), columnCfgs: [ { text: 'FormattedID', dataIndex: 'FormattedID' }, { text: 'ref', dataIndex: 'ref' }, { text: 'Name', dataIndex: 'Name', flex: 1 }, { text: 'Score', dataIndex: 'Score' }, { text: 'BusVal 1', dataIndex: 'Bv1' }, { text: 'BusVal 2', dataIndex: 'Bv2' }, { text: 'BusVal 3', dataIndex: 'Bv3' }, { text: 'BusVal 4', dataIndex: 'Bv4' }, { text: 'BusVal 5', dataIndex: 'Bv5' }, { text: 'BusVal Total', dataIndex: 'BvTotal' } ] }); } }); Rally.launchApp('BVApp', { name: 'Business Values App' }); var exampleHtml = '<div id="example-intro"><h1>Business Values App</h1>' + '<div>Own sample app for Business Values</div>' + '</div>'; // Default app viewport uses layout: 'fit', // so we need to insert a container into the viewport var viewport = Ext.ComponentQuery.query('viewport')[0]; var appComponent = viewport.items.getAt(0); var viewportContainerItems = [{ html: exampleHtml, border: 0 }]; //hide advanced cardboard live previews in examples for now viewportContainerItems.push({ xtype: 'container', items: [appComponent] }); viewport.remove(appComponent, false); viewport.add({ xtype: 'container', layout: 'vbox', items: viewportContainerItems }); }); </script> <!--App styles--> <style type="text/css"> .app { /* Add app styles here */ } </style>

    Read the article

  • Why isn't this file reading/writing program working?

    - by user320950
    This program is supposed to read files and write them. I took the file open checks out because they kept causing errors. The problem is that the files open like they are supposed to and the names are correct but nothing is on any of the text screens. Do you know what is wrong? #include<iostream> #include<fstream> #include<cstdlib> #include<iomanip> using namespace std; int main() { ifstream in_stream; // reads itemlist.txt ofstream out_stream1; // writes in items.txt ifstream in_stream2; // reads pricelist.txt ofstream out_stream3;// writes in plist.txt ifstream in_stream4;// read recipt.txt ofstream out_stream5;// write display.txt float price=' ',curr_total=0.0; int wrong=0; int itemnum=' '; char next; in_stream.open("ITEMLIST.txt", ios::in); // list of avaliable items out_stream1.open("listWititems.txt", ios::out); // list of avaliable items in_stream2.open("PRICELIST.txt", ios::in); out_stream3.open("listWitdollars.txt", ios::out); in_stream4.open("display.txt", ios::in); out_stream5.open("showitems.txt", ios::out); in_stream.close(); // closing files. out_stream1.close(); in_stream2.close(); out_stream3.close(); in_stream4.close(); out_stream5.close(); system("pause"); in_stream.setf(ios::fixed); while(in_stream.eof()) { in_stream >> itemnum; cin.clear(); cin >> next; } out_stream1.setf(ios::fixed); while (out_stream1.eof()) { out_stream1 << itemnum; cin.clear(); cin >> next; } in_stream2.setf(ios::fixed); in_stream2.setf(ios::showpoint); in_stream2.precision(2); while((price== (price*1.00)) && (itemnum == (itemnum*1))) { while (in_stream2 >> itemnum >> price) // gets itemnum and price { while (in_stream2.eof()) // reads file to end of file { in_stream2 >> itemnum; in_stream2 >> price; price++; curr_total= price++; in_stream2 >> curr_total; cin.clear(); // allows more reading cin >> next; } } } out_stream3.setf(ios::fixed); out_stream3.setf(ios::showpoint); out_stream3.precision(2); while((price== (price*1.00)) && (itemnum == (itemnum*1))) { while (out_stream3 << itemnum << price) { while (out_stream3.eof()) // reads file to end of file { out_stream3 << itemnum; out_stream3 << price; price++; curr_total= price++; out_stream3 << curr_total; cin.clear(); // allows more reading cin >> next; } return itemnum, price; } } in_stream4.setf(ios::fixed); in_stream4.setf(ios::showpoint); in_stream4.precision(2); while ( in_stream4.eof()) { in_stream4 >> itemnum >> price >> curr_total; cin.clear(); cin >> next; } out_stream5.setf(ios::fixed); out_stream5.setf(ios::showpoint); out_stream5.precision(2); out_stream5 <<setw(5)<< " itemnum " <<setw(5)<<" price "<<setw(5)<<" curr_total " <<endl; // sends items and prices to receipt.txt out_stream5 << setw(5) << itemnum << setw(5) <<price << setw(5)<< curr_total; // sends items and prices to receipt.txt out_stream5 << " You have a total of " << wrong++ << " errors " << endl; }

    Read the article

  • c windows connect() fails. error 10049

    - by Joshua Moore
    The following two pieces of code compile, but I get a connect() failed error on the client side. (compiled with MinGW). Client Code: // thanks to cs.baylor.edu/~donahoo/practical/CSockets/code/TCPEchoClientWS.c #include <stdio.h> #include <winsock.h> #include <stdlib.h> #define RCVBUFSIZE 32 // size of receive buffer void DieWithError(char *errorMessage); int main(int argc, char* argv[]) { int sock; struct sockaddr_in echoServAddr; unsigned short echoServPort; char *servIP; char *echoString; char echoBuffer[RCVBUFSIZE]; int echoStringLen; int bytesRcvd, totalBytesRcvd; WSAData wsaData; if((argc < 3) || (argc > 4)){ fprintf(stderr, "Usage: %s <Sever IP> <Echo Word> [<Echo Port>]\n", argv[0]); exit(1); } if (argc==4) echoServPort = atoi(argv[3]); // use given port if any else echoServPort = 7; // echo is well-known port for echo service if(WSAStartup(MAKEWORD(2, 0), &wsaData) != 0){ // load winsock 2.0 dll fprintf(stderr, "WSAStartup() failed"); exit(1); } // create reliable, stream socket using tcp if((sock=socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) DieWithError("socket() failed"); // construct the server address structure memset(&echoServAddr, 0, sizeof(echoServAddr)); echoServAddr.sin_family = AF_INET; echoServAddr.sin_addr.s_addr = inet_addr(servIP); // server IP address echoServAddr.sin_port = htons(echoServPort); // establish connection to the echo server if(connect(sock, (struct sockaddr*)&echoServAddr, sizeof(echoServAddr)) < 0) DieWithError("connect() failed"); echoStringLen = strlen(echoString); // determine input length // send the string, includeing the null terminator to the server if(send(sock, echoString, echoStringLen, 0)!= echoStringLen) DieWithError("send() sent a different number of bytes than expected"); totalBytesRcvd = 0; printf("Received: "); // setup to print the echoed string while(totalBytesRcvd < echoStringLen){ // receive up to the buffer size (minus 1 to leave space for a null terminator) bytes from the sender if(bytesRcvd = recv(sock, echoBuffer, RCVBUFSIZE-1, 0) <= 0) DieWithError("recv() failed or connection closed prematurely"); totalBytesRcvd += bytesRcvd; // keep tally of total bytes echoBuffer[bytesRcvd] = '\0'; printf("%s", echoBuffer); // print the echo buffer } printf("\n"); closesocket(sock); WSACleanup(); exit(0); } void DieWithError(char *errorMessage) { fprintf(stderr, "%s: %d\n", errorMessage, WSAGetLastError()); exit(1); } Server Code: // thanks cs.baylor.edu/~donahoo/practical/CSockets/code/TCPEchoServerWS.c #include <stdio.h> #include <winsock.h> #include <stdlib.h> #define MAXPENDING 5 // maximum outstanding connection requests #define RCVBUFSIZE 1000 void DieWithError(char *errorMessage); void HandleTCPClient(int clntSocket); // tcp client handling function int main(int argc, char **argv) { int serverSock; int clientSock; struct sockaddr_in echoServerAddr; struct sockaddr_in echoClientAddr; unsigned short echoServerPort; int clientLen; // length of client address data structure WSAData wsaData; if (argc!=2){ fprintf(stderr, "Usage: %s <Server Port>\n", argv[0]); exit(1); } echoServerPort = atoi(argv[1]); if(WSAStartup(MAKEWORD(2, 0), &wsaData)!=0){ fprintf(stderr, "WSAStartup() failed"); exit(1); } // create socket for incoming connections if((serverSock=socket(PF_INET, SOCK_STREAM, IPPROTO_TCP))<0) DieWithError("socket() failed"); // construct local address structure memset(&echoServerAddr, 0, sizeof(echoServerAddr)); echoServerAddr.sin_family = AF_INET; echoServerAddr.sin_addr.s_addr = htonl(INADDR_ANY); // any incoming interface echoServerAddr.sin_port = htons(echoServerPort); // local port // bind to the local address if(bind(serverSock, (struct sockaddr*)&echoServerAddr, sizeof(echoServerAddr) )<0) DieWithError("bind() failed"); // mark the socket so it will listen for incoming connections if(listen(serverSock, MAXPENDING)<0) DieWithError("listen() failed"); for (;;){ // run forever // set the size of the in-out parameter clientLen = sizeof(echoClientAddr); // wait for a client to connect if((clientSock = accept(serverSock, (struct sockaddr*)&echoClientAddr, &clientLen)) < 0) DieWithError("accept() failed"); // clientSock is connected to a client printf("Handling client %s\n", inet_ntoa(echoClientAddr.sin_addr)); HandleTCPClient(clientSock); } // NOT REACHED } void DieWithError(char *errorMessage) { fprintf(stderr, "%s: %d\n", errorMessage, WSAGetLastError()); exit(1); } void HandleTCPClient(int clientSocket) { char echoBuffer[RCVBUFSIZE]; // buffer for echostring int recvMsgSize; // size of received message // receive message from client if((recvMsgSize = recv(clientSocket, echoBuffer, RCVBUFSIZE, 0) <0)) DieWithError("recv() failed"); // send received string and receive again until end of transmission while(recvMsgSize > 0){ // echo message back to client if(send(clientSocket, echoBuffer, recvMsgSize, 0)!=recvMsgSize) DieWithError("send() failed"); // see if there's more data to receive if((recvMsgSize = recv(clientSocket, echoBuffer, RCVBUFSIZE, 0)) <0) DieWithError("recv() failed"); } closesocket(clientSocket); // close client socket } How can I fix this?

    Read the article

  • Checkbox to Show and Hide only for the near DIV

    - by Holp
    Select all options... Then, when the user uncheck "B" and check it again, the "D" parents must be hidden. I have to do it without give then IDs. <html> <head> <title>Form</title> <style> * { font-family: Segoe UI, Verdana; font-size: 10pt; } #total { padding: 10px; position: fixed; top: 10px; left: 500px; width: 150px; height: 100px; } p { margin: 5px; } .grupo { padding: 5px 0 5px 0; } </style> <script src="jquery-1.4.2.min.js" type="text/javascript"></script> </head> <body> <div class="grupo"> <p class="pergunta">A) Lorem ipsum dolor sit amet, nulla nec tortor?</p> <p><label><input type="radio" name="P-1" value="R-1-1" />Sim</label></p> <p><label><input type="radio" name="P-1" value="R-1-2" />Não</label></p> </div> <div class="grupo"> <p class="pergunta"><label><input type="checkbox" name="P-2" value="R-2-3" />B) Donec libero risus, commodo vitae</label></p> <div class="dependente"> <div class="grupo"> <p class="pergunta">C) Lorem ipsum dolor sit amet, nulla nec tortor?</p> <p><label><input type="radio" name="P-3" value="R-3-1" />Morbi in orci</label></p> <p><label><input type="radio" name="P-3" value="R-3-2" />Nulla purus lacus, pulvinar vel</label></p> <p><label><input type="radio" name="P-3" value="R-3-3" />Aliquam ante</label></p> <p><label><input type="radio" name="P-3" value="R-3-4" />Suspendisse scelerisque dui nec velit</label></p> </div> <div class="grupo"> <p class="pergunta"><label><input type="checkbox" name="P-4" value="R-4-5" />D) Donec libero risus, commodo vitae</label></p> <div class="dependente"> <div class="grupo"> <p class="pergunta">E) Lorem ipsum dolor sit amet, nulla nec tortor?</p> <p><label><input type="radio" name="P-5" value="R-5-1" />Morbi in orci</label></p> <p><label><input type="radio" name="P-5" value="R-5-2" />Nulla purus lacus</label></p> </div> </div> </div> </div> </div> <div class="grupo"> <p class="pergunta">F) Lorem ipsum dolor sit amet, nulla nec tortor?</p> <p><label><input type="radio" name="P-6" value="R-6-1" />Morbi in orci</label></p> <p><label><input type="radio" name="P-6" value="R-6-2" />Nulla purus lacus, pulvinar vel</label></p> <p><label><input type="radio" name="P-6" value="R-6-3" />Aliquam ante</label></p> <p><label><input type="radio" name="P-6" value="R-6-4" />Suspendisse scelerisque dui nec velit</label></p> </div> <script type="text/javascript"> $('.dependente').hide(); $(':checkbox').click(function () { var checked = this.checked; $('.dependente:first',$(this).parents('div:first')).css('display',checked ? 'block':'none'); $('.dependente input',$(this).parents('div:first')).attr('checked', false).change(); }); </script> </body> </html>

    Read the article

  • Self-relation messes up contents in fetching

    - by holographix
    Hi folks, I'm dealing with an annoying problem in core data I've got a table named Character, which is made as follows I'm filling the table in various steps: 1) fill the attributes of the table 2) fill the Character Relation (charRel) FYI charRel is defined as follows I'm feeding the contents by pulling the data from an xml, the feeding code is this curStr = [[NSMutableString stringWithString:[curStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]] retain]; NSLog(@"Parsing relation within these keys %@, in order to get'em associated",curStr); NSArray *chunks = [curStr componentsSeparatedByString: @","]; for( NSString *relId in chunks ) { NSLog(@"Associating %@ with id %@",[currentCharacter valueForKey:@"character_id"], relId); NSFetchRequest *request = [[NSFetchRequest alloc] init]; NSPredicate *predicate = [NSPredicate predicateWithFormat:@"character_id == %@", relId]; [request setEntity:[NSEntityDescription entityForName:@"Character" inManagedObjectContext:[self managedObjectContext] ]]; [request setPredicate:predicate]; NSerror *error = nil; NSArray *results = [[self managedObjectContext] executeFetchRequest:request error:&error]; // error handling code if(error != nil) { NSLog(@"[SYMBOL CORRELATION]: retrieving correlated symbol error: %@", [error localizedDescription]); } else if([results count] > 0) { Character *relatedChar = [results objectAtIndex:0]; // grab the first result in the stack, could be done better! [currentCharacter addCharRelObject:relatedChar]; //VICE VERSA RELATIONS NSArray *charRels = [relatedChar valueForKey:@"charRel"]; BOOL alreadyRelated = NO; for(Character *charRel in charRels) { if([[charRel valueForKey:@"character_id"] isEqual:[currentCharacter valueForKey:@"character_id"]]) { alreadyRelated = YES; break; } } if(!alreadyRelated) { NSLog(@"\n\t\trelating %@ with %@", [relatedChar valueForKey:@"character_id"], [currentCharacter valueForKey:@"character_id"]); [relatedChar addCharRelObject:currentCharacter]; } } else { NSLog(@"[SYMBOL CORRELATION]: related symbol was not found! ##SKIPPING-->"); } [request release]; } NSLog(@"\t\t### TOTAL OF REALTIONS FOR ID %@: %d\n%@", [currentCharacter valueForKey:@"character_id"], [[currentCharacter valueForKey:@"charRel"] count], currentCharacter); error = nil; /* SAVE THE CONTEXT */ if (![managedObjectContext save:&error]) { NSLog(@"Whoops, couldn't save the symbol record: %@", [error localizedDescription]); NSArray* detailedErrors = [[error userInfo] objectForKey:NSDetailedErrorsKey]; if(detailedErrors != nil && [detailedErrors count] > 0) { for(NSError* detailedError in detailedErrors) { NSLog(@"\n################\t\tDetailedError: %@\n################", [detailedError userInfo]); } } else { NSLog(@" %@", [error userInfo]); } } at this point when I print out the values of the currentCharacter, everything looks perfect. every relation is in its place. in example in this log we can clearly see that this element has got 3 items in charRel: <Character: 0x5593af0> (entity: Character; id: 0x55938c0 <x-coredata://67288D50-D349-4B19-B7CB-F7AC4671AD61/Character/p86> ; data: { catRel = "<relationship fault: 0x9a29db0 'catRel'>"; charRel = ( "0x9a1f870 <x-coredata://67288D50-D349-4B19-B7CB-F7AC4671AD61/Character/p74>", "0x9a14bd0 <x-coredata://67288D50-D349-4B19-B7CB-F7AC4671AD61/Character/p109>", "0x558ba00 <x-coredata://67288D50-D349-4B19-B7CB-F7AC4671AD61/Character/p5>" ); "character_id" = 254; examplesRel = "<relationship fault: 0x9a29df0 'examplesRel'>"; meaning = "\n Left"; pinyin = "\n zu\U01d2"; "pronunciation_it" = "\n zu\U01d2"; strokenumber = 5; text = "\n \n <p>The most ancient form of this symbol"; unicodevalue = "\n \U5de6"; }) then when I'm in need of retrieving this item I perform an extraction, like this: // at first I get the single Character record NSFetchRequest *request = [[NSFetchRequest alloc] init]; NSError *error; NSPredicate *predicate = [NSPredicate predicateWithFormat:@"character_id == %@", self.char_id ]; [request setEntity:[NSEntityDescription entityForName:@"Character" inManagedObjectContext:_context ]]; [request setPredicate:predicate]; NSArray *fetchedObjs = [_context executeFetchRequest:request error:&error]; when, for instance, I print out in NSLog the contents of charRel NSArray *correlations = [singleCharacter valueForKey:@"charRel"]; NSLog(@"CHARACTER OBJECT \n%@", correlations); I get this Relationship fault for (<NSRelationshipDescription: 0x5568520>), name charRel, isOptional 1, isTransient 0, entity Character, renamingIdentifier charRel, validation predicates (), warnings (), versionHashModifier (null), destination entity Character, inverseRelationship (null), minCount 1, maxCount 99 on 0x6937f00 hope that I made myself clear. this thing is driving me insane, I've googled all over world, but I couldn't find a solution (and this make me think to as issue related to bad coding somehow :P). thank you in advance guys. k

    Read the article

  • Elapsed time of running a C program

    - by yCalleecharan
    Hi, I would like to know what lines of C code to add to a program so that it tells me the total time that the program takes to run. I guess there should be counter initialization near the beginning of main and one after the main function ends. Is the right header clock.h? Thanks a lot... Update I have a Win Xp machine. Is it just adding clock() at the beginning and another clock() at the end of the program? Then I can estimate the time difference. Yes, you're right it's time.h. Here's my code: #include <stdio.h> #include <stdlib.h> #include <math.h> #include <share.h> #include <time.h> void f(long double fb[], long double fA, long double fB); int main() { clock_t start, end; start = clock(); const int ARRAY_SIZE = 11; long double* z = (long double*) malloc(sizeof (long double) * ARRAY_SIZE); int i; long double A, B; if (z == NULL) { printf("Out of memory\n"); exit(-1); } A = 0.5; B = 2; for (i = 0; i < ARRAY_SIZE; i++) { z[i] = 0; } z[1] = 5; f(z, A, B); for (i = 0; i < ARRAY_SIZE; i++) printf("z is %.16Le\n", z[i]); free(z); z = NULL; end = clock(); printf("Took %ld ticks\n", end-start); printf("Took %f seconds\n", (double)(end-start)/CLOCKS_PER_SEC); return 0; } void f(long double fb[], long double fA, long double fB) { fb[0] = fb[1]* fA; fb[1] = fb[1] - 1; return; } Some errors with MVS2008: testim.c(16) : error C2143: syntax error : missing ';' before 'const' testim.c(18) :error C2143: syntax error : missing ';' before 'type' testim.c(20) :error C2143: syntax error : missing ';' before 'type' testim.c(21) :error C2143: syntax error : missing ';' before 'type' testim.c(23) :error C2065: 'z' : undeclared identifier testim.c(23) :warning C4047: '==' : 'int' differs in levels of indirection from 'void *' testim.c(28) : error C2065: 'A' : undeclared identifier testim.c(28) : warning C4244: '=' : conversion from 'double' to 'int', possible loss of data and it goes to 28 errors. Note that I don't have any errors/warnings without your clock codes. LATEST NEWS: I unfortunately didn't get a good reply here. But after a search on Google, the code is working. Here it is: #include <stdio.h> #include <stdlib.h> #include <math.h> #include <share.h> #include <time.h> void f(long double fb[], long double fA, long double fB); int main() { clock_t start = clock(); const int ARRAY_SIZE = 11; long double* z = (long double*) malloc(sizeof (long double) * ARRAY_SIZE); int i; long double A, B; if (z == NULL) { printf("Out of memory\n"); exit(-1); } A = 0.5; B = 2; for (i = 0; i < ARRAY_SIZE; i++) { z[i] = 0; } z[1] = 5; f(z, A, B); for (i = 0; i < ARRAY_SIZE; i++) printf("z is %.16Le\n", z[i]); free(z); z = NULL; printf("Took %f seconds\n", ((double)clock()-start)/CLOCKS_PER_SEC); return 0; } void f(long double fb[], long double fA, long double fB) { fb[0] = fb[1]* fA; fb[1] = fb[1] - 1; return; } Cheers

    Read the article

  • .NET interview, code structure and the design

    - by j_lewis
    I have been given the below .NET question in an interview. I don’t know why I got low marks. Unfortunately I did not get a feedback. Question: The file hockey.csv contains the results from the Hockey Premier League. The columns ‘For’ and ‘Against’ contain the total number of goals scored for and against each team in that season (so Alabama scored 79 goals against opponents, and had 36 goals scored against them). Write a program to print the name of the team with the smallest difference in ‘for’ and ‘against’ goals. the structure of the hockey.csv looks like this (it is a valid csv file, but I just copied the values here to get an idea) Team - For - Against Alabama 79 36 Washinton 67 30 Indiana 87 45 Newcastle 74 52 Florida 53 37 New York 46 47 Sunderland 29 51 Lova 41 64 Nevada 33 63 Boston 30 64 Nevada 33 63 Boston 30 64 Solution: class Program { static void Main(string[] args) { string path = @"C:\Users\<valid csv path>"; var resultEvaluator = new ResultEvaluator(string.Format(@"{0}\{1}",path, "hockey.csv")); var team = resultEvaluator.GetTeamSmallestDifferenceForAgainst(); Console.WriteLine( string.Format("Smallest difference in ‘For’ and ‘Against’ goals > TEAM: {0}, GOALS DIF: {1}", team.Name, team.Difference )); Console.ReadLine(); } } public interface IResultEvaluator { Team GetTeamSmallestDifferenceForAgainst(); } public class ResultEvaluator : IResultEvaluator { private static DataTable leagueDataTable; private readonly string filePath; private readonly ICsvExtractor csvExtractor; public ResultEvaluator(string filePath){ this.filePath = filePath; csvExtractor = new CsvExtractor(); } private DataTable LeagueDataTable{ get { if (leagueDataTable == null) { leagueDataTable = csvExtractor.GetDataTable(filePath); } return leagueDataTable; } } public Team GetTeamSmallestDifferenceForAgainst() { var teams = GetTeams(); var lowestTeam = teams.OrderBy(p => p.Difference).First(); return lowestTeam; } private IEnumerable<Team> GetTeams() { IList<Team> list = new List<Team>(); foreach (DataRow row in LeagueDataTable.Rows) { var name = row["Team"].ToString(); var @for = int.Parse(row["For"].ToString()); var against = int.Parse(row["Against"].ToString()); var team = new Team(name, against, @for); list.Add(team); } return list; } } public interface ICsvExtractor { DataTable GetDataTable(string csvFilePath); } public class CsvExtractor : ICsvExtractor { public DataTable GetDataTable(string csvFilePath) { var lines = File.ReadAllLines(csvFilePath); string[] fields; fields = lines[0].Split(new[] { ',' }); int columns = fields.GetLength(0); var dt = new DataTable(); //always assume 1st row is the column name. for (int i = 0; i < columns; i++) { dt.Columns.Add(fields[i].ToLower(), typeof(string)); } DataRow row; for (int i = 1; i < lines.GetLength(0); i++) { fields = lines[i].Split(new char[] { ',' }); row = dt.NewRow(); for (int f = 0; f < columns; f++) row[f] = fields[f]; dt.Rows.Add(row); } return dt; } } public class Team { public Team(string name, int against, int @for) { Name = name; Against = against; For = @for; } public string Name { get; private set; } public int Against { get; private set; } public int For { get; private set; } public int Difference { get { return (For - Against); } } } Output: Smallest difference in for' andagainst' goals TEAM: Boston, GOALS DIF: -34 Can someone please review my code and see anything obviously wrong here? They were only interested in the structure/design of the code and whether the program produces the correct result (i.e lowest difference). Much appreciated. "P.S - Please correct me if the ".net-interview" tag is not the right tag to use"

    Read the article

  • PHP Form checkbox question

    - by Sef
    Hello, I have a form that takes the following inputs: Name: IBM Surface(in m^2): 9 Floor: (Checkbox1) Phone: (Checkbox2) Network: (Checkbox3) Button to send to a next php page. All those values above are represented in a table when i press the submit button. The first two (name and surname) are properly displayed in the table. The problem is with the checkboxes. If i select the first checkbox the value in the table should be presented with 1. If its not selected the value in the table should be empty. echo "<td>$Name</td>"; // works properly echo "<td>$Surface</td>"; // works properly echo "<td>....no idea for the checkboxes</td>; Some part of my php code with the variables: <?php if (!empty($_POST)) { $standnaam = $_POST["name"]; $oppervlakte = $_POST["surface"]; $verdieping = $_POST["floor"]; $telefoon = $_POST["telefoon"]; $netwerk = $_POST["netwerk"]; if (is_numeric($surface)) { $_SESSION["name"]=$name; $_SESSION["surface"]=$surface; header("Location:ExpoOverzicht.php"); } else { echo "<h1>Wrong input, Pleasee fill in again</h1>"; } if(!empty($floor) && ($phone) && ($network)) { $_SESSION["floor"]=$floor; $_SESSION["phone"]=$phone; $_SESSION["network"]=$network; header("Location:ExpoOverzicht.php"); } } ?> Second page with table: <?php $name= $_SESSION["name"]; $surface= $_SESSION["surface"]; $floor= $_SESSION["floor"]; $phone= $_SESSION["phone"]; $network= $_SESSION["network"]; echo "<table class=\"tableExpo\">"; echo "<th>name</th>"; echo "<th>surface</th>"; echo "<th>floor</th>"; echo "<th>phone</th>"; echo "<th>network</th>"; echo "<th>total price</th>"; for($i=0; $i <= $_SESSION["name"]; $i++) { echo "<tr>"; echo "<td>$name</td>"; // gives right output echo "<td>$surface</td>"; // gives right output echo "<td>...</td>"; //wrong output (ment for checkbox 1) echo "<td>...</td>"; //wrong output (ment for checkbox 2) echo "<td>...</td>"; //wrong output (ment for checkbox 3) echo "<td>....</td>"; echo "</tr>;"; } echo "</table>"; <form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post" id="form1"> <h1>Vul de gegevens in</h1> <table> <tr> <td>Name:</td> <td><input type="text" name="name" size="18"/></td> </tr> <tr> <td>Surface(in m^2):</td> <td><input type="text" name="surface" size="6"/></td> </tr> <tr> <td>Floor:</td> <td><input type="checkbox" name="floor" value="floor"/></td> </tr> <tr> <td>Phone:</td> <td><input type="checkbox" name="phone" value="phone"/></td> </tr> <tr> <td>Network:</td> <td><input type="checkbox" name="network" value="network"/></td> </tr> <tr> <td><input type="submit" name="verzenden" value="Verzenden"/></td> </tr> </table> There might be a few spelling mistakes since i had to translate it. Best regards.

    Read the article

  • Does Microsoft hate firefox? ASP.Net gridview performance in firefox bug?

    - by Maxim Gershkovich
    Could someone please explain the significant difference in speed between a firefox updatepanel async postback and one performed in IE? Average Firefox Postback Time For 500 objects: 1.183 Second Average IE Postback Time For 500 objects: 0.295 Seconds Using firebug I can see that the majority of this time in FireFox is spent on the server side. A total of 1.04 seconds. Given this fact the only thing I can assume is causing this problem is the way that ASP.Net renders its controls between the two browsers. Has anyone run into this problem before? VB.Net Code Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click GridView1.DataBind() End Sub Public Function GetStockList() As StockList Dim res As New StockList For l = 0 To 500 Dim x As New Stock With {.Description = "test", .ID = Guid.NewGuid} res.Add(x) Next Return res End Function Public Class Stock Private m_ID As Guid Private m_Description As String Public Sub New() End Sub Public Property ID() As Guid Get Return Me.m_ID End Get Set(ByVal value As Guid) Me.m_ID = value End Set End Property Public Property Description() As String Get Return Me.m_Description End Get Set(ByVal value As String) Me.m_Description = value End Set End Property End Class Public Class StockList Inherits List(Of Stock) End Class Markup <form id="form1" runat="server"> <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager> <script type="text/javascript" language="Javascript"> function timestamp_class(this_current_time, this_start_time, this_end_time, this_time_difference) { this.this_current_time = this_current_time; this.this_start_time = this_start_time; this.this_end_time = this_end_time; this.this_time_difference = this_time_difference; this.GetCurrentTime = GetCurrentTime; this.StartTiming = StartTiming; this.EndTiming = EndTiming; } //Get current time from date timestamp function GetCurrentTime() { var my_current_timestamp; my_current_timestamp = new Date(); //stamp current date & time return my_current_timestamp.getTime(); } //Stamp current time as start time and reset display textbox function StartTiming() { this.this_start_time = GetCurrentTime(); //stamp current time } //Stamp current time as stop time, compute elapsed time difference and display in textbox function EndTiming() { this.this_end_time = GetCurrentTime(); //stamp current time this.this_time_difference = (this.this_end_time - this.this_start_time) / 1000; //compute elapsed time return this.this_time_difference; } //--> </script> <script type="text/javascript" language="javascript"> var time_object = new timestamp_class(0, 0, 0, 0); //create new time object and initialize it Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler); Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler); function BeginRequestHandler(sender, args) { var elem = args.get_postBackElement(); ActivateAlertDiv('visible', 'divAsyncRequestTimer', elem.value + ''); time_object.StartTiming(); } function EndRequestHandler(sender, args) { ActivateAlertDiv('visible', 'divAsyncRequestTimer', '(' + time_object.EndTiming() + ' Seconds)'); } function ActivateAlertDiv(visstring, elem, msg) { var adiv = $get(elem); adiv.style.visibility = visstring; adiv.innerHTML = msg; } </script> <asp:UpdatePanel ID="UpdatePanel1" runat="server"> <Triggers> <asp:AsyncPostBackTrigger ControlID="Button1" EventName="click" /> </Triggers> <ContentTemplate> <asp:UpdateProgress ID="UpdateProgress1" runat="server" AssociatedUpdatePanelID="UpdatePanel1"> </asp:UpdateProgress> <asp:Button ID="Button1" runat="server" Text="Button" /> <div id="divAsyncRequestTimer" style="font-size:small;"> </div> <asp:GridView ID="GridView1" runat="server" DataSourceID="ObjectDataSource1" AutoGenerateColumns="False"> <Columns> <asp:BoundField DataField="ID" HeaderText="ID" SortExpression="ID" /> <asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" /> </Columns> </asp:GridView> <asp:ObjectDataSource ID="ObjectDataSource1" runat="server" SelectMethod="GetStockList" TypeName="WebApplication1._Default"> </asp:ObjectDataSource> </ContentTemplate> </asp:UpdatePanel> </form>

    Read the article

  • Improving HTML scrapper efficiency with pcntl_fork()

    - by Michael Pasqualone
    With the help from two previous questions, I now have a working HTML scrapper that feeds product information into a database. What I am now trying to do is improve efficiently by wrapping my brain around with getting my scrapper working with pcntl_fork. If I split my php5-cli script into 10 separate chunks, I improve total runtime by a large factor so I know I am not i/o or cpu bound but just limited by the linear nature of my scraping functions. Using code I've cobbled together from multiple sources, I have this working test: <?php libxml_use_internal_errors(true); ini_set('max_execution_time', 0); ini_set('max_input_time', 0); set_time_limit(0); $hrefArray = array("http://slashdot.org", "http://slashdot.org", "http://slashdot.org", "http://slashdot.org"); function doDomStuff($singleHref,$childPid) { $html = new DOMDocument(); $html->loadHtmlFile($singleHref); $xPath = new DOMXPath($html); $domQuery = '//div[@id="slogan"]/h2'; $domReturn = $xPath->query($domQuery); foreach($domReturn as $return) { $slogan = $return->nodeValue; echo "Child PID #" . $childPid . " says: " . $slogan . "\n"; } } $pids = array(); foreach ($hrefArray as $singleHref) { $pid = pcntl_fork(); if ($pid == -1) { die("Couldn't fork, error!"); } elseif ($pid > 0) { // We are the parent $pids[] = $pid; } else { // We are the child $childPid = posix_getpid(); doDomStuff($singleHref,$childPid); exit(0); } } foreach ($pids as $pid) { pcntl_waitpid($pid, $status); } // Clear the libxml buffer so it doesn't fill up libxml_clear_errors(); Which raises the following questions: 1) Given my hrefArray contains 4 urls - if the array was to contain say 1,000 product urls this code would spawn 1,000 child processes? If so, what is the best way to limit the amount of processes to say 10, and again 1,000 urls as an example split the child work load to 100 products per child (10 x 100). 2) I've learn that pcntl_fork creates a copy of the process and all variables, classes, etc. What I would like to do is replace my hrefArray variable with a DOMDocument query that builds the list of products to scrape, and then feeds them off to child processes to do the processing - so spreading the load across 10 child workers. My brain is telling I need to do something like the following (obviously this doesn't work, so don't run it): <?php libxml_use_internal_errors(true); ini_set('max_execution_time', 0); ini_set('max_input_time', 0); set_time_limit(0); $maxChildWorkers = 10; $html = new DOMDocument(); $html->loadHtmlFile('http://xxxx'); $xPath = new DOMXPath($html); $domQuery = '//div[@id=productDetail]/a'; $domReturn = $xPath->query($domQuery); $hrefsArray[] = $domReturn->getAttribute('href'); function doDomStuff($singleHref) { // Do stuff here with each product } // To figure out: Split href array into $maxChilderWorks # of workArray1, workArray2 ... workArray10. $pids = array(); foreach ($workArray(1,2,3 ... 10) as $singleHref) { $pid = pcntl_fork(); if ($pid == -1) { die("Couldn't fork, error!"); } elseif ($pid > 0) { // We are the parent $pids[] = $pid; } else { // We are the child $childPid = posix_getpid(); doDomStuff($singleHref); exit(0); } } foreach ($pids as $pid) { pcntl_waitpid($pid, $status); } // Clear the libxml buffer so it doesn't fill up libxml_clear_errors(); But what I can't figure out is how to build my hrefsArray[] in the master/parent process only and feed it off to the child process. Currently everything I've tried causes loops in the child processes. I.e. my hrefsArray gets built in the master, and in each subsequent child process. I am sure I am going about this all totally wrong, so would greatly appreciate just general nudge in the right direction.

    Read the article

  • spring mvc forward to jsp

    - by jerluc
    I currently have my web.xml configured to catch 404s and send them to my spring controller which will perform a search given the original URL request. The functionality is all there as far as the catch and search go, however the trouble begins to arise when I try to return a view. <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver" p:order="1"> <property name="mediaTypes"> <map> <entry key="json" value="application/json" /> <entry key="jsp" value="text/html" /> </map> </property> <property name="defaultContentType" value="application/json" /> <property name="favorPathExtension" value="true" /> <property name="viewResolvers"> <list> <bean class="org.springframework.web.servlet.view.BeanNameViewResolver" /> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value="" /> </bean> </list> </property> <property name="defaultViews"> <list> <bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" /> </list> </property> <property name="ignoreAcceptHeader" value="true" /> </bean> This is a snippet from my MVC config file. The problem lies in resolving the view's path to the /WEB-INF/jsp/ directory. Using a logger in my JBoss setup, I can see that when I test this search controller by going to a non-existent page, the following occurs: Server can't find the request Request is sent to 404 error page (in this case my search controller) Search controller performs search Search controller returns view name (for this illustration, we'll assume test.jsp is returned) Based off of server logger, I can see that org.springframework.web.servlet.view.JstlView is initialized once my search controller returns the view name (so I can assume it is being picked up correctly by the InternalResourceViewResolver) Server attempts to return content to browser resulting in a 404! A couple things confuse me about this: I'm not 100% sure why this isn't resolving when test.jsp clearly exists under the /WEB-INF/jsp/ directory. Even if there was some other problem, why would this result in a 404? Shouldn't a 404 error page that results in another 404 theoretically create an infinite loop? Thanks for any help or pointers! Controller class [incomplete]: @Controller public class SiteMapController { //-------------------------------------------------------------------------------------- @Autowired(required=true) private SearchService search; @Autowired(required=true) private CatalogService catalog; //-------------------------------------------------------------------------------------- @RequestMapping(value = "/sitemap", method = RequestMethod.GET) public String sitemap (HttpServletRequest request, HttpServletResponse response) { String forwardPath = ""; try { long startTime = System.nanoTime() / 1000000; String pathQuery = (String) request.getAttribute("javax.servlet.error.request_uri"); Scanner pathScanner = new Scanner(pathQuery).useDelimiter("\\/"); String context = pathScanner.next(); List<ProductLightDTO> results = new ArrayList<ProductLightDTO>(); StringBuilder query = new StringBuilder(); String currentValue; while (pathScanner.hasNext()) { currentValue = pathScanner.next().toLowerCase(); System.out.println(currentValue); if (query.length() > 0) query.append(" AND "); if (currentValue.contains("-")) { query.append("\""); query.append(currentValue.replace("-", " ")); query.append("\""); } else { query.append(currentValue + "*"); } } //results.addAll(this.doSearch(query.toString())); System.out.println("Request: " + pathQuery); System.out.println("Built Query:" + query.toString()); //System.out.println("Result size: " + results.size()); long totalTime = (System.nanoTime() / 1000000) - startTime; System.out.println("Total TTP: " + totalTime + "ms"); if (results == null || results.size() == 0) { forwardPath = "home.jsp"; } else if (results.size() == 1) { forwardPath = "product.jsp"; } else { forwardPath = "category.jsp"; } } catch (Exception ex) { System.err.println(ex); } System.out.println("Returning view: " + forwardPath); return forwardPath; } }

    Read the article

  • Runtime error on UVa Online Judge on Erdos Number

    - by 2012 - End of the World
    I am solving the Erdos number problem from the programming challenges in JAVA. The code runs perfectly in my machine. However on the online judge it results in a runtime error. Could anyone point out the mistake i made? http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=985 Here is the code import java.util.*; import java.io.*; class Main { private String inputLines[]; private String namesToBeFound[]; private String namesInEachBook[][]; private String searchItem; private boolean solnfound=false; private static final BufferedReader br =new BufferedReader(new InputStreamReader(System.in)); static String read() throws IOException { String line; while(true) { line=br.readLine(); if(line==null) break; //eof else if(line.length()==0) continue; //blank line else { line=line.trim().replaceAll("\\s+"," "); return line; } } return null; } public static void main(String args[]) throws IOException { Main ob=new Main(); int totalPapers,calcAuthors,totalScenarios; //First input number of scenarios totalScenarios=Integer.parseInt(read()); //Now start a loop for reading total number of scenarios for(int scenario=1;scenario<=totalScenarios;scenario++) { //Now read the line containing the number of papers and authors StringTokenizer line=new StringTokenizer(read()," "); totalPapers=Integer.parseInt(line.nextToken()); calcAuthors=Integer.parseInt(line.nextToken()); //Read a line containing author names along with book names ob.inputLines=new String[totalPapers]; for(int i=0;i<totalPapers;i++) ob.inputLines[i]=read(); //Read a line containing the names to be searched ob.namesToBeFound=new String[calcAuthors]; for(int i=0;i<calcAuthors;i++) ob.namesToBeFound[i]=read(); //Now generate the array ob.buildArray(); //Now search System.out.println("Scenario "+scenario); for(int i=0;i<calcAuthors;i++) { ob.searchItem=ob.namesToBeFound[i]; if(ob.searchItem.equals("Erdos, P.")) { System.out.println("Erdos, P. 0"); continue; } ob.search(ob.namesToBeFound[i],1,new ArrayList()); if(ob.solnfound==false) System.out.println(ob.searchItem+" infinity"); ob.solnfound=false; } } } private void buildArray() { String str; namesInEachBook=new String[inputLines.length][]; for(int i=0;i<inputLines.length;i++) { str=inputLines[i]; str=str.substring(0,str.indexOf(':')); str+=","; namesInEachBook[i]=new String[(countCommas(str)+1)>>1]; for(int j=0;j<namesInEachBook[i].length;j++) { str=str.trim(); namesInEachBook[i][j]=""; namesInEachBook[i][j]+=str.substring(0,str.indexOf(','))+","; str=str.substring(str.indexOf(',')+1); namesInEachBook[i][j]+=str.substring(0,str.indexOf(',')); str=str.substring(str.indexOf(',')+1); } } } private int countCommas(String s) { int num=0; for(int i=0;i<s.length();i++) if(s.charAt(i)==',') num++; return num; } private void search(String searchElem,int ernosDepth,ArrayList searchedElem) { ArrayList searchSpace=new ArrayList(); searchedElem.add(searchElem); for(int i=0;i<namesInEachBook.length;i++) for(int j=0;j<namesInEachBook[i].length;j++) { if(namesInEachBook[i][j].equals(searchElem)) //Add all authors name in this group { for(int k=0;k<namesInEachBook[i].length;k++) { if(namesInEachBook[i][k].equals("Erdos, P.")) //Found { solnfound=true; System.out.println(searchItem+" "+ernosDepth); return; } else if(searchedElem.contains(namesInEachBook[i][k]) || searchSpace.contains(namesInEachBook[i][k])) continue; searchSpace.add(namesInEachBook[i][k]); } break; } } Iterator i=searchSpace.iterator(); while(i.hasNext()) { String cSearchElem=(String)i.next(); search(cSearchElem,ernosDepth+1,searchedElem); } } }

    Read the article

  • Java programming accessing object variables

    - by Haxed
    Helo, there are 3 files, CustomerClient.java, CustomerServer.java and Customer.java PROBLEM: In the CustomerServer.java file, i get an error when I compile the CustomerServer.java at line : System.out.println(a[k].getName()); ERROR: init: deps-jar: Compiling 1 source file to C:\Documents and Settings\TLNA\My Documents\NetBeansProjects\Server\build\classes C:\Documents and Settings\TLNA\My Documents\NetBeansProjects\Server\src\CustomerServer.java:44: cannot find symbol symbol : method getName() location: class Customer System.out.println(a[k].getName()); 1 error BUILD FAILED (total time: 0 seconds) CustomerClient.java import java.io.*; import java.net.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.border.*; public class CustomerClient extends JApplet { private JTextField jtfName = new JTextField(32); private JTextField jtfSeatNo = new JTextField(32); // Button for sending a student to the server private JButton jbtRegister = new JButton("Register to the Server"); // Indicate if it runs as application private boolean isStandAlone = false; // Host name or ip String host = "localhost"; public void init() { JPanel p1 = new JPanel(); p1.setLayout(new GridLayout(2, 1)); p1.add(new JLabel("Name")); p1.add(jtfName); p1.add(new JLabel("Seat No.")); p1.add(jtfSeatNo); add(p1, BorderLayout.CENTER); add(jbtRegister, BorderLayout.SOUTH); // Register listener jbtRegister.addActionListener(new ButtonListener()); // Find the IP address of the Web server if (!isStandAlone) { host = getCodeBase().getHost(); } } /** Handle button action */ private class ButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) { try { // Establish connection with the server Socket socket = new Socket(host, 8000); // Create an output stream to the server ObjectOutputStream toServer = new ObjectOutputStream(socket.getOutputStream()); // Get text field String name = jtfName.getText().trim(); String seatNo = jtfSeatNo.getText().trim(); // Create a Student object and send to the server Customer s = new Customer(name, seatNo); toServer.writeObject(s); } catch (IOException ex) { System.err.println(ex); } } } /** Run the applet as an application */ public static void main(String[] args) { // Create a frame JFrame frame = new JFrame("Register Student Client"); // Create an instance of the applet CustomerClient applet = new CustomerClient(); applet.isStandAlone = true; // Get host if (args.length == 1) { applet.host = args[0]; // Add the applet instance to the frame } frame.add(applet, BorderLayout.CENTER); // Invoke init() and start() applet.init(); applet.start(); // Display the frame frame.pack(); frame.setVisible(true); } } CustomerServer.java import java.io.*; import java.net.*; public class CustomerServer { private String name; private int i; private ObjectOutputStream outputToFile; private ObjectInputStream inputFromClient; public static void main(String[] args) { new CustomerServer(); } public CustomerServer() { Customer[] a = new Customer[30]; try { // Create a server socket ServerSocket serverSocket = new ServerSocket(8000); System.out.println("Server started "); // Create an object ouput stream outputToFile = new ObjectOutputStream( new FileOutputStream("student.dat", true)); while (true) { // Listen for a new connection request Socket socket = serverSocket.accept(); // Create an input stream from the socket inputFromClient = new ObjectInputStream(socket.getInputStream()); // Read from input //Object object = inputFromClient.readObject(); for (int k = 0; k <= 2; k++) { if (a[k] == null) { a[k] = (Customer) inputFromClient.readObject(); // Write to the file outputToFile.writeObject(a[k]); //System.out.println("A new student object is stored"); System.out.println(a[k].getName()); break; } if (k == 2) { //fully booked outputToFile.writeObject("All seats are booked"); break; } } } } catch (ClassNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } finally { try { inputFromClient.close(); outputToFile.close(); } catch (Exception ex) { ex.printStackTrace(); } } } } Customer.java public class Customer implements java.io.Serializable { private String name; private String seatno; public Customer(String name, String seatno) { this.name = name; this.seatno = seatno; } public String getName() { return name; } public String getSeatNo() { return seatno; } }

    Read the article

  • Find the set of largest contiguous rectangles to cover multiple areas

    - by joelpt
    I'm working on a tool called Quickfort for the game Dwarf Fortress. Quickfort turns spreadsheets in csv/xls format into a series of commands for Dwarf Fortress to carry out in order to plot a "blueprint" within the game. I am currently trying to optimally solve an area-plotting problem for the 2.0 release of this tool. Consider the following "blueprint" which defines plotting commands for a 2-dimensional grid. Each cell in the grid should either be dug out ("d"), channeled ("c"), or left unplotted ("."). Any number of distinct plotting commands might be present in actual usage. . d . d c c d d d d c c . d d d . c d d d d d c . d . d d c To minimize the number of instructions that need to be sent to Dwarf Fortress, I would like to find the set of largest contiguous rectangles that can be formed to completely cover, or "plot", all of the plottable cells. To be valid, all of a given rectangle's cells must contain the same command. This is a faster approach than Quickfort 1.0 took: plotting every cell individually as a 1x1 rectangle. This video shows the performance difference between the two versions. For the above blueprint, the solution looks like this: . 9 . 0 3 2 8 1 1 1 3 2 . 1 1 1 . 2 7 1 1 1 4 2 . 6 . 5 4 2 Each same-numbered rectangle above denotes a contiguous rectangle. The largest rectangles take precedence over smaller rectangles that could also be formed in their areas. The order of the numbering/rectangles is unimportant. My current approach is iterative. In each iteration, I build a list of the largest rectangles that could be formed from each of the grid's plottable cells by extending in all 4 directions from the cell. After sorting the list largest first, I begin with the largest rectangle found, mark its underlying cells as "plotted", and record the rectangle in a list. Before plotting each rectangle, its underlying cells are checked to ensure they are not yet plotted (overlapping a previous plot). We then start again, finding the largest remaining rectangles that can be formed and plotting them until all cells have been plotted as part of some rectangle. I consider this approach slightly more optimized than a dumb brute-force search, but I am wasting a lot of cycles (re)calculating cells' largest rectangles and checking underlying cells' states. Currently, this rectangle-discovery routine takes the lion's share of the total runtime of the tool, especially for large blueprints. I have sacrificed some accuracy for the sake of speed by only considering rectangles from cells which appear to form a rectangle's corner (determined using some neighboring-cell heuristics which aren't always correct). As a result of this 'optimization', my current code doesn't actually generate the above solution correctly, but it's close enough. More broadly, I consider the goal of largest-rectangles-first to be a "good enough" approach for this application. However I observe that if the goal is instead to find the minimum set (fewest number) of rectangles to completely cover multiple areas, the solution would look like this instead: . 3 . 5 6 8 1 3 4 5 6 8 . 3 4 5 . 8 2 3 4 5 7 8 . 3 . 5 7 8 This second goal actually represents a more optimal solution to the problem, as fewer rectangles usually means fewer commands sent to Dwarf Fortress. However, this approach strikes me as closer to NP-Hard, based on my limited math knowledge. Watch the video if you'd like to better understand the overall strategy; I have not addressed other aspects of Quickfort's process, such as finding the shortest cursor-path that plots all rectangles. Possibly there is a solution to this problem that coherently combines these multiple strategies. Help of any form would be appreciated.

    Read the article

  • Transferring data from 2d Dynamic array in C to CUDA and back

    - by Soumya
    I have a dynamically declared 2D array in my C program, the contents of which I want to transfer to a CUDA kernel for further processing. Once processed, I want to populate the dynamically declared 2D array in my C code with the CUDA processed data. I am able to do this with static 2D C arrays but not with dynamically declared C arrays. Any inputs would be welcome! I mean the dynamic array of dynamic arrays. The test code that I have written is as below. #include "cuda_runtime.h" #include "device_launch_parameters.h" #include <stdio.h> #include <conio.h> #include <math.h> #include <stdlib.h> const int nItt = 10; const int nP = 5; __device__ int d_nItt = 10; __device__ int d_nP = 5; __global__ void arr_chk(float *d_x_k, float *d_w_k, int row_num) { int index = (blockIdx.x * blockDim.x) + threadIdx.x; int index1 = (row_num * d_nP) + index; if ( (index1 >= row_num * d_nP) && (index1 < ((row_num +1)*d_nP))) //Modifying only one row data pertaining to one particular iteration { d_x_k[index1] = row_num * d_nP; d_w_k[index1] = index; } } float **mat_create2(int r, int c) { float **dynamicArray; dynamicArray = (float **) malloc (sizeof (float)*r); for(int i=0; i<r; i++) { dynamicArray[i] = (float *) malloc (sizeof (float)*c); for(int j= 0; j<c;j++) { dynamicArray[i][j] = 0; } } return dynamicArray; } /* Freeing memory - here only number of rows are passed*/ void cleanup2d(float **mat_arr, int x) { int i; for(i=0; i<x; i++) { free(mat_arr[i]); } free(mat_arr); } int main() { //float w_k[nItt][nP]; //Static array declaration - works! //float x_k[nItt][nP]; // if I uncomment this dynamic declaration and comment the static one, it does not work..... float **w_k = mat_create2(nItt,nP); float **x_k = mat_create2(nItt,nP); float *d_w_k, *d_x_k; // Device variables for w_k and x_k int nblocks, blocksize, nthreads; for(int i=0;i<nItt;i++) { for(int j=0;j<nP;j++) { x_k[i][j] = (nP*i); w_k[i][j] = j; } } for(int i=0;i<nItt;i++) { for(int j=0;j<nP;j++) { printf("x_k[%d][%d] = %f\t",i,j,x_k[i][j]); printf("w_k[%d][%d] = %f\n",i,j,w_k[i][j]); } } int size1 = nItt * nP * sizeof(float); printf("\nThe array size in memory bytes is: %d\n",size1); cudaMalloc( (void**)&d_x_k, size1 ); cudaMalloc( (void**)&d_w_k, size1 ); if((nP*nItt)<32) { blocksize = nP*nItt; nblocks = 1; } else { blocksize = 32; // Defines the number of threads running per block. Taken equal to warp size nthreads = blocksize; nblocks = ceil(float(nP*nItt) / nthreads); // Calculated total number of blocks thus required } for(int i = 0; i< nItt; i++) { cudaMemcpy( d_x_k, x_k, size1,cudaMemcpyHostToDevice ); //copy of x_k to device cudaMemcpy( d_w_k, w_k, size1,cudaMemcpyHostToDevice ); //copy of w_k to device arr_chk<<<nblocks, blocksize>>>(d_x_k,d_w_k,i); cudaMemcpy( x_k, d_x_k, size1, cudaMemcpyDeviceToHost ); cudaMemcpy( w_k, d_w_k, size1, cudaMemcpyDeviceToHost ); } printf("\nVerification after return from gpu\n"); for(int i = 0; i<nItt; i++) { for(int j=0;j<nP;j++) { printf("x_k[%d][%d] = %f\t",i,j,x_k[i][j]); printf("w_k[%d][%d] = %f\n",i,j,w_k[i][j]); } } cudaFree( d_x_k ); cudaFree( d_w_k ); cleanup2d(x_k,nItt); cleanup2d(w_k,nItt); getch(); return 0;

    Read the article

  • SimpleXMLElement empty object

    - by Mike
    Hi, I am trying to parse an xml file using XmlReader but although I am getting a return from the xml file for the (commission) node for some reason I am getting an empty SimpleXMLElement Object returned as well. I don't know if its something to do with while loop,switch or something I missed in the parse setup. This is the xml file I am trying to read from, as you can see there is only 1 result returned: <?xml version="1.0" encoding="UTF-8"?> <cj-api> <commissions total-matched="1"> <commission> <action-status> new </action-status> <action-type> lead </action-type> <aid> 10730981 </aid> <commission-id> 1021015513 </commission-id> <country> </country> <event-date> 2010-05-08T08:08:55-0700 </event-date> <locking-date> 2010-06-10 </locking-date> <order-id> 345007 </order-id> <original> true </original> <original-action-id> 787692438 </original-action-id> <posting-date> 2010-05-08T10:01:22-0700 </posting-date> <website-id> 3201921 </website-id> <cid> 2815954 </cid> <advertiser-name> SPS EurosportBET </advertiser-name> <commission-amount> 0 </commission-amount> <order-discount> 0 </order-discount> <sid> 0 </sid> <sale-amount> 0 </sale-amount> </commission> </commissions> </cj-api> This is my parser: <?php // read $response (xml feed) $file = "datafeed.xml"; $xml = new XMLReader; $xml->open($file); // loop to read in data while ($xml->read()) { switch ($xml->name) { // find the parent node for each commission payment case 'commission': // initalise xml parser $dom = new DomDocument(); $dom_node = $xml ->expand(); $element = $dom->appendChild($dom_node); $dom_string = $dom->saveXML($element); $commission = new SimpleXMLElement($dom_string); // read in data $action_status = $commission->{'action-status'}; $action_type = $commission->{'action-type'}; $aid = $commission->{'aid'}; $commission_id = $commission->{'commission-id'}; $country = $commission->{'country'}; $event_date = $commission->{'event-date'}; $locking_date = $commission->{'locking-date'}; $order_id = $commission->{'order-id'}; $original = $commission->{'original'}; $original_action_id = $commission->{'original_action-id'}; $posting_date = $commission->{'posting-date'}; $website_id = $commission->{'website-id'}; $cid = $commission->{'cid'}; $advertiser_name = $commission->{'advertiser-name'}; $commission_amount = $commission->{'commission-amount'}; $order_discount = $commission->{'order-discount'}; $sid = $commission->{'sid'}; $sale_amount = $commission->{'sale-amount'}; print_r($aid); break; } } ?> The result is : SimpleXMLElement Object ( [0] => 10730981 ) SimpleXMLElement Object ( ) Why is it returning the second object: SimpleXMLElement Object ( ) and what do I need to do correct it? Thanks.

    Read the article

  • Screen capture code produces black bitmap

    - by wadetandy
    I need to add the ability to take a screenshot of the entire screen, not just the current window. The following code produces a bmp file with the correct dimensions, but the image is completely black. What am I doing wrong? void CaptureScreen(LPCTSTR lpszFilePathName) { BITMAPFILEHEADER bmfHeader; BITMAPINFO *pbminfo; HBITMAP hBmp; FILE *oFile; HDC screen; HDC memDC; int sHeight; int sWidth; LPBYTE pBuff; BITMAP bmp; WORD cClrBits; RECT rcClient; screen = GetDC(0); memDC = CreateCompatibleDC(screen); sHeight = GetDeviceCaps(screen, VERTRES); sWidth = GetDeviceCaps(screen, HORZRES); //GetObject(screen, sizeof(BITMAP), &bmp); hBmp = CreateCompatibleBitmap ( screen, sWidth, sHeight ); // Retrieve the bitmap color format, width, and height. GetObject(hBmp, sizeof(BITMAP), (LPSTR)&bmp) ; // Convert the color format to a count of bits. cClrBits = (WORD)(bmp.bmPlanes * bmp.bmBitsPixel); if (cClrBits == 1) cClrBits = 1; else if (cClrBits bmiHeader.biSize = sizeof(BITMAPINFOHEADER); pbminfo-bmiHeader.biWidth = bmp.bmWidth; pbminfo-bmiHeader.biHeight = bmp.bmHeight; pbminfo-bmiHeader.biPlanes = bmp.bmPlanes; pbminfo-bmiHeader.biBitCount = bmp.bmBitsPixel; if (cClrBits bmiHeader.biClrUsed = (1bmiHeader.biCompression = BI_RGB; // Compute the number of bytes in the array of color // indices and store the result in biSizeImage. // The width must be DWORD aligned unless the bitmap is RLE // compressed. pbminfo-bmiHeader.biSizeImage = ((pbminfo-bmiHeader.biWidth * cClrBits +31) & ~31) /8 * pbminfo-bmiHeader.biHeight; // Set biClrImportant to 0, indicating that all of the // device colors are important. pbminfo-bmiHeader.biClrImportant = 0; CreateBMPFile(lpszFilePathName, pbminfo, hBmp, memDC); } void CreateBMPFile(LPTSTR pszFile, PBITMAPINFO pbi, HBITMAP hBMP, HDC hDC) { HANDLE hf; // file handle BITMAPFILEHEADER hdr; // bitmap file-header PBITMAPINFOHEADER pbih; // bitmap info-header LPBYTE lpBits; // memory pointer DWORD dwTotal; // total count of bytes DWORD cb; // incremental count of bytes BYTE *hp; // byte pointer DWORD dwTmp; int lines; pbih = (PBITMAPINFOHEADER) pbi; lpBits = (LPBYTE) GlobalAlloc(GMEM_FIXED, pbih-biSizeImage); // Retrieve the color table (RGBQUAD array) and the bits // (array of palette indices) from the DIB. lines = GetDIBits(hDC, hBMP, 0, (WORD) pbih-biHeight, lpBits, pbi, DIB_RGB_COLORS); // Create the .BMP file. hf = CreateFile(pszFile, GENERIC_READ | GENERIC_WRITE, (DWORD) 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, (HANDLE) NULL); hdr.bfType = 0x4d42; // 0x42 = "B" 0x4d = "M" // Compute the size of the entire file. hdr.bfSize = (DWORD) (sizeof(BITMAPFILEHEADER) + pbih-biSize + pbih-biClrUsed * sizeof(RGBQUAD) + pbih-biSizeImage); hdr.bfReserved1 = 0; hdr.bfReserved2 = 0; // Compute the offset to the array of color indices. hdr.bfOffBits = (DWORD) sizeof(BITMAPFILEHEADER) + pbih-biSize + pbih-biClrUsed * sizeof (RGBQUAD); // Copy the BITMAPFILEHEADER into the .BMP file. WriteFile(hf, (LPVOID) &hdr, sizeof(BITMAPFILEHEADER), (LPDWORD) &dwTmp, NULL); // Copy the BITMAPINFOHEADER and RGBQUAD array into the file. WriteFile(hf, (LPVOID) pbih, sizeof(BITMAPINFOHEADER) + pbih-biClrUsed * sizeof (RGBQUAD), (LPDWORD) &dwTmp, ( NULL)); // Copy the array of color indices into the .BMP file. dwTotal = cb = pbih-biSizeImage; hp = lpBits; WriteFile(hf, (LPSTR) hp, (int) cb, (LPDWORD) &dwTmp,NULL); // Close the .BMP file. CloseHandle(hf); // Free memory. GlobalFree((HGLOBAL)lpBits); }

    Read the article

  • How to bring out checboxes based on drop down list selection from DB

    - by user2199877
    I got stuck again. Can't overcome this step: loop through (in a form of checkboxes) pallets based on the lot drop down list selection, so it can be further submitted to complete the table. Please, please help. So, basically, first submit button (drop down menu) brings into the table lot number and description and also checkboxes to choose pallets. Second submit button (checboxes) brings into the table pallets numbers and weights. Thank you for any help. <?php mysql_connect('localhost','user',''); mysql_select_db('base'); $query="SELECT DISTINCT lot_number FROM pl_table"; $result=mysql_query($query); ?> <form action="" method="POST"> <select name="option_chosen"> <option>-- Select lot --</option> <?php while(list($lot_number)=mysql_fetch_row($result)) { echo "<option value=\"".$lot_number."\">".$lot_number."</option>"; } ?> </select> <input type='submit' name='submitLot' value='Submit' /> </form> <!-- need help here <h4>-- Select pallets --</h4> <form action="" method="POST"> <input type='submit' name='submitPal' value='Submit'/> </form> --> <table border="1" id="table"> <tr> <th width=80 height=30>Lot<br/>number</th> <th width=110 height=30>Description</th> <th width=90 height=30>Pallet<br/>number</th> <th width=60 height=30>Net</th> <th width=60 height=30>Gross</th> </tr> <?php if($_SERVER['REQUEST_METHOD'] =='POST') {$option_chosen=$_POST['option_chosen']; $query="SELECT * FROM pl_table WHERE lot_number='$option_chosen'"; $run=mysql_query($query); $row=mysql_fetch_array($run, MYSQLI_ASSOC); echo "<tr><td>".''."</td>"; echo "<td rowspan='5'>".$row['descr']."</td>"; echo "<td><b>".'Total weight'."<b></td>"; echo "<td>".''."</td><td>".''."</td></tr>"; echo "<td>".$row['lot_number']."</td>"; echo "<td colspan='3'>".''."</td>"; //This to be echoed when "select pallets" submited //echo "<tr><td>".$row['lot_number']."</td>"; //echo "<td>".$row['pallet_number']."</td>"; //echo "<td>".$row['net']."</td><td>".$row['gross']."</td></tr>"; } ?> </table> the table +--------------------------+-------------------------+---------+-------+ | id | lot_number | descr | pallet_number | net | gross | +--------------------------+-------------------------+---------+-------+ | 1 | 111 | black | 1 | 800 | 900 | | 2 | 111 | black | 2 | 801 | 901 | | 3 | 111 | black | 3 | 802 | 902 | | 4 | 222 | white | 1 | 800 | 900 | | 5 | 222 | white | 2 | 801 | 901 | | 6 | 222 | white | 3 | 802 | 902 | +--------------------------+-------------------------+---------+-------+

    Read the article

< Previous Page | 228 229 230 231 232 233 234 235 236 237 238  | Next Page >