pid
int64 2.28k
41.1M
| label
int64 0
1
| text
stringlengths 1
28.3k
|
---|---|---|
26,787,995 | 0 | <p>Absolutely positioned elements are removed from the normal document flow, so they won't fill up 100% of their parent like regular static block level elements. Instead, they rely on their content width or a specified width. Firefox seems to apply the content width a bit differently than Chrome or IE, which is why it appears cut off.</p> <p>Not sure of your use-case or what browsers you support, but you have a couple options: </p> <ol> <li>Set a width on the absolutely positioned element</li> <li>If you don't need to <a href="http://caniuse.com/#search=flex" rel="nofollow">support < IE 10 or opera mini</a>, you can <a href="https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Flexible_boxes" rel="nofollow">use flexbox instead</a> of the media object</li> <li>If you just don't want the text cut off, you can use the newer <a href="https://github.com/stubbornella/oocss/blob/master/oocss/src/components/media/_media.scss" rel="nofollow">OOCSS method for media objects</a> which uses <code>display: table-cell</code> for media body. This has the caveat that your media object basically take up as much room as it can since it behaves like a table cell, which may not be what you're after.</li> </ol> |
38,942,505 | 0 | <p>I have altered the accepted answer's data and query.</p> <p>The data is now a sample of a data from a 5 star rating system.<br> The function now correctly uses average values of all the posts.</p> <p>The difference is in the calculation of those average values, instead PHP, they are calculated in the SQL, for the purpose of the answer.</p> <p><s>You can see it in action on SQL Fiddle: <a href="http://sqlfiddle.com/#!9/84d8b/2/2" rel="nofollow">http://sqlfiddle.com/#!9/84d8b/2/2</a></s></p> <hr> <h2>The updated query</h2> <p>The new fiddle: <a href="http://sqlfiddle.com/#!9/3cdfe/1/2" rel="nofollow">http://sqlfiddle.com/#!9/3cdfe/1/2</a></p> <pre><code>SET @avg_total_votes := (SELECT AVG(meta_value) FROM postmeta WHERE meta_key ='this_num_votes'); SET @avg_total_rating := (SELECT AVG(meta_value) FROM postmeta WHERE meta_key ='this_rating'); SELECT posts.ID, posts.title, getmeta_votes.meta_value AS votes, getmeta_rating.meta_value AS rating, ( ( (@avg_total_votes * @avg_total_rating) + (getmeta_votes.meta_value * getmeta_rating.meta_value) ) / ( @avg_total_votes + getmeta_votes.meta_value ) ) AS factor FROM posts LEFT JOIN postmeta AS getmeta_votes ON posts.ID = getmeta_votes.post_id AND getmeta_votes.meta_key = 'this_num_votes' LEFT JOIN postmeta AS getmeta_rating ON posts.ID = getmeta_rating.post_id AND getmeta_rating.meta_key = 'this_rating' WHERE NOT getmeta_votes.meta_value = 0 AND NOT getmeta_rating.meta_value = 0 ORDER BY factor DESC; </code></pre> <p>I have found this query construction to be much faster, the previous one was working for 2 hours on a 2,000+ posts data set (1,000,000+ wp_postmeta rows), until terminated.</p> <p>This one runs in 0.04 sec.</p> |
38,512,896 | 0 | java regex match words that aren't numbers <p>I have a json missing quotes </p> <pre><code>{ data: [{ timestamp: 1467720920, val: { min: 6.90, max: 7.25, avg: 7.22 }, temp: { min: 75.49, max: 75.49, avg: 75.49 }, gps: { lat: 0.707581, long: -1.941864, hdop: 2.54, ttf: 49.4 } }], id: A1000049A6248C, groupId: HU5PPC1E, rssi: -93, cell: { timestamp: 1467731669, rssi: -93, lat: 0.735554, long: -1.974655 } } } </code></pre> <p>I need to put quotes around all of the words to the left of the colon and all of the words that aren't purely numbers to the right of the colon. So I need quotes around A1000049A6248C but not -1.974655. How do I make a regex to do this in java? I've tried </p> <p><code>json.replaceAll("(\\w+|[+-]([0-9]*[.])?[0-9]+)", "\"$1\"");</code> </p> <p>which will put every word in quotes. I've also tried something like this to get a word that isn't all numbers <code>json.replaceAll("\\b(?!\\d*)\\b", "\"$1\"");</code></p> <p><strong>Expected format</strong></p> <pre><code>{ "data": [ { "timestamp": 1463494202, "val": { "min": 6.75, "max": 7.19, "avg": 7.14 }, "temp_int": { "min": 54.28, "max": 54.28, "avg": 54.28 }, "gps": { "lat": 0.711407, "long": -1.460091, "hdop": 1.42, "ttf": 42 } } ], "id": "A1000049A624D1", "groupId": "299F7G5AR", "rssi": -83, "cell": { "timestamp": 1463501353, "rssi": -83, "lat": 0, "long": 0 } } </code></pre> |
31,204,453 | 0 | <p>I'm afraid <code>document.save()</code> only returns a populated version of <code>model</code>. You can see all files in <code>model.files</code> but then it would be up to you to figure out which was the last one.</p> <p>One alternative is to create the file before adding it to document. You should be able to do:</p> <pre><code>//... File.create({ name: req.param("name"), creator: req.param("userID"); }, function(err, file){ if (err) {return res.serverError(err);} var newFileId = file.id; document.files.add(file.id); document.save(function(err, model) { if (err) {return res.serverError(err);} // the Document modal console.log(model); // the last insert id console.log('last inserted id:', newFileId); res.send(1); }); }); //... </code></pre> <p>In this case <code>newFileId</code> will have the id you need. Performance wise it should be the same as internally waterline has to create the file in similar way.</p> |
22,474,325 | 0 | My $_FILES['file']['name'] is producing gibberish <p>I am uploading files with the following code using Bootstrap as my front-end framework.</p> <pre><code><form method="POST" enctype="multipart/form-data" action= "php/up-load.php" role="form" <div class="form-group"> <label for="file" class="col-sm-5 control-label"> Select file(Compressed format) </label> <div> <input type="hidden" name="MAX_FILE_SIZE" value="1000000000"/> <input type="file" id="file" name="file" accept=".zip, .rar"/> </div> </div> <div> <button type="submit" class="btn btn-primary" name="upload" id="upload">Send</button> </div> </form> </code></pre> <p>My php code is; </p> <pre><code>@ $original=$_FILES['file']['name']; @ $kiss=pathinfo($original, PATHINFO_EXTENSION); $allowed_extensions = array(".zip","rar","bzip2","iso","gz","rz","7z","tar","tgz","bz2","tbz2","lzma","tlz"); $result = in_array ("$kiss", $allowed_extensions); if (!$result) { // Wrong file type } else { //proceed.. } </code></pre> <p>My problem is that the</p> <pre><code>$_FILES['file']['name']; </code></pre> <p>is returning gibberish such as <code>php7vy8X9</code> and <code>phpY8wQVR</code> . Have tried everything. What could be the problem?</p> |
34,608,616 | 0 | Objective C model - How to download image inside a model class? <p>I have the following model of a box, it is meant to download images in a background thread and create an image from this downloaded image.</p> <p>The viewcontroller has a custom uicollectioncell, but its just a uiimageview; nothing too complex.</p> <p>In the <code>cellForItemAtIndexPath</code> I want to assign the cell's imageview using the model's downloaded image.</p> <p>However, its not quite working;</p> <ol> <li>The image never appears</li> <li>If I move the background image downloader to the <code>cellForItemAtIndexPath</code> and change a few items then the image loads fine.</li> </ol> <p>But what I'm wanting is to seperate the ViewContoller and the model; the model should do the heavy lifting and the viewcontroller simply handles the display.</p> <p>Code follows</p> <pre><code>// ViewController: View Did Load - (void)viewDidLoad { [super viewDidLoad]; if (!self.picturesArray) self.picturesArray = [NSMutableArray arrayWithCapacity:kNumberOfCells]; self.collectionView.delegate = self; self.collectionView.dataSource = self; self.collectionView.backgroundColor = [UIColor clearColor]; for (int i=0; i<kNumberOfCells; i++) { Box *box = [[Box alloc] init]; [self.picturesArray addObject:box]; box = nil; } } // ViewController : collectionView delegage - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { MyCustomCollectionViewCell *cell = (MyCustomCollectionViewCell *) [collectionView dequeueReusableCellWithReuseIdentifier:cellId forIndexPath:indexPath]; Box *box = self.picturesArray[indexPath.row]; cell.backgroundColor = box.bgColor; cell.imageView.image = box.image; return cell; } </code></pre> <p>The <code>box</code> model is as follows</p> <pre><code>// Box model with an image property - (instancetype)init { self = [super init]; if (self) { NSURL *url = [NSURL URLWithString:kUrlString]; // Block variable to be assigned in block. __block NSData *imageData; dispatch_queue_t backgroundQueue = dispatch_queue_create("imagegrabber.bgqueue", NULL); // Dispatch a background thread for download dispatch_async(backgroundQueue, ^(void) { imageData = [NSData dataWithContentsOfURL:url]; if (imageData.length >0) { // self.image is a property of the box model self.image = [[UIImage alloc] initWithData:imageData]; // Update UI on main thread dispatch_async(dispatch_get_main_queue(), ^(void) { }); } }); } return self; } </code></pre> <p>My question is this:</p> <ol> <li>How do I get the box model to download the image and then in my cellAtIndexPath make the cell's imageView assign its image from that downloaded boxmodel image?</li> </ol> <p>A further unrelated question</p> <ol> <li>Isn't it best practice to seperate the model from the actual downloading of items? But if I'm not meant to put this in the view controller, and not the model where does it go and how/whem would you call it?</li> </ol> <p>Thanks for now</p> |
31,788,660 | 0 | Excel Chart colorize 3D bars <p>Colorzing a 3D-Bar chart with Excel and interop does not work:</p> <p>Creation of chart:</p> <pre><code>chartRange = xlsSheet.Range[xlsSheet.Cells[1, 1], xlsSheet.Cells[array.GetLength(0), array.GetLength(1)]]; chartPage.SetSourceData(chartRange, Excel.XlRowCol.xlRows); chartPage.ChartType = Excel.XlChartType.xl3DColumn; chartPage.Location(Excel.XlChartLocation.xlLocationAsNewSheet, oOpt); </code></pre> <p>Changing color:</p> <pre><code>Excel.Series series = (Excel.Series)chartPage.SeriesCollection(1); Excel.Point pt = series.Points(2); pt.Format.Fill.ForeColor.RGB = (int)Excel.XlRgbColor.rgbPink; </code></pre> <p>Problem: Nothing will change inside the chart, but there is also no error. Just showing this random colors on the bars.</p> |
14,905,038 | 0 | <p>If you call <code>System.exit()</code> your code won't execute <code>finally</code>, because that call terminates your JVM. </p> |
13,775,908 | 0 | <p>According to the comment in the source of HashMap, it has to be a power of two. It makes sense in a HashMap, because of how the hashing works.</p> <p>However, there is no reason why power of two makes sense in an arraylist. If there was any reason behind choosing such a number, it would have been mentioned in the source itself. </p> <p>IMHO, it is just an arbitrary number, large enough to avoid frequent resizing(better performance) and small enough not to waste memory on unused capacity.</p> |
10,530,657 | 0 | <pre><code> var latlong = "(2.34000000, -4.500000000)" var coords = latlong.replace(/[\(\) ]/g,'').split(','); console.log(coords[0]) console.log(coords[1]) </code></pre> |
3,518,810 | 0 | <p>Change <code>"Mode=Share Deny Write"</code> to <code>"Mode=Read"</code></p> <p>in connection string</p> |
718,363 | 0 | Why does IE7 fetch every favicon at startup? <p>I am trying to understand what IE7 is up to and why it takes forever to start up.</p> <p>I've been using Fiddler 2 to monitor traffic and the content of headers. I'll start Fiddler 2, then fire up IE7. And each time i do this I see that this browser always appears to chase down a favicon for every single site in my bookmarks. Worse it tries for both ICO and GIF format for each. </p> <p>I can't understand this. Am I mis-configured or is this a well-known 'feature' ?</p> |
3,932,774 | 0 | divide 64bit in two 32bit registers by 32bit <p>I am trying to write an x86 emulator in JavaScript for education purposes. I have already written a compiler and at the moment I am trying to write the x86 emulator in JavaScript.</p> <p>I have however a problem with the DIV instruction. According to <a href="http://siyobik.info/index.php?module=x86&id=72" rel="nofollow">http://siyobik.info/index.php?module=x86&id=72</a> DIV takes a 64bit number as input by interpreting EDX as the higher 32bit and EAX as the lower 32bit. It then divides this number by the DIV parameter and puts the result (if it is not greater than 0xFFFFFFFF) into EAX and the remainder into EDX.</p> <p>As JavaScript does not support 64bit integer I need to apply some tricks. But so far I did not come up with something useful.</p> <p>Does someone here have an idea how to implement that correctly with 32bit arithmetic?</p> |
17,523,964 | 0 | listing generic relations in Django <p>I have a <strong>generic relation</strong> in a class called <strong>Unsubscribe</strong>. The relation at the moment links to a class called <strong>Contact</strong>.</p> <p>I would like to <strong>list all Unsubscribe Contacts</strong> in view. My question is, <strong>where do I list from?</strong> Contacts or Unsubscribed? i.e. Should I be writing a view from my contacts app or my unsubscribe app, which end should I come at it from?</p> <p>Thanks</p> <pre><code>class Unsubscribe(models.Model): """ Notes: See: http://www.screamingatmyscreen.com/2012/6/django-and-generic-relations/ """ content_type = models.ForeignKey(ContentType, help_text="Represents the name of the model") object_id = models.PositiveIntegerField(help_text="stores the object id") content_object = generic.GenericForeignKey('content_type', 'object_id') reason = models.CharField(max_length=60) request_made = models.DateTimeField(auto_now_add=True, help_text="Shows when object was created.") </code></pre> |
34,631,211 | 0 | <pre><code><div ><img src="<%=request.getContextPath() %>/images/logo.gif" title="Your Title" /></div> </code></pre> |
20,323,103 | 0 | <p>When using == or != or > or < if the types of the two expressions are different it will attempt to convert them to string, number, or Boolean etc<br/> use below code to compare </p> <pre><code>if ( Date.parse ( currentdate) > Date.parse ( enddate) ) { // your code } </code></pre> |
39,691,107 | 0 | <p>You are embedding your data in the <code>Header</code> section of PostMan. These are for <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers" rel="nofollow">HTTP Headers</a> and not what you want. When using angular's post method, the parameters are in fact embedded into the Body section of a POST request. </p> <p>Put your parameters in the <code>Body</code> section of Postman and it should work.</p> |
18,537,117 | 0 | <p>Divide and conquer. <code>printf</code>. Patience.</p> |
27,276,680 | 1 | How to get the last executed command in IDLE as in R? <p>When I use R and execute a command in the command window, I can just press up and I get the last executed command in the current command line. What key do I need to press in order to get the same in Python? </p> <p>Edit: When I asked this question, I did not know what IDLE or iPython is. I just googled "download python" and downloaded it. But now I know I am using IDLE.</p> |
24,548,796 | 0 | <p>This can only go wrong if you copied d3dcompiler_47.dll from your Windows directory. Which is not suitable to run on older Windows versions.</p> <p>You <em>must</em> use the redistributable version of it. You'll find it back in the Windows SDK directory. Like C:\Program Files (x86)\Windows Kits\8.1\Redist\D3D on most machines. Pick the x86 or the x64 version of it, depending on the platform target you used to compile your program.</p> |
755,889 | 0 | <p>Try console.log() in the event to see if it is launched. Changing the store should work, however for other widgets like grid you have also to call refreshing methods.</p> |
28,623,648 | 0 | <p>Just do</p> <pre><code>String attValue = driver.findElement(byAnyMethod).getAttribute("AttributeName"); </code></pre> <p>Hope it helps</p> |
34,573,051 | 0 | <p>CSS: </p> <pre><code>h2 { color: blue; background-color: white; text-align: center; } header { background-color: black; width: 100%; height: 100px; } </code></pre> <p>Hope this work :) </p> |
21,344,191 | 0 | <p>Store the schedule as an iCalendar <a href="http://stackoverflow.com/questions/tagged/rrule?sort=votes">rrule</a> (or a more normalized version if your prefer). </p> <p>Create a function to return upcoming dates for the rule. </p> <p>Create a materialized view of upcoming dates if you need to, to boost performance. </p> <p><a href="http://repo.or.cz/w/davical.git?a=blob;f=dba/rrule_functions.sql;hb=HEAD" rel="nofollow">PostgreSQL Functions for RRULE handling</a></p> <p>Use Table Inheritance to model the geographical locations. You should consider City to be a child of State and not County, as some cities <em>contain</em> counties. </p> <p>You want to be able point a single foreign key at an abstract geographical location such as "Ohio" or "Cuyahoga County, Ohio"</p> <p>Use a junction table to map multiple locations to a campaign.</p> <pre><code>--postgresql syntax create table campaigns ( campaign_id int primary key, name text unique, rrule text not null check ( is_valid_rrule(rrule) ) --you would need to write this ); create table locations ( location_id int primary key, type text not null check ( type in ('COUNTRY', 'PRIMARY_DIVISION','SECONDARY_DIVISION') ), --use a lookup table in real life name text not null, parent_id int null references locations (location_id) check ( type = 'COUNTRY' or parent_id is not null), unique (name, parent_id) ); create table campaign_locations ( campaign_id int references campaigns(campaign_id), location_id int references locations(location_id), primary key (campaign_id, location_id) ); --insert some locations: insert into locations values (1, 'COUNTRY', 'United States of America', null), (2, 'PRIMARY_DIVISION', 'Ohio', 1), (3, 'SECONDARY_DIVISION', 'Cuyahoga County', 2), (4, 'SECONDARY_DIVISION', 'Adams County', 2); --create a campaign with a recurrence rule: insert into campaigns values (1, 'My Campaign', 'FREQ=WEEKLY;BYDAY=MO,WE'); --associate a campaign with Cuyahoga and Adams counties: insert into campaign_locations values (1, 3), (1, 4); </code></pre> |
3,038,454 | 0 | Lambda Expressions in T4 Templates <p>Whilst putting together a T4 template I threw in a simple lambda expression:</p> <pre><code><#=string.Join(",", updateFields.ConvertAll(field => field.Name).ToArray())#> </code></pre> <p>This causes the template to fail to generate with the error:</p> <pre><code>Compiling transformation: Invalid expression term '>' </code></pre> <p>On the line with the lambda expression.</p> <p>This has been checked outside of a template and works fine. Does T4 not support working with lambda expressions? If not, are there any other language features that are unsupported in the context of a T4 template?</p> <p>Thanks!</p> |
39,322,006 | 0 | How to compile scala files from eclipse <p>I could not find any relevant answer to my following question : </p> <p>I'm trying to compile an existing scala and java project from eclipse. I have installed the software from eclipse as well - but i'm still having errors.</p> <p><a href="http://i.stack.imgur.com/nxuo0.png" rel="nofollow">i.e - erros in scala class</a></p> <p>What should i do in order to correctly compile the scala files?</p> |
15,351,389 | 0 | <p>I don't think so. SMO supports SQL versions going back to before that syntax was supported. Aside from making smaller DML scripts, they have very little to gain by adding that functionality to SMO and it costs them maintainability in the code base.</p> |
11,517,023 | 0 | <p>Recover the id and use in the second activity:</p> <pre><code>public void onItemClick(AdapterView<?> parent, View view, int position, long id) { String rowid = String.valueOf(id) Bundle bundle = new Bundle(); bundle.putString("ID", rowid); intent.putExtras(bundle); startActivity(intent); } </code></pre> <p>Retrieve in second activity using:</p> <pre><code>String rowid= getIntent().getExtras().getString("ID"); </code></pre> <p>Don't forget to convert the id from string back to long and add 1 after you retrieve it in your second activity</p> |
26,717,074 | 0 | gmaps4rails change map id <p>I have a Rails 3.2.x app which I'm using <code>gmaps4rails 2.0.0.pre</code> (yes I know it's an old version). I'm using this to plot different vehicles (units) on a map in a gps view/controller. Now I'm trying to leverage <code>gmaps4rails</code> to display a map in a different view/controller to display a building (facility) location in the facility show view.</p> <p>On initial page load I display the facility's marker on a map in the proper location. However after a few moments the marker will disappear entirely. I know why this is happening but not how to fix it.</p> <p>I have the following <code>Coffeescript</code> which looks for an <code>ID</code> of <code>#map</code> and calls <code>/units</code> and <code>/gps</code> paths to update the GPS view/map in quasi-realtime.</p> <p><strong>gps.js.coffee</strong></p> <pre><code>$ -> if $("#map").length > 0 setInterval (-> $.getScript "/units" # Get all current locations, find each marker in the map, and update it's position $.getJSON "/gps", (data) -> $.each(data, (i, val) -> marker = $.grep Gmaps.map.markers, (e) -> e.id is val.id marker[0].setPosition(val.lat, val.lng) if marker[0]? ) ), 5000 $('.marker-link').on 'click', -> id = $(this).data("marker-id") marker = $.grep Gmaps.map.markers, (e) -> e.id is id marker[0].showInfowindow() if marker[0]? </code></pre> <p>So the problem is that the default <code>ID</code> for gmaps4rails maps is <code>#map</code>. I'm trying to figure out how to create a new map using the plugin with a different <code>ID</code> so that I can display a facility location and not call the coffeescript to refresh.</p> <p>Here's what my facility model/view/controller look like. Everything works but the marker disappears due to the coffee script calling <code>#map</code>. I don't want to lose this coffeescript functionality as it updates my gps show view with markers properly. I'd like to figure out a way to generate a gmaps4rails map and change the <code>ID</code>.</p> <p><strong>facility.rb</strong></p> <pre><code> acts_as_gmappable process_geocoding: false </code></pre> <p><strong>facilities_controller</strong></p> <pre><code>def show @facility = Facility.find(params[:id]) @marker = @facility.to_gmaps4rails do |facility, marker| #marker.infowindow render_to_string(partial: "unit_infowindow", locals: {unit: unit}) marker.json({id: facility.id}) end respond_to do |format| format.html # index.html.erb format.json { render json: @marker } end end </code></pre> <p><strong>facility show.html.erb</strong></p> <pre><code><div class="well"> <%= gmaps(markers: {data: @marker, options: {rich_marker: true, "auto_zoom" => false}}) %> </div> </code></pre> <p>Is there a way to generate a gmaps4rails map, and override the default <code>ID</code> of <code>#map</code> so I can keep the marker from disappearing and continue to use my coffeescript in my GPS view?</p> <p>If anyone has any suggestions, please let me know. I would greatly appreciate it.</p> <p>And if my question is confusing or needs more explanation, I will be happy to update it.</p> |
24,754,437 | 0 | <p>First thing is: you don't need to afraid cache's loose between requests - it's rather information that you shouldn't use it as a <em>regular</em> persistence layer.</p> <p>For main question: most probably <a href="http://playframework.com/documentation/2.3.x/ScalaSessionFlash" rel="nofollow"><strong>Flash</strong> scope</a> will be more suitable solution for this task. </p> <p>Remember that cache values will be available for other users, so if some user will perform similar action in the almost the same time (60 seconds) it will get value from others action - Flash as it's stored in the cookie will be individual.</p> <p>If you want to stay with cache - (i.e. in case that you want to store objects much bigger than 4kb) at least make sure that the cache <strong>keys</strong> contains some user specific, unique elements, like:</p> <pre><code>Cache.set("userData"+currentUser.id, userData, 60) </code></pre> |
29,388,384 | 0 | How to fire a keyboard shortcut function in JavaScript? <p>I have a record functionality in my website. If a user hits <kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>R</kbd> the recording will begin. Now I would like a button named <code>RECORD</code> in my html page, so that when a user hits that button recording will start.</p> <pre><code><button type="submit" class="btn btn-primary" data-toggle="tooltip" data-placement="top" onclick="record_session()" title="Start Recording">Record</button> </code></pre> <p>in my function below</p> <pre><code>function record_session(){ //how can i trigger or initiate ctrl+alt+r here?? } </code></pre> |
25,570,856 | 0 | <p>This line is not necessary and should be removed from your code:</p> <pre><code>gpuErrchk( cudaMalloc((void**)&dev_inp, sizeof(unsigned char)*flipped.rows*flipped.cols) ); </code></pre> <p>This line creates a device allocation, and assigns the pointer for that allocation to <code>dev_inp</code>.</p> <p>The problem arises here:</p> <pre><code>gpuErrchk( cudaGraphicsResourceGetMappedPointer((void **)&dev_inp, &size, cuda_resource) ); </code></pre> <p>This line acquires a <em>new</em> pointer, derived from the <code>cuda_resource</code> object, to another, different allocation, and places that pointer into <code>dev_inp</code>, <strong>overwriting</strong> your previously allocated pointer (from <code>cudaMalloc</code>). The new pointer acquired in this line already has an underlying device allocation. You do not need to allocate for it separately/additionally at this point.</p> <p>At this point, if you try to free <code>dev_inp</code>:</p> <pre><code>gpuErrchk(cudaFree(dev_inp)); // <--- Error here </code></pre> <p>You are attempting to free data that your program did not explicitly allocate (via <code>cudaMalloc</code>), and is furthermore a necessary component of the persistent (at this point) <code>cuda_resource</code> object. You don't want to do that. Unfortunately, the original pointer that was placed in <code>dev_inp</code> is now lost (overwritten), and so there is no way to "free" it in your program, and you will have a memory leak, as long as the program is executing.</p> <p>The solution is not to perform the extra, unneeded allocation:</p> <pre><code>gpuErrchk( cudaMalloc((void**)&dev_inp, sizeof(unsigned char)*flipped.rows*flipped.cols) ); </code></pre> <p>This then means that the corresponding <code>cudaFree</code> operation should be eliminated as well:</p> <pre><code>gpuErrchk(cudaFree(dev_inp)); // <--- Error here </code></pre> <p>I would not use <code>cudaDeviceReset</code> anywhere in a CUDA code, especially a CUDA/OpenGL code, until the program is actually exiting. There are a few other very specialized situations where you might want to use <code>cudaDeviceReset</code> before the point at which you actually intended to exit your program, but they don't apply here.</p> |
24,414,708 | 0 | clang: error: linker command failed with exit code 1 with duplicate symbol _TableLookup in database.o and main.o <p>After changing the code, I got new error in database_definitions.h header file. The error is near the 'extern const Lookup_Table TableLookup[TABLE_COUNT];' and mentioned the error in the code with comments next to it. I also got warning in 'database.c' file near the return &(TableLookup[index]); in the 'Lookup_Table* GetTableMetadata(char *tableName)' function. The error is pasted in the code next to it. Kindly review and help me in solving in this issue.</p> <pre><code>**database.c**: const Lookup_Table TableLookup[TABLE_COUNT]= { { .tableName = "Folder_Table", // .tableInitializer = (void*)&InitFolder_Table, .tableMemory = sizeof(Folder_Table), .columns = 5, .columnNames = {"folderID","field1","field2","field3","field4"}, // Fill out field name metadata .columnSize = {SIZE_OF(Folder_Table,folderID), SIZE_OF(Folder_Table,field1), SIZE_OF(Folder_Table,field2), SIZE_OF(Folder_Table,field3), SIZE_OF(Folder_Table,field4)}, .columnType = {TYPE_INT, TYPE_FLOAT, TYPE_INT, TYPE_FLOAT, TYPE_TEXT}, .subTable = {{.tableName = "Item_Table", .pointerOffset = offsetof(Folder_Table,item)}, {.tableName = "nextRow", .pointerOffset = offsetof(Folder_Table, nextRow)}, {.tableName = "lastRow", .pointerOffset = offsetof(Folder_Table, lastRow)}, {.tableName = "\0", .pointerOffset = 0 }}, }, { .tableName = "Item_Table", // .tableInitializer = (void*)&InitItem_Table, .tableMemory = sizeof(Item_Table), .columns = 4, .columnNames = {"ItemID\0","FolderID\0","field1\0","field2\0"}, .columnSize = {SIZE_OF(Item_Table,itemID), SIZE_OF(Item_Table,folderID), SIZE_OF(Item_Table,field1), SIZE_OF(Item_Table,field2)}, .columnType = {TYPE_INT, TYPE_INT, TYPE_TEXT, TYPE_FLOAT}, .subTable = {{.tableName = "nextRow", .pointerOffset = offsetof(Item_Table, nextRow)}, {.tableName = "lastRow", .pointerOffset = offsetof(Item_Table, lastRow)}, {.tableName = "\0", .pointerOffset = 0}}, } }; //==================================================================================== // Struct Table Initializer and metadata functions //==================================================================================== //------------------------------------------------------------------------------------ // Find the memory size of a table specified by name //------------------------------------------------------------------------------------ int GetTableSize(char *tableName) { int index; //// Find function matching function name string for (index=0 ; index < TABLE_COUNT; index++) { if (strcmp(TableLookup[index].tableName, tableName)) { return(TableLookup[index].tableMemory); } } return 1; // Return error, should this be an exception? } //------------------------------------------------------------------------------------ // Return the index of of the table from the table-lookuptable //------------------------------------------------------------------------------------ Lookup_Table* GetTableMetadata(char *tableName) { //// Find function matching function name string for (int index=0; index < TABLE_COUNT; index++) { if (strcmp(TableLookup[index].tableName, tableName)) { `return &(TableLookup[index]);//error: 'Returning 'const Lookup_Table*(aka 'const structLookup_Table') from a function with result type 'Lookup_Table'(aka 'struct Lookup_Table") discards qualifiers`' } } return 0; // Return error } **database.h**: #ifndef database_h #define database_h #include "database_definitions.h" #define ONE_ROW 1 //==================================================================================== // Function Definitions //==================================================================================== int SQLOpen(void); //isc_db_handle SQLGetDatabase(void); Lookup_Table* GetTableMetadata(char *tableName); Sub_Table* GetSubTableMetadata(char *tableName, char *subTableName); #endif **database_definitions.h**: #ifndef database_database_h #define database_database_h extern const Lookup_Table TableLookup [TABLE_COUNT]; //error:unknown type name 'Lookup_Table' //==================================================================================== // SQL Table Metadata Structures //==================================================================================== typedef struct Folder_Table // Table type name gets "_Table" added to the SQLite name { //// Fields // Comments are added to seperate the fields, Relationships, and metadata int folderID; // Fields are added as elements of the type and length listed in SQLite float field1; int field2; float field3; char field4[40]; // string length '40' is queried from SQLite settings for field //// Relationships struct Item_Table *item; // Pointer to the sub-table struct Folder_Table *nextRow; // Linked List Pointer to the next-row struct Folder_Table *lastRow; // Linked List Pointer to the last-row } Folder_Table; typedef struct Item_Table { //// Fields int itemID; int folderID; char field1[32]; float field2; //// Relationships Folder_Table *folder; struct Item_Table *nextRow; struct Item_Table *lastRow; } Item_Table; typedef struct Sub_Table { char tableName [TABLE_NAME_LENGTH]; // Sub-table name int pointerOffset; // Sub-table pointer memory offset in the struct }Sub_Table; typedef struct Lookup_Table { char tableName [TABLE_NAME_LENGTH]; // Stores table name void (*tableInitializer)(void *); // Pointer to the initializer function int tableMemory; // Size of the table memory instance int columns; // Number of columns in the table char columnNames[MAX_COLUMNS][COLUMN_NAME_LENGTH]; // Array of column names int columnSize [MAX_COLUMNS]; // Array of column variable memory sizes int columnType [MAX_COLUMNS]; // Array of column variable types Sub_Table subTable [MAX_SUB_TABLES]; // Stores sub-table pointers }Lookup_Table; #endif **main.c**: #include <stdio.h> #include "database.h" int main(int argc, const char * argv[]) { // SQLOpen(); return 0; } </code></pre> |
6,490,672 | 0 | <p>See</p> <p><code>$_SERVER['HTTP_HOST']</code></p> <p>More verbose <a href="http://php.net/manual/en/reserved.variables.server.php" rel="nofollow">http://php.net/manual/en/reserved.variables.server.php</a></p> |
6,140,793 | 0 | I have a syntax error in my PHP script? <p>I am working on a project were I need to turn text in a table cell into a dynamic link and I am getting an error when escaping to HTML.</p> <p>Here are the line of code I am trying to turn into a link. It works perfect before I try to make it a link.</p> <pre><code>echo "<td><a>" . (isset($resultSetArray[$x]["assessment"]["owner1"]) ? ucwords(strtolower($resultSetArray[$x]["assessment"]["owner1"])) : '') . "</a></td>"; </code></pre> <p>It returns a name from the database. I need this name to be a link to another page, with the name in the URL.</p> <p>Here is what I tried without success. Where am I going wrong?</p> <pre><code>echo "<td>" . "<a href=\"http://Company.com/secure/IndSearch?owner=" (isset($resultSetArray[$x]["assessment"]["owner1"]) ? ucwords(strtolower($resultSetArray[$x]["assessment"]["owner1"])) : '')"/" (isset($resultSetArray[$x]["assessment"]["owner1"]) ? ucwords(strtolower($resultSetArray[$x]["assessment"]["owner1"])) : '') . "</a></td>"; </code></pre> |
21,699,730 | 0 | how to run a java rmi program in the property of a jsp button <pre><code> <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@page import="com.studytrails.tutorials.springremotingrmiclient.TestSpringRemotingRmi" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body bgcolor="red"> <h1><font color=blue>login successfull</font></h1> <h2><font color="lightgreen"> <form action="${pageContext.request.contextPath}/MyServlet" method="post"> <input type=submit name="n1" value="Click here to play the video"> </form> </h2> </body> </html> Need to run the below program when clicking the button in jsp file. package com.studytrails.tutorials.springremotingrmiclient; import java.io.*; import java.io.File.*; import java.net.Socket; import java.net.UnknownHostException; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.core.io.Resource; import com.studytrails.tutorials.springremotingrmiserver.*; public class TestSpringRemotingRmi { public static void main(String[] args) throws IOException { ApplicationContext context = new ClassPathXmlApplicationContext("spring-config-client.xml"); GreetingService greetingService = (GreetingService)context.getBean("greetingService"); String greetingMessage = greetingService.getGreeting("Alpha"); System.out.println("The greeting message is : " + greetingMessage); greetingService.getText(); } } </code></pre> <p>In above program I am trying to run java <code>TestSpringRemotingRmi</code> class in the time of button click performed in jsp file. MyServlet file contains the code for process the request from jsp file. but I try to call the default constructor of that call using jsp but it does not work. guide me to solve this problem. </p> |
39,801,975 | 0 | <p>One data.table way of indexing a column by number would be to convert to a column name , convert to an R symbol, and evaluate:</p> <pre><code>mydata[ , eval( as.symbol( names(mydata)[1] ) )] [1] "ID123" "ID22" "AAA" > grep("^ID", mydata[,eval(as.symbol(names(mydata)[1]))]) [1] 1 2 </code></pre> <p>But this is not really an approved path to success because of the DT FAQ #1 as well as the fact that row numbers are not considered as valid targets. The philosophy (as I understand it) is that row numbers are accidental and you should be storing your records with unique identifiers.</p> |
33,453,542 | 0 | <p>If you are using AppCompatActivity then you can directly do the following in your main/parent activity.</p> <blockquote> <p><code>int FEATURE_ACTION_BAR_OVERLAY</code> : Flag for requesting an Action Bar that overlays window content.</p> </blockquote> <pre><code>@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); supportRequestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY); setContentView(yourview) } </code></pre> <p>And make sure you do not set any background for the action bar.<br> Using <code>supportRequestWindowFeature</code> is a convenience for calling <code>getWindow().requestFeature().</code></p> |
3,896,276 | 0 | <p>Mads, that did just the trick! Thank you so much, I knew there was a very simple solution that I just wasn't seeing. Here is the magical line that converts an XML string to JSON: </p> <pre><code>String ret = XML.toJSONObject(aStringOfXml).toString(); </code></pre> |
35,936,122 | 0 | Detect visibility of the fragment inside a navigation drawer <p>I have a fragment in the SDK that the wrapper application may display in the navigation drawer. I want to detect when this fragment will be visible to the user, for tracking purposes, from the Fragment itself. Is there any way to do it ?</p> |
39,870,690 | 0 | how can i get Get date text .Not able to get any text on the whole page.Attached Image <pre><code>List<WebElement> getAllTextOnPage = driver.findElements(By.id("com.condecosoftware.deskbooking:id/action_bar_root")); </code></pre> <p><a href="https://i.stack.imgur.com/yF9vE.png" rel="nofollow"><img src="https://i.stack.imgur.com/yF9vE.png" alt="enter image description here"></a></p> |
13,516,738 | 0 | <p>I had the same problem : primefaces (or richfaces) offers rowspan only for header and footer.</p> <p>Then I tried to use the icefaces <code>ace:datatable</code> component and it run by adding only one attribute in the colum(s) you want to be "rowspanable" : <code>ace:column</code> : <code>groupBy="#{bean.field}"</code>.</p> <p>You give as usual a list of rows and this component generates all rowspan automatically (I think by autodetecting neigbourhood of equals values) in the generated html table.</p> <p>It runs altogether with primefaces components : at this moment I have primefaces outputlabel in the icefaces datatable cells ant this icefaces datatable is inside a primefaces panel.</p> |
21,857,708 | 0 | <p>div ids==>opened,phone1 each has a flip ep</p> <pre><code><div class="w" id="opened">BEGIN<div class="ep"></div></div> <div class="w" id="phone1">PHONE INTERVIEW 1<div class="ep"></div></div> </code></pre> <p>eg:<a href="http://jsplumbtoolkit.com/demo/dynamicAnchors/jquery.html" rel="nofollow">http://jsplumbtoolkit.com/demo/dynamicAnchors/jquery.html</a> how to make <code>instance.connect({ source:tmp_source, target:tmp_target });</code> run in a for block.</p> <p>eg:</p> <pre><code>for(){ var tmp_source="opened"; var tmp_target="phone1"; instance.connect({ source:tmp_source, target:tmp_target });// this line not run } </code></pre> |
1,912,183 | 0 | <p>I recently joined this company and i see they are using UniObjects.Net dll for interacting with this Data base Check it out its from IBM not sure about the performance though</p> |
10,323,899 | 0 | Recording user action to an array with Jquery <p>I am trying to make a simple user click action recorder in jquery but am having some trouble. I want the user to click a record button then once clicked record what he clicks on. Then press stop button to stop recording. What I have so far is:</p> <pre><code>var stack = new Array(); var recordmode = false; $('#record').click(function(){ recordmode = true; alert('You are now in record mode'); }); $('#stop').click(function(){ recordmode = false; console.log(stack);//output what's in the array stack = []; //erase the array }); $('#note_markers').click(function(){ if(recordmode){ $('.one_0').click( function(){ stack.push('one_0'); }) $('.one_1').click( function(){ stack.push('one_1') ; }) } }); </code></pre> <p>and later the start and stop buttons.</p> <pre><code><a id='record'>R</a> <a id='stop'>stop</a> <div id="one_notes"> <a class="one_0"></a> <a class="one_1"></a> <a class="one_2"></a> <a class="one_3"></a> </div> </code></pre> <p>Also before stopping and erasing the array..I would like to build a URL in the form of /one_0/one_1/one_0 etc with what was in recorded in the array. (haven't got to that part yet though)</p> <p>What happens is the first click is not recorded and after that it starts putting in two of the same element. I can't figure out why I am getting the current behavior. </p> <p>Any ideas?</p> <p>As a side note is there a way to get the name of ANY clicked element?</p> |
17,490,647 | 0 | <p>Why not simple:</p> <pre><code>.a { color: red; } .b { color: blue; } .c { color: yellow; } </code></pre> <p>The difference between those two is that first one covers all six types:</p> <pre><code>.one .a, .one .b, .one .c, .two .a, .two .b, .two .c </code></pre> <p>While the second one only covers 4:</p> <pre><code>.one .a, .one .b, .two .a, .two .c </code></pre> <p>With respect to your markup - no difference at all, except that the very first case (without <code>.one</code> and <code>.two</code>) will be sliiiiiightly faster.</p> <p>Also, see <a href="http://www.css-101.org/descendant-selector/go_fetch_yourself.php">this</a>.</p> |
14,955,957 | 0 | Angular js - data integrated in app Controller without external json . how to render data <p>how can i tell angular to inject the data from scope.shits into ShitDetail Controller?</p> <pre><code>function ShitCtrl($scope) { $scope.shits = [ { "id": "goMedus", "name": "goMedus", "snippet": "Fast just got faster with Nexus S.", "copy": "hallo" }, </code></pre> <p>and here is the data injecton in the tutorial done via json. i would like to get oscar mike without because i have troubles in connecting to external json with grails urlMappings, so i would like to do this later on. any help appreciated</p> <pre><code>function ShitDetailCtrl($scope, $routeParams) { $scope.shitId = $routeParams.shitId; } </code></pre> <p>my view looks like so:</p> <pre><code>TBD: detail view for {{shitId}} and {{shitName}} </code></pre> <p>shitId gets rendered and shitName not.</p> |
30,963,247 | 0 | <p>You want to know the difference in these lines:</p> <pre><code>Base obj1 = new Derived(); Derived obj2 = new Derived(); </code></pre> <p>In both the cases the object constructed is of class <code>Derived</code>but references are different. You are able to use reference of type <code>Base</code> because <code>Derived</code> is also <code>Base</code> (assuming <code>Derived</code> extends <code>Base</code>) hence can be used. But which one should we prefer? The former one because it makes robust design.</p> <p>Consider the Collections Framework in Java which has a <code>List</code> interface and two implementations: <code>ArrayList</code> and <code>LinkedList</code>. We can write our program to use a <code>LinkedList</code> or an <code>ArrayList</code> specifically. But then our code depends on those specific implementations. So we should write our program to depend on the super type, <code>List</code>, instead then our program can work for either of the <code>List</code> implementations. </p> <p>In short this is one rule of OOP design: <code>Program to an interface</code>.</p> |
19,171,799 | 0 | <p>I have the same exact issue with Safari 6.1, getting <code>MEDIA_ERR_SRC_NOT_SUPPORTED</code> when trying to load a file from an input, like so:</p> <pre class="lang-js prettyprint-override"><code>var fileInput = document.querySelector('#file'), video = document.querySelector('video'); fileInput.addEventListener('change', function(evt){ evt.preventDefault(); var file = evt.target.files[0]; var url = window.URL.createObjectURL(file); video.src = url; video.addEventListener('error', function(err){ // This craps out in Safari 6 console.error(video.error, err); alert('nay :('); }); }); </code></pre> <p><strike>Try <code>video.addEventListener('error', logError)</code> or something to figure out if you have the same issue. I suspect Safari doesn't support yet videos with <code>blob</code>-type source.</strike></p> <p><strong>UPDATE</strong>: Yup, it's a bug. See <a href="https://bugs.webkit.org/show_bug.cgi?id=101671" rel="nofollow">https://bugs.webkit.org/show_bug.cgi?id=101671</a> and help us let the webkit maintainers this is something that needs to be fixed.</p> <p><strong>UPDATE, 2015</strong>: It works now, updated the code.</p> |
18,448,447 | 0 | <p>I've found a solution to my problem. Here again (in short) what I tried to accomplish.</p> <p>Task build an <code>NSMutableArray</code> which will act as the dataSource object for a <code>UITableView</code> each entry includes core data fetch and processing operations parallelise work and add results on completion, make sure access to the <code>NSMutableArray</code> is regulated start working with the dataSource object on completion</p> <p>Problems the number of entries in the dataSource object can vary</p> <p>Here's was worked for me. The category on 'NSMutableArray' is a convenience method to make sure the access is serialized. With that implementation you have parallelised the work as much as possible and you can savely write </p> <p>[self prepareDataSource]; [self.tableView reloadData];</p> <p>without worrying that some work is still in progress.</p> <pre class="lang-c prettyprint-override"><code>dispatch_queue_t queue = dispatch_queue_create("com.yourdomain.serializedAccess", DISPATCH_QUEUE_CONCURRENT); - (void)prepareDataSource { [self.dataSource removeAllObjects]; dispatch_group_t group = dispatch_group_create(); [self prepareWorkEntry1FromManagedObjectContext:self.privateContext forDataSource:self.dataSource group:group]; [self prepareWorkEntry2FromManagedObjectContext:self.privateContext forDataSource:self.dataSource group:group]; [self prepareWorkEntry3FromManagedObjectContext:self.privateContext forDataSource:self.dataSource group:group]; dispatch_group_wait(group, DISPATCH_TIME_FOREVER); } - (void)prepareWorkEntry1FromManagedObjectContext:(NSManagedObjectContext *)context forDataSource:(NSMutableArray *)array group:(dispatch_group_t)group { __weak typeof(self) weakSelf = self; dispatch_group_enter(group); [context performBlock:^{ Object *object = nil; createObject(object); if (object) { [array serializedAddObject:object withQueue:weakSelf.queue group:group]; } else { dispatch_group_leave(group); } }]; } @implementation NSMutableArray (ResourceProtection) - (void)serializedAddObject:(id)object withQueue:(dispatch_queue_t)queue group:(dispatch_group_t)group { if (group == NULL) { dispatch_barrier_async(queue, ^{ [self addObject:object]; }); } else { dispatch_barrier_async(queue, ^{ [self addObject:object]; dispatch_group_leave(group); }); } } @end </code></pre> <p>EDIT: As far as the ResourceProtection category is concerned you have to make sure</p> <ol> <li>dispatch_group_enter is called before dispatch_group_leave</li> <li>dispatch_group_enter and dispatch_group_leave are balanced</li> </ol> <p>Here it is an observed, synchronized writer scheme for a mutable object.</p> |
5,279,815 | 0 | Eclipse CDT Headless Build Question <p>Using Eclipse CDT 7.0, is there a way to specifiy to build just a single build configuration on the commandline when doing a headless build?</p> |
7,777,145 | 0 | <p>LDAP-compliant directory servers should provide information about the <code>namingContexts</code> when the root DSE is queried. For more information about the root DSE, see "<a href="http://www.evernote.com/shard/s5/sh/e6bdc1cd-068d-4d63-93f1-a3275f7a703b/b5968790355e854a35ba36dc775144b9" rel="nofollow">LDAP: The root DSE</a>". The <a href="http://www.unboundid.com/products/ldap-sdk/" rel="nofollow">UnboundID LDAP SDK</a> provides a class to encapsulate the root DSE and a convenience method to retrieve it.</p> |
33,192,074 | 0 | Programming principles and practice (2nd) by Bjarne stroustrup - Chapter 3.3 , code isn't working <p>So i just started reading this book and copy pasted from the pdf file this code :</p> <pre><code>// read name and age (2nd version) int main() { cout << "Please enter your first name and age\n"; string first_name = "???"; // string variable // ("???” means “don’t know the name”) int age = –1; // integer variable (–1 means “don’t know the age”) cin >> first_name >> age; // read a string followed by an integer cout << "Hello, " << first_name << " (age " << age << ")\n"; } </code></pre> <p>The book says it should output</p> <pre><code>Hello, 22 (age –1) </code></pre> <p>if i input</p> <pre><code>22 Carlos </code></pre> <p>but i get this error</p> <pre><code>D:\C++\Part I The Basics\Programs\3.Read name and age (2nd).cpp|9|error: stray '\226' in program| </code></pre> <p>And the program isn't compiling.</p> <p>I realized that in the line below the "minus 1" isn't actually a "minus" "-" sign. .. " – " " - " It is bigger than the minus, see?</p> <pre><code>int age = –1 </code></pre> <p>So i changed that sign with a minus sign and typed 22 Carlos and it outputs Hello 22, 0 instead of Hello 22, -1.</p> <p>My questions are: </p> <p>Why is the program not working when i simply copy paste it from the pdf?</p> <p>Why it's not working even after i change the – sign with a minus "-" sign?</p> |
9,786,118 | 0 | <p>The Reachability APIs will provide the connection change notifications to your app so that you can know when the connectivity changed from WWAN to wifi. It will not tell you if you've changed from Edge to 3G or LTE unfortunately. The Reachability API also has methods to test reachability to a specific host. So, in your app you can listen for the notifications that the connection method has changed, then when it does change test reachability to your target host and at that time make the decision whether to rebuild the session or leave it intact.</p> |
17,680,150 | 0 | <p>You can use Object instant of StudentUnion. Object will accept all classes. </p> <pre><code>public class CommonComparator implements Comparator<Object> { public int compare(Object s1, Object s2){ .... return result // 1 or 0; } } </code></pre> |
12,521,983 | 0 | JS Validation if dropdown value selected or not <p>I am trying to write a validation block inside my JS to check if the user has selected a value or not and pop up a message if the value is not selected. </p> <pre><code>function validate(form) { var success = true; var message = ""; if (form.dropdown.selectedIndex == 0 ) { form.save.disabled=true; if (0 < message.length) { message += "\n"; } message += "dropdown value should be selected."; } if (0 < message.length) { alert(message); success = false; } return success; } </code></pre> <p>When I click on Save button I call this function. I don't see errors in the logs. Can anyone tell me what am I doing wrongly here? Or can you guide me what is the correct method to validate if the user has selected a value before allowing to save?</p> <p>Thanks!</p> |
2,999,048 | 0 | <p>I would use php personally. Then you can save which page layout you chose for them as a session var making it easy to load that layout on each page refresh. You would probably also want to save into the database with their username (if they login) and if they visit later show them the same layout.</p> |
20,440,321 | 0 | <p>First look at the exception<br> <em>java.lang.OutOfMemoryError: bitmap size exceeds VM budget</em><br> and most probably this is the line in your code <br> <em>at com.PACKAGE.MainActivity$MyListAdapter.getView(MainActivity.java:132)</em> (notice your package)</p> <p>You tried to load an image larger than your heap supported. The size in MB of the compressed file is of little importance, as any image will be expanded in memory as a bitmap. Thus only the pixel format and pixel count matters. In your case 2200x2048 might me to much.</p> <p>As possible solutions for the memory problem<br/></p> <ul> <li><strong>Use a lower resolution image, or manually load the image using BitmapFactory where you have the option to downsample</strong><br/></li> <li><strong>Use <em>android:largeHeap="true"</em> in manifest might help.</strong> Not good practice, if can be avoided.</li> </ul> <p>The ANR comes because you do a lot of work (loading large image) on the UI thread. Lower resolution image might help also to this problem, but you should consider loading the images in a worker thread<br> <a href="http://developer.android.com/guide/components/processes-and-threads.html" rel="nofollow">http://developer.android.com/guide/components/processes-and-threads.html</a>, <strong>Worker threads</strong></p> |
15,530,180 | 0 | <p>Ajax code to call the add_driver.php </p> <pre><code>if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { //here you can put some code to execute if the call to add_driver.php was ok } } xmlhttp.open("GET","add_driver.php",true); xmlhttp.send(); } </code></pre> |
26,048,323 | 0 | Code not executed in TFrame.Create <p>I have created a component with TFrame as ancestor with the following code:</p> <pre><code>type TCHAdvFrame = class(TFrame) private { Private declarations } FOnShow : TNotifyEvent; FOnCreate : TNotifyEvent; protected procedure CMShowingChanged(var M: TMessage); message CM_SHOWINGCHANGED; public { Public declarations } constructor Create(AOwner: TComponent) ; override; published property OnShow : TNotifyEvent read FOnShow write FOnShow; property OnCreate : TNotifyEvent read FOnCreate write FOnCreate; end; implementation {$R *.dfm} { TCHAdvFrame } procedure TCHAdvFrame.CMShowingChanged(var M: TMessage); begin inherited; if Assigned(OnShow) then begin ShowMessage('onShow'); OnShow(self); end; end; constructor TCHAdvFrame.Create(AOwner: TComponent); begin ShowMessage('OnCreate1'); inherited ; ShowMessage('OnCreate2'); if Assigned(OnCreate) then begin ShowMessage('OnCreate3'); OnCreate(self); end; </code></pre> <p>I have registered the new component and did some tests. ShowMessage('OnCreate1'); and ShowMessage('OnCreate2'); are correctly executed <strong>but not ShowMessage('OnCreate3');</strong></p> <p>This prevents to add code during the implementation of a new instance of TCHAdvFrame.</p> <p>Why is it and how can I solve this ? </p> |
32,504,044 | 0 | <p>You can use for loop like this, </p> <pre><code>for(i=1;i<=num;i++){ txtView.append(word+"\n"); } </code></pre> |
1,998,303 | 0 | <pre><code>$randomPool = array_rand ( $butters->users->user, 10 ); </code></pre> |
23,489,606 | 0 | <p>If you want <code>Monster1</code> image to come from the array <code>kanaCharacters</code> with the index number from <code>imageDisplay</code> wouldn't you do this?</p> <pre><code>NSArray *array = [NSArray arrayWithObjects:@"a",@"b",@"c", nil]; //Setup array int imageDisplay = arc4random_uniform([array count]); //Find random int from array count UIImageView *monster1 = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 100, 50)]; //Setup UIImageView monster1.image = [UIImage imageNamed:array[imageDisplay]]; //Display image which is randomly selected from array [self.view addSubview:monster1]; //Add image to view </code></pre> |
17,751,107 | 0 | Gradle compile dependency ordering in InteliJ <p>I have a gradle project with subprojects, and Servlet API 2.5. I've added Servlet 3.0 and compile fine from command line gradle. However, InteliJ loads Servlet 2.5 classes first, so I am unable to compile. </p> <p>How can I manage dependency ordering within InteliJ?</p> |
22,127,764 | 0 | <p>in you initializers try doing something like this </p> <pre><code>#config/initializers/devise.rb #provider1 config.omniauth :facebook, ENV['FACEBOOK_APP_ID'], ENV['FACEBOOK_SECRET'], :site => 'https://graph.facebook.com/', :authorize_path => '/oauth/authorize', :access_token_path => '/oauth/access_token', :scope => 'email, user_birthday, read_stream, read_friendlists, read_insights, read_mailbox, read_requests, xmpp_login, user_online_presence, friends_online_presence, ads_management, create_event, manage_friendlists, manage_notifications, publish_actions, publish_stream, rsvp_event, user_about_me, user_activities, user_birthday, user_checkins, user_education_history, user_events, user_groups, user_hometown, user_interests, user_likes, user_location, user_notes, user_photos, user_questions, user_relationships, user_relationship_details, user_religion_politics, user_status, user_subscriptions, user_videos, user_website, user_work_history' #provider2 config.omniauth :twitter, ENV['TWITTER_KEY'], ENV['TWITTER_SECRET'], :scope => { :secure_image_url => 'true', :image_size => 'original', :authorize_params => { :force_login => 'true' } } #provider3 config.omniauth :google_oauth2, ENV["GOOGLE_KEY"], ENV["GOOGLE_SECRET"] </code></pre> |
7,668,931 | 0 | <p>Yop you should be looking into push notification (it's a lot more complicated than the periodic agent...)</p> <p>But periodic agent are set to 30 mins (and 25sec of code execution I think) and there is NOTHING you can do about it. Also note that the user can decide to deactivate your periodic agent in the options.</p> <p>But pushing notifications every 5 minutes on a phone might not be good idea anyway... It's gonna drain the battery quickly!</p> <p>What are you trying to accomplish?</p> |
39,526,282 | 0 | <p><code>[B@5f18cd5</code> is not a byte, it's a string representation of a reference. You can't turn them back into anything. </p> <pre><code>public class Ref { public static void main(final String[] args) { System.out.println(new Ref()); } } //Outputs: Ref@19e0bfd </code></pre> <p><code>foo@address</code> is a reference. You're not actually writing values into the file but references as String. <code>B[</code> means that you're writing <code>byte[]</code> into a file but not the actual bytes <em>in</em> that array. </p> <p><strong>Update</strong></p> <p>You're probably looking for something like this:</p> <pre><code>public static void main(final String[] args) throws FileNotFoundException, IOException { final File f = new File("/tmp/output"); final ObjectOutputStream oos = new ObjectOutputStream( new FileOutputStream(f)); for (int i = 0; i < 8; i++) { final double d = Math.sin(i); System.out.println(d); oos.writeDouble(d); } oos.flush(); oos.close(); System.out.println("---"); final ObjectInputStream ois = new ObjectInputStream( new FileInputStream(f)); for (int i = 0; i < 8; i++) System.out.println(ois.readDouble()); ois.close(); } </code></pre> |
39,831,694 | 0 | <p>If you follow through the <a href="https://referencesource.microsoft.com/#System.Xml/System/Xml/Serialization/XmlSerializer.cs,292c7197dcb706a1" rel="nofollow">reference source</a> you end up <a href="https://referencesource.microsoft.com/#System.Xml/System/Xml/Serialization/Compilation.cs,661" rel="nofollow">here</a>.</p> <p>It would seem it's the directory that <code>XmlSerializer</code> will put the serializer assembly it generates. </p> <p>If not specified (which is the case with all other overloads), it uses the <a href="https://msdn.microsoft.com/en-us/library/system.xml.serialization.configuration.xmlserializersection.tempfileslocation(v=vs.110).aspx" rel="nofollow"><code>TempFilesLocation</code></a> which can be configured <a href="http://stackoverflow.com/questions/3302752/changing-where-xmlserializer-outputs-temporary-assemblies">per this related question</a>.</p> |
5,444,897 | 0 | <p>Sounds like your friend can set up a reverse proxy rule on their web server for your file. <a href="http://httpd.apache.org/docs/2.0/mod/mod_proxy.html" rel="nofollow">http://httpd.apache.org/docs/2.0/mod/mod_proxy.html</a></p> |
7,491,065 | 0 | Grails Criteria not working in Integration Test <p>We have a simple method that gets all of a specific domain object where a property equals a hard coded string. This method is within MyDomainService.</p> <pre><code>def List<MyDomain> getAllDomain() { List resultList def criteria = MyDomain.createCriteria() resultList = criteria.list() { eq('property1', 'READY') } return resultList } </code></pre> <p>We also are writing a simple integration test for this method. The test is as follows.</p> <pre><code>void testGetAllDomain() { List original = MyDomain.list() original.each{ it.property1 = 'NOTREADY' it.save(flush:true) } def result = MyDomainService.getAllDomain() assertEquals 0, result.size() //All objects should be set to NOTREADY, and not retrieved. THIS is failing. } </code></pre> <p>I have tried setting </p> <pre><code>def transactional = false </code></pre> <p>and leaving my code as is. I tried setting transactional to false and wrapping the code in .withTransaction{}. I also tried the standard config and that didn't work. What I have noticed is that if I do</p> <pre><code>def List<MyDomain> getAllDomain() { List original = MyDomain.list() original.each{ it.property1 = 'NOTREADY' it.save(flush:true) } List resultList def criteria = MyDomain.createCriteria() resultList = criteria.list() { eq('property1', 'READY') } return resultList } </code></pre> <p>then the results come back as expected. This makes me believe it has something to do with the transaction within the integration test. Any ideas?</p> |
1,821,978 | 0 | <p>No, as explained in answers to the linked question, you can't do that. Modify the interface to pass in a factory object. (NB: <code>Class</code> makes a bad factory.)</p> |
16,889,391 | 0 | <p>Here's how (in C#):</p> <p>First, you create your name value collection using the inputs you need like:</p> <pre><code>var nvc = new NameValueCollection { {"q", input}, {"source", "en"}, {"target", "en"}, {"key","Your translate API key here"} }; </code></pre> <p>Then you can call a function like this one:</p> <pre><code>internal string Post(string url, ref CookieContainer cookieJar, NameValueCollection nvc, string referer = null) { var postdata = string.Join("&", Array.ConvertAll(nvc.AllKeys, key => string.Format("{0}={1}", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(nvc[key])))); var request = (HttpWebRequest)WebRequest.Create(url); request.CookieContainer = cookieJar; request.UserAgent = "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:21.0) Gecko/20100101 Firefox/21.0"; request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; request.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7"); request.Headers.Add("Accept-Encoding", "gzip, deflate"); request.Headers.Add("Accept-Language", "en-us"); request.Method = "POST"; request.KeepAlive = true; request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = postdata.Length; if (!string.IsNullOrEmpty(referer)) request.Referer = referer; var writer = new StreamWriter(request.GetRequestStream()); writer.Write(postdata); writer.Close(); var response = (HttpWebResponse)request.GetResponse(); var resp = (new StreamReader(response.GetResponseStream())).ReadToEnd(); return resp; } </code></pre> <p>Here's the call:</p> <pre><code>var result=Post("https://www.googleapis.com/language/translate/v2/detect",ref new CookieContainer(),nvc); </code></pre> <p>for small values of input, you can use GET instead of POST, just append postdata onto the url after a <code>?</code>.</p> <p>For google translate API, the response is in JSON format, there are many posts on how to parse JSON responses, so I won't go into that here, but these should help you get started: <a href="http://stackoverflow.com/questions/7699972/how-to-decode-a-json-string-using-c?lq=1">How to decode a JSON string using C#?</a> <a href="http://stackoverflow.com/questions/7721261/convert-json-file-to-c-sharp-object?lq=1">Convert JSON File to C# Object</a></p> |
21,287,588 | 0 | Sorting Array of Arrays having variable number of elements <p>I have to sort an array of arrays. I've searched for solutions however my problem is: </p> <ol> <li>need to sort arrays that may have different sizes from a script run to another. </li> <li>need to sort not only by one or two elements, but, if possible based in all elements.</li> </ol> <p>For example, for the following inputs:</p> <pre><code>[[2,3,4,5,6],[1,3,4,5,7],[1,3,4,5,8]] [[5,2,3],[2,2,4],[2,2,5]] </code></pre> <p>The output should be, respectively:</p> <pre><code>[[1,3,4,5,7],[1,3,4,5,8],[2,3,4,5,6]] [[2,2,4],[2,2,5],[5,2,3]] </code></pre> |
35,970,550 | 0 | <p>Try the regex bellow <code> (^|\s)([#][a-zA-Z\d-]+) </code></p> <p>Working regex example:</p> <p><a href="https://regex101.com/r/kJ2qR3/2" rel="nofollow">https://regex101.com/r/kJ2qR3/2</a></p> |
20,664,291 | 0 | Fetching Custom Variable Values using Piwik API <p>I am trying to use this api CustomVariables.getCustomVariablesValuesFromNameId (idSite, period, date, idSubtable, segment = '') from piwik to fetch CustomVariable values. But there is no example for it and also how to get idsubtable value ?</p> <p>Is there any way to fetch custom variable values from piwik using api ?</p> <p>Any help or example would be appreciated.</p> |
36,248,990 | 0 | <p>You can do the following:</p> <pre><code>$(selector).on('click', function(e){ e.preventDefault(); $(this).parent().addClass('active').siblings('.active,.current') .removeClass('active current'); }); </code></pre> <p>First you go to the upper level (<code>LI</code>) and add <code>active</code> class to it. Then, selecting its siblings with classes <code>active</code> and <code>current</code>, and remove those classes from the matched elements.</p> <p>Note that I also added <code>e.preventDefault()</code> to prevent and redirect action when you click on the <code>A</code> element.</p> |
35,399,002 | 0 | <p>The way you handle the cookies appears to be correct. In terms of the shopping cart you can simply JSON.stringify it.</p> <p>To save the cart:</p> <pre><code>$cookies.put("shoppingCart", JSON.stringify($scope.shopping_cart)); </code></pre> <p>To retrieve the cart:</p> <pre><code>var cartCookie = $cookies.get("shoppingCart"); if (cartCookie) { cartCookie = JSON.parse(cartCookie); } </code></pre> |
3,923,213 | 0 | <p>For the first two steps regular OLE automation using the <code>Outlook2000.pas</code> unit that comes bundled with Delphi should work fine though you might want to take a look at Dmitry Streblechenko's Redemption library: <a href="http://dimastr.com/redemption/">http://dimastr.com/redemption/</a> which simplifies many of the more low-level (Extended-)MAPI tasks significantly.</p> <p>For intercepting the sent message you should create an instance of <code>TItems</code> and connect it to the folder reference you could get from <code>OutlookApplication.Session.GetDefaultFolder(olFolderSentMail)</code>. You can then assign an event handler to its <code>OnItemAdd</code> event.</p> <p>For drag & drop from Outlook into your application you can take a look at Anders Melanders excellent (and free) Drag&Drop library (includes examples for interacting with Outlook): <a href="http://melander.dk/delphi/dragdrop/">http://melander.dk/delphi/dragdrop/</a></p> |
32,556,353 | 0 | <p>You could just use the <code>/assets</code> folder instead of <code>/res</code> and load <code>drawable</code>s for your avatars directly.</p> <p><code>String avatarName = firstSpinner + '_' + secondSpinner + '.png'; Drawable d = Drawable.createFromStream(getAssets().open("avatars/" + avatarName), null);</code></p> |
6,879,141 | 0 | <p>You would use the "Content-Disposition" header to provide a recommended filename and force the web browser to show the save dialog.</p> <p>For example:</p> <pre><code><?php header('Content-type: text/xml'); header('Content-Disposition: attachment; filename="downloaded.xml"'); // ...your other code ?> </code></pre> <p>This isn't guaranteed to work on all server setups and all browsers so you will find further information on the PHP header function page: <a href="http://php.net/manual/en/function.header.php" rel="nofollow">http://php.net/manual/en/function.header.php</a></p> |
34,149,871 | 0 | <p>Your problem is basically in this bit:</p> <pre><code>G.add_edge((s,r), hrc_dict[(s,r)]) </code></pre> <p>networkx interprets this as "add an edge between the first argument <code>(s,r)</code> and the second argument <code>hrc_dict[(s,r)]</code>." So for example <code>('Hillary Clinton', 'Cheryl Mills'): 354</code> becomes an edge between the node <code>('Hillary Clinton', 'Cheryl Mills')</code> and the node <code>354</code>. Instead try</p> <pre><code>G.add_edge(s, r, count = hrc_dict[(s,r)]) </code></pre> |
29,159,995 | 0 | Creating nested fluent API in Java <p>We are trying to come up with fluent API for nested Object. Consider we have following three classes</p> <p>Attribute : name : String Value : Object</p> <p>Item : action : String attributes : </p> <p>Order : action : String attributes : items : </p> <p>Here we want to have fluent API which can help to build above Objects.</p> <p>Now we need to have builders as follows:</p> <h3>Attribute Builder</h3> <pre><code>AttributeBuilder.make().name().value().build(); </code></pre> <h3>Item Builder</h3> <pre><code>ItemBuilder.make().action() .attribute() .name().value().build() .attribute() .name().value().build() .build(); </code></pre> <h3>Order Builder</h3> <pre><code>OrderBuilder.make().action() .attribute() .name().value().build() .attribute() .name().value().build() .item() .action() .attribute() .name().value().build() .attribute() .name().value().build() .build() .build(); </code></pre> <p>We may later nest the Order Object in Some other object.</p> <p>So is there any way to achieve such nested DSL building ?</p> |
14,390,146 | 0 | <p>You can ask your <code>NSManagedObjectModel</code> by sending <code>versionIdentifiers</code> to the receiver.</p> <pre><code>- (NSSet *)versionIdentifiers </code></pre> <p>The docu is <a href="https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/CoreDataFramework/Classes/NSManagedObjectModel_Class/Reference/Reference.html#//apple_ref/doc/uid/TP40003610" rel="nofollow">here</a></p> |
10,604,139 | 0 | <p>I don't have access to Oracle, but I believe something along these lines should work...</p> <pre><code>WITH ranked_data AS ( SELECT COUNT(DISTINCT product_type) OVER (PARTITION BY brand_id) AS brand_rank, MIN(product_type) OVER (PARTITION BY brand_id) AS first_product_type, * FROM yourTable ) SELECT * FROM ranked_data ORDER BY brand_rank, first_product_type, brand_id, product_type, product_description </code></pre> <p><br/></p> <p>An alternative is to JOIN on to a sub-query to calculate the two sorting fields.</p> <pre><code>SELECT yourTable.* FROM yourTable INNER JOIN ( SELECT brand_id, COUNT(DISTINCT product_type) AS brand_rank, MIN(product_type) AS first_product_type, FROM yourTable GROUP BY brand_id ) AS brand_summary ON yourTable.brand_id = brand_summary.brand_id ORDER BY brand_summary.brand_rank, brand_summary.first_product_type, yourTable.brand_id, yourTable.product_type, yourTable.product_description </code></pre> |
34,136,291 | 0 | <p>This error was caused by an error with the user permissions for sysadmin.</p> <p>Adding “NT AUTHORITY\NETWORK SERVICE” as sysadmin in the SQL server instance resolved the issues.</p> |
40,078,892 | 0 | I am showing aspx page(Add Item form) inside jquery modal, whenever I upload an image the page refreshes and loads as a normal webpage <p>I have 2 files :- </p> <ol> <li>Items.aspx with the list of items in a grid view, A button(to open a form for adding new item), and a div with id testing.</li> </ol> <p>code Inside Items.aspx</p> <pre><code> <%@ Page Title="" Language="C#" MasterPageFile="~/Basic.Master" AutoEventWireup="true" CodeBehind="Items.aspx.cs" Inherits="FlowerShopAdminPanel.Items" %> <asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server"> </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="header" runat="server"> <div id="dvGrid" class="container"> <!-- This contains the gridview --> </div> <div id="testing"></div> <script> function openDialog($itemid,$categoryid) { $('#testing').dialog({ modal: true, dialogClass: "no-close", open: function () { $(this).load('AddItem.aspx?itemid=' + $itemid+'&categoryid='+$categoryid); $(".ui-dialog-titlebar-close", ui.dialog | ui).hide(); }, height: 500, width: 500, title: 'Add Item' }); } </script> <style> .image { height: 30vh; } .no-close .ui-dialog-titlebar-close { display: none; } </style> </asp:Content> </code></pre> <p>This loads a form to add item in a jquery modal. we can upload image to that item using a Button . Above function is on another aspx form in which I am </p> <ol start="2"> <li><p>AddItem.aspx</p> <p></p> <p> </p> <pre><code> <div> <asp:Label runat="server" Text="Category Name"></asp:Label> <asp:DropDownList runat="server" ID="category_ddl"></asp:DropDownList> </div> <div> <asp:Label runat="server" Text="Item Name"> </asp:Label> <asp:TextBox runat="server" ID="itemname_txt"></asp:TextBox> </div> <div> <asp:Label runat="server" Text="Description"></asp:Label> <asp:TextBox runat="server" TextMode="MultiLine" Rows="5" Columns="50" ID="description_txt"></asp:TextBox> </div> <div> <asp:Label runat="server" Text="Main Image"></asp:Label> <asp:FileUpload runat="server" ID="mainimage_fileupload"/><br /> <asp:Image runat="server" ID="mainimage_img" Visible="false" /> <asp:Button runat="server" ID="fileupload_btn" Text="Upload" OnClick="fileupload_btn_Click" /> <asp:Label runat="server" ID="filename_lbl" Visible="false" ForeColor="Red" Font-Bold="true"></asp:Label> </div> <div> <asp:Label runat="server" Text="Active"> </asp:Label> <asp:CheckBox runat="server" ID="isActive_chk"/> </div> <div> <asp:Button runat="server" ID="addItem_btn" Text="Add Item" OnClick="addItem_btn_Click"/> <asp:Button runat="server" ID="cancel_btn" Text="Cancel" OnClick="cancel_btn_Click"/> </div> </div> </form> </code></pre> <p> </p></li> </ol> <p>Whenever I upload the image it opens up as a normal aspx page. Basically, Whenever the aspx page is refreshed, it opens up as a normal web page. I always want to open it in the jQuery modal.</p> <p>Please help in resolving this issue. </p> <p>Thank you</p> |
40,183,870 | 0 | <p>Maybe someone will find this useful: somehow I had named the directory <code>'templatetags '</code> instead of <code>'templatetags'</code>, that is -- with a space at the end. Took hours to finally realize.</p> |
36,777,974 | 0 | android - viewpager OutOfMemoryError <p>I have a problem. I want to get image URL from JSON and setting to viewpager. I tried it with <code>drawable</code> folder, but large images are causing problems. If the image would be small, then I would not have a problem. How can I get large images? I benefited from this article : <a href="http://manishkpr.webheavens.com/android-viewpager-as-image-slide-gallery-swipe-gallery/" rel="nofollow">enter link description here</a></p> <p>GalleryActivity</p> <pre><code>@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_gallery); ViewPager viewPager = (ViewPager)findViewById(R.id.viewpa); GalleryAdapter ga = new GalleryAdapter(this); viewPager.setAdapter(ga); } </code></pre> <p>Gallery Adapter (extending PagerAdapter)</p> <pre><code>Context context; private int[] GalImages = new int[] { R.drawable.one, R.drawable.two, R.drawable.three }; GalleryAdapter(Context context){ this.context=context; } @Override public int getCount() { return GalImages.length; } @Override public boolean isViewFromObject(View view, Object object) { return view == ((ImageView) object); } @Override public Object instantiateItem(ViewGroup container, int position) { ImageView imageView = new ImageView(context); int padding = context.getResources().getDimensionPixelSize(R.dimen.padding_medium); imageView.setPadding(padding, padding, padding, padding); imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE); imageView.setImageResource(GalImages[position]);// error on this line when large image ((ViewPager) container).addView(imageView, 0); return imageView; } @Override public void destroyItem(ViewGroup container, int position, Object object) { ((ViewPager) container).removeView((ImageView) object); } </code></pre> <p>And logcat outputs</p> <pre><code>java.lang.OutOfMemoryError at android.graphics.BitmapFactory ... </code></pre> |
33,640,631 | 0 | <p><em>(From the above comments:)</em> There are several problems here:</p> <ul> <li><p>You pass the address of the local variable <code>var selfPtr</code> to the callback. That address becomes invalid as soon as the <code>hookUpSocket()</code> function returns. See <a href="http://stackoverflow.com/questions/30786883/swift-2-unsafemutablepointervoid-to-object">Swift 2 - UnsafeMutablePointer<Void> to object</a> for a way to pass a pointer to <code>self</code> to the callback, more information here: <a href="http://stackoverflow.com/questions/33294620/how-to-cast-self-to-unsafemutablepointervoid-type-in-swift">How to cast self to UnsafeMutablePointer<Void> type in swift</a>.</p></li> <li><p><code>inputStream</code> and <code>outputStream</code> must be registered with a run loop.</p></li> <li><p><code>inputStream</code> and <code>outputStream</code> are local variables of the callback function so they are deallocated when the function returns. They should be properties of your class instead.</p></li> </ul> |
34,857,027 | 0 | How to Fit Image in CircleImage plugin of Xamarin.Forms <p>I am using following code.</p> <pre><code> <StackLayout BackgroundColor="#303D43" HeightRequest="170" Padding="10" HorizontalOptions="Fill" VerticalOptions="Start"> <StackLayout HeightRequest="120" WidthRequest="120" Padding="0,0,0,10" HorizontalOptions="Fill" VerticalOptions="Fill" > <controls:CircleImage x:Name="profileImage" BorderColor="White" BorderThickness="1" HorizontalOptions="Center" Aspect="AspectFill" WidthRequest="96" HeightRequest="96" > </controls:CircleImage> </StackLayout> <Label x:Name="lblTitle" FontSize="22" TextColor="White" HeightRequest="20" HorizontalOptions="Center" /> </StackLayout> </code></pre> <p><a href="https://i.stack.imgur.com/PomJz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PomJz.png" alt="enter image description here"></a> </p> <p>As you can see in case of portrait image , space left at left and right while in case of horizontal image space left at top and bottom. How to fix this. I have tried Aspect="AspectFill" AspectFit and Fill all three enums but no success..</p> <p>using this Plugin</p> <p><a href="https://github.com/jamesmontemagno/Xamarin.Plugins/tree/master/ImageCircle" rel="nofollow noreferrer">https://github.com/jamesmontemagno/Xamarin.Plugins/tree/master/ImageCircle</a></p> |
7,696,452 | 0 | <p>You should print the error (using <a href="http://msdn.microsoft.com/en-us/library/ms679360.aspx" rel="nofollow"><code>GetLastError</code></a>). I suspect you are not initializing things:</p> <pre><code>WSADATA wsaData = {0}; WSAStartup(MAKEWORD(2, 2), &wsaData); </code></pre> |
20,128,267 | 0 | C++ binary files and iterators: getting away with a 1:1 using ifstreambuf_iterator? <p><a href="http://stackoverflow.com/a/13665583/2485710">This answer</a> points out the fact that C++ is not well suited for the iteration over a binary file, but this is what I need right now, in short I need to operate on files in a "binary" way, yes all files are binary even the .txt ones, but I'm writing something that operates on image files, so I need to read files that are well structured, were the data is arranged in a specific way.</p> <p>I would like to read the entire file in a data structure such as <code>std::vector<T></code> so I can almost immediately close the file and work with the content in memory without caring about disk I/O anymore.</p> <p>Right now, the best way to perform a complete iteration over a file according to the standard library is something along the lines of</p> <pre><code>std::ifstream ifs(filename, std::ios::binary); for (std::istreambuf_iterator<char, std::char_traits<char> > it(ifs.rdbuf()); it != std::istreambuf_iterator<char, std::char_traits<char> >(); it++) { // do something with *it; } ifs.close(); </code></pre> <p>or use <code>std::copy</code>, but even with <code>std::copy</code> you are always using <code>istreambuf</code> iterators ( so if I understand the C++ documentation correctly, you are basically reading 1 byte at each call with the previous code ).</p> <p>So the question is: how do I write a custom iterator ? from where I should inherit from ?</p> <p>I assume that this is also important while writing a file to disk, and I assume that I could use the same iterator class for writing, if I'm wrong please feel free to correct me.</p> |
6,045,094 | 0 | Deleting From DGV -- Index [x] does not have a value <p><strong>The Setup:</strong> I have a two DataGridViews, each bound to a BindingList<> of custom business objects. These grids have a special row containing the mathematical totals of all rows in that grid -- this special row is reflective of a corresponding special object in the BindingList<> (I specify that so that you are aware that this is not a row being added to the DGV, but an object being added to the BindingList<>). </p> <p><strong>The Error:</strong> There comes a time, periodically, where I must find and remove the Totals Row object from the BindingList<> (and thus from the DGV). Here is the original code I was using to do this:</p> <pre><code>private void RemoveTotalRow() { for (int i = UnderlyingGridList.Count - 1; i >= 0; i--) { if (UnderlyingGridList[i].IsTotalRow) UnderlyingGridList.RemoveAt(i); } } </code></pre> <p>(It's not super-important, but the reason I'm cycling through all records is to protect against the possibility that there could be more than one Totals row, by mistake). This code <strong>works flawlessly</strong> for one of the two grids under all circumstances. However, on the second grid I get the following error when the RemoveAt method is called:</p> <pre><code>The following exception occurred in the DataGridView: System.IndexOutOfRangeException: Index 5 does not have a value. at System.Windows.Forms.CurrencyManager.get_Item(Int32 index) at System.Windows.Forms.DataGridView.DataGridViewDataConnection.GetError(Int32 rowIndex) To replace this default dialog please handle the DataError event. </code></pre> <p>...where '5' is the index of the totals row. <a href="http://stackoverflow.com/questions/890950/datagridview-on-winforms-throws-exception-when-i-delete-a-record">I found this question</a>, which is essentially the same, except that the accepted answer is to either: 1) Not use an underlying list, which I must do, or 2) Delete from the grid instead of from the list. I have tried #2 by replacing the innermost method call from my code example above with this:</p> <pre><code>if (UnderlyingGridList[i].IsTotalRow) brokenDataGrid.Rows.RemoveAt(i); </code></pre> <p>This throws the same error. <a href="http://stackoverflow.com/questions/1630200/net-datagridview-index-0-does-not-have-a-value">I also found this question</a>, which suggests rebinding after the change - however, this is not feasible as it is possible for this code to be called once per second and if the list is too heavily populated it will make the grid unusable (I know this from bad experiences).</p> <p>I could just handle the grid's DataError event, but I'd rather not have the thing popping a million errors per minute, even if they are silent. Any help would be greatly appreciated.</p> |
35,833,349 | 0 | <p>You can't use the <code>CBCharacteristicProperties.Broadcast</code> property with characteristics you create yourself. From the <a href="https://developer.apple.com/library/prerelease/ios/documentation/CoreBluetooth/Reference/CBCharacteristic_Class/index.html#//apple_ref/c/tdef/CBCharacteristicProperties" rel="nofollow">documentation</a>:</p> <blockquote> <ul> <li><p><strong>CBCharacteristicPropertyBroadcast</strong> The characteristic’s value can be broadcast using a characteristic configuration descriptor.</p> <p>This property is not allowed for local characteristics published via the <code>addService:</code> method of the <code>CBPeripheralManager</code> class. This means that you cannot use this property when you initialize a new <code>CBMutableCharacteristic</code> object via the <code>initWithType:properties:value:permissions:</code> method of the <code>CBMutableCharacteristic</code> class.</p></li> </ul> </blockquote> |
24,908,293 | 0 | <pre><code>user=bob lastb $user -t $(date -d "$(last $user | head -n 1 | tr -s '[:space:]' '\t' | cut -f 4-7)" +%Y%m%d%H%M%S) </code></pre> <p>More readably</p> <pre><code> user=bob last_login=$(last $user | head -n 1 | tr -s '[:space:]' '\t' | cut -f 4-7) datetime=$(date -d "$last_login" +%Y%m%d%H%M%S) lastb $user -t $datetime </code></pre> <p>Note that my <code>last</code> output looks a little different from yours, with an extra field: adjust your <code>cut</code> columns accordingly</p> <pre><code>$ last glennj -n 1 glennj pts/7 :0 Sun Jul 20 19:01 still logged in wtmp begins Fri Jul 4 21:15:28 2014 </code></pre> |
21,753,656 | 0 | How to disable cell click of grid <p>I want to know if there is a way to disable clicking on a certain cell of a grid once its value is set in Google Web Toolkit?I tried <code>setEnabled(false)</code>, but it's not defined for cell</p> |
11,609,062 | 0 | ActiveMQ CLIENT on Java 1.4 <p>We are using Active MQ in the most current version 5.6.0. Now we have the problem that a new client has to be connected, unfortunately this client is developed with IBM JDK 1.4. Adding ActiveMQ to the application lead to the following error: </p> <pre><code>UNEXPECTED ERROR OCCURRED: org/apache/activemq/ActiveMQConnectionFactory (Unsupported major.minor version 50.0) STACK TRACE: java.lang.UnsupportedClassVersionError: org/apache/activemq/ActiveMQConnectionFactory (Unsupported major.minor version 50.0) </code></pre> <p>We don't want to switch to an older ActiveMQ version, since there are other applications using the current version. Now my questions (I know the FAQ and especially <a href="http://activemq.apache.org/can-i-use-activemq-5x-or-later-on-java-14.html" rel="nofollow">http://activemq.apache.org/can-i-use-activemq-5x-or-later-on-java-14.html</a>):</p> <p>Are there any ActiveMQ client jars which are usable to connect to Active MQ 5.6.0? For example is it possible to use an ActiveMQ 4.0 client to connect to Active MQ 5.6.0? Is it possible to use any other protocol for this purpose? Has anyone a succesful solution running?</p> <p>If I have to use retrotranslator which is the minimum set on jars I have to translate? Has anyone the experience with IBM JDK 1.4? </p> <p>Thanks for your answers!</p> |
11,602,702 | 0 | <p>You probably want <a href="https://github.com/mikeash/MAObjCRuntime" rel="nofollow">this.</a> Objective-C wrapper for the Objective-C runtime.</p> |
23,081,615 | 0 | <p>you could use the audioplayer for playback instead of sound. So</p> <pre><code>player = audioplayer(signal, Fs); </code></pre> <p>Player is the the audioplayer object (check MATLAB help on audioplayer) which you can play using</p> <pre><code>play(player); </code></pre> <p>While the sound is playing you can do whatever you want. For example there is a CurrentSample property which shows you the sample played at the moment. You can get it</p> <pre><code>c_sample = get(player,'CurrentSample'); </code></pre> <p>and use it for your plotting purposes.</p> |
8,438,493 | 0 | <p>The problems with the code in my initial attempt were:</p> <ol> <li>the read() method should return a value, so it should say:</li> </ol> <pre><code>return this.callParent([object]); </code></pre> <ol> <li><p>The alias should have been <code>'reader.my-json'</code></p></li> <li><p>The results needed to be mapped because it was an array:</p></li> </ol> <pre><code>object.Results = Ext.Array.map(object.Results, Ext.decode); </code></pre> <p>With those fixed, the store can use the simpler reader definition:</p> <pre><code>reader: { type: 'my-json', root: 'Results', totalProperty: 'Total' } </code></pre> <p>But see the complete test case in the original question for the full code. I apologize for not having thoroughly tested the code I initially proposed.</p> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.