text
stringlengths
8
267k
meta
dict
Q: How to put begin-commit transaction in controller: cakephp? I'm working on a controller that will update a few tables. I am able to call my model from my controller and inside the model function I can make a begin and commit my query, it can rollback should an error happen. Here is my sample: Controller: //update table when update button is clicked if (!empty($this->data)) { if ($this->Item->update($this->data)) { $this->Item->create(); $this->redirect('/sample'); return; } else { $this->set('data', $this->data); } } Model: function update($data) { $this->begin($this); if(!parent::save($data)) { $this->rollback($this); return false; } $this->commit(); return true; } Now this works fine. But what I need to do is to call another model in my controller like "$this->"ANOTHER MODEL HERE"->update()". I need to have rollback should a problem occur with either model transaction. What I'm thinking is to put a commit in my controller after both model call succeeds. Much like this: CONTROLLER PHP: BEGIN TRANSACTION ->CALLS MODEL1 IF(MODEL1 == ERROR){ ROLLBACK } ->CALLS MODEL2 IF(MODEL2 == ERROR){ ROLLBACK } COMMIT WHEN NO PROBLEM IS ENCOUNTERED So is it possible to perform commit in controller? I am only able to do it in model. Thanks in advance! A: So is it possible to perform commit in controller? I am only able to do it in model. Yes, you can perform commit or rollback from within the controller. You need to get the datasource from one of your models first. In the controller code, simply reference one of the models you are using (assuming they are all in the same database): $ds = $this->MyModelName->getdatasource(); Then you can begin, commit, and rollback to that datasource from within the controller. $ds->begin(); // do stuff and save data to models if($success) { $ds->commit(); } else { $ds->rollback(); } I actually have a rollback or commit in more than one place if I am bailing on the action and redirecting or finalizing in some step and redirecting. I just illustrate a simple case here. Handling transactions in the controller makes the most sense to me since the controller action is where the transaction boundaries really reside conceptually. The idea of a transaction naturally spans updates to multiple models. I have been doing this using postgres as the back end database with Cake 2.2 and 2.3 and it works fine here. YMMV with other db engines though I suspect. A: Trasactions are to be enhanced in futures versions of CakePHP, as you can see in this CakePHP Lighthouse ticket. There are two possible solutions proposed there, and I am showing you a third one. You could create a custom method to save it, and manually commit the transactions: public function saveAndUpdate($data) { $ds = $this->getDataSource(); $ds->begin(); if ($this->save($data)) { foreach(Array('Model1', 'Model2') as $model) { if (!ClassRegistry::init($model)->update()) { $db->rollback(); return false; } } return $db->commit() !== false; } return false; } I wrote this code to illustrate how I though about your problem, although I didn't test. More useful links: * *Transactions at CakePHP Book *About CakePHP Behaviors *How to create Behaviors A: I used commit within my if statements and rollback in my else statements. Since I was using two different models from within a controller, I created two different datasources $transactiondatasource = $this->Transaction->getDataSource(); $creditcarddatasource = $this->Creditcard->getDataSource(); $transactiondatasource->begin(); $creditcarddatasource->begin(); if (CONDITION){ $creditcarddatasource->commit(); $transactiondatasource->commit(); CakeSession::delete('Cart'); } else { $this->Session->setFlash(__('MESSAGE')); $creditcarddatasource->rollback(); $transactiondatasource->rollback(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7523562", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Preventing MKMapView from continually re-zooming and re-centering to user location I seem to have the opposite problem from many of those posted here about MKMapView. Rather than not being able to get it to zoom to and display the current location, I can't seem to get it to stop doing so. Here's what happens: * *I launch the app *The MKMapView shows my location with a blue dot *I zoom out and away on the map using my fingers *After a few seconds, the MKMapView suddenly zooms back in to center on my current location again I've tried telling my CLLocationManager to stopUpdatingLocation (no effect, since an MKMapView knows how to use CoreLocation), and I've tried telling the MKMapView to setShowsUserLocation:NO (no blue dot displayed at all, which is not what I want). I even tried eliminating my CLLocationManager (no effect). What is causing this and how do I stop it? Yes, I do set the location manager's accuracy and distance in -loadView. I don't implement -mapViewDidFinishLoadingMap:. Here is my implementation of -locationManager:didUpdateToLocation:fromLocation: - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { // How many seconds ago was this new location created? NSTimeInterval t = [[newLocation timestamp] timeIntervalSinceNow]; // CLLocationManagers will return the last found location of the device first, // you don't want that data in this case. If this location was made more than 3 // minutes ago, ignore it. if (t < -180) { // This is cached data, you don't want it, keep looking return; } [locationManager stopUpdatingLocation]; } I think this is the centering you're asking about, @Anna Karenina: - (void)mapView:(MKMapView *)mv didUpdateUserLocation:(MKUserLocation *)u { CLLocationCoordinate2D loc = [u coordinate]; // Display the region 500 meters square around the current location MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(loc, 500, 500); [mv setRegion:region animated:YES]; } A: Dont implement - (void)mapView:(MKMapView *)mv didUpdateUserLocation:(MKUserLocation *)u method. Instead use locationmanager didUpdateToLocation. didUpdateUserLocation is called multiple times without any reason.where didUpdateToLocation is called when any location changes occurred. Then u can manually set the mkmapview region in the didUpdateToLocation method. A: First, and I dont know that this will effect things much, but do you set your location managers accuracy and distance filter at all in viewDidLoad (or wherever you are implementing your locationManager): [locationManager setDesiredAccuracy:kCLLocationAccuracyBest]; [locationManager setDistanceFilter:kCLDistanceFilterNone]; Second, check these 2 functions in your source (ignore the content of the actual functions I have listed here, it is just for illustration and to show usage) and if possible, provide your code for these functions so we can better assist: - (void)mapViewDidFinishLoadingMap:(MKMapView *)mapView { [activityIndicator stopAnimating]; } - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { NSDate* eventDate = newLocation.timestamp; NSTimeInterval howRecent = [eventDate timeIntervalSinceNow]; if (abs(howRecent) < 15.0) { NSLog(@"New Latitude %+.6f, Longitude %+.6f", newLocation.coordinate.latitude, newLocation.coordinate.longitude); } } A: I use dispatch_once in MKMapViewDelegate method to zoom only once at the beginning. Here is the code. - (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ CLLocationCoordinate2D newCoordinate = CLLocationCoordinate2DMake(mapView.userLocation.coordinate.latitude, mapView.userLocation.coordinate.longitude); MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(newCoordinate, 500, 500); [mapView setRegion:region animated:YES]; }); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7523563", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: FTP webrequest in c# can any one explain , In FTP GetResponse() method by using MKD , how to create directory name having symbol (#) . it is not working . A: You should try an urlencode your directory string before I am just guessing have not tested this string directory = HttpServerUtility.UrlEncode("RITCH#ME");
{ "language": "en", "url": "https://stackoverflow.com/questions/7523564", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: partial page update in jquery Simple Request i have simple request I'm beginner in jquery so all i want to do is to do button when i click it increment counter variable and update only label on page not all page also i will use same code to make clock in page thank you A: Without you trying some code it is hard to be of specific help, but here is how to read a click, increment a counter, update a label, and call a make clock function. $(function() { function incrementCounter() { var $counter = $('#counter'), count = parseInt($counter).text()); if (!count) count = 0; count++; $counter.text(count); } function updateLabel(newText) { $('label').text(newText); } function makeClock() { // I have no idea what you mean by this but insert your code here. } $('button').click(function() { incrementCounter(); updateLabel(); makeClock(); }); }); A: The increment one you can do it like this: <script type="text/javascript" src="jquery-1.6.3.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $('#button').click(function() { current = parseInt($('#label').html()); $('#label').html(current+1); }); }); </script> <input type='button' value=' Increase! ' id='button' /> Count: <span id='label'>0</span>
{ "language": "en", "url": "https://stackoverflow.com/questions/7523573", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Sending anything *other* than GET using JQuery ajax I'm at the beginning of my ajax learning curve. I have a simple javascript function that uses jQuery.ajax() to send data to the server and receive a simple text response. The function is correctly invoked on the server as expected and the response (which includes the value of request.method as seen by the server) is returned and displayed via alert(). However, no matter what type: I specify in my $.ajax() call, the server always reports it has received a GET. Here is my javascript (again, I do see the alert(), and it always reports GET): <script type="text/javascript"> function SendContactEntry() { var payload = 'date=' + $('input[name=contact_date]').val() + '&us=' + $('input[name=contact_us]').val() + '&then=' + $('input[name=contact_them]').val() + '&note=' + encodeURIComponent($('input[name=contact_us]').val()); $.ajaxSetup({ jsonp: null, jsonpCallback: null}); $.ajax({type: 'POST', url: '/contact', data: payload, cache: false, contentType: 'application/json', dataType: "text", success: function (response){ alert(response); } } ); } </script> and here is the CherryPy handler on the server: class Contact: def index(self): return 'You sent a %s request' % cherrypy.request.method I included the call to $.ajaxSetup() because of the answer to this question, but it doesn't seem to make a difference. (jQuery and CherryPy are both latest versions, Python is 2.7) EDITED: More Info. Looking at my CherryPy console, I see that the server is receiving the POST. It's returning status 301 (moved) and then immediately it receives the same request as a GET and responds with status 200. So it looks as if CherryPy is internally redirecting the POST to my handler as a GET. But why? A: I'm afraid I'm going to have to answer my own question. The problem is that CherryPy redirects /contact to /contact/ if /contact matches an internal index() handler. The redirect is a GET. Changing url: '/contact', to url: '/contact/', solves the problem. I found the answer here. A: To send a post request to the server try this open("POST","filename.extension",true);
{ "language": "en", "url": "https://stackoverflow.com/questions/7523574", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to correctly retrieve setup UILevel in installer class I am trying to follow the code at this link in order to determine in my installer class if the setup is ran as silent. But I must be doing something wrong, because the Context.Parameters["UILevel"] seems to contain no value. In my setup project, I added a custom action on Install, where I passed /UILevel="[UILevel]" into CustomActionData field. I then linked this custom action to the primary output of the installer dll project, which contains the installer class below: using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration.Install; using System.Linq; namespace CustomActionLibrary { [RunInstaller(true)] public partial class MyInstaller : Installer { string uiLevelString = string.Empty; public bool IsSilentInstall { get { if (!String.IsNullOrEmpty(uiLevelString)) { int level = Convert.ToInt32(uiLevelString); return level <= 3; } else return false; } } public MyInstaller() { InitializeComponent(); } public override void Install(IDictionary stateSaver) { base.Install(stateSaver); uiLevelString = Context.Parameters["UILevel"]; } public override void Commit(IDictionary savedState) { //System.Diagnostics.Process.Start("http://www.google.ro?q=" + uiLevelString); if (IsSilentInstall) { //do stuff here if it's silent install. } base.Commit(savedState); } } } I thought that if I add the custom action on Install, I should retrieve Context.Parameters["UILevel"] in the Install override. But Context.Parameters["UILevel"] never gets populated. I also tried retrieving it on the constructor of the class but it throws nullref, and in the commit event, but still nothing. How could I properly retrieve this value? A: I solved it, it's retrieving the UILevel value correctly on the AfterInstall event handler. private void SecureUpdaterInstaller_AfterInstall(object sender, InstallEventArgs e) { uiLevelString = this.Context.Parameters["UILevel"]; System.Diagnostics.Process.Start("http://www.google.ro?q=afterInstall_" + uiLevelString); } It makes sense - it's populating the value from the Install custom action, and it's retrieving it on AfterInstall.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523576", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: (SQL SCRIPT + SQL SERVER 2005) Weird '-' symbols I was writing a SQL script like the following for SQL server 2005: select '============================' select '~~~~~~~~~~~~~~' select char(13) + 'Control 127232:' exec xp_loginconfig go I noticed that there is a '-' symbols after my string of 'select '============================'' and also after my string of '~~~~~~~~~~~~~~'. Sample output: ============================ - ~~~~~~~~~~~~~~ - Control 127232: I would like to remove this '-' symbols if possible? thanks A: Perhaps instead of SELECTing this information, you would be more interested in PRINTing it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523577", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Change the default name of relationship in django admin I have a ManyToMany relationship follow as: class Subtopic(models.Model): id = models.PositiveIntegerField(primary_key=True) name = models.CharField(max_length=128) class Meta: verbose_name = 'Subtopic' def __unicode__(self): return self.name class Question(models.Model): qid = models.PositiveIntegerField(primary_key=True) subtopics = models.ManyToManyField(Subtopic) class Meta: verbose_name = 'Question' In the admin interface, I would like to change the default names in this picture. http://flic.kr/p/apx3j8 The first name is the relationship of two class such as Subtopic and Question. Second is the name of Subtopic class. And finally is Question class Django model automatically generates an intermediary table namely Question_Subtopics and I can not meddle in this table. Please help me to achieve it. Thanks. A: that text is filled with __unicode__, which is similar to java's toString(). class Subtopic(models.Model): ... def __unicode__(self): return self.name Just do that, and you'll be fine :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7523580", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Are there any alternatives for Android Market statistics? I am having some issues with Android market statistics as they have not been updated for more than a week. This issue seems to be reoccurring with no solution from Google. Are there any alternatives that I can use for my app to get statistics like how many people are using it, what kind of mobile phones and/or Android version are being used. Will Google analytics do the job? Is there any other stat service dedicated for mobile phones only? A: To see what Google Analytics can to on mobile devices, take a look at the Google Code page for Google Analytics. A listing of the dimensions and metrics available with Google Analytics is available here. If you are looking for a free service, I think this is the one you want to use. If you are more interested in pay services, there are plenty. Here are a few from a simple google search: * *WebTrends *Bango *Localytics
{ "language": "en", "url": "https://stackoverflow.com/questions/7523582", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Make a customized widget observable? I had create a simple keywords highlighting editor, it just wrap a StyledText widget: public class SQLSegmentEditor extends Composite { private StyledText st; public SQLSegmentEditor(Composite parent) { super(parent, SWT.NONE); this.setLayout(new FillLayout()); st = new StyledText(this, SWT.WRAP | SWT.BORDER | SWT.V_SCROLL); st.addLineStyleListener(new SQLSegmentLineStyleListener()); } } How can I make it can be used in data-binding? I am looking for the proper way, not just one that makes it work. I want to observer the text content of the inner StyledText. For example : I can just add a getStyledText method to return the wrapped StyledText widget for using it in databinding. But this will take a risk. In order to keep my editor behavior correctly, I should keep the StyledText widget not visible to client code. A: Although I don't understand your argument of not exposing the wrapped widget to the client, here is a possible solution. The widget can provide a WritableValue that can be bound directly via databinding by the client. That means the binding goes over 3 parties: the clients target, the wrapping writable-value and the SWT source. The only drawback is that you have a direct dependency to Databinding in your widget. Here is a snippet. import org.eclipse.core.databinding.DataBindingContext; import org.eclipse.core.databinding.observable.value.WritableValue; import org.eclipse.jface.databinding.swt.ISWTObservableValue; import org.eclipse.jface.databinding.swt.WidgetProperties; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.widgets.Composite; public class SQLSegmentEditor extends Composite { private final StyledText st; private final WritableValue value = new WritableValue(); public SQLSegmentEditor(Composite parent, DataBindingContext ctx) { super(parent, SWT.NONE); assert ctx != null; setLayout(new FillLayout()); st = new StyledText(this, SWT.WRAP | SWT.BORDER | SWT.V_SCROLL); ISWTObservableValue swtBinding = WidgetProperties.text(SWT.Modify) .observe(st); ctx.bindValue(value, swtBinding); } public WritableValue getValue() { return value; } } So the client code would look like: DataBindingContext ctx = new DataBindingContext(); SQLSegmentEditor sqlSegmentEditor = new SQLSegmentEditor(getParent(), ctx); IObservableValue modelObservable = //setup my model-observable ctx.bindValue(modelObservable, sqlSegmentEditor.getValue());
{ "language": "en", "url": "https://stackoverflow.com/questions/7523583", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Cascade insert with JPA/Hibernate (EclipseLink) I have two tables like this | PERSON | | EMPLOYEE | | id | fullName | | personId | code | EMPLOYEE.personId is a primary key as well as foreign key pointing to PERSON.id I have these two classes: @Entity @Table(name="PERSON") @Inheritance(strategy=InheritanceType.JOINED) public abstract class Person implements Serializable { protected int id; protected String fullName; @Id @Column("id") public int getId() { return this.id } public void setId(int id) { this.id = id; } @Column("fullName") public int getFullName() { return this.fullName } public void setId(int fullName) { this.fullName = fullName; } } @Entity @Table(name="EMPLOYEE") @PrimaryKeyJoinColumn(name="personId") public class Employee extends Person implements Serializable { private String code; public Employee(String code) { setCode(code); } @Column("code") public String getCode() { return this.code } public void setCode(String code) { this.code = code; } } And when I wanna insert a new record into EMPLOYEE table: entityTransaction.begin(); Employee emp = new Employee("EMP001"); emp.setFullName("hiri"); this.entityManager.persist(emp); entityTransaction.commit(); It throws an exception says: Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (...) Error Code: 1452 Call: INSERT INTO EMPLOYEE (code, personId) VALUES (?, ?) bind => [EMP001, 0] As you can see, it is supposed to insert a new Person record first an Employee after that, but in fact it doesn't, the foreign key personId=0 causes the problem. Can you help me? Thanks! A: You do not need @PrimaryKeyJoinColumn when using Inheritance. It will be managed for you automatically. You do need to have a unique ID value though. If you intend to use sequence generation you need to add @GeneratedValue to the id. @Id @GeneratedValue @Column("id") public int getId() { return this.id }
{ "language": "en", "url": "https://stackoverflow.com/questions/7523589", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Generating HTML Form from database using PHP I'm building a basic website that will offer a quiz dynamically generated from a MySQL database. Based on my current database schema, I'm having trouble understanding how I will generate the 'choices' to different questions in a Quiz Web App. Here is the database schema: CREATE TABLE user ( user_id INT UNSIGNED PRIMARY KEY, username VARCHAR(32) NOT NULL UNIQUE, password VARCHAR(128) NOT NULL, ... ) Engine=InnoDB; CREATE TABLE quiz ( quiz_id INT UNSIGNED PRIMARY KEY, title VARCHAR(64) ) Engine=InnoDB; CREATE TABLE question ( question_id INT UNSIGNED PRIMARY KEY, quiz_id INT UNSIGNED NOT NULL, question VARCHAR(1024), FOREIGN KEY (quiz_id) REFERENCES quiz (quiz_id) ) Engine=InnoDB; CREATE TABLE question_choices ( choice_id INT UNSIGNED PRIMARY KEY, question_id INT UNSIGNED NOT NULL, is_correct_choice TINYINT(1), choice VARCHAR(512), FOREIGN KEY (question_id) REFERENCES question (question_id) ) Engine=InnoDB; CREATE TABLE quiz_response ( response_id INT UNSIGNED PRIMARY KEY, user_id INT UNSIGNED NOT NULL, question_id INT UNSIGNED NOT NULL, response INT UNSIGNED NOT NULL, is_correct TINYINT(1), answer_time FLOAT, UNIQUE KEY (user_id, question_id) FOREIGN KEY (user_id) REFERENCES user (user_id), FOREIGN KEY (question_id) REFERENCES question (question_id), FOREIGN KEY (response) REFERENCES question_choices (choice_id), ) Engine=InnoDB; Here is the code I have produced so far in my quiz.php script: // If this user has never taken this quiz, insert empty responses into the quiz_response table $query = "SELECT * FROM quiz_response WHERE user_id = '" . $_SESSION['user_id'] . "'"; $data = mysqli_query($dbc, $query); if (mysqli_num_rows($data) == 0) { //First grab the list of questions to create empty responses //Grab all questions from question table //Rework code in the future to accommodate multiple quizes $query = "SELECT question_id from question"; $data = mysqli_query($data, $query); $questionIDs = array(); while ($row = mysqli_fetch_array($data)) { array_push($questionIDs, $row['question_id']); } // Insert empty response rows into the response table, one row per question foreach ($questionIDs as $question_id) { $query = "INSERT INTO quiz_response (user_id, question_id) VALUES ('" . $_SESSION['user_id']. "', '$question_id')"; mysqli_query($dbc, $query); } } // If the quiz form has been submitted, write the form responses to the database if (isset($_POST['submit'])) { // Write the quiz response rows to the response table foreach ($_POST as $response_id => $response) { $query = "UPDATE quiz_response SET response = '$response' WHERE response_id = '$response_id'"; mysqli_query($dbc, $query); } echo '<p>Your responses have been saved.</p> } // Grab the response data from the database to generate the form $query = "SELECT qr.response_id, qr.question_id, qr.response, q.question, quiz.quiz " . "FROM quiz_response AS qr " . "INNER JOIN question AS q USING (question_id) " . "INNER JOIN quiz USING (quiz_id) " . "WHERE qr.user_id = '" . $_SESSION['user_id'] . "'"; $data = mysqli_query($dbc, $query); $responses = array(); while ($row = mysqli_fetch_array($data)) { // Pull up the choices for each question $query2 = "SELECT choice_id, choice FROM question_choice " . "WHERE question_id = '" . $row['question_id'] . "'"; $data2 = mysqli_query($dbc, $query2); $choices = array(); while ($row2 = mysqli_fetch_array($data2)) { array_push($choices, $row2); } // Rename choices // Eventually push choices into $responses array // array_push($responses, $row); } mysqli_close($dbc); // Generate the quiz form by looping through the response array echo '<form method="post" action="' . $_SERVER['PHP_SELF'] . '">'; echo '<h2>' . $page_title . '</h2>'; $question_title = $responses[0]['question']; echo '<label for="' . $responses[0][response_id'] . '">' . $responses[0]['question'] . '</label><br />'; foreach ($responses as $response) { // Only start a new question if the question changes if ($question_title != $response['question']) { $question_title = $response['question']; echo '<br /><label for="' . $response['response_id'] . '">' . $response['question'] . '</label><br />'; } // Display the choices // Choice 1 // Choice 2 // Choice 3 // Choice 4 } echo '<br /><br />'; echo '<input type="submit" value="Grade Me!" name="submit" />'; echo '</form>'; I'm having trouble pulling the choice options out of the question_choice table and using them to populate the form. Can I put the choice_id and choice columns into the $responses array and access them in the generating form section without renaming them? At this point I feel I need to rename. Any help would be greatly appreciated! A: I hope I'm understanding your question correctly. It seems like you're asking given the structure of your data, how would you represent choices to the user. Let's say your choice data for a particular question #27801 looks like this in your question_choice table: choice_id question_id is_correct_choice choice 1 27801 0 Blue 2 27801 0 Green 3 27801 1 Red 4 27801 0 Shoe After you've tokenized the data, you can output a group of choices as a radio group with the question_id as part of the group name, and the choice_id as the individual values: <input type="radio" name="27801" value="1" /> Blue <br /> <input type="radio" name="27801" value="2" /> Green <br /> <input type="radio" name="27801" value="3" /> Red <br /> <input type="radio" name="27801" value="4" /> Shoe <br /> Then when the quiz has been submitted, you can determine the $correct_choice_num by iterating through each choice looking at the value of is_correct_choice. You can get around having to do this iteration if you store corrent_choice_num in your database, but that might mean having one more table. Anyway, once your script has $correct_choice_num, you can compare that against the choice that the user selected. if ( $correct_choice_num == $_POST["$question_id"] ) { // This was the correct choice, do something } (The benefit of doing the scoring server-side is that the user can't cheat to find the correct choices by looking at the source of the HTML document) This is just an example to get you started. Hope that helps! A: SELECT the table, get the options out of the question_choice via a MySQL query, make the rows variables and then echo them.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523594", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: EGL_BAD_MATCH with Droid/Droid 2 I've been testing my OpenGL ES 2 app on various phones. I've ran into a problem with the Droid and Droid 2. Every EGL config I try results in an EGL_BAD_MATCH. I've tried many combinations of EGL configurations, including configurations that work on other phones, and every combination results in an EGL_BAD_MATCH. Has anyone ran into this problem or know of any solutions? Thanks A: I also had this problem on select Motorola and Samsung handsets. The problem is the phone reports a different pixel format than the surface is expecting. You need to setup the surface view with the appropriate pixel format for that phone, which is most likely PixelFormat.RGB565 Kevin A: It is not an issue of handsets types, this issue can be on any handset and i don't know weather this problem is related to pixelFormat. But, I have solved it by deleting current emulator and create new emulator. If you deploy application on your device then you have to reboot your device. A: Ensure you have set EGL_PBUFFER_BIT for the EGL_SURFACE_TYPE in the attributes passed into eglChooseConfig() call.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523597", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Javascript - clicking an image using code I have an image on a page. I cannot change the page. When you click on the images this page has, a function run and processes the image. The image is not a button. To make the image respond to clicks, the page developer added a listener to it. In fact, every image on that page has a listener. The listener is listening the "img" tag. When you click on an image, the Javascript checks to see if that image should respond to a click and then runs or not a function. I am developing some automation to fill the form where this image is. This automation script needs to fill the form and click on that image. How do I click on that image using javascript? What should I look on the code to discover the method that runs when the image is clicked? My problem is this: as the listener is attached to all images on that page but just some respond to the clicks, I suppose that the function attached to the listener has to receive a reference to the image that needed to be process... this is what complicates everything... If you guys want, I can zip the page and the javascripts and put it here. thanks A: Dispatch a click event: var target = yourImage; //<--(insert your image here); if(document.createEvent) { //Normal W3C event model var clickEvent = document.createEvent("MouseEvents"); clickEvent.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, 0, null); target.dispatchEvent(clickEvent); } else { //IE event model target.fireEvent("onclick"); } Normally, clicks are attached to an element using element.addEventListener and element.attachEvent, but sometimes element.onclick is used. If the page uses jQuery, it might use the live method, which attaches to the root node. However, the previous method should work correctly since the event's target is set to target. A: http://jsfiddle.net/efortis/9nmAR/ $(document).ready(function (){ $('img').click(function() { alert($(this).attr('alt')); }); $('img').eq(0).click(); // << I think this is what you need });
{ "language": "en", "url": "https://stackoverflow.com/questions/7523598", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP Gmagick extension Is there a way to get all the colors of an image? Example this image The output should have the colors: yellow,black,blue. It can also result in a Hex Value. Can someone tell me any idea how to get that result? or maybe someone has already implemented this one, kindly show it to me. Thanks. Any help would be greatly rewarded and appreciated. A: What about this thread: most colors used (color analysis)
{ "language": "en", "url": "https://stackoverflow.com/questions/7523608", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android 2.3.3 Listview Background Is Gray So I have a rather annoying issue with a listview. My app was working just fine until the Android 2.3.3 update on my Droid 2. (Still seems to work fine on a Samsung Evo) There are a few aspects of this issue. 1. The background is always gray in empty slots. 2. The last entry in the list appears to be invisible until it is selected. When selected you can see the black text, but no background. 3. Other/Older entries in the list do show with the correct background color. I have tried quite a few things, and nothing seems to fix this. Thoughts? Listview definition <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_height="wrap_content" android:gravity="left|center" android:layout_width="wrap_content" android:layout_alignParentBottom="true" android:paddingLeft="1px"> <TextView android:text="" android:id="@+id/list_view_text_view" android:layout_width="wrap_content" android:textSize="13sp" android:singleLine="false" android:layout_height="wrap_content" android:layout_marginLeft="1sp"> </TextView> </LinearLayout> Main Layout of listview <ListView android:id="@+id/ListView01" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_alignRight="@+id/Button06" android:layout_below="@+id/TextView01" android:layout_alignLeft="@+id/TextView01" android:layout_marginBottom="2sp" android:layout_marginRight="2sp" android:layout_marginLeft="2sp" android:layout_above="@+id/EditText01" android:transcriptMode="normal" android:footerDividersEnabled="false" android:headerDividersEnabled="false" android:gravity="bottom" > </ListView> Listveiw Adapter private class EfficientAdapter extends BaseAdapter { private LayoutInflater mInflater; public EfficientAdapter(Context context) { mInflater = LayoutInflater.from(context); } public int getCount() { return comment_list.size(); } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { convertView = mInflater.inflate(R.layout.listview, null); holder = new ViewHolder(); holder.text = (TextView) convertView .findViewById(R.id.list_view_text_view); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } holder.text.setText(comment_list.get(position).toString()); return convertView; } class ViewHolder { TextView text; } } This is the code i use to try and set the background in my main routine. list_view_comments.setBackgroundResource(R.color.color_con); list_view_comments.setDrawingCacheBackgroundColor(R.color.color_con); list_view_comments.setBackgroundColor(R.color.color_con); list_view_comments.setCacheColorHint(R.color.color_con); A: Your issue is the same as this issue on SO... Listview background is grey on Droid 3 Here is the solution that Motorola gives us as a workaround... http://community.developer.motorola.com/t5/MOTODEV-Blog/Why-Does-My-ListView-Look-Different/ba-p/17462 Basically they (Motorola) are using a customized theme that you must override using attributes like android:overScrollFooter="@null" Edit - The link above no longer works for some reason. However, as Kevin said in the comments, the solution will still work. A: Hi use this may be it is helpful to you. list_view_comments.setBackgroundColor(getResources().getColor(R.color.color_con)); A: How to draw a ListView in OS v2.3 so that the extra space below your last row item displays your specified background instead of the gray default footer background color: overScrollFooter is unacceptable to most builds. height="wrap_content" by itself only works if there are no other widgets below your ListView. Removing layout_alignParentBottom="true" can work, but can also damage the screen layout depending on the ListView's relationship with other widgets. The most straightforward way to reduce the height of your ListView so there is no extra footer space that Motorola OS v2.3 wants to paint gray, is to wrap the ListView in another Layout such as a LinearLayout. Make the LinearLayout whatever size you wish and reduce the height of the internal ListView to "wrap_content". If you want more explanation and an example, navigate here: List View Footer Background on Android 2.3.3.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523614", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: sql query to create a new table I have a table as follows: table 1 temp_id node_name variable_1 variable_2 variable_3 1 ab a b y 2 sdd a a a 3 u a s s and another table as follows: table 2 temp_id node_name variable_1 variable_2 variable_3 1 ab as sb y 2 sdd a a a 3 u a s s I want to fetch all the records from table 1 only where the combination variable_1, variable_2 and variable_3 of table 1 doesnot match with table 2. for example in table 1 first record has a,b,y (variable_1, variable_2 and variable_3) and it this does not exists in table2. How can I do that in TSQL? A: It is not clear whether there a requirement for an outer join. I assume that the columns are all NOT NULL qualified; the condition gets much more complex if any of the variable_X columns can hold nulls. SELECT T1.* FROM Table1 AS T1 JOIN Table2 AS T2 ON T1.Temp_ID = T2.Temp_ID AND T1.Node_Name = T2.Node_Name WHERE T1.Variable_1 != T2.Variable_1 OR T1.Variable_2 != T2.Variable_2 OR T1.Variable_3 != T2.Variable_3; If NULLS are allowed, then you have to write: SELECT T1.* FROM Table1 AS T1 JOIN Table2 AS T2 ON T1.Temp_ID = T2.Temp_ID AND T1.Node_Name = T2.Node_Name WHERE (T1.Variable_1 != T2.Variable_1 OR (T1.Variable_1 IS NULL AND T2.Variable_1 IS NOT NULL) OR (T2.Variable_1 IS NULL AND T1.Variable_1 IS NOT NULL) ) OR (T1.Variable_2 != T2.Variable_2 OR (T1.Variable_2 IS NULL AND T2.Variable_2 IS NOT NULL) OR (T2.Variable_2 IS NULL AND T1.Variable_2 IS NOT NULL) ) OR (T1.Variable_3 != T2.Variable_3 OR (T1.Variable_3 IS NULL AND T2.Variable_3 IS NOT NULL) OR (T2.Variable_3 IS NULL AND T1.Variable_3 IS NOT NULL) ); Note that this is not the same as: SELECT T1.* FROM Table1 AS T1 JOIN Table2 AS T2 ON T1.Temp_ID = T2.Temp_ID AND T1.Node_Name = T2.Node_Name WHERE NOT (T1.Variable_1 = T2.Variable_1 AND T1.Variable_2 = T2.Variable_2 AND T1.Variable_3 = T2.Variable_3); A: select * from table1 t1, table2 t2 where t1.temp_id = t2.temp_id and ( t1.var1 != t2.var1 OR t1.var2 != t2.var2 OR t1.var3 != t2.var3) A: select * from table1 t1 left outer join table2 t2 on t1.temp_id = t2.temp_id where t1.var1 <> t2.var1 OR t1.var2 <> t2.var2 OR t1.var3 <> t2.var3 A: It is unclear to me if you want to check the existence against all rows in table2 select T1.* from table1 as T1 where not exists (select * from table2 as T2 where T1.variable_1 = T2.variable_1 and T1.variable_2 = T2.variable_2 and T1.variable_3 = T2.variable_3 ) or you you only want to check against the rows where temp_id is a match. select T1.* from table1 as T1 left outer join table2 as T2 on T1.temp_id = T2.temp_id and T1.variable_1 = T2.variable_1 and T1.variable_2 = T2.variable_2 and T1.variable_3 = T2.variable_3 where T2.temp_id is null With your test data the result is the same: https://data.stackexchange.com/stackoverflow/qt/113272/ A: How about this: select * from Table1 T1 LEFT OUTER JOIN Table2 T2 on T1.temp_id = T2.temp_id where WHERE (T1.variable_1 <> T2.variable_1 AND T1.variable_2 <> T2.variable_2 AND T1.variable_3 <> T2.variable_3)
{ "language": "en", "url": "https://stackoverflow.com/questions/7523615", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: Inheritance issue C# I've got a small problem with inheritance in my application. I've got a base class Client, which has a subclass Job. Basically, I'm trying to create a constructor for Job but I'm getting an error saying "'Job_Manager_Application.Client' does not contain a constructor that takes 0 arguments" Can't figure out why it's doing this? Thanks in advance. A: Your Client class has a constructor that takes parameters. Therefore your Job constructor needs to pass parameters to Client. Example: class Client{ public string Name {get;set;} public Client(string name){ this.Name = name; } } -- class Job:Client{ public double Rate {get;set;} public Job(double rate){ // This won't compile, because Client won't have its "name" parameter. } public Job(string name, double rate) : base(name){ // So you need to pass a parameter from your Job constructor using "base" keyword. this.Rate = rate; } public Job(double rate) : base("Default Name"){ // You could do this, this is legal. } } A: Why is Job a subclass of a Client? Inheritance represents is a relationships (a Cat is a Animal so class Cat : Animal { }). A Job is not a Client. Anyway, your error message is clear. You don't have an accessible parameterless constructor on Client. You need to explicitly invoke a constructor on client from a constructor on Job then. class Client { public string Name { get; set; } public Client(string name) { this.Name = name; } } class Job : Client { public Job(string name) : base(name) { } } See that base(name) there? That is invoking the base constructor Client.Client(string) on Client. If you don't specify a base constructor explicitly, the compiler tries to find an accessible parameterless constructor. If there is not one, you get the compile time error that you experienced. So, you either need to do as I've done above, which is invoke an accessible non-parameterless constructor explicitly, or add a parameterless constructor to Client. But please, rethink your model. A Job is not a Client. A: Client has a constructor that takes arguments and you aren't calling it properly public class Job { public Job(int num) { } } public class Client : Job { public Client() : base(1) {} }
{ "language": "en", "url": "https://stackoverflow.com/questions/7523617", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: setShadowLayer causes slow draw time in GridView? I'm currently working with a GridView containing ImageViews and would like shadows behind my images. There are potentially, say, 15 images visible in the grid at any time. Working under the assumption that I want my screen to render at 50fps to appear smooth, my math shows that I want the total draw time of each ImageView to be no worse than around 1.3ms. I took a look at how Romain Guy was doing shadows in his Shelves app: http://code.google.com/p/shelves/source/browse/trunk/Shelves/src/org/curiouscreature/android/shelves/util/ImageUtilities.java That seemed to make sense, so I created the following class: public class ShadowImageView extends ImageView { private static final int SHADOW_RADIUS = 8; private static final int SHADOW_COLOR = 0x99000000; private static final Paint SHADOW_PAINT = new Paint(); static { SHADOW_PAINT.setShadowLayer(SHADOW_RADIUS / 2.0f, 0.0f, 0.0f, SHADOW_COLOR); SHADOW_PAINT.setColor(0xFF000000); SHADOW_PAINT.setStyle(Paint.Style.FILL); } public ShadowImageView(Context context, AttributeSet attrs) { super(context, attrs); } @Override public void onDraw(Canvas canvas) { final int containerWidth = getMeasuredWidth(); final int containerHeight = getMeasuredHeight(); canvas.drawRect( SHADOW_RADIUS / 2.0f, SHADOW_RADIUS / 2.0f, containerWidth - SHADOW_RADIUS / 2.0f, containerHeight - SHADOW_RADIUS / 2.0f, SHADOW_PAINT); } } (Obviously this just gives me black rectangles with shadows, but was enough for getting an initial guess on performance.) Scrolling through the grid was pretty choppy, so I checked the draw times I was getting in Hierarchy Viewer: ~3.5ms per ImageView. This comes out to around 19fps at best. If I remove the setShadowLayer() statement, however, Hierarchy Viewer shows draw times around 0.2ms per ImageView. If I forget all about drawRect() and instead create a nine-patch with shadow edges, calling setBackgroundResource(R.drawable.my_nine_patch) in onDraw(), I see draw times around 1.5ms per ImageView. Are there known performance issues using Paint with a shadowLayer? Am I doing something silly in the above code?
{ "language": "en", "url": "https://stackoverflow.com/questions/7523622", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: is there a way to reverse a hash without rainbow tables? Possible Duplicate: md5 decoding. How they do it? this page suggests that a hash algorithm like md5() and sha1() can be reversed because of the huge processing power that we have nowadays. At this point i tought it was only possible with Rainbow Tables. Was i wrong? In case Rainbow Tables is the only way to go, how someone could reverse a hash that was made with a salt? A: A rainbow table is "just" a big table of precomputed hash values with some trickery to store only a small portion of the table and still be able to lookup all values. In fine details, a rainbow table which can "invert" N possible values (i.e. there are N hash outputs for which the table will yield a corresponding input) takes time about 1.7*N to build -- so building the table is actually slower than "just" trying out the N inputs and see if one matches the given hash output. The table advantage is when you have several hash outputs for which you want to find a matching input. A: Maybe you could use the following attack, adopting, the technique used to make the hash is a simple calculation. For example, if the calculation would be made with a modular hash in 100, we have: Example input: 8379547378 Output hash: 78 A general formula for the hash value 78 would be 78 +100*k (k belonging integers). Thus, one could try all the possible sequences. Note that this reduces the search space from 100% to 1% in this case the module 100. If it were possible to establish a hunch that this number was 10 digits, we could make the search even further reduced to 78 +100 k (10^7<=k< 10^8). Another way would be to populate a database with a number of really great of hashes and their entrances, then search in this database. I hope I have helped a little. A: First, in general, it is not possible to "reverse" a cryptographic hash function. This is because these functions generally take far more input data than they output. For instance, MD5 takes 512 input bits (64 bytes) and produces 128 bits output (16 bytes). Thus, there is simply not enough information in the input to reconstruct the output. In fact, there will be approximately 2^384 (a really big number) of different inputs that have exactly the same output hash. Instead cryptographers talk about three different kinds of attacks on hashes: * *first preimage attack: given a hash h, find any message m such that hash(m) = h *second preimage attack: given a fixed message m1, find any other message m2 such that hash(m1) = hash(m2) *collision attack: find any two messages m1 and m2 such that hash(m1) = hash(m2) Now back to this "reversing" business. When you want to "break a MD5 password", what you really want to do is a first preimage attack: find any "password" m such that hash(m) matches stored hash h. Normally this would take on the order of 2^128 guesses to do by brute force (more than all the computers on earth could manage in a century). There exist known weaknesses in MD5 that bring this down to ~2^123, which is still too hard to be practical. But because passwords are generally short strings of letters and numbers, there are far fewer than 2^128 passwords that people are actually likely to use. There's more like 2^40 (ie around a trillion). That's still a lot, but not so many that it's impossible to try them all if you have a year or so or a lot of PS3s. But what if you knew you wanted to break a whole lot of passwords? Rather than make 2^40 guesses each time, you can store the hashes of all the likely passwords on disk for future use. This is (more or less) what a rainbow table is: someone has already done all the work so that you just lookup the answer and skip most of the work. You are right that using a salt breaks that. Now you're back to 2^40 guesses and your roomful of PS3s again. Using a better hash function (like SHA512 or SKEIN) doesn't really change this because it doesn't change the number of likely passwords you need to try. Lesson: you need to use a really hard to guess password! Ok, but aren't MD5 and SHA1 still considered broken? Yes, but not in ways that really matter here (yet). The exciting news in this area has all been about collision attacks, which are relevant to breaking parts of SSL security and digital signatures, but aren't relevant to breaking stored passwords. Cryptographers expect this work to lead to even better attacks before long, so it's probably not a good idea to use MD5 or SHA1 in new programs, but programs that are using MD5/SHA1 + proper salting for password storage are still fine. A: Well, this question in general is a duplicate of This Question. However, to answer your exact questions: At this point i tought it was only possible with Rainbow Tables. Was i wrong? Technically, yes you are wrong. No hash function is unrecoverable, given enough processing power. The key point, is how much processing power it takes, which in most cases is far bigger than you can imagine. The reason is that the number of possible values increases exponentially at each stage of the hash cycle. For MD5, each stage (there are 64 of them) would multiply the number of possibilities by 10^77 (a lot of zeros). So to successfully reverse an MD5, you'd have to try a really large number of possible permutations (a back-of-envelope calculation shows somewhere on the order of 10^4932 tries). With the fastest super computer ever created today (about 8 petaflops, or 8x10^15 floating point operations per second), you're looking at approximately 10^4908 years to reverse it. Which incidentally is 2.5x10^4898 times the age of the universe right now. Really, it's an enormous number that's beyond our human ability to comprehend... And that's an absolute best possible case situation. So technically it is possible to reverse. But practically, no it is not. In case Rainbow Tables is the only way to go, how someone could reverse a hash that was made with a salt? The thing is that nobody needs to reverse it. They just need to find a collision. Basically, a collision is two inputs that lead to the same output. So if hash(a) = x and hash(b) = x, a and b are collisions of each other. So, all we need to do is find a collision (which believe it or not is easier than finding the exact input, since there are technically an infinite number of inputs that can give a particular output). With input the size of passwords, typically the collision is the original password. The easiest way to find this collision is with a precomputed list of hashes (typically called a rainbow table). Basically all you need to do is then look up the hash in the table to see if the original is there. If so, you're done (that easy). Salts are typically added to combat rainbow tables. This is because if the user enters 1234 as their password, and you use abcdefghijklmnop as the salt, the original would be 1234abcdefgjhijklmnop, which is significantly less likely to appear in a rainbow table. So adding a strong salt will protect against precomputed rainbow tables. Brute Forcing However, there is a significant concern if you just do hash(pass + salt). It's not susceptible to precomputed rainbow tables, but it is susceptible to brute forcing. The reason is that cryptographic hash functions (such as sha1, md5, sha256, etc) are designed to be fast. Their traditional role is in Signing, so they need to be fast to be useful. However, in password storage this is the weakness. With modern GPU's, an attacker could brute force (just try every possible password permutation) a simple hash with salt in a matter of hours (for more details, see my blog post about it)... The best prevention The best prevention has two features: * *It's not easy to pre-compute a table of values (a rainbow table) *It's not fast to hash a single value (not easy to brute force). As it turns out, there's a simple way of doing that using a hash function. Simply iterate over it and make the output dependent upon a large number of hash functions: var result = password + salt; for (var i = 0; i < 10000000; i++) { result = hash(result + salt); } The key is that by making it artificially slow and using a salt, you're making it resistant to precomputation and brute forcing. As it turns out, there are 2 standard algorithms that do this (well, use the principles). The best one is Blowfish hash (bcrypt) which doesn't really use a hash primitive function, but uses the key derivation cycle of the Blowfish cipher. It's available in PHP via crypt(). To use it: $hash = crypt($password, '$2a$07$' . $salt . '$'); And verify it with $hash == crypt($password, $hash); The other method (which is slightly less preferred) is PBKDF2. To program it in PHP: function pbkdf2($hashFunc, $password, $salt, $iterations, $length = 32) { $size = strlen(hash($hashFunc, '', true)); $len = ceil($length / $size); $result = ''; for ($i = 1; $i <= $len; $i++) { $tmp = hash_hmac($hashFunc, $salt . pack('N', $i), $password, true); $res = $tmp; for ($j = 1; $j < $iterations; $j++) { $tmp = hash_hmac($hashFunc, $tmp, $password, true); $res ^= $tmp; } $result .= $res; } return substr($result, 0, $length); } Note: None of these will protect a user against a very weak password. If they enter a dictionary word, or a common password it will still be likely that an attacker will be able to crack it. They will however add to the defense against moderate strength passwords... Some more reading: * *Many hash iterations, append salt every time? *Fundimental difference between hashing and encryption *MD5 decoding, how they do it *The Rainbow Table Is Dead *You're storing your password incorrectly *Password storage, salt vs multiple hashes A: Technically any standard hashing algorithms is not reversible! so once you get the hash of a message, there should be no way to get the original message out of its hash string. The only way people try to crack it is to use brute force attack. Brute forcing is the stupidest thing you can do, trying all possible keys! That explains why one of the characteristic of a secure cryptographic algorithm is to have a large key space. But if you utilize the process in some cases it can be practical, that's what exactly rainbow tables do. A rainbow table is a precomputed table for all possible combinations up to a certain length. That means you create all possible combination of characters(upper case and lower case), numbers and special characters up to certain length. As far as I know the most complete rainbow table can break hash of strings up to 10 characters which include numbers, uppercase and special characters, so if you have string longer than that there shouldn't be any security concern about breaking the hash itself. as you can see here the size of the table that can break vista passwords up to 8 characters is over 100GB and that number increases exponentially which makes it kind of impossible to go further that 10 or 12 characters. As long as your string is not easy to guess, long enough and it contains upper case letters, numbers and special characters, there no need to worry :) A: The brute-forcing that page is talking about is basically the generation of a rainbow table on the fly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523625", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Trusted_Connection vs Integrated Security affects connection pooling I was running some application performance monitoring on my ASP.NET 4.0 application (on Windows 2008 RC2, connected to a SQL Server 2005 database) and noticed that the connections did not appear to be pooling. We run the application pool under a specific user and use integrated security. With a connection string like: <add name="myConnection" connectionString="Server=DBSrv;Database=DB1;Trusted_Connection=true;" providerName="System.Data.SqlClient"/> On a hunch i slightly modified the connection string to use the Integrated Security syntax instead of trusted_connection. After making the change the connections began using the connection pool. <add name="myConnection" connectionString="Server=DBSrv;Database=DB1;Persist Security Info=False;Integrated Security=SSPI;" providerName="System.Data.SqlClient"/> I can't find any documentation anywhere that suggests that these formats would affect pooling. Has anyone come across something similiar? A: The tool I was using (dynatrace), that was reporting that the connection pooling was behaving differently based on the connectionstring format appears to be the culprit. A more recent upgrade of dynatrace no longer showed a difference. Apparently this was a phantom issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523626", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Posting on Tumblr using oAuth and C# I'm trying to develop a simple application to interact with Tumblr using v2 APIs. I'm able to go past every step in the oAuth flow (thanks to the documentation found on Twitter) and obtain an authorized and authenticated token and secret. But when it comes to posting, I get a 401 unauthorized error. This is the relevant code snippet: private void post_Click(object sender, System.Windows.RoutedEventArgs e) { url = new Uri("http://api.tumblr.com/v2/blog/*myblog*.tumblr.com/post"); Random random = new Random(); nonce = random.Next(1234000, 9999999).ToString(); TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0); timestamp = Convert.ToInt64(ts.TotalSeconds).ToString(); string method = "POST"; StringBuilder sb = new StringBuilder(); sb.AppendFormat("{0}&", method); sb.AppendFormat("{0}&", upperCaseUrl(HttpUtility.UrlEncode(url.ToString()))); sb.AppendFormat("body%3D{0}%26", upperCaseUrl(HttpUtility.UrlEncode(textBox.Text))); sb.AppendFormat("oauth_consumer_key%3D{0}%26", consumerKey); sb.AppendFormat("oauth_nonce%3D{0}%26", nonce); sb.AppendFormat("oauth_signature_method%3D{0}%26", "HMAC-SHA1"); sb.AppendFormat("oauth_timestamp%3D{0}%26", timestamp); sb.AppendFormat("oauth_token%3D{0}%26", token); sb.AppendFormat("oauth_version%3D{0}%26", "1.0"); sb.AppendFormat("type%3D{0}", "text"); System.Diagnostics.Debug.WriteLine(sb.ToString()); string signingKey = consumerSecret + '&' + secret; HMACSHA1 signing = new HMACSHA1(Encoding.ASCII.GetBytes(signingKey)); byte[] bytearray = Encoding.ASCII.GetBytes(sb.ToString()); MemoryStream stream = new MemoryStream(bytearray); signature = Convert.ToBase64String(signing.ComputeHash(stream)); ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3; StringBuilder header = new StringBuilder(); header.Append("OAuth "); header.AppendFormat("oauth_consumer_key=\"{0}\", ", consumerKey); header.AppendFormat("oauth_token=\"{0}\", ", token); header.AppendFormat("oauth_nonce=\"{0}\", ", nonce); header.AppendFormat("oauth_timestamp=\"{0}\", ", timestamp); header.AppendFormat("oauth_signature_method=\"{0}\", ", "HMAC-SHA1"); header.AppendFormat("oauth_version=\"{0}\", ", "1.0"); header.AppendFormat("oauth_signature=\"{0}\"", upperCaseUrl(HttpUtility.UrlEncode(signature))); System.Diagnostics.Debug.WriteLine(header.ToString()); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = WebRequestMethods.Http.Post; request.Headers.Add("Authorization", header.ToString()); try { HttpWebResponse response = request.GetResponse() as HttpWebResponse; StreamReader reader = new StreamReader(response.GetResponseStream()); if (reader.ReadToEnd() == "201: Created") { control.Invoke((MethodInvoker)delegate { statusText.Text = "Post successfully sent!"; }); } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); } } The function is called upon clicking on a button and get the body text from a text box. The signing part is correct because it has been tested with other services (Twitter etc.) and it still provides valid signatures for Tumblr itself. The Authorization header is pretty much the same I've used to request a token and to authorize it, and the base string only contains the type of the content (text in this case) and the body, apart from the oauth_* standard parameters. I also checked the code with the tools available on hueniverse.com, but still nothing. Probably I'm missing some HTTP header or I'm POSTing the wrong request. Any ideas? Thanks. A: there is a full example on github that may help you... https://github.com/jthigpen/TumblrAPI.NET
{ "language": "en", "url": "https://stackoverflow.com/questions/7523630", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: PHP changing number to words I have stored in my DB a row and in that row SubCategories it has the following 2,56,81 What I need to do is change the numbers to the correct SubCategories ie: 1 = Sports 2 = Camping 3 = Climing etc I thought I would be able to do the following $parts = explode(',', $row['SubCategories']); But now I ran into a slight issue with how do I turn that into the words? A: You'll have to create an array with the word definitions, and then use the numbers as keys: $words = array ( 1 => 'Sports', 2 => 'Camping', 3 => 'Climbing' ); $parts = explode(',', '1,3'); for ( $i = 0; $i < count($parts); $i++ ) { $parts[$i] = $words[ $parts[$i] ]; } See it in action: http://codepad.org/vs2dJi5E A: You're going to have to do a query for those category names, using a WHERE IN() (Details here). However, it would be better to just have a parent column in the row for the subcategory, and query WHERE parent = 2 to get subcategories for that category
{ "language": "en", "url": "https://stackoverflow.com/questions/7523634", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Setting Button Text Color with a Style I have not been able to set the text color of a Button using a predefined style. I must be missing something simple. For example, I have a button: <Button android:id="@+id/calculate_button" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/calculate" android:background="@drawable/rounded_bottom_shape" android:padding="5dp" android:textAppearance="@style/CalcResultStyle"> </Button> And the corresponding style is: <style name="CalcResultStyle"> <item name="android:textSize">12sp</item> <item name="android:textColor">#FFF</item> </style> The size portion works fine, but the color does not. The only workaround I have found is to set the textColor on the actual button, which means changing colors on a number of buttons becomes a pain. I also prefer to set the textColor attribute in my styles using a color reference such as @color/Brown for example, but setting the color using a reference or explicitly seems to make no difference. A: I use this. Maybe it will help you. Can you please tell me what you wrote in rounded_bottom_shape? <Button android:id="@+id/calculate_button" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Calculate" android:background="#454545" android:padding="5dp" style="@style/CalcResultStyle"> </Button>
{ "language": "en", "url": "https://stackoverflow.com/questions/7523640", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: Links to Controller methods: CodeIgniter I'm following this tutorial on CodeIgniter: http://ie.mirror.twsweb-int.com/codeigniter/user_guide/tutorial/index.html 4th page of tutorial: http://ie.mirror.twsweb-int.com/codeigniter/user_guide/tutorial/create_news_items.html In the 4th page of the tutorial, he mentions that you should create your own successful entry page. I want to create a link on the success.php that links back to the index page (calls news_index). IE in terms of URLs, I want a link that goes from http://example.com/codeigniter/index.php/news/create to http://example.com/codeigniter/index.php/news/ How are dynamic URLs like that made on CodeIgniter? A: First load the URL helper in your controller or Autoload file. Then use the site_url() function and just pass news. <?php echo site_url('news');?> A: If you take a look at this page - http://ie.mirror.twsweb-int.com/codeigniter/user_guide/helpers/url_helper.html you can see how the site_url() function works. You just echo site_url('controller/method/segment1/segment2/etc'); so if you wanted to link to the http://example.com/codeigniter/index.php/news/ page you can do <?php echo site_url('news'); ?> and if you wanted to link to the http://example.com/codeigniter/index.php/news/create you can do <?php echo site_url('news/create'); ?> A: you configure them on the routes.php on your codeigniter files. A: You can set site_url/base_url in config.php and load the URL helper in autoload.php file.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523650", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Do you release the object which is being returned in a function? This is for an iPhone APP written in Objective-C using Xcode 4. The quick question is if you have a function which returns an NSArray which was ALLOC'ed in that function, do you have to release it? Here is the more detailed question. I run "Analyse" on my iPhone app and it complains about a possible memory leak on one of my functions The function creates a NSArray out of a NSMutableArray and returns the NSArray. What I am doing is taking an NSMutableArray of class objects and creating an NSArray of NSStrings out of them. I have simplified the code as much as possible to show the problem so don't worry if it looks like its not doing anything useful. -(NSArray *)encodeArray { // I use a NSMutableArray here because I do not know how big the starting // array will be (I hard coded the 20 here for now) NSMutableArray *tmp = [[NSMutableArray alloc]init ]; for (int y = 0;y<20;y++) { // create the NSString object and add it to the tmp array NSString *cardcount = [NSString stringWithFormat:@"%i%",y]; [tmp addObject:cardcount]; } // create the array we will be returning out of the NSMutableArray NSArray *array = [[NSArray alloc] initWithArray:tmp copyItems:YES]; // release the tmp array we created. [tmp release]; // return our array // This is the location of the potential memory leak. SHOULD I RELEASE THIS // If I DO - HOW DO I RETURN IT. return array; } Do I need to release the array? If so, how can I still return it? Maybe there is a better way to perform what I am doing? The overall goal is to create a NSArray so that I can use the NSUserDefaults to save the application state. A: Typically, you want to return an auto-released array in this case. IF you release it in your function, it will be deallocated before your caller has a chance to retain its own copy. If you don't autorelease it, then when your caller retains the returned object you will have a retain count of 2, and it is likely to leak. So, just change your return statement to this: return [array autorelease]; A: As a rule of thumb; if you (by you I mean the current scope of the object) retain/copy/etc an object, then you must release/autorelease it somewhere. Since whoever calls encodeArray didn't do the retaining on array, they are not responsible for releasing it. Therefore, it needs to be set to be autoreleased before being returned: -(NSArray *)encodeArray { // I use a NSMutableArray here because I do not know how big the starting // array will be (I hard coded the 20 here for now) NSMutableArray *tmp = [[NSMutableArray alloc] init]; for (int y = 0;y<20;y++) { // create the NSString object and add it to the tmp array NSString *cardcount = [NSString stringWithFormat:@"%i%",y]; [tmp addObject:cardcount]; } // create the array we will be returning out of the NSMutableArray // Named initializers indicate that the object will be autoreleased: NSArray *array = [NSArray arrayWithArray:tmp]; // release the tmp array we created. [tmp release]; // return our array return array; } Or: -(NSArray *)encodeArray { // I use a NSMutableArray here because I do not know how big the starting // array will be (I hard coded the 20 here for now) NSMutableArray *tmp = [[NSMutableArray alloc] init]; for (int y = 0;y<20;y++) { // create the NSString object and add it to the tmp array NSString *cardcount = [NSString stringWithFormat:@"%i%",y]; [tmp addObject:cardcount]; } // create the array we will be returning out of the NSMutableArray NSArray *array = [[NSArray alloc] initWithArray:tmp]; // release the tmp array we created. [tmp release]; // return our array return [array autorelease]; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7523652", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How the jquery Datepicker set some date to highlight? I'm use jquery Datepicker [link:http://docs.jquery.com/UI/Datepicker] now,and if I want Set some date to highlight, not just highlight the date now, how can I set the option? For example: There I want 24/09/2011, 25/09/2011 and 27/09/2011 to highlight. A: You'll have to use the beforeShowDay option: var dates = []; // array of the dates you want to highlight, stored as strings $('selector').datepicker({ beforeShowDay: function(date) { if ($.inArray(date.toString(), dates) != -1) { return [true, 'highlight']; } } }); See this question for more information: Can the jQuery UI Datepicker be made to disable Saturdays and Sundays (and holidays)?
{ "language": "en", "url": "https://stackoverflow.com/questions/7523653", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why can't I log a user out of facebook in an AIR desktop application? I'm building an AIR desktop app with facebook support using Adobe Flash builder. So far it's working alright, except for one detail, once a user logs in, that session stays open, even if the logout button is pressed. My logout code look like so: protected function logout():void { FacebookDesktop.logout(handleLogout, APP_ORIGIN); } I set APP_ORIGIN to "http://www.facebook.com". I checked Adobe's documentation and they say: appOrigin:String (default = null) — (Optional) The site url specified for your app. Required for clearing html window cookie. But I don't know what that means, what is the 'site url specified by my app'? Where do I get it? Sorry if this is a noob question. A: After trying 20 different workarounds, the only solution that worked for me is: http://nekyouto-tech.blogspot.de/2012/09/fb-adobe-air-logout-bug.html var uri:String = APP_ORIGIN; var params:URLVariables = new URLVariables(); params.next = uri; params.access_token = FacebookDesktop.getSession().accessToken; var req:URLRequest = new URLRequest("https://www.facebook.com/logout.php"); req.method = URLRequestMethod.GET; req.data = params; var netLoader:URLLoader = new URLLoader(); netLoader.load(req); FacebookDesktop.logout(handleLogout, APP_ORIGIN); A: This is what worked for me public function facebookLogout():void { if (FacebookDesktop.getSession() != null) { var uri:String = "http://www.facebook.com/"; var params:URLVariables = new URLVariables(); params.next = uri; params.access_token = FacebookDesktop.getSession().accessToken; var req:URLRequest = new URLRequest("https://www.facebook.com/logout.php"); req.method = URLRequestMethod.GET; req.data = params; var netLoader:URLLoader = new URLLoader(); netLoader.load(req); FacebookDesktop.logout(handleLogout, uri); } } A: Nevermind, I figured it out, what I did was define my app origin as localhost and now it works.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523655", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: compile error: no class template, too many initializers, no matching function I haven't been able to remove compile errors using boost::signals. Any idea would be appreciated. Since I've been porting a program that's written 2 years ago adjusting to the current environment, I'm still new to boost::signals. The codes below are what I modified the original program to simplify for the question purpose. I want a direct solution to my question. But besides that, because there are many questions regarding to boost::signals (but I've given up figuring out which one is the right/closest to my case), I'd give a vote to the ones that suggest in the answer area more proper titles of this question in order to make this a better archived question. boostProve_Doc.h #ifndef FC_H #define FC_H #include <vector> #include "iostream" #include "boost/signal.hpp" typedef boost::signal<void()> PostUpdateSignal; typedef PostUpdateSignal::slot_function_type PSlot; class Doc { public: Doc(uint width, uint height) { std::cout << "In constructor. width= " << width << ", height= " << height << std::endl; } ~Doc() { //Do ... } void connectPostUpdate(PSlot s) { sig.connect(s); } protected: PostUpdateSignal sig; }; #endif boostProve_View.cpp: #include <string> #include <iostream> #include <boost/thread.hpp> #include <boost/date_time.hpp> #include <boost/bind.hpp> #include <boostProve_Doc.h> using namespace std; class View { public: View() { setupCrowd(); } ~View() { //do something... } private: Doc *crowd_; void setupCrowd() { crowd_->connectPostUpdate(&View::correctR); } void correctR() { // do something.. } }; int main(int argc, char** argv) { View c(); return 0; } Error: $ g++ boostProve_View.cpp -I . /usr/lib/libboost_signals.so In file included from /usr/include/boost/function/detail/maybe_include.hpp:13, from /usr/include/boost/function/detail/function_iterate.hpp:14, from /usr/include/boost/preprocessor/iteration/detail/iter/forward1.hpp:47, from /usr/include/boost/function.hpp:64, from /usr/include/boost/thread/future.hpp:20, from /usr/include/boost/thread.hpp:24, from boostProve_View.cpp:3: /usr/include/boost/function/function_template.hpp: In member function ‘void boost::function0<R>::assign_to(Functor) [with Functor = void (View::*)(), R = void]’: /usr/include/boost/function/function_template.hpp:722: instantiated from ‘boost::function0<R>::function0(Functor, typename boost::enable_if_c<boost::type_traits::ice_not::value, int>::type) [with Functor = void (View::*)(), R = void]’ /usr/include/boost/function/function_template.hpp:1064: instantiated from ‘boost::function<R()>::function(Functor, typename boost::enable_if_c<boost::type_traits::ice_not::value, int>::type) [with Functor = void (View::*)(), R = void]’ boostProve_View.cpp:20: instantiated from here /usr/include/boost/function/function_template.hpp:903: error: no class template named ‘apply’ in ‘struct boost::detail::function::get_invoker0<boost::detail::function::member_ptr_tag>’ /usr/include/boost/function/function_template.hpp:913: error: too many initializers for ‘boost::detail::function::basic_vtable0<void>’ /usr/include/boost/function/function_template.hpp: In member function ‘bool boost::detail::function::basic_vtable0<R>::assign_to(F, boost::detail::function::function_buffer&) [with F = void (View::*)(), R = void]’: /usr/include/boost/function/function_template.hpp:915: instantiated from ‘void boost::function0<R>::assign_to(Functor) [with Functor = void (View::*)(), R = void]’ /usr/include/boost/function/function_template.hpp:722: instantiated from ‘boost::function0<R>::function0(Functor, typename boost::enable_if_c<boost::type_traits::ice_not::value, int>::type) [with Functor = void (View::*)(), R = void]’ /usr/include/boost/function/function_template.hpp:1064: instantiated from ‘boost::function<R()>::function(Functor, typename boost::enable_if_c<boost::type_traits::ice_not::value, int>::type) [with Functor = void (View::*)(), R = void]’ boostProve_View.cpp:20: instantiated from here /usr/include/boost/function/function_template.hpp:492: error: no matching function for call to ‘boost::detail::function::basic_vtable0<void>::assign_to(void (View::*&)(), boost::detail::function::function_buffer&, boost::detail::function::basic_vtable0<R>::assign_to(F, boost::detail::function::function_buffer&) [with F = void (View::*)(), R = void]::tag)’ Environment: Ubuntu 10.10, g++ (Ubuntu/Linaro 4.4.4-14ubuntu5) 4.4.5 9/30/11 Update) Thanks to the suggestion, I solved the issue by doing this: crowd_->connectPostUpdate(boost::bind(&View::correctR, this)); A: The problem is that your slot wants a function of type void (*)(), whereas you're giving it an argument of type void (View::*)(). A member function pointer is not the same as a function pointer, unfortunately. One way you could fix this is to make correctR static, which would give it the correct signature. If that fails, you might want to investigate things such as Boost's Bind library. See this part of the C++ FAQ Lite for more on pointers to member functions.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523665", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get the test from the currently selected item in a Gtkiconview? I'm programming in C++ with the GTK+ library (not gtkmm). I have a Gtkiconview where each cell contains an icon and text. I'm relatively new to GTK. How can I get the text field from the currently selected cell? Thanks in advance. EDIT: Found answer at http://www.gtkforums.com/viewtopic.php?f=3&t=55193&p=71166 A: I'm using GTK with python, but here is the general GTK method of doing : * *Get the path to the selected cell(s) *take the first one (or build a for loop if you have to treat all the selected ones) *read the text from the model (here it s assumed that the text is the first one) selected = iconView.get_selected_items() i = selected[0][0] theText = model[i][0] Hope this can show you the way.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523667", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do you create a n by n box of X's in python using string manipulation? (eg. replace, count, find, len, etc.) Get a number from the user (n) and create an n x n box of "X"es on the screen. Without using loops yet. e.g. If they entered 12: XXXXXXXXXXXX XXXXXXXXXXXX XXXXXXXXXXXX XXXXXXXXXXXX XXXXXXXXXXXX XXXXXXXXXXXX XXXXXXXXXXXX XXXXXXXXXXXX XXXXXXXXXXXX XXXXXXXXXXXX XXXXXXXXXXXX XXXXXXXXXXXX The point of this assignment is to use string manipulation to create this box. I can do it with a loop but I'm not sure how to do it with just strings. Can anyone help me out? A: You can "multiply" strings. For example, 'x' * 3 gives you xxx. So: size = int(input()) # convert whatever you have to int print(size * (size * 'X' + '\n')) # print the whole thing This isn't very intuitive (very few languages will let you do that), but getting the input should be straightforward enough. A: You could also use join: print('\n'.join(['X'*12]*12)) A: I would do: size = int(raw_input()) print ('X' * size + '\n') * size, In 3.x, that would be size = int(input()) print(('X' * size + '\n') * size, end='')
{ "language": "en", "url": "https://stackoverflow.com/questions/7523669", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Embedding audio/video in showoff presentations Has anyone figured out a good way to embed video and audio into showoff presentations? Currently I am just putting video on youtube and linking to it like this in the slide: !SLIDE full-page # My Video <iframe title="YouTube video player" width="640" height="410" src="http://www.youtube.com/embed/oHg5SJYRHA0" frameborder="0" allowfullscreen> </iframe> I was wondering if anyone had a better/more efficient way of putting in video and/or audio. Thanks for the help! A: You can host it yourself and try to leverage the browser's capabilities. Here's an approach: <video controls width="360" height="240" poster="placeholder.jpg"> <source src="movie.ogv" type="video/ogg"> <source src="movie.mp4" type="video/mp4"> <object type="application/x-shockwave-flash" width="360" height="240" data="player.swf?file=movie.mp4"> <embed flashvars="file=movie.mp4" allowfullscreen="true" allowscriptaccess="always" id="player1" name="player1" src="player.swf" width="480" height="270" /> <p>You need Flash or a modern browser to view this video</p> </object> </video> It will try leveraging HTML5's video tag on browsers that support ogg or mp4. If that fails, it tries using flash (I used JW Player for this example, but it could be any other one). If all fails, it tells the viewer it needs flash or a modern browser. Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523670", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Converting an Ext.data.TreeStore to JSON I need to stringify an Ext.data.TreeStore (cause I wanna save it to Local Storage), but calling Ext.encode() doesn't work -- I get a circular structure error. Has anyone done this before? A: I can't think of anyway, maybe it's just not possible to save it like it is with normal store. I think your best bet is to save it item by item.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523672", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Server on virtual machine setup? I just started to learn about networking and decided to run my own node.js server The problem is i have almost no idea what im doing :( I installed a virtual ubuntu 64 server, installed nodejs and all the prereqs. I downloaded a sample (https://github.com/ry/node_chat) and dont know if its working or not. i run node on the server file and get "server running at 127.0.0.1:1337" How do i see it on my host (physical) machine? Thanks!! ps i have no domain, virtual is running on NAT network and my physical is behind a router A: In your virtual machine (ubuntu 64bit) start the terminal and run ifconfig This should give you the ip address assigned to your virtual machine (192.168.x.x) something like that. On your host open up a browser and type in http://192.168.x.x: in your case will be 1337. I would recommend you configure your VM to always have that ip static and setup the hosts files on your host machine to point to the ip address, making it easier to get to the server.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523678", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Possible for PHP app built on top of codeigniter to connect to a MySQL AND a mongoDB database at the same time? I have a web application built in codeigniter and hosted with cloudcontrol. I use a normal MySQL database for all of my data persistance, and now I want to use a mongodb database in addition to the MySQL database. I want to use mongodb as a job queue to persist messages between my workers and my application servers. I've gotten the inspiration to do this from this tutorial: http://www.captaincodeman.com/2011/05/28/simple-service-bus-message-queue-mongodb/ * *Is this possible (using two different types of databases simultaniously -- with/without hacking codeigniter, I would assume it is) *Any tips for accomplishing this? ---- EDIT ---- I've included this library in my CI project: https://github.com/alexbilbie/codeigniter-mongodb-library And when I attempt to load it via: $this->load->library('mongo_db'); I run into this: I'm not sure how I can get mysql and mongodb working together... ---- EDIT ---- Nevermind my above question, I improperly set up the config file and confused the error... A: Yes this is possible, out of the box. You need to define two groups in your config, one for mysql and one for mongodb. In your application you can then load in these databases by group name. In your confugration.php: $db['mysql']['hostname'] = "localhost"; $db['mysql']['username'] = "root"; $db['mysql']['password'] = ""; $db['mysql']['dbdriver'] = "mysql"; //... (full config omitted for brevity) $db['mongodb']['hostname'] = "localhost"; $db['mongodb']['username'] = "root"; $db['mongodb']['password'] = ""; $db['mongodb']['dbdriver'] = "mongodb"; //... (full config omitted for brevity) And then you would load in your databases as follows: $mysqlDB = $this->load->database('mysql', TRUE); $mongoDB = $this->load->database('mongodb', TRUE); Take a look at the user guide on how to connect to multiple databases and on how to specify configuration groups.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523682", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: how to display items i want on a toast? my first time doing an app on android. i have 4 strings and a lisview.i want to display the strings whenever user press the items on the listview on a toast. can any one help me on this ? For eg: there are Event 1 ,event 2 and event 3 on my list view. and when user press event 1. it will display the date, time , venue for that event. listview.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub Context context = getApplicationContext(); Toast.makeText(context, "Date: "+date +" " +"Tme: "+ time, Toast.LENGTH_LONG).show(); Toast.makeText(context,"hi",Toast.LENGTH_LONG).show(); } }); This is the codes for extracting it out from googleCalendar date = contentResult[0].substring(10, 21); time = contentResult[0].substring(21, 36); location = contentResult[2].substring(6); description = contentResult[4].substring(18); eventTitle[i] = name; eventDate[i] = date; eventTime[i] = time; eventVenue[i] = location; eventContent[i] = description; event[i] = name + " " + "Date: " +date + " " + "Time: " +time + " " +" Location:"+ location+ "Event Description:"+ description ; A: You would need to set your lists onItemClickListener like so: private OnItemClickListener mMessageClickedHandler = new OnItemClickListener() { public void onItemClick(AdapterView parent, View v, int position, long id) { // Display a messagebox. Toast.makeText(this,"You clicked something!",Toast.LENGTH_SHORT).show(); } }; myList.setOnItemClickListener(mMessageClickedHandler); Of course you would have to input your own data (I'm guessing from a database or web service) to the Toast message indicating the date, time, and location of the event. EDIT: In response to your comment, it sounds like you are new to Android development. You might want to check out this great tutorial to learn how to use SQLite, and the Android SDK in general.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523683", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Native Android development vs web mobile development I have to develop as soon as posible an appication (for android) similar to foursquare, I need to store some details in the phone and retrieve some other data from a web service. I can develop with phonegap or like a native app. What option do you recomend? What are the advantages and disadvantages of each one? A: I think that to develop an app similar to foursquare you need to develop a native app. In fact I believe that you'll need to integrate the app with the use of the GPS and maps... this is not simple but this features are well documented. Good luck :) A: For as soon as possible, choose the platform you're more familiar with. Native development is in Java, Phonegap is in JavaScript and HTML. If you don't know either, hire someone who does - that'll be much faster that learning from scratch. Probably cheaper, too.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523685", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Rails date select assigns month a value when blank I am using Rails date_select as follows: <%= date_select :user, :birthday, {:start_year => Time.now.year, :end_year => 1910,:order => [:day,:month,:year], :prompt => { :day => 'day', :month => 'month', :year => 'year' }}, { :class => "default" } %> When a user forgets to enter a value for the day or month and submit the form when the information is put into the model an error is generated. However the day and month fields also get assigned to 1. This results in the form showing 1 for the day field and January for the month field. How can I stop this from happening?
{ "language": "en", "url": "https://stackoverflow.com/questions/7523686", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jQuery - How to select all checkboxes EXCEPT a specific one? I have a jQuery selector that looks like this ... $("input:checkbox").click(function(event) { // DO STUFF HERE } Everything was working well until I was asked to add another checkbox that has nothing to do with the original checkboxes. How do I create a selector for all checkboxes except for one? Thank you. A: You can do the following: $("input:checkbox").not(":eq(0)") being the "0" the index of your desired checkbox (in this case the first on the DOM) A: Well.. we need to know more about the HTML for a specific answer, but there are two methods that I can think of. 1) if you know the name of the one that you don't want then remove that one with not $("input:checkbox").not('#the_new_checkbox_id').click(function(event) { // DO STUFF HERE } 2) use something that the correct inputs have in common to select them. $("input:checkbox[name=whatItIsNamed]").click(function(event) { // DO STUFF HERE } A: $('input:checkbox:not("#thatCheckboxId")').click(function(event) { // DO STUFF HERE } Just give the checkbox in question a unique id="" A: If all the checkboxes are within another element, you can select all checkboxes within that element. Here is an example with one parent element. <div class="test"><input type="checkbox"><input type="checkbox"></div> The jQuery below also works with multiple divs as well: <div class="test"><input type="checkbox"><input type="checkbox"></div> <div class="test"><input type="checkbox"><input type="checkbox"></div> jQuery: $('.test input:checkbox') That selects just the checkboxes within any element with class "test". -Sunjay03 A: i used this - dont want to select the checkbox named with "subscription" so i used "$(':checkbox:not(checkbox[name=nameofyourcheckboxyoudontwantto]').each(function(){" $('#checked_all').click(function (event) { var checkbox = $(".compare_checkbox").is(":checked"); if (checkbox) { // Iterate each checkbox $(':checkbox:not(:checkbox[name=subscription])').each(function () { this.checked = false; }); } else { $(':checkbox:not(:checkbox[name=subscription])').each(function () { this.checked = true; }); } }); enter image description here
{ "language": "en", "url": "https://stackoverflow.com/questions/7523687", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: how to add an OnClick event on DropDownList's ListItem that is added dynamically? Say I have the following code: DropDownList changesList = new DropDownList(); ListItem item; item = new ListItem(); item.Text = "go to google.com"; changesList.Items.Add(item); How do you dynamically add an OnClick event to item so that google.com will be visited after clicking on the item? A: Add this to your code: DropDownList changesList = new DropDownList(); ListItem item; item = new ListItem(); item.Text = "go to google.com"; item.Value = "http://www.google.com"; changesList.Items.Add(item); changesList.Attributes.Add("onChange", "location.href = this.options[this.selectedIndex].value;"); A: First declare the dropdownlist <asp:DropDownList ID="ddlDestination" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddl_SelectedIndexChanged"> <asp:ListItem Text="Select Destination" Selected="True" /> <asp:ListItem Text="Go To Google.com" Value="http://www.google.com" /> <asp:ListItem Text="Go To Yahoo.com" Value="http://www.yahoo.com" /> <asp:ListItem Text="Go To stackoverflow.com" Value="http://www.stackoverflow.com" /> </asp:DropDownList> Second, in the code behind put this code protected void ddl_SelectedIndexChanged(object sender, EventArgs e) { if (ddlDestination.SelectedIndex > 0) { string goToWebsite = ddlDestination.SelectedValue; Response.Redirect(goToWebsite); } } Hope this helps
{ "language": "en", "url": "https://stackoverflow.com/questions/7523688", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: There is an error in my C# program that occur a stack overflow Exception i have 2 forms. one of them is a form that User select a school class so click OK. I use public int[] grad_class=new int[2]; for save which School class has selected. (list of classes is COMBO BOX) after that i open another new form to edit information of that class' students. i use Switch like this: switch(grad_class) { case "11": something to do..., break; case "12": something to do..., break; } But My problem : I define "grad_class" in form No.1 . so when i want to use that i have to do this: form1 f1 = new form1(); f1.grade_class; and in form No.2 i call this code. in form No.1 i call: form2 f2 = new form2(); OCCUR STACK OVERFLOW EXCEPTION !!! A: You state: form1 f1 = new form1(); f1.grade_class; and in form No.2 i call this code. in form No.1 i call: form2 f2 = new form2(); Well, there's your issue right there. You state that in form1 you call form2.ctor and in form2 you call form1.ctor. So your code looks like this: public form1() { var f2 = new form2(); } public form2() { var f1 = new form1(); } Well, of course this results in a stack overflow. These are mutally recursive functions. You have no return condition, so you exhaust your stack space. Quite simply, what is happening is that the machine has to store state about where to go next when a method is finished. It typically stores this information in space called the stack. The stack is bounded though, so if you push too many "this is where to go next" blocks onto the stack by repeatedly invoking methods, you will exhaust this stack space and hit the infamous stack overflow exception. Edit: You said: namespace TeacherBook { public partial class ChooseGrade : Form { public int[] grad_class=new int[2]; //int array for grade & class (first for Grade,second for class) EditStudent StdForm = new EditStudent(); } namespace TeacherBook { public partial class EditStudent : Form { ChooseGrade ChGrade = new ChooseGrade(); // define form } } Effectively what I suspected. You have a field initializer in ChooseGrade that instantiates a new instance of EditStudent. But EditStudent has a field initializer that instantiates a new instance of ChooseGrade. So when you instantiate a new instance of ChooseGrade, this causes the constructor for EditStudent to be invoked, which causes the constructor for ChooseGrade to be invoked, which causes the constructor for EditStudent to be invoked, and on and on it goes until you overflow your stack.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523691", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-4" }
Q: Attach one element's event handlers into another in JS Let's say I have this part. <input id="text1" type="text" name="text1" onchange="alert('valueA');" /><br /> <input id="text2" type="text" name="text2" /><br /> What I'd want to do is to get the onchange event handler of the input="text1" and attach to another element's event, "text2". So far , it's okay.I can get DOM0 hanlder of input "text1" and attach to text 2 as DOM2 . _handler= $('#text1')[0].onchange; $('#text2').change(function (event) { if (typeof _handler=== "function") { _handler.call(this, event); } But, the problem is , I want to change/add some js codes before attaching into "text2". For example , before attaching into "text2", I want to change "alert('valueA');" into "alert('valueA.This is text2')"; How can I do to achieve this? The alert statement is just the example ,and please don't give solutions something like storing alert message into global variable, show the variable's value..etc. Thanks. A: This cannot be done. You cannot change the code inside of a function. Although Javascript functions are mutable objects, you can only add properties and methods to them, but you can't change the code inside of 'em. If you want to use the evil eval (as you've specified in the comments), you could convert the function to a string, replace whatever text you want inside the function, and then eval it: $('#text2').change(function (event) { eval( '(' + $('#text1')[0].onchange.toString().replace('valueA', 'valueB') + ')()' ); }); And here's the fiddle: http://jsfiddle.net/A4w2W/ But, please please please don't do this. This is the worst possible way to write code, ever!! You should seriously reconsider your approach to this whole matter. A: Technically, no. But there are other solutions. <script type="text/javascript"> <!-- alertvalue = "valueA"; //--> </script> <input id="text1" type="text" name="text1" onchange="alert(alertvalue);" /><br /> <input id="text2" type="text" name="text2" /><br /> <script type="text/javascript"> $('#text2').change(function(event) { alert(alertvalue + '. This is text2'); }); </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/7523701", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Referencing associations with Ruleby on Rails I've recently started messing with a gem called 'ruleby', a rule-engine for Ruby. The documentation for ruleby is a bit sparse, however, and I can't seem to figure out how to properly reference associations for the rule-writing bit. I'm stumped both the 'pattern' part of the rule and also in the executing block part of the rule. For example, let's say I had a rule which would only be executed only when a user submitted a positive review. I could, for instance, write the following: rule :positive_review, [Review, :review, method.review_rating == "positive"] do |v| assert (store positive_review somehow) end So it's at this point that I get lost. I would like to write a rule which would reference back to the user and check the total number of positive reviews that the user of this positive review and possibly execute certain actions based on this number. If anyone could point me in the right direction, I would be greatly appreciative. Thanks. A: I dont quite understand why you are asserting a fact inside of a rule, that should already be done. The github example code probably answered you by now but in case not: First you initialise the engine, I did it like this so I could call on it more than once. rule_engine = Ruleby::Core::Engine.new RULES_ENG = RulesEngineCaller.new(rule_engine) EngineRulebook.new(rule_engine).rules Then you assert your facts @events = Event.all @events.each do |event| @rule_engine.assert event end Then you run your engine @rule_engine.match if you want to add events you can just by calling assert per fact to the existing engine, it will just add to it until you either delete inside the engine or rebuild it. The rulebook is where you add your facts for me I did it programatically: class EngineRulebook < Rulebook def rules Rails.logger.debug "#{Time.now.utc} - Loading Rules into Rulebook" #msg = Notification.new() @rules = Rule.all @rules.each do |rule_name| case #hard coded rule - for auto cleaning when (rule_name.title == "SYSTEM ADMIN - auto-clean delete rule") && (rule_name.group.title == "Notification Admin") rule [Event, :m, m.terminate_flag == 1] do |v| if v[:m].rules.include?(rule_name) == false #output matched rule to console & logfile Rails.logger.info "#{Time.now.utc} - match rule #{rule_name.id} #{rule_name.title} - #{v[:m].ticket_id} - #{v[:m].description}" #add reference so rule doesn't fire again @event = Event.find_by_id(v[:m].id) @event.rules << rule_name v[:m].rules << rule_name modify v[:m] #Retract v[:m] would remove the fact from the rules engine, need to remove all related facts though #so dont use this as other rules may be requires as rules do not fire in order end end end I also did it as a case statement as I was loading rules programmatically. I also put a check in to say has this rule run before because each time you run the engine it will assess all facts, even ones that have already matched. Hopefully you have an answer, if not hopefully this helped.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523706", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: DrawText in CGRect for PDF I'm trying to create a PDF and I have some text. It is longer than one line, so I'm not sure how I need to write it into my context. Do I calculate a CGRect the size of my text first? From there, how would I do word wrap or things like that in creating a PDF? So far all I've been able to do is to just draw a title at the correct location :-. Thanks. A: I recommend using Core Text, as this is a fairly powerful text rendering framework that plays nicely with Quartz. What you're trying to do is easily accomplished using the CTFrame class.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523708", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to create PDF on Silverlight 4 I need to create & display a PDF document in Silverlight 4. PDF document will be generated dynamically. The PDF document will contain plain text & some images. Is there any API I can use to achieve my requirement ? A: You can use this: http://silverlightpdf.codeplex.com/ A: Yes! We create PDF Document. In silverlight By using PDFSharp.dll. It's Opensource dll file. You can download the dll file below Link http://www.pdfsharp.net/Downloads.ashx Please click below link for reference puprpose. http://www.pdfsharp.net/wiki/Booklet-sample.ashx as so many examples as given its easy to understand.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523715", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: JSON Weirdness Needs More Elegant Approach Basically, I'm working on a page that includes four different JSON "thingies" (objetcs,arrays). Forgive my lack of proper terminology. When I get the JSON, it comes in as an object with a bunch of sub-objects, and each "sub-object" looks like this: "token":"government", "title":"Government", "isSelected":false, "type":"CATEGORY", "subtype":"INDUSTRY", "count":12 So the first task is to loop through each JSON and populate a box full of checkboxes, using the title as the label and the isSelected to indicate the checked status. So far, so good. BTW, somewhere aslong the way, I picked up a JS script that checks whether an object is JSON or an array, and according to that "quick & dirty" test, my object is an array. Or an array object (you know, the one is created with [ ] and the other with { })? Anyway, when the end user checks and un-checks checkboxes, I need to keep track of it all and immediately send back changes to the server (when the user clicks a DONE button). The crazy thing is that by looping through the objects, I was able to change the isSelected value to true . . . just not back to false. for(var i = 0; i < $array.length; i++){ $array[z].isSelected = true; } Perhaps I was up too late when I worked on all of this, but using the same approach, I could not change $array[z].isSelected to false when the checkbox got de-selected. In the end, I converted the JSON "thingy" to a string, search and replaced the corresponding values, and then converted the string back into an object. This is all working now, but I feel as though I've just used up a roll of duct tape on something that could have been put together by snapping the pieces together nicely. Question: Did I miss the boat totally and is there a simple way to change values of JSON objects? If so, could you point me in the right direction? A: That JSON thingy is just a string representation of a javascript object. One way of creating an object is var myObject = { "myName": "AName", "myType": "AType" }; This object can be referenced as myObject, with the properties myObject.myName and myObject.myType containing values AName and AType. You should be able to just reference the object by name as objName.token objName.title etc. If you have trouble try parsing the json with javascript then reference the result as above. This should make it easier for you to access, manipulate or delete data in the objects properties as well. The nesting of these as below can be referenced as myObject.moreProperties.prop1 etc var myObject = { "myName": "AName", "myType": "AType", "moreProperties": { "prop1": "vaue1", "prop2": "vaue2", } };
{ "language": "en", "url": "https://stackoverflow.com/questions/7523717", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Dynamic class generation in CoffeeScript What is the best way to dynamically create classes in CoffeeScript, in order to later instantiate objects of them? I have found ways to do it, but I am not sure if there is maybe an even better (or simpler) way to achieve it. Please let me know your thoughts on my code. Let's start with simple non-dynamic classes: class Animal constructor: (@name) -> speak: -> alert "#{@name} says #{@sound}" class Cat extends Animal constructor: (@name) -> @sound = "meow!" garfield = new Cat "garfield" garfield.speak() As expected, garfield says meow! But now we want to dynamically generate classes for more animals, which are defined as follows: animalDefinitions = [ kind: 'Mouse' sound: 'eek!' , kind: 'Lion' sound: 'roar!' ] The first naive attempt fails: for animal in animalDefinitions animal.class = class extends Animal constructor: (@name) -> @sound = animal.sound mutant = new animalDefinitions[0].class "mutant" mutant.speak() The animal we just created, mutant, should be a mouse. However, it says roar! This is because animal.sound only gets evaluated when we instantiate the class. Luckily, from JavaScript we know a proven way to solve this: a closure: for animal in animalDefinitions makeClass = (sound) -> class extends Animal constructor: (@name) -> @sound = sound animal.class = makeClass(animal.sound) mickey = new animalDefinitions[0].class "mickey" mickey.speak() simba = new animalDefinitions[1].class "simba" simba.speak() Now it works as desired, mickey mouse says eek! and simba the lion says roar! But it looks somewhat complicated already. I am wondering if there is an easier way to achieve this result, maybe by accessing the prototype directly. Or am I completely on the wrong track? A: Since sound is a default value for an Animal instance, you can set it as a property on class definition: class Cat extends Animal sound: 'meow!' garfield = new Cat "garfield" garfield.speak() # "garfield says meow!" then for animal in animalDefinitions animal.class = class extends Animal sound: animal.sound mutant = new animalDefinitions[0].class "mutant" mutant.speak() # "mutant says eek!" If you want sound to be overridable, you can do class Animal constructor: (@name, sound) -> @sound = sound if sound? speak: -> console.log "#{@name} says #{@sound}" A: For your immediate problem (which is that the closure in the loop does not capture the current value, but the latest one), there is the do construct: for animal in animalDefinitions do (animal) -> animal.class = class extends Animal constructor: (@name) -> @sound = animal.sound I somehow expected CoffeeScript to take care of that automatically, since this is a common error in JavaScript, but at least with do there is a concise way to write it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523719", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to get a PhoneGap based app to authenticate against an ASP.NET Forms Authentication backend? Has anyone managed to get ASP.NET Forms Authentication (with cookies) working with a PhoneGap based mobile application? I have come across the following questions about managing cookies within PhoneGap and configuring the server properly: * *Where cookie is managed in phonegap app with jquery? *https://github.com/phonegap/phonegap-iphone/issues/190 *Asp.Net Forms Authentication when using iPhone UIWebView But unfortunately neither of these solutions work. The requests coming from a PhoneGap application do not indicate an authenticated user even though when I run the same dashboard.html code as a file in Safari the requests show up as authenticated. A: SOLUTION: cookieless="UseCookies" in web.config FINALLY did it for me: <authentication mode="Forms"> <forms loginUrl="~/Account/LogOn" timeout="2880" cookieless="UseCookies" /> </authentication> REF: https://groups.google.com/forum/?fromgroups#!topic/phonegap/Thj0fS2GDh4 A: If you're creating a cookie in a phonegap app, you're basically creating a cookie for the localhost. When you go out to the .net server, that server can't see that cookie. This is very general, but I hope that this helps a little? A: You may use in web.config , cookieless="UseCookies" in authentication tag A: As I don't know your requirements, this may be a silly answer, but, why you don't consider in this case to deliver the functionality not from a ASP.NET service but from a WCF/Service Stack service? I'm currently working also in a PhoneGap application but it is served by a REST web service (Service Stack) and I think this kind of architecture offers a lot of flexibility.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523721", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: Related Documents in VS 2010? Back in Visual Studio 6 I was able to add a "Related Document" to a project to quickly and easily open Word files I used for version history notes, etc. How do I do this in Visual Studio 2010 if this is available? A: Just use "Add->Existing Item".
{ "language": "en", "url": "https://stackoverflow.com/questions/7523726", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: data missing, but not the record...weird Tomcat/Struts2/JPA2(EclipseLink)/MySql I have several different entities that are exhibiting an intermittent problem and I am puzzled. * *Most of the time EntityX shows up everywhere it is supposed (edit form, lists of EntityX, etc.) *Every so often, an instance of EntityX (or Y or Z) will be blank. Whether retrieved by itself (edit form) or in a list of EntityXs. *By blank, I mean the record shows up but all fields are blank/null. A better example: in a list of EntityXs (in a web page), there is actually a blank row where this instance of EntityX is, but no actual field data. *I go directly to DB and all is well, all data is there. At a loss, I restarted Tomcat and that "fixed" the problem temporarily, but it continues to surface. Also noticed that once all the Tomcat sessions expire after users go home, problem goes away without restart. Tomcat could be the issue I know, but can't imagine what. JPA was my first guess. Any thoughts would be helpful. Thanks.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523728", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Return multiple values from a method Hi guys i'm having a problem regarding returning multiple values from a method. I'm using 'out' to return other value from a method, here the snippet: public DataTable ValidateUser(string username, string password, out int result) { try { //Calls the Data Layer (Base Class) if (objDL != null) { int intRet = 0; sqlDT = objDL.ValidateUser(username, password, out intRet); } } catch (Exception ex) { ErrorHandler.Handle(ex); OnRaiseErrorOccuredEvent(this, new ErrorEventArgs(ex)); } return sqlDT; } then when i compile having a error like this: "The out parameter 'return' must be assigned to before control leaves the current method" Anyone guys can help me solve this. A: That means in all possibilities (inside and outside the if, in the catch), your result variable must be assigned. The best approach would be to give it a default value at the start of the function: public DataTable ValidateUser(string username, string password, out int result) { result = 0; try { //Calls the Data Layer (Base Class) if (objDL != null) { int intRet = 0; sqlDT = objDL.ValidateUser(username, password, out intRet); result = intRet; } //.... A: The parameter result of your method is marked as out. Parameters marked with out must be assigned within your method, i.e result = 5; This is enforced so callers of your method have the guarantee that the parameter that is passed with out is always set once your method finishes. A: You're not setting the result variable in the method. I'm guessing you want to add an extra line such as result = intRet;
{ "language": "en", "url": "https://stackoverflow.com/questions/7523733", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to parse HTML Heading I have this HTML i am parsing. <div id="articleHeader"> <h1 class="headline">Assassin's Creed Revelations: The Three Heroes</h1> <h2 class="subheadline">Exclusive videos and art spanning three eras of assassins.</h2> <h2 class="publish-date"><script>showUSloc=(checkLocale('uk')||checkLocale('au'));document.writeln(showUSloc ? '<strong>US, </strong>' : '');</script> <span class="us_details">September 22, 2011</span> What i want to do it parse the "headline" subheadline and publish date all to seperate Strings A: Just use the proper CSS selectors to grab them. Document document = Jsoup.connect(url).get(); String headline = document.select("#articleHeader .headline").text(); String subheadline = document.select("#articleHeader .subheadline").text(); String us_details = document.select("#articleHeader .us_details").text(); // ... Or a tad more efficient: Document document = Jsoup.connect(url).get(); Element articleHeader = document.select("#articleHeader").first(); String headline = articleHeader.select(".headline").text(); String subheadline = articleHeader.select(".subheadline").text(); String us_details = articleHeader.select(".us_details").text(); // ... A: Android has a SAX parser built into it . You can use other standard XML parsers as well. But I think if ur HTML is simple enough u could use RegEx to extract string.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523738", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do you check if a website is online in C#? I want my program in C# to check if a website is online prior to executing, how would I make my program ping the website and check for a response in C#? A: if (!NetworkInterface.GetIsNetworkAvailable()) { // Network does not available. return; } Uri uri = new Uri("http://stackoverflow.com/any-uri"); Ping ping = new Ping(); PingReply pingReply = ping.Send(uri.Host); if (pingReply.Status != IPStatus.Success) { // Website does not available. return; } A: A Ping only tells you the port is active, it does not tell you if it's really a web service there. My suggestion is to perform a HTTP HEAD request against the URL HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("your url"); request.AllowAutoRedirect = false; // find out if this site is up and don't follow a redirector request.Method = "HEAD"; try { response = request.GetResponse(); // do something with response.Headers to find out information about the request } catch (WebException wex) { //set flag if there was a timeout or some other issues } This will not actually fetch the HTML page, but it will help you find out the minimum of what you need to know. Sorry if the code doesn't compile, this is just off the top of my head. A: You have use System.Net.NetworkInformation.Ping see below. var ping = new System.Net.NetworkInformation.Ping(); var result = ping.Send("www.google.com"); if (result.Status != System.Net.NetworkInformation.IPStatus.Success) return; A: Small remark for Digicoder's code and complete example of Ping method: private bool Ping(string url) { try { HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); request.Timeout = 3000; request.AllowAutoRedirect = false; // find out if this site is up and don't follow a redirector request.Method = "HEAD"; using (var response = request.GetResponse()) { return true; } } catch { return false; } } A: The simplest way I can think of is something like: WebClient webClient = new WebClient(); byte[] result = webClient.DownloadData("http://site.com/x.html"); DownloadData will throw an exception if the website is not online. There is probably a similar way to just ping the site, but it's unlikely that the difference will be noticeable unless you are checking many times a second.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523741", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "40" }
Q: Cannot serialize interface System.Linq.IQueryable I'm faced with an error, "Cannot serialize interface System.Linq.IQueryable." when I try to run my method in my web service. My class is as such: public class AirlineSearchStrong { public Flight_Schedule flightSchedule { get; set; } public Flight_Schedule_Seats_and_Price flightScheduleAndPrices { get; set; } public Airline airline { get; set; } public Travel_Class_Capacity travelClassCapacity { get; set; } } [WebMethod] public IQueryable SearchFlight(string dep_Date, string dep_Airport, string arr_Airport, int no_Of_Seats) { AirlineLinqDataContext db = new AirlineLinqDataContext(); var query = (from fs in db.Flight_Schedules join fssp in db.Flight_Schedule_Seats_and_Prices on fs.flight_number equals fssp.flight_number join al in db.Airlines on fs.airline_code equals al.airline_code join altc in db.Travel_Class_Capacities on al.aircraft_type_code equals altc.aircraft_type_code where fs.departure_date == Convert.ToDateTime(dep_Date) where fs.origin_airport_code == dep_Airport where fs.destination_airport_code == arr_Airport where altc.seat_capacity - fssp.seats_taken >= no_Of_Seats select new AirlineSearchStrong { flightSchedule = fs, flightScheduleAndPrices = fssp, airline = al, travelClassCapacity = altc }); return query; } I've tried IQueryable, IList and returning .ToList() but most of it has turned out to be unsuccessful A: i dont think you can use Iqueryable or Ienumerable as they both do lazy execution and are not serializable. The query gets executed only when you iterate through the collection.so it doesn't make sense to return the query to the caller and asking him to iterate as his end.you need to pass a List or an Array. You may need to change the return type to List<Type> A: Hows about public IEnumerable<AirlineSearchStrong> SearchFlight(string dep_Date, string dep_Airport, string arr_Airport, int no_Of_Seats) { ... return query.ToList(); } Your trying to serialize a representation of the data, the linq query itself, instead of the data resulting from executing the query, thats why it isnt working. You need to enumerate the linq query into an enumerable set, and serialize that. AirlineSearchStrong might need to be marked [Serializable()]
{ "language": "en", "url": "https://stackoverflow.com/questions/7523744", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Why was HTML5 Web Workers support removed from the Android browser in versions 2.2 and up? I'm trying to learn something about JavaScript threading. And from a tutorial I learned about HTML5 API web worker. This API enables JavaScript multi-threading. So I start to figure out how and where can I use this feature. Form http://caniuse.com/#search=worker I find this API is only supported in lower version of Android browser. It is unavailable in Android 2.2 and later. Is this result correct? If it is, is it because of the performance consideration? On which version will this API be available? A: from config.h of Android 2.2. commit 68698168e7547cc10660828f1fb82be7a8efa845 Author: Steve Block Date: Wed Mar 17 14:37:19 2010 +0000 Disable workers This is because V8 on Android does not have the required locking. Also disables channel messaging, which is used only with workers. Bug: 2522239 Change-Id: I6cb91b4048c7e1a0351e422561625397a2e98986 via http://code.google.com/p/android/issues/detail?id=10004#c7 A: * *Web Workers are available again on the built-in Android Browser since 4.4 *Shared Workers are still unsupported on both Android Browser and Chrome for Android. A: Regarding when the API will be available, Web Workers (but not shared workers) are now available in Chrome Mobile, available only for ICS (Android 4.0) and higher devices. Note that the built-in browser on Android 4 does not support workers; you must install Chrome.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523745", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "42" }
Q: How to modify an image before caching it with HJCache? I've been using HJCache to do asynch image loading and caching. It works great, but I have use case where I can't seem to get HJCache to handle. I have an images loaded in a table view, and the same images appears bigger when you select the corresponding tableviewcell. HJCache does a great job of caching the image so it doesn't have to reload it after getting it once. However, I would like to resize the image (and do some cropping, etc) in the tableview thumbnail. The problem is, that it's a very expensive task to do and it ends up lagging the scrolling of the tableview if it's done in the drawRect of the cell. I would like to cache the "modified" image along with the original so that the image processing only has to happen once. How do i get an instance of the already cached UIImage, apply the processing, and then add that one to the cache as well (with a different oid). I only seem to be able to cache an image by giving a URL. Thank you, Matt
{ "language": "en", "url": "https://stackoverflow.com/questions/7523750", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What is the best practice to query dates in SQL when parameterised queries are not possible My brief is to implement a interface which has a method that looks something like 'GetValuesSqlStatement' below: public string SqlPattern { get { ... } } //this varies; eg. "SELECT name FROM someTable WHERE startDate < {0}" public string DatabaseType { get { ... } } //this varies; eg. "SqlServer" public string GetValuesSqlStatement(List<object> paramValues) { //...desired logic here, using DatabaseType, SqlPattern and paramValues } Now, because this must produce an executable SQL statement, I can't use parameters in the execution of the query. And the interface I must implement is non-negotiable. What is the best way to proceed to make sure the dates in the result are interpreted by the database query engine correctly? Assuming that the paramValues contain .NET DateTime objects, how should these be formatted to string before plugging into the SQL pattern string? What is the most common universal date format across must databases? (eg. something like 'dd-mmm-yyyy'). NB: I only really need to worry about Sql Server from 2005 onwards and Oracle 10g onwards. So the SQL must be valid T SQL and PL SQL and mean the same thing in both flavours. A: If you use date format 'yyyy-mm-dd' with any DB you should be fine. This is as per ISO 8601 ( http://www.iso.org/iso/date_and_time_format ) A: I think the only unambiguous date format for SQL Server is YYYYMMDD: * *Bad habits to kick : mis-handling date / range queries *Bad Habits to Kick : Using shorthand with date/time operations Oracle uses a DATE 'YYYY-MM-DD' notation: http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/sql_elements003.htm#BABGIGCJ While there may be a notation which works for both in some scenarios, I doubt there is one which works for both with all possible regional server settings. Like you said, YYYY-MON-DD might be useful - it's Oracle's default. A: I'm providing my own answer to this, even though it's veering from the scope of the question because it might be a useful suggestion for others with a similar question. I just realised I can simply expect each instance (or each customer in a different part of the world) to optionally specify a format string in the latter part of the parameter place-holder. Eg. implementation: public string SqlPattern { get { return "SELECT name FROM someTable WHERE startDate < {0:yyyy-mm-dd}"; } } And then my component doesn't need to worry about how to format the date at all. By default I can use 'yyyymmdd' or even better just use the server's culture to pick a default. Otherwise use the custom-specified pattern. This would be a generic approach applicable to other types that need to be formatted out to a string for SQL too.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523752", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Is it a design flaw that Perl subs aren't lexically scoped? { sub a { print 1; } } a; A bug,is it? a should not be available from outside. Does it work in Perl 6*? * Sorry I don't have installed it yet. A: At the risk of another scolding by @tchrist, I am adding another answer for completeness. The as yet to be released Perl 5.18 is expected to include lexical subroutines as an experimental feature. Here is a link to the relevant documentation. Again, this is very experimental, it should not be used for production code for two reasons: * *It might not be well implemented yet *It might be removed without notice So play with this new toy if you want, but you have been warned! A: If you see the code compile, run and print "1", then you are not experiencing a bug. You seem to be expecting subroutines to only be callable inside the lexical scope in which they are defined. That would be bad, because that would mean that one wouldn't be able to call subroutines defined in other files. Maybe you didn't realise that each file is evaluated in its own lexical scope? That allows the likes of my $x = ...; sub f { $x } A: Yes, I think it is a design flaw - more specifically, the initial choice of using dynamic scoping rather than lexical scoping made in Perl, which naturally leads to this behavior. But not all language designers and users would agree. So the question you ask doesn't have a clear answer. Lexical scoping was added in Perl 5, but as an optional feature, you always need to indicate it specifically. With that design choice I fully agree: backward compatibility is important. A: Are you asking why the sub is visible outside the block? If so then its because the compile time sub keyword puts the sub in the main namespace (unless you use the package keyword to create a new namespace). You can try something like { my $a = sub { print 1; }; $a->(); # works } $a->(); # fails In this case the sub keyword is not creating a sub and putting it in the main namespace, but instead creating an anonymous subroutine and storing it in the lexically scoped variable. When the variable goes out of scope, it is no longer available (usually). To read more check out perldoc perlsub Also, did you know that you can inspect the way the Perl parser sees your code? Run perl with the flag -MO=Deparse as in perl -MO=Deparse yourscript.pl. Your original code parses as: sub a { print 1; } {;}; a ; The sub is compiled first, then a block is run with no code in it, then a is called. For my example in Perl 6 see: Success, Failure. Note that in Perl 6, dereference is . not ->. Edit: I have added another answer about new experimental support for lexical subroutines expected for Perl 5.18. A: In Perl 6, subs are indeed lexically scoped, which is why the code throws an error (as several people have pointed out already). This has several interesting implications: * *nested named subs work as proper closures (see also: the "will not stay shared" warning in perl 5) *importing of subs from modules works into lexical scopes *built-in functions are provided in an outer lexical scope (the "setting") around the program, so overriding is as easy as declaring or importing a function of the same name *since lexpads are immutable at run time, the compiler can detect calls to unknown routines at compile time (niecza does that already, Rakudo only in the "optimizer" branch). A: Subroutines are package scoped, not block scoped. #!/usr/bin/perl use strict; use warnings; package A; sub a { print 1, "\n"; } a(); 1; package B; sub a { print 2, "\n"; } a(); 1; A: Named subroutines in Perl are created as global names. Other answers have shown how to create a lexical subroutines by assigning an anonymous sub to a lexical variable. Another option is to use a local variable to create a dynamically scoped sub. The primary differences between the two are call style and visibility. The dynamically scoped sub can be called like a named sub, and it will also be globally visible until the block it is defined in is left. use strict; use warnings; sub test_sub { print "in test_sub\n"; temp_sub(); } { local *temp_sub = sub { print "in temp_sub\n"; }; temp_sub(); test_sub(); } test_sub(); This should print in temp_sub in test_sub in temp_sub in test_sub Undefined subroutine &main::temp_sub called at ...
{ "language": "en", "url": "https://stackoverflow.com/questions/7523757", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Why doesn't slidedown sometimes gracefully move the content below it? I have 2 buttons on a page with a hidden div underneath each. Each use the same jquery code to slideDown() the hidden object directly underneath. Both 'work' technically as in the outcome is the same, but the transition is very different. The problem is that 1 slides all the content underneath the object nice and smooth like, while the other slides down the hidden stuff over the top of the content underneath - THEN once the slide is complete, all the content underneath snaps below it. What would cause this kind of behaviour?
{ "language": "en", "url": "https://stackoverflow.com/questions/7523760", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to convert urls in content to be links using javascript Convert the url in CONENT to be clickable and make it shorter. For example: Convert the content Balabala The link is http://www.google.com/?aaaaabefaaaaaaaaaaaafeeafaeff3asefffffffffff to Balabala The link is <a href=http://www.google.com/?aaaaabefaaaaaaaaaaaafeeafaeff3asefffffffffff>http://www.google.com/?aa...</a> A: Something like this may help: <div id='result'> </div> <script> var content = "The link is http://www.google.com/?q=hello visit it!"; var result = content.replace(/(http:\/\/(www\.)?([^(\s)]+))/, "<a href='$1'>$3</a>"); document.getElementById('result').innerHTML = result; </script> A: Here is a function that replaces any URLs inside a string with an anchor: function linkify(str){ var url = 'http://www.google.com/?aaaaabefaaaaaaaaaaaafeeafaeff3asefffffffffff'; return str.replace(/https?\:\/\/\S+/, function(url){ var shortUrl = url.substring(0, 20) + '...'; return shortUrl.link(url) }) } linkify("Balabala The link is http://www.google.com/?aaaaabefaaaaaaaaaaaafeeafaeff3asefffffffffff") // "Balabala The link is <a href="http://www.google.com/?aaaaabefaaaaaaaaaaaafeeafaeff3asefffffffffff">http://www.google.com/?aaaaabe...</a>" The "cut" length can be passed as the second argument. A: Something like: len = 15; //set how long of a string you would like to show url = "http://www.google.com/?aaaaabefaaaaaaaaaaaafeeafaeff3asefffffffffff"; //if the original url is smaller than or equal to the length than do nothing //otherwise take the len number of chars and append ... after shorturl = (url.length <= len) ? url : url.substr(0,len) + "..."; link = "<a href='" + url + "'>" + shorturl + "</a>";
{ "language": "en", "url": "https://stackoverflow.com/questions/7523763", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Determining Razor Web Page Hierarchy I have a custom view page class in an ASP.NET Razor web site (not MVC). What I need to be able to do is determine the child pages that are within the parent page. Is there any way to determine this? Thanks A: I don't know if this can be used, but you might be able to. var pageHierachy = HttpContext.Current.Request.Path; It will get the path of the page you're currently on. You might be able to play around with it to make it do exactly what you want it to. Good luck :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7523764", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to use python timeit when passing variables to functions? I'm struggling with this using timeit and was wondering if anyone had any tips Basically I have a function(that I pass a value to) that I want to test the speed of and created this: if __name__=='__main__': from timeit import Timer t = Timer(superMegaIntenseFunction(10)) print t.timeit(number=1) but when I run it, I get weird errors like coming from the timeit module.: ValueError: stmt is neither a string nor callable If I run the function on its own, it works fine. Its when I wrap it in the time it module, I get the errors(I have tried using double quotes and without..sameoutput). any suggestions would be awesome! Thanks! A: Timer(superMegaIntenseFunction(10)) means "call superMegaIntenseFunction(10), then pass the result to Timer". That's clearly not what you want. Timer expects either a callable (just as it sounds: something that can be called, such as a function), or a string (so that it can interpret the contents of the string as Python code). Timer works by calling the callable-thing repeatedly and seeing how much time is taken. Timer(superMegaIntenseFunction) would pass the type check, because superMegaIntenseFunction is callable. However, Timer wouldn't know what values to pass to superMegaIntenseFunction. The simple way around this, of course, is to use a string with the code. We need to pass a 'setup' argument to the code, because the string is "interpreted as code" in a fresh context - it doesn't have access to the same globals, so you need to run another bit of code to make the definition available - see @oxtopus's answer. With lambda (as in @Pablo's answer), we can bind the parameter 10 to a call to superMegaIntenseFunction. All that we're doing is creating another function, that takes no arguments, and calls superMegaIntenseFunction with 10. It's just as if you'd used def to create another function like that, except that the new function doesn't get a name (because it doesn't need one). A: You should be passing a string. i.e. t = Timer('superMegaIntenseFunction(10)','from __main__ import superMegaIntenseFunction') A: One way to do it would be by using partial so that the function, 'superMegaIntenseFunction' is used as a callable (ie without the ()) in the timer or directly inside timeit.timeit. Using partial will pass the argument to the function when it will be call by the timer. from functools import partial from timeit import timeit print(timeit(partial(superMegaIntenseFunction, 10), number=1)) A: Make it a callable: if __name__=='__main__': from timeit import Timer t = Timer(lambda: superMegaIntenseFunction(10)) print(t.timeit(number=1)) Should work A: A note for future visitors. If you need to make it work in pdb debugger, and superMegaIntenseFunction is not in the global scope, you can make it work by adding to globals: globals()['superMegaIntenseFunction'] = superMegaIntenseFunction timeit.timeit(lambda: superMegaIntenseFunction(x)) Note that the timing overhead is a little larger in this case because of the extra function calls. [source]
{ "language": "en", "url": "https://stackoverflow.com/questions/7523767", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "82" }
Q: Prevent page from scrolling when page elements are removed I have a bunch of divs that i am removing from the document using javascript. When this is done, the length of the page is often shortened significantly, and if the user had scrolled down the page, it gets abruptly recentered because the entire page now fits on the window. This causes the user to no longer have their mouse over the same buttons on the page. I'd like to prevent this auto scrolling, but it seems like it may be difficult. I admit that it doesn't make much sense to allow a page to be scrolled off of its contents. Seems like the best I could do is to leave dummy divs as placeholders. Once the user scrolls back up, then clean them up to shrink the page. Are there other, cleaner solutions? A: You could just set the divs to be removed to visibility: hidden (add a class or similar) so they still take up room in the document. At a suitable time you actually remove them and allow the document to reflow.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523771", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Loop_expression in 'for' statement in Objective-C Is it possible to put 'x/10' as a loop_expression in 'for' statement as following: for ( ; numberD != 0 ; x / 10) { resultNumber = numberD / x; NSLog (@"Display %i", resultNumber); numberD /= 10; } I tried to run this way, but it fails to do it. Any suggestions of how to do it, if I need the loop to divide x by 10 every time? A: Untested, but I believe your operator is wrong. for ( ; numberD != 0 ; x /= 10) { resultNumber = numberD / x; NSLog (@"Display %i", resultNumber); numberD /= 10; } A: I would say better use a while loop instead if for loop. while(numberD != 0) { resultNumber = numberD / x; NSLog (@"Display %i", resultNumber); numberD /= 10; x /= 10; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7523772", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: 2^power without using math.pow and multiplication Is there any way to use code 2^power without using math.pow or multiplication operator. So far, I've though of using 2 counters and additions, but my programs doesn't seem to be working. Here is my work thus far. int counter=0; // k int userNumber=0; // p int power=0; int sum=0; cout << "Enter a non-negative number: "; cin >> userNumber; while (userNumber > counter) { power +=2; counter++; power++; } sum = power - 1; // post-condition: Sum = 2^p -1 cout << "The output is " << sum << endl; return 0; A: You can calculate 2^n with bit-manipulation. Simply do: 1 << n; This works because left-shifting with binary numbers is equivalent to multiplying by 2. A: Check out the ldexp function. A: pow = 1; while(userNumber > counter){ pow = pow+pow; counter++; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7523773", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Prototype Javascript Framework - Fetching PHP response So I am using Prototype JavaScript Framework, I have no choice, so other frameworks/library unfortunately will not help. In brief, using Prototype.js I am sending a request to a PHP page like this: <input type="button" value="submit by AJAX" onclick="sendRequest();" /> <script> function sendRequest(){ var url = "a_php_page.php"; var pars = "param={\"some JSON parameters\"}"; //alert(pars); var codeAjax = new Ajax.Request(url, { method :'post', parameters :pars, asynchronous :true, onSuccess : function(result){ document.write(JSON.stringify(result.responseText)); } }); } </script> and the PHP is like this: <?php header('Content-Type:text/plain'); echo "Hello this is a response!!"; ?> I have spent hoursss and yet I cannot get the plain text in the php as a response. I have also tried JSON.stringify(result) and all I see is a rather complex object with request and all kinds of text embedded into it and nowhere does it contains "Hello this is a response!" Here is JSON.stringify(result): { "request" : { "options" : { "method" : "post", "asynchronous" : true, "contentType" : "application/x-www-form-urlencoded", "encoding" : "UTF-8", "parameters" : "param={\"xxxxxx"]}", "evalJSON" : true, "evalJS" : true }, "transport" : { "statusText" : "", "responseText" : "", "response" : "", "onabort" : null, "readyState" : 4, "upload" : { "onloadstart" : null, "onabort" : null, "onerror" : null, "onload" : null, "onprogress" : null }, "onerror" : null, "status" : 0, "responseXML" : null, "onprogress" : null, "onload" : null, "withCredentials" : false, "onloadstart" : null, "responseType" : "" }, "url" : "http://xxxxx/xxxxx.php", "method" : "post", "parameters" : { "param" : "{xxxxxx}" }, "body" : "param={xxxxxx}", "_complete" : true }, "transport" : { "statusText" : "", "responseText" : "", "response" : "", "onabort" : null, "readyState" : 4, "upload" : { "onloadstart" : null, "onabort" : null, "onerror" : null, "onload" : null, "onprogress" : null }, "onerror" : null, "status" : 0, "responseXML" : null, "onprogress" : null, "onload" : null, "withCredentials" : false, "onloadstart" : null, "responseType" : "" }, "readyState" : 4, "status" : 0, "statusText" : "", "responseText" : "", "headerJSON" : null, "responseXML" : null, "responseJSON" : null } A: If you try this, you are not able to get a plain text result from PHP? onSuccess : function(result){ $('some_id').update(result.responseText); } result.responseText should just be a string representing everything that was returned from your PHP script back to prototype's Ajax.Request. A: The problem with document.write() is it writes out where the script executes but on a callback from an asynchronous action that is... where? I can't be sure so prefer to name an element to write to. function sendRequest() { var url = "a_php_page.php"; new Ajax.Updater('element_id', url, { parameters: { param: "some value" }, insertion: 'bottom' }); } Also, I like to pass an object to parameters because Prototype can then encode the data in the best way - it is less work & worry for you. When debugging AJAX get something like Firebug and watch the network tab, filter by XHR (XmlHttpRequest) and your PHP output will be listed along with the HTTP status code. The status code is important because if it isn't "200" then it's not successful and the page will not update. The result dump says "responseText" : "" several times which suggests no content is being returned at all. Make sure to check the content in Firebug too. A: result.status is 0. This indicates your Ajax request could not contact the server. Check your URL and network connection. Interestingly, prototype.js does not treat response code 0 as failure, so you need to test for it: onSuccess : function(result){ if (result.status == 0) { // report error } else { // true success, handle response } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7523774", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Separating two divs with CSS Say I have two divs A and B, which are currently aligned side by side. How can I get A to be separated from B by 50px, while still letting A to take up 70% of the remaining space and B the remaining 30%? EDIT: Accepted the answer a little early before I actually tried. Whoops. JSFiddles: A Tale of Two Divs Now separated, but now with the second one on a second line? A: Try this out if it solves your problem. <html> <head> <style type="text/css"> #Content { border: 3px solid blue; position: relative; height: 300px; } #divA { border: 3px solid red; position: absolute; margin-right: 25px; left: 5px; top: 5px; bottom: 5px; right: 70%; } #divB { border: 3px solid green; position: absolute; right: 5px; top: 5px; bottom: 5px; left: 30%; margin-left: 25px; } </style> </head> <body> <div id="Content"> <div id="divA"> </div> <div id="divB"> </div> </div> </body> </html> A: just set the margin-left or padding-left of div B A: I believe your selected answer will not work: http://jsfiddle.net/cNsXh/ edit: Sorry, the above example was not correct at first. Now it is. /edit As you can see, div #b will move under div #a because margin-left (or padding-left) will be added to the 30%. And because we're mixing percentage with pixel values here, we will not be able to define values that will guarantee to always add up to exactly 100%. You'll need to use a wrapper for div #b which will have 30% width, and not define a width for div #b, but define margin-left. Because a div is a block element it will automatically fill the remaining space inside the wrapper div: http://jsfiddle.net/k7LRz/ This way you will circumvent the CSS < 3 box-model features which oddly enough was defined such that defining a dimension (width / height) will NOT subtract margins and/or paddings and/or border-width. I believe CSS 3's box-model will provide more flexible options here. But, admittedly, I'm not sure yet about cross-browser support for these new features. A: @wrongusername; i know you accept that answer but you can check this solution as well in this you have no need to give extra mark-up & if you give padding to your div it's not affect the structure. CHECK THIS EXAMPLE: http://jsfiddle.net/sandeep/k7LRz/3/ A: http://jsfiddle.net/efortis/HJDWM/ #divA{ width: 69%; } #divB{ width: 29%; margin-left: 2%; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7523778", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How to Implement transaction in function for an XML file? I am passing an XML file to my function. I am making insert/update query for some xmlElements. After executing that query on database,immediatly I will update those xmlElements.Next I will move to another xmlElement . Now I want to implement transaction for this function. Because if any insertion/updateion fails for any xmlElement in middle of that xml file, I want to roll back all my changes in that xml file. I want to rollback changes in database and in my xml file. How can I implement transaction for this function? Thanks & Regards, SJN.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523785", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: EF 4.0 update uniqueidentifier I am trying to update a colum with datatype uniqueidentifier using EF v4.0. I am getting an error Conversion failed when converting from a character string to uniqueidentifier. is there any workarounds for this issue. thanks Ben A: uniqueidentifier -> the value should use Guid type in c#
{ "language": "en", "url": "https://stackoverflow.com/questions/7523796", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I update the frame of a Windows Media Player COM? I have a windows media player COM in my Windows Form project that plays and opens videos admirably. However, I would like to be able to grab the first frame of the loaded video so my program users can preview the video (and, ideally, recognize one video from another). How can I update the frame displayed by the windows media player object? I have tried using the following code at the end of my openFileDialog event response: private void openFileDialog1_FileOk(object sender, CancelEventArgs e) { Text = openFileDialog1.SafeFileName + " - MPlayer 2.0"; //mediaPlayer1.openPlayer(openFileDialog1.FileName); mediaPlayer1.URL = openFileDialog1.FileName; //hopefully, this will load the first frame. mediaPlayer1.Ctlcontrols.play(); mediaPlayer1.Ctlcontrols.pause(); } However, when I run this, the pause command gets ignored (Auto-play for video loading is turned off, so the video won't start playing without calling .play(), above). If I had to guess, I'd say that this is because of some threading operation that calls play, moves on to call pause, calls pause, and then, finally, the play resolves, and the video starts - but because the .pause resolved before the .play, the net effect is the .pause is ultimately unheeded. Firstly, is there a way other than .play(); .pause(); to snag a preview image of the video for the AxWindowsMediaPlayer object? If not, how can I make sure that my .pause() doesn't get ignored? (I know that .play(); .pause(); works in the general case, because I tested with a separate button that invoked those two methods after the video finished loading, and it worked as expected) A: You can't do a lot of things with this COM. However Follow this link and you will find a Class that will help you extract an image from a Video file. You could simply get extract the image and just put it in top of the video, or next to it. This is a simple workaround for your requirement. If not happy with it, I would strongly recommend not using this COM at all and use some other open source video player/plugins. There a lot of real good ones, but I could recommend the VLC Plugin, or try finding another. Good luck in your quest. Hanlet A: While the Windows Media Player Com might not officially support a feature like this, its quite easy to 'fake' this. If you use a CtlControls2, you have access to the built-in "step(1)" function, which proceeds exactly one frame. I've discovered that if you call step(1) after calling pause(), searching on the trackbar will also update the video. It's not pretty, but it works! A: This is a little trick to solve the common step(-1) not working issue. IWMPControls2 Ctlcontrols2 = (IWMPControls2)WindowsMediaPlayer.Ctlcontrols; double frameRate = WindowsMediaPlayer.network.encodedFrameRate; Console.WriteLine("FRAMERATE: " + frameRate); //Debug double step = 1.0 / frameRate; Console.WriteLine("STEP: " + step); //Debug WindowsMediaPlayer.Ctlcontrols.currentPosition -= step; //Go backwards WindowsMediaPlayer.Ctlcontrols.pause(); Ctlcontrols2.step(1);
{ "language": "en", "url": "https://stackoverflow.com/questions/7523797", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Multi Thread vs Single Thread with Asp.net 3.5 I'm currently working with a web application and it has a custom made workflow implemented using .net classes. In that workflow, we update some data base values and send emails to users base on certain business logics. System has 400 concurrent users and 10000 user base and also users can create Purchase request with maximum 52 Purchase request lines. Average Purchase request data load in this application is 10 -15 Purchase request in 10 minutes. User do some actions using web application which is implemented using ASP.net 3.5 and based on user input will need to execute workflow. My Question is due to the the work load we have, We are trying to execute workflow in a separate thread apart from UI thread. Is it a good decision to take or workflow should run on same UI thread ? A: Last time I had to work in a similar scenario we actually had the workflow as a totally separated application from the UI. The reason we did this is because if something failed on the UI it would not affect our workflow, and the other way around. That separate application also was multithreading. After some work I was put out of the project, but I know my Colleague did some more work on it, and he even added a couple of extra Console Applications working at the same time. You can never be too careful. A: When dealing with web applications, the thing you have to keep in mind with threading is "Will this task take a long time to complete". If Not, then there is no reason to spin off a thread. Threading doesn't magically make your app work faster, particularly if you just have to wait for the results anyways. If the work does take a significant amount of time, then spinning off to a background thread would allow the IIS worker processes to be recycled and accept new incoming requests. Spinning off more threads can actually cause more load on your system, since you're now firing up 2x as many threads, each with it's own stack, and other resources. It only makes sense if you get an actual gain out of it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523799", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Trying to manipulate lines in a document with regex I have a text document that was poorly formatted for my purposes, and I had to make some changes. But now I have another problem, which is a lot of sentences "stranded" on their own, like this: \n [some text here, bla bla bla.]\n \n Does anyone know of a way to represent a sentence with regular expressions? I want to join these sentences with the paragraph above or below. I swear I searched both Google and this site before asking. Edit: Sorry, I lost access to my original post, and couldn't comment on Amber's answer. I'll register an account for future questions. Plus, I neglected to mention the fact that I'm using Notepad++. A: How about looking for any pair of newlines with only a single terminating punctuation mark between them? E.g. \n([^\n.?!]+[.?!][^\n.?!]*)\n and then just replace that with... '\n\1 '
{ "language": "en", "url": "https://stackoverflow.com/questions/7523803", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Strange legend using aes(colour) in ggplot2 I have this code: x <- seq(-600, 600, length=10000) dat1 <- data.frame(x=x, SD=400, val = (1/(1+10^(-x/400)))) dat2 <- data.frame(x=x, SD=200, val = (1/(1+10^(-x/200)))) dat3 <- data.frame(x=x, SD=600, val = (1/(1+10^(-x/600)))) dat <- rbind(dat1, dat2, dat3) ggplot(data=dat, aes(x=x, y=val, colour=SD)) + geom_line(aes(group=SD)) What I expected is to have 3 curves and I do. However the legend shows that there are 6 curves - for SD 100, 200, 300, 400, 500, 600 instead of only 200, 400, 600. Why is that and how do I fix this? A: The legend is not indicating the presence of 6 curves. You've mapped the continuous variable SD to the aesthetic colour, which results in a continuous colour scale, i.e. a gradient. If you want only the three values in the legend, try wrapping SD in factor: ggplot(data=dat, aes(x=x, y=val, colour=factor(SD))) + geom_line(aes(group=SD))
{ "language": "en", "url": "https://stackoverflow.com/questions/7523804", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is it possible to fix SlickGrid's column-resizing bug? I've recently (re-)discovered SlickGrid, and am considering using it for a project I'm working on, mainly because in many ways it appears to be the most versatile and powerful and performant (forgive the neologism) JavaScript grid yet created. There are only a few problems. The first is that it very annoyingly doesn't resize its columns the way users expect: at the same time that they resize the column header. Many would be quick to point out that this has no practical implication, but I value usability and elegance greatly, and this damages both. As far as usability, the first time I tried to resize a column I really thought it was not working. Undoubtedly others will be confused as well. As far as elegance, it just completely breaks the sense of actually physically manipulating objects. I don't actually need all the power that SlickGrid gives for this current project, but if its weaknesses can be overcome I see no reason not to use it for everything when I need a grid. In most respects it is extremely impressive. A: Setting the syncColumnCellResize option when initialising the grid forces the grid to resize the columns synchronously as the user resizes the column header. var grid; var columns = [ ... columns stuff var options = { ... other options, syncColumnCellResize: true }; var data = [ ... data stuff grid = new Slick.Grid("#myGrid", data, columns, options);
{ "language": "en", "url": "https://stackoverflow.com/questions/7523806", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Jquery-Tools Tabs AJAX Caching... so close yet so far JqueryTools Tabs is really wonderful [http://flowplayer.org/tools/demos/tabs/ajax.html]. The only catch is that these AJAX-enabled tabs don't do any caching. So each tab click means a fresh reload each time. We're almost there though, take a look at these threads : [http://flowplayer.org/tools/forum/25/74554] and [http://flowplayer.org/tools/forum/25/32829]. Unfortunately I haven't gotten it to work with my implementation which is essentially this one [http://flowplayer.org/tools/demos/tabs/ajax.html]. Has anybody solved this one? Please share it, many JqueryTools Tabs users all around the world will be eternally grateful !! (At least one will be). Thank you, Gene A: If you really don't wanna reload each tab for each click, why don't you render the whole page at once. One of the reasons you can load the tabs via ajax is so that you can get updates without having to reload the whole page. If you want the tabs to be cached, load the whole page at once, and you'll save yourself the overhead of a request for each tab the first time it loads. Ajax is great for some things, but unnecessary for others.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523809", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can't get publishProgress to work properly. Help? I have an AsyncTask that takes urls and gets the content length for all urls that are passed through. I'd like to have the progress bar update in the titlebar and have an alertbox display when it is done getting the final value. But I'm having trouble understanding how to make this all function together. The code I have now moves the progress bar but will not have the alertbox show. I don't have a custom title bar, instead I'm calling the requestWindowFeature(FEATURE_PROGRESS). Any help would be appreciated. This is my Async Class private class MyClass extends AsyncTask<URL, Integer, Float> { protected Float doInBackground(URL... urls) { try { for(int i = 0; i<urls.length; i++) { url = urls[i]; urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.setDoOutput(true); urlConnection.connect(); size = urlConnection.getContentLength(); total += size; while(progress<total) { progress++; publishProgress(progress); } } } catch(MalformedURLException e) { e.printStackTrace(); } catch(IOException iox) { iox.printStackTrace(); } finally { urlConnection.disconnect(); } return total; } protected void onProgressUpdate(Integer... values) { setProgressBarVisibility(true); setProgress(values[0]); } Edit: I understand that publishProgress passes data to onProgressUpdate from the doInBackground method. But with this code above, all the urls content length are being added to "total". And I think the above code is correct. My implementation of this is: Push a button from the main class. That button passes all the urls to the AsyncTask. While the urls get the length and add to total (in background) a progress bar appears in the title bar until the background work is done. Then an alert dialog prompts the user for a choice. What is happening though is the progress bar reaches the end and the alert dialog doesn't show up. Before I started adding this progress bar, the alert dialog showed up. Now it doesn't. How can I go about getting the progress bar to increment properly with the url content length....dismiss the progress bar.....then load the alert dialog in onPostExecute? protected void onPostExecute(final Float result) { setProgressBarVisibility(false); AlertDialog.Builder alertbox = new AlertDialog.Builder(Vacation.this); alertbox.setMessage(TEXT STUFF); alertbox.setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface arg0, int arg1) { } }); alertbox.setNegativeButton("No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface arg0, int arg1) { } }); alertbox.show(); } A: sat is right but u can do that in onPostExecute() methode which is having the UI thread access always remember only doInBackground() does not have UI thread access rest all 3 methode has. if you need more than be specific and show the code where you are finding difficulty.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523811", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I process multiple files concurrently? I've a scenario where web archive files (warc) are being dropped by a crawler periodically in different directories. Each warc file internally consists of thousand of HTML files. Now, I need to build a framework to process these files efficiently. I know Java doesn't scale in terms of parallel processing of I/O. What I'm thinking is to have a monitor thread which scans this directory, pick the file names and drop into a Executor Service or some Java blocking queue. A bunch of worker threads (maybe a small number for I/O issue) listening under the executor service will read the files, read the HTML files within and do respective processing. This is to make sure that threads do not fight for the same file. Is this the right approach in terms of performance and scalability? Also, how to handle the files once they are processed? Ideally, the files should be moved or tagged so that they are not being picked up by the thread again. Can this be handled through Future objects ? A: In recent versions of Java (starting from 1.5 I believe) there are already built in file change notification services as part of the native io library. You might want to check this out first instead of going on your own. See here A: My key recommendation is to avoid re-inventing the wheel unless you have some specific requirement. If you're using Java 7, you can take advantage of the WatchService (as suggested by Simeon G). If you're restricted to Java 6 or earlier, these services aren't available in the JRE. However, Apache Commons-IO provides file monitoring See here. As an advantage over Java 7, Commons-IO monitors will create a thread for you that raises events against the registered callback. With Java 7, you will need to poll the event list yourself. Once you have the events, your suggestion of using an ExecutorService to process files off-thread is a good one. Moving files is supported by Java IO and you can just ignore any delete events that are raised. I've used this model in the past with success. Here are some things to watch out for: * *The new file event will likely be raised once the file exists in the directory. HOWEVER, data will still be being written to it. Consider reasonable expectations for file size and how long you need to wait until a file is considered 'whole' *What is the maximum amount of time you must spend on a file? *Make your executor service parameters tweakable via config - this will simplify your performance testing Hope this helps. Good luck.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523816", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Event JavaScript when Esc on click? How to make the event when the Esc key is pressed; please give me an example of an alert ();. A: document.body.onkeyup = function(e){ if(e.keyCode == 27){ alert('Yay'); } } A: if your interested in using jquery, check this code <script type="text/javascript"> $("CssSelector").on("keyup", HandleKeyEvent(e)); function HandleKeyEvent(e) { if ( e.keyCode == 27 && e.key == "Escape" ) { //--> Do Something alert("It Works"); } } ); </script> Sorry I have just realized that this is an old question from 2011.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523820", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Cross Browser Compatibility and docType declaration I designed a webpage and tested it on firefox, chrome & IE-8. The webpage is displayed fine on firefox & chrome but not on IE. In the process of making it compatible, I changed the DocType declaration from HTML 4.01 Transitional to XHTML 1.1 to HTML 4.01 Strict. This failed to fix the cross compatability. Also, I found that the webpage design is messed up on firefox & chrome when I change the DocType from HTML 4.01 Transitional to XHTML 1.1. Now my question is, if DocType does matter in designing webpages, which one should I use for cross compatibilty? Is there another solution that does not involve DocType? A: It sounds like you're only changing the DOCTYPE, but not changing any HTML or CSS. This is something you'll need to do since each DOCTYPE will be rendered differently. I recommend one of the STRICT ones - HTML4.01 STRICT, XHTML1.0 STRICT, or XHTML1.1, depending on your needs. Or HTML5 (although I haven't used it yet myself). Also, make sure you've got the doctype declaration correct and have included the xmlns in the html tag if you're using XHTML. For reference: * *QuirksMode has a lot a great information, including browser compatibility info. *A List Apart also has really helpful articles. *I refer to the HTML and CSS2 Specifications often. And to check your doctypes: HTML 4.01 Strict, Transitional, Frameset <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd"> XHTML 1.0 Strict, Transitional, Frameset <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd"> XHTML 1.1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> HTML5 <!DOCTYPE html>
{ "language": "en", "url": "https://stackoverflow.com/questions/7523822", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to pass NSDictionary values to UITableViewCell properly Hey guys I have a problem, I have a NSDictionary of NSArrays and im trying to set up alphabetical sections so AAAAA, BBBB, CCCC.... etc however when I pass my values over its printing out all of the A values right into one uitableviewcell then the B's in the next... which is not right what Im after. Im hoping to have alphabetical sections with one NSArray/Dictionary value per UItableviewcell.. this is how Im currently setting it up, I think maybe I might be missing an If statment however Im just not exactly sure how to do this so would like some help if possible.. thanks in advance. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; } cell.accessoryType = UITableViewCellAccessoryNone; //make sure their are no tickes in the tableview cell.selectionStyle = UITableViewCellSelectionStyleNone; // no blue selection // Configure the cell... if(indexPath.row < [self.arraysByLetter count]){ NSArray *keys = [self.arraysByLetter objectForKey:[self.sectionLetters objectAtIndex:indexPath.row]]; NSString *key = [keys description]; NSLog(@"thingy %@", key); cell.textLabel.text = key; } return cell; } This is what it looks like on the emulator UPdate I made chages to my code as suggested below and now this is what happens... when emulator first loads I then scroll to the bottom of the list and back to the top and it looks like this. A: NSString *key = [keys description]; Here you're setting the text to be the string representation of ALL the keys. :) I think you want this (and I hope I've interpreted your code properly) NSArray *keys = [self.arraysByLetter objectForKey:[self.sectionLetters objectAtIndex:indexPath.section]]; NSString *key = [keys objectAtIndex:indexPath.row]; NSLog(@"thingy %@", key); So, get the KeysArray using the IndexPath section, then get the value of the cell using the IndexPath row.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523827", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to use IF Statement or Case when in Where Clause SQL Please help, how can I insert If or Case in Where clause This is part of my code and I receive errors however I insert If or Case When. This is the error Msg 156, Level 15, State 1, Procedure p5, Line 35 Incorrect syntax near the keyword 'BETWEEN' AS WITH t1 AS (SELECT 0 n UNION ALL SELECT 0 n UNION ALL SELECT 0 UNION ALL SELECT 0) ,Calendario AS (SELECT DATEADD(day, (ROW_NUMBER() OVER (ORDER BY a.n)), @CheckIn) AS Fetcha FROM t1 a, t1 b, t1 c, t1 d, t1 e, t1 f) SELECT @noches= convert(int,@Checkout - @CheckIn), @Sum = SUM(dbl*@canthabdbl),@SumSGL = SUM(SGL*@canthabsgl), @SumTPL = SUM(isnull(Triple,0)*@canthabtpl),@SumCUAD = SUM(isnull(Cuad,0)*@canthabcdpl),@SumChd = SUM(isnull(Chd,0)*@cantchd), @totalhab = (@Sum+@SumSGL+@SumTPL+@SumCUAD+@SumChd), @average = (@totalhab/@noches) FROM hotelsnew JOIN Calendario ON Calendario.Fetcha BETWEEN Desde AND Hasta+1 WHERE CASE WHEN @checkout>hasta THEN Calendario.Fetcha BETWEEN @CheckIn+1 AND @CheckOut-1 AND Hoteles = @IDHotel AND tipohabitacion = @IDTipo AND Id_plan = @IDPlan ELSE Calendario.Fetcha BETWEEN @CheckIn AND @CheckOut AND Hoteles = @IDHotel AND tipohabitacion = @IDTipo AND Id_plan = @IDPlan END RETURN A: Untested guess. See if this works. WHERE ( @checkout>hasta AND Calendario.Fetcha BETWEEN @CheckIn+1 AND @CheckOut-1 AND Hoteles = @IDHotel AND tipohabitacion = @IDTipo AND Id_plan = @IDPlan ) OR ( @checkout <= hasta AND Calendario.Fetcha BETWEEN @CheckIn AND @CheckOut AND Hoteles = @IDHotel AND tipohabitacion = @IDTipo AND Id_plan = @IDPlan ) A: Try this: WHERE Calendario.Fetcha BETWEEN CASE WHEN @checkout>hasta THEN @CheckIn+1 ELSE @CheckIn END AND CASE WHEN @checkout>hasta THEN @CheckOut-1 ELSE @CheckOut END AND Hoteles = @IDHotel AND tipohabitacion = @IDTipo AND Id_plan = @IDPlan A: CASE statements typically go in the select part, like this: SELECT CASE ContactType WHEN 'Person' THEN LastName ELSE BusinessName END FROM Contacts For your WHERE clause, I would recommend rewriting it to be something like this: WHERE (@checkout>hasta AND Calendario.Fetcha BETWEEN @CheckIn+1 AND @CheckOut-1 AND Hoteles = @IDHotel AND tipohabitacion = @IDTipo AND Id_plan = @IDPlan) OR (@checkout<=hasta AND Calendario.Fetcha BETWEEN @CheckIn AND @CheckOut AND Hoteles = @IDHotel AND tipohabitacion = @IDTipo AND Id_plan = @IDPlan)
{ "language": "en", "url": "https://stackoverflow.com/questions/7523829", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Cufon not working after ajax request Initially cufon replaces the main page text. After loading another page file, cufon doesn't apply it's replacement to the newly loaded content. Why? I added cufon.refresh(); as the very last of the chained functions. I notice cufon is trying to replace the font, how ever it seems like the default font is overriding the cufon font. I notice the cufon changed font briefly before it defaults back to the regular font. So I know it's attempting to replace the text. Maybe my order of operations are wrong? Any help is appreciated. If my code is messy as is, feel free to clean it up, always open for suggestions. Here's my code: $(document).ready(function(){ $.ajaxSetup({cache:false}); // Hide Colored Lines $("div#line-2,div#line-3,div#line-4,div#line-5,div#line-6,div#line-7,div#line-8,div#line-9,div#line-10").hide(); $("div#linksContainer a, div#meContainer a").click(function(){ var toLoad = $(this).attr('href')+' #homeContent'; var post_id = $(this).attr("rel"); if(post_id == "25"){ $("#home").fadeIn(2400); $("div#line-1").animate({height: 'toggle'},1200); $("div#line-2,div#line-3,div#line-4,div#line-5,div#line-6,div#line-7,div#line-8,div#line-9,div#line-10").hide(); }else if(post_id == "5"){ $("#home").hide('fast'); $("div#line-2").animate({height: 'toggle'},1200); $("div#line-1,div#line-3,div#line-4,div#line-5,div#line-6,div#line-7,div#line-8,div#line-9,div#line-10").hide(); }else if(post_id == "7"){ $("#home").hide('fast'); $("div#line-3").animate({height: 'toggle'},1200); $("div#line-2,div#line-1,div#line-4,div#line-5,div#line-6,div#line-7,div#line-8,div#line-9,div#line-10").hide(); }else if(post_id == "337"){ $("#home").hide('fast'); $("div#line-4").animate({height: 'toggle'},1200); $("div#line-2,div#line-3,div#line-1,div#line-5,div#line-6,div#line-7,div#line-8,div#line-9,div#line-10").hide(); }else if(post_id == "13"){ $("#home").hide('fast'); $("div#line-5").animate({height: 'toggle'},1200); $("div#line-2,div#line-3,div#line-4,div#line-1,div#line-6,div#line-7,div#line-8,div#line-9,div#line-10").hide(); }else if(post_id == "339"){ $("#home").hide('fast'); $("div#line-6").animate({height: 'toggle'},1200); $("div#line-2,div#line-3,div#line-4,div#line-5,div#line-1,div#line-7,div#line-8,div#line-9,div#line-10").hide(); }else if(post_id == "341"){ $("#home").hide('fast'); $("div#line-7").animate({height: 'toggle'},1200); $("div#line-2,div#line-3,div#line-4,div#line-5,div#line-6,div#line-1,div#line-8,div#line-9,div#line-10").hide(); }else if(post_id == "212"){ $("#home").hide('fast'); $("div#line-8").animate({height: 'toggle'},1200); $("div#line-2,div#line-3,div#line-4,div#line-5,div#line-6,div#line-7,div#line-1,div#line-9,div#line-10").hide(); }else if(post_id == "11"){ $("#home").hide('fast'); $("div#line-9").animate({height: 'toggle'},1200); $("div#line-2,div#line-3,div#line-4,div#line-5,div#line-6,div#line-7,div#line-8,div#line-1,div#line-10").hide(); }else if(post_id == "16"){ $("#home").hide('fast'); $("div#line-10").animate({height: 'toggle'},1200); $("div#line-2,div#line-3,div#line-4,div#line-5,div#line-6,div#line-7,div#line-8,div#line-9,div#line-1").hide(); } $('#homeContent').hide('fast',loadContent); $('#load').remove(); $('#wrapper').append('<span id="load">LOADING...</span>'); $('#load').fadeIn('normal'); function loadContent(){ $("#homeContent").load(toLoad,{id:post_id},showNewContent()); } function showNewContent(){ $("#homeContent").show('fast',hideLoader()); } function hideLoader() { $('#load').fadeOut('normal',changeFonts()); } function changeFonts(){ Cufon.refresh(); } return false; }); Cufon.replace('h1, h2, p, strong', { fontFamily: 'Museo 300' }); Cufon.replace('h3, h4, h5, h6, #postContent a', { fontFamily: 'Quicksand Book' }); }); A: change $('#load').fadeOut('normal',changeFonts()); to $('#load').fadeOut('normal',changeFonts); and it should be alright. Same goes for your other animation/load callbacks, you want to pass the function objects, not their return value.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523834", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: AttributeError: 'function' object has no attribute 'my_args' How can I get access to my_args list data type in __main__? test1.py #!/usr/bin/env python def main(): print 'main function' one() def one(): print 'one function' my_args = ["QA-65"] def two(): print 'two function' if __name__ == "__main__": main() getattr(my_args, pop) A: You can if you return them from one(): #!/usr/bin/env python def main(): print 'main function' args = one() # returns my_args, which i'm assigning to args print 'i got args from one():', args print args.pop() def one(): print 'one function' my_args = ["QA-65"] return my_args def two(): print 'two function' if __name__ == "__main__": main() #getattr(my_args, pop) # ^^^ Moved this up to main() ^^^ Outputs: main function one function i got args from one(): ['QA-65'] QA-65 A: You can do this using global. #!/usr/bin/env python def main(): print 'main function' one() def one(): print 'one function' global my_args my_args = ["QA-65"] def two(): print 'two function' if __name__ == "__main__": main() print my_args.pop() Demo. Just because you can doesn't mean you should!
{ "language": "en", "url": "https://stackoverflow.com/questions/7523835", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Evaluate[] seems to not work inside Button[] Any idea how to get this to work? y = {}; Table[Button[x, AppendTo[y, Evaluate[x]]], {x, 5}] Result: Click [1] , click [2], get {6,6} I'm trivializing the actual task, but the goal is to set what a button does inside a Map or a Table or ParallelTable. Please Help! EDIT Figured it out... Evaluate works at first level only. Here, it's too deep. So I used ReplaceRule: Remove[sub]; y = {}; Table[Button[x, AppendTo[y, sub]] /. sub -> x, {x, 5}] A: Replacement rules and pure functions offer concise alternatives to With. For example: y={}; Range[5] /. x_Integer :> Button[x, AppendTo[y, x]] or y = {}; Replace[Range[5], x_ :> Button[x, AppendTo[y, x]], {1}] or y = {}; Array[Button[#, AppendTo[y, #]] &, {5}] or y = {}; Button[#, AppendTo[y, #]] & /@ Range[5] For another example comparing these techniques, see my post here, where they are applied to a problem of creating a list of pure functions with parameter embedded in their body (closures). A: This is a job for With. With is used to insert an evaluated expression into another expression at any depth -- even into parts of the expression that are not evaluated right away like the second argument to Button: y = {}; Table[With[{x = i}, Button[x, AppendTo[y, x]]], {i, 5}] In simple cases like this, some people (myself included) prefer to use the same symbol (x in this case) for both the With and Table variables, thus: y = {}; Table[With[{x = x}, Button[x, AppendTo[y, x]]], {x, 5}] A: Evaluate works at first level only. Here, it's too deep. So I used ReplaceRule: Remove[sub]; y = {}; Table[ Button[x, AppendTo[y, sub]] /. sub -> x, {x, 5}]
{ "language": "en", "url": "https://stackoverflow.com/questions/7523836", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: How do I set the correct content type in a WCF binding without using app.config? I have created a service reference to the CRM 2011 Organization.svc from a test console application. Everything works perfectly using the binding generated in the app.config. (Example of the service hosted by Microsoft here.) This now needs to be moved into our "real" application and hosted in a DLL that will be deployed to the GAC. In following the app's conventions, the binding needs to be generated by code. I've started off trying to use the binding we use for our other WCF services: BasicHttpBinding binding = new BasicHttpBinding(); binding.SendTimeout = TimeSpan.FromMinutes(1); binding.OpenTimeout = TimeSpan.FromMinutes(1); binding.CloseTimeout = TimeSpan.FromMinutes(1); binding.ReceiveTimeout = TimeSpan.FromMinutes(10); binding.AllowCookies = true; binding.BypassProxyOnLocal = false; binding.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard; binding.MessageEncoding = WSMessageEncoding.Text; binding.TextEncoding = System.Text.Encoding.UTF8; binding.TransferMode = TransferMode.Buffered; binding.UseDefaultWebProxy = true; binding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly; binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows; Unfortunately at the point the WCF service is called (using the Execute method with an OrganizationRequest), this error occurs: System.ServiceModel.ProtocolException: Content Type text/xml; charset=utf-8 was not supported by service http://server:5555/xrmservices/2011/organization.svc. The client and service bindings may be mismatched. I'm not sure what the specific problem is with the binding, but my attempts at converting it to code have failed with the same error so far. Here's the working binding defined in app.config: <bindings> <customBinding> <binding name="CustomBinding_IOrganizationService"> <security defaultAlgorithmSuite="Default" authenticationMode="SspiNegotiated" requireDerivedKeys="true" securityHeaderLayout="Strict" includeTimestamp="true" keyEntropyMode="CombinedEntropy" messageProtectionOrder="SignBeforeEncryptAndEncryptSignature" messageSecurityVersion="WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10" requireSecurityContextCancellation="true" requireSignatureConfirmation="false"> <localClientSettings cacheCookies="true" detectReplays="true" replayCacheSize="900000" maxClockSkew="00:05:00" maxCookieCachingTime="Infinite" replayWindow="00:05:00" sessionKeyRenewalInterval="10:00:00" sessionKeyRolloverInterval="00:05:00" reconnectTransportOnFailure="true" timestampValidityDuration="00:05:00" cookieRenewalThresholdPercentage="60" /> <localServiceSettings detectReplays="true" issuedCookieLifetime="10:00:00" maxStatefulNegotiations="128" replayCacheSize="900000" maxClockSkew="00:05:00" negotiationTimeout="00:01:00" replayWindow="00:05:00" inactivityTimeout="00:02:00" sessionKeyRenewalInterval="15:00:00" sessionKeyRolloverInterval="00:05:00" reconnectTransportOnFailure="true" maxPendingSessions="128" maxCachedCookies="1000" timestampValidityDuration="00:05:00" /> <secureConversationBootstrap /> </security> <textMessageEncoding maxReadPoolSize="64" maxWritePoolSize="16" messageVersion="Default" writeEncoding="utf-8"> <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" /> </textMessageEncoding> <httpTransport manualAddressing="false" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" allowCookies="false" authenticationScheme="Anonymous" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" keepAliveEnabled="true" maxBufferSize="65536" proxyAuthenticationScheme="Anonymous" realm="" transferMode="Buffered" unsafeConnectionNtlmAuthentication="false" useDefaultWebProxy="true" /> </binding> </customBinding> </bindings> Does anyone know how to set the correct binding in code and/or read the binding from XML? A: I just had the same task to solve. This worked for me (for http). var security = SecurityBindingElement.CreateSspiNegotiationBindingElement(); security.DefaultAlgorithmSuite = SecurityAlgorithmSuite.Default; security.SecurityHeaderLayout = SecurityHeaderLayout.Strict; security.IncludeTimestamp = true; security.KeyEntropyMode = SecurityKeyEntropyMode.CombinedEntropy; security.MessageProtectionOrder = MessageProtectionOrder.SignBeforeEncryptAndEncryptSignature; security.MessageSecurityVersion = MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10; security.LocalClientSettings.CacheCookies = true; security.LocalClientSettings.DetectReplays = true; security.LocalClientSettings.ReplayCacheSize = 900000; security.LocalClientSettings.MaxClockSkew = new TimeSpan(0, 5, 0); security.LocalClientSettings.MaxCookieCachingTime = new TimeSpan(23, 0, 0, 0); security.LocalClientSettings.ReplayWindow = new TimeSpan(0, 5, 0); security.LocalClientSettings.SessionKeyRenewalInterval = new TimeSpan(15, 0, 0); security.LocalClientSettings.SessionKeyRolloverInterval = new TimeSpan(0, 5, 0); security.LocalClientSettings.ReconnectTransportOnFailure = true; security.LocalClientSettings.TimestampValidityDuration = new TimeSpan(0, 5, 0); security.LocalClientSettings.CookieRenewalThresholdPercentage = 60; security.LocalServiceSettings.DetectReplays = true; security.LocalServiceSettings.IssuedCookieLifetime = new TimeSpan(10, 0, 0); security.LocalServiceSettings.MaxStatefulNegotiations = 128; security.LocalServiceSettings.ReplayCacheSize = 900000; security.LocalServiceSettings.MaxClockSkew = new TimeSpan(0, 5, 0); security.LocalServiceSettings.NegotiationTimeout = new TimeSpan(0, 1, 0); security.LocalServiceSettings.ReplayWindow = new TimeSpan(0, 5, 0); security.LocalServiceSettings.InactivityTimeout = new TimeSpan(0, 2, 0); security.LocalServiceSettings.SessionKeyRenewalInterval = new TimeSpan(15, 0, 0); security.LocalServiceSettings.SessionKeyRolloverInterval = new TimeSpan(0, 5, 0); security.LocalServiceSettings.ReconnectTransportOnFailure = true; security.LocalServiceSettings.MaxPendingSessions = 128; security.LocalServiceSettings.MaxCachedCookies = 1000; security.LocalServiceSettings.TimestampValidityDuration = new TimeSpan(0, 5, 0); var textEncoding = new TextMessageEncodingBindingElement { MaxReadPoolSize = 64, MaxWritePoolSize = 16, MessageVersion = MessageVersion.Default, WriteEncoding = System.Text.Encoding.UTF8, ReaderQuotas = new XmlDictionaryReaderQuotas { MaxDepth = 32, MaxArrayLength = 16384, MaxBytesPerRead = 4096, MaxNameTableCharCount = 16384, MaxStringContentLength = 8192 } }; var httpTransport = new HttpTransportBindingElement { ManualAddressing = false, MaxBufferSize = 65536, MaxReceivedMessageSize = 65536, AllowCookies = false, AuthenticationScheme = AuthenticationSchemes.Anonymous, BypassProxyOnLocal = false, DecompressionEnabled = true, HostNameComparisonMode = HostNameComparisonMode.StrongWildcard, KeepAliveEnabled = true, MaxBufferPoolSize = 524288, ProxyAuthenticationScheme = AuthenticationSchemes.Anonymous, TransferMode = TransferMode.Buffered, UnsafeConnectionNtlmAuthentication = false, UseDefaultWebProxy = true, }; var binding = new CustomBinding(new List<BindingElement> { security, textEncoding, httpTransport }); var endpoint = new EndpointAddress(_serviceUri); var service = new OrganizationServiceClient(binding, endpoint); A: Creating a custom channel factory is a key part of solving this. The article Get your WCF client configuration from anywhere is very helpful for reading a .config file from a location of your choice using a custom service client. The alternative of setting all the values in a very similar way to the app.config format is described in Calling WCF Service using Client Channel Factory which describes how to create a custom binding. I found that not all of the security properties could be set this way (or at least I couldn't find them).
{ "language": "en", "url": "https://stackoverflow.com/questions/7523842", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Change Image when a button is clicked I have an image and a button within a panel. When the button is clicked I would like my image to be replaced with another image at random based on an array of stored images. I'm stuck on implementing a change image function within the button. Assistance would be appreciated. A: You could do it using jQuery by: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script> <script> $(document).ready(function() { // Handler for .ready() called. var imageList = ['one.png', 'two.png', 'three.png', 'four.png']; $('#btn').click(function(){ var imgName = imageList[Math.floor(Math.random()*imageList.length)]; $('#image').attr('src', imgName); }); }); </script> <button id="btn">Click Me</button> <img id="image" src="someimage.png" /> A: refToYourImage.onclick = function() { refToYourImage.src = arrOfRandomImages[Math.floor(Math.random() * arrOfRandomImages.length)]; } A: Something like this? <img id = "IM" src = "someImageReference"/> <button onclick = "changeImage(document.getElementById('IM'))">Change image</button> <script type = "text/javascript"> function changeImage(image) { var images = new Array{"image paths","here"}; var rand = Math.round(Math.random() * images.length); image.src = images[rand]; } </script> A: The best would be to have a separate panel with a card layout for the images. This way you can easily add animations when swiching the images. Example new Ext.Panel({ id:'imagePanel', layout: 'card', cardSwitchAnimation: 'fade', items:[ {html:'<img src="/img1.jpg" />'}, {html:'<img src="/img2.jpg" />'}, {html:'<img src="/img3.jpg" />'}, {html:'<img src="/img4.jpg" />'} ] }); And then have this to switch the image Ext.getCmp('imagePanel').setActiveItem(Math.floor(Math.random()*numImages);
{ "language": "en", "url": "https://stackoverflow.com/questions/7523845", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is collaboration tools in SharePoint 2010? Please give me know what is collaboration tools in SharePoint 2010? Thanks! A: Collaboration tools in SharePoint 2010: * *Discussion Board *Blog *Wiki *Tagging *Bookmarking *Rating. *Activity feeds
{ "language": "en", "url": "https://stackoverflow.com/questions/7523853", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-4" }
Q: How can I combine JQuery selectors and variables to shorten code for easier scaleability? I have this piece of javascript that is working. var footerColour = $.color.extract($("div#one.footer"), 'background-color'); var newrgba = $.color.parse(footerColour).add('a', -0.5).toString() $("div#one.footer").css("background-color", ''+ newrgba +''); var navColour = $.color.extract($("div#two.nav"), 'background-color'); var newrgba1 = $.color.parse(navColour).add('a', -0.5).toString() $("div#two.nav").css("background-color", ''+ newrgba1 +''); It is checking two different divs for a colour and changing the css colour value with the returned colour from a jQuery colour plugin that I have. I plan to continue to add more of these, but figured this could probably be written out in a more compact or combined way to allow for more items to be added without repeating the same three lines of code each time. I have looked into arrays, but have been unable to find the exact answer and syntax to help with this. Any ideas? Thanks. A: You can put the colour change stuff in a function and then call the function with each id (or selector) that you want to apply it to: function changeBackground(selector) { var footerColour = $.color.extract($(selector), 'background-color'); var newrgba = $.color.parse(footerColour).add('a', -0.5).toString(); $(selector).css("background-color", ''+ newrgba +''); } changeBackground("div#one.footer"); changeBackground("div#two.nav"); changeBackground("add other item here"); // or pass them all at once changeBackground("div#one.footer, div#two.nav, etc"); // or give them all a common class and pass that changeBackground(".someCommonClass"); If you used the latter options to update all at once you should probably loop through each item matching the selector and update them one by one (otherwise either it wouldn't work or they'd all end up with the same colour): function changeBackground(selector) { $(selector).each(function() { var footerColour = $.color.extract($(this), 'background-color'); var newrgba = $.color.parse(footerColour).add('a', -0.5).toString(); $(this).css("background-color", ''+ newrgba +''); }); } Note: given that ID is supposed to be unique, you can select just on the id. so $("#one") instead of $("div#one.footer") - unless you want to select on that id only when it has the "footer" class. A: Just add a common class to the elements which need to see these changes and use the following code: Assuming common class is 'changeBG' jQuery('.changeBG').each(function() { var navColor = jQuery.color.extract(jQuery(this), 'background-color'); var newRGBA = jQuery.color.parse(navColor).add('a', -0.5).toString(); jQuery(this).css("background-color", ''+ newRGBA +''); }); This should solve shorten your code. A: I would do something like this: function changeColor(arr, colorType){ // Define length of array var i = arr.length; // Loop over each item in array while(i--){ // Create jQuery object with element from array var $elem = $( arr[i] ); // Run the color change logic var color = $.color.extract($elem, colorType); var newColor = $.color.parse(color).add('a', -0.5).toString(); $elem.css(colorType, newColor); } } // Array of jQuery selectors var elems = ["div#one.footer","div#two.nav"]; // Pass array and color type to changeColor function changeColor(elems, "background-color"); This function takes an array of strings that must be valid jQuery selectors and a colorType which could be anything with color (I assume your plugin supports more than just background-color). EDIT Ooops, I had an incorrect variable name in there. It was $elem.css(colorType, color); but it should have been $elem.css(colorType, newColor);. Anyway, this function gives you greater flexibility because you can change the color type in the function call. You would execute one function per array and just specify a color type. You could easily add another parameter for colorChange to handle the 'a', -0.5 part. This method also results in fewer function calls which would likely make it faster than the other solutions here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523855", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Attempting to create two 50% high divs-stacked in a push/pull "hideTop/showBoth/HideBottom" configuration The layout solution I'm trying to pull off involves a 960px(W) x 100%(H) centered wrapper. Within that wrapper are two stacked divs (960px(W) x 50%(H) stacked on top of another 960px(W) x 50%(H)). The interface I'm looking for is three varying views, animated with jquery. * *(default) Both divs visible *click down arrow icon and have top div increase it's height to 99% leaving a 1% reveal (on which provides an up arrow icon to toggle back to the 50/50 view). *click up arrow icon and have bottom div increase it's height to 99% leaving a 1% reveal and a down arrow icon to toggle back to the 50/50 view. Push and pull, two equally important pieces of content, both better seen at full screen height. A: This is a good start: http://jsfiddle.net/e2G6Y/. You will need to modify the class detection part (if($(this).attr("class") == "equal")) if you want it to work on multiple classes. You will also need to add the re-open arrows as you see fit.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523856", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Java Relative URL for URL class I have a file in my working project. It's in the current directory of source code. Main -> src [packeges] -> plugin ->MyLib.jar -> other I have a class in a packege of the src folder. Now I want to load the jar file to URL class like, new URL("jar:file:/./plugin/MyLib.jar!/") // this relative file path is wrong Could you please tell me what is the corrent relative path here? A: I think that "." refers to the current directory of your binaries (*.class), not of your source code. Try create a url relative to your binaries.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523860", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ui slider with text box input We have a ui slider we utilise, and it works flawlessly. code: jQuery(function() { jQuery( "#slider-range-min" ).slider({ range: "min", value: 1, step: 1000, min: 0, max: 5000000, slide: function( event, ui ) { jQuery( "#amount" ).val( "$" + ui.value ); } }); jQuery( "#amount" ).val( "$" + $( "#slider-range-min" ).slider( "value" ) ); }); As you can see we allow user to pick anything between 0 and 5,000,000. Html is: <div id="slider-range-min" style="width: 460px; float:left;margin:10px;"></div> What I want to do is add a text input element which works in harmony with the slider, so as user slides the texy box increases, decreases whatever.. Or if the user types numbers into the input element the slider moves appropriately. Any help please ? Preview is: A: You need to update the input element (like you're doing now for the #amount element) on slide: $("#slider").slider({ range: "min", value: 1, step: 1000, min: 0, max: 5000000, slide: function(event, ui) { $("input").val("$" + ui.value); } }); Additionally, you need to bind to the change event for the input element and call the slider's value method: $("input").change(function () { var value = this.value.substring(1); console.log(value); $("#slider").slider("value", parseInt(value)); }); Example: http://jsfiddle.net/andrewwhitaker/MD3mX/ There's no validation going on here (you must include the "$" sign for it to work). You could add some more robust input sanitation to enhance it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523864", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: DataBase (datamodel) to build a folder structure Planning on building a Folder based structure in Java. I will be using a jquery plugin for the GUI, so I don't need need information on how to display the folder structure. I am looking for the backend logic on how folder information is stored, such that it can be retrieved in a quick and efficient manner. Each folder will have multiple subfolders. From a leaf folder, we should be able access the root quickly and efficiently Example: +Folder1 |__SubFolder1_1 |__SubFolder1_2 |_SubSubFolder1_2_1 |_ +Folder2 |__SubFolder2_1 |_SubFolder2_1_1 |_SubFolder2_1_2 |_SubFolder2_1_2_1 New folders could be added randomly. Folder can be renamed. Folders can be deleted. My Question is: How would these folder details be stored in the database? Again, I am looking for a fast and efficient means of storing and retrieving this information. A: This is good question, but without a lot of specifics, it is hard to talk about the 'best' solution. You can map this to the abstract question of how to store an n-ary tree in a relational database. Here are some of the variables that affect the problem: * *What is the total size of the directory structure? *How many separate VMs perform writes to the structure? *Are move operations frequent? *Is faulting an entire subtree an important operation too? *Does your database support tree walks, or do you need a solution that works with any reasonable relational database? The following assumes your database doesn't have special provisions for performing tree walks. There are two pure persistence models for n-ary trees. The first is to simply write each node with a parent reference: | NodeId | ParentId | Name | .... |--------|----------|------------|----- This approach simplifies the move of a folder, but deletes, queries for all nested subfolders and finding root become expensive. The second pure model is to persist every ancestral relationship separate from the folder details | NodeId | Name | .... |--------|----------|------ ... | NodeId | AncestorId | Distance | |--------|------------|----------| ... Here, the folder /food/dairy/cheese/cheddar would produce | NodeId | Name | |--------|----------| | #0 | (root) | | #1 | food | | #2 | dairy | | #3 | cheese | | #4 | cheddar | | NodeId | AncestorId | Distance | |--------|------------|----------| | #1 | #0 | 1 | | #2 | #0 | 2 | | #2 | #1 | 1 | | #3 | #0 | 3 | | #3 | #1 | 2 | | #3 | #2 | 1 | | #4 | #0 | 4 | | #4 | #1 | 3 | | #4 | #2 | 2 | | #4 | #3 | 1 | This approach is very expensive for moves, and a new directory causes d inserts, where d is the distance from the root. But a subtree listing is a single query. The ancestry path is also a single query; an order by Distance desc will let you get to the root and first folder quickly. But narrowly reading your question, a variant of the first approach, simply adding root as well might be the right approach for you: | NodeId | ParentId | RootId | Name | .... |--------|----------|--------|------------|----- Note that moving a folder will be expensive, because you need to determine all nested subfolders, and update all those records' RootId. A: For storing in DB, the easiest and most straight forward way is to have an parent_folder_id for each folder/node. This should be good enough in most scenario, especially you are going to construct the folder object structure and do manipulation base on the object model. Depends on your requirement, there is a quite common case that you need to * *Find out all subfolders under certain folder *Perform the lookup directly from DB, by SQL. If it is what you are looking for, then there is a interesting method that you may have a look: Each DB record will have 2 extra number field, let's call it LEFT and RIGHT assume a tree like this: ROOT + A | + A1 | + A2 + B + B1 What is going to be stored in DB is Node LEFT RIGHT ... other fields ROOT 1 12 A 2 7 A1 3 4 A2 5 6 B 8 11 B1 9 10 * *each parent node is having LEFT = first child's LEFT - 1, and RIGHT = last child's RIGHT + 1 *leaf node will have LEFT and RIGHT being 2 consecutive number *each node's LEFT should be = prior sibling's RIGHT + 1, RIGHT = next sibling's LEFT - 1 When you need to find all nodes under certain node (N) by SQL, simply find out all nodes with LEFT > N.LEFT and RIGHT < N.RIGHT You can easily perform insert/delete by bulk updating related nodes by (not a difficult task, leave it to you :P ) This is probably not very OO friendly but in case the requirement I mentioned is what you need, u may consider using this method. A: Linked List, which is documented in the Java API here: http://download.oracle.com/javase/6/docs/api/java/util/LinkedList.html As a general Computer Science structure, read this: http://en.wikipedia.org/wiki/Linked_list I hope it helps A: For the database, keep it simple. A table named folder - the only columns would be Id, Name, ParentId. Now every folder will have a parent, and some folders will have children. To load children: SELECT * FROM Folder WHERE Id == ParentFolderId
{ "language": "en", "url": "https://stackoverflow.com/questions/7523866", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Syntax errors in my assembly code I had this code and I was wondering if anyone would be willing to help me get it working. TITLE MASM Template (main.asm) ; Description: this code is supposed to print out each letter followed by a space and then the capitalized version on seperate lines ; Revision date: INCLUDE Irvine32.inc .data myArray byte 'l','s','d','t','h','c','f','u','c','k' ;my array of 10 characters .code main PROC mov ecx,0 ;clears ecx mov ecx,LENGTHOF myArray ;should be 10 mov edi,OFFSET myArray ;will point to the beginning of the array mov eax,0 ;clears eax mov esi,0 ;clears esi LOne: mov eax,myArray[esi] ;points the pointer at the beginning of myArray WriteChar eax ;prints the designated value in the array WriteChar 32 ;prints a space (32 is the ascii value for ' ') sub eax,32 ;subtracts 32 from the ascii value of the char ;the capital version of each letter is -32 of its ascii value WriteChar eax ;prints the capital version call CLRF ;prints new line inc esi ;increments esi to the next array value dec ecx ;decrements ecx, moving it through the array loop LOne ;loops back until ecx is equal to zero exit main ENDP END main It won't compile giving me syntax errors. 1>main.asm(22): error A2008: syntax error : eax 1>main.asm(23): error A2008: syntax error : WriteChar 1>main.asm(26): error A2008: syntax error : eax 1>main.asm(21): error A2022: instruction operands must be the same size 1>main.asm(27): error A2006: undefined symbol : CLRF A: Ah, Kip Irvine's book... I remember wanting to write my own library so I wouldn't have to use his... You need to call those library functions, that's not how you do it in assembly languages. Assuming his library hasn't changed since the 4th edition, WriteChar requires you to move the character you wish to write into the register al. Crlf doesn't require any arguments so you can just call it, but spelling matters. ;) mov al, BYTE PTR [edi + esi] call WriteChar ; print the character found at [edi + esi] call Crlf ; print a new line After you get the syntax right, you'll want to double check your logic.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523869", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-8" }
Q: Replace all non numeric characters in MSSQL with an empty string My current MSSQL table has a "phone" column which is a varchar. Unfortunately, the phone numbers that are already in the database are not in standard format. For example, 888-888-8888 OR 888/888/8888 OR (888)8888888 OR 8888888888. I want to get all the rows that are equivalent to 88888888, i.e it should match with 888-888-8888, (888)888888 etc. I have tried using REPLACE() but there are certain rows where entries have other alphabetic characters like "e", "ex", "ext", etc. So I would like to replace all non-numeric characters. What would be the best way to get the "matching" rows using MSSQL query? A: You can try this function (MS SQL Server): CREATE FUNCTION uf_RemoveNotNumbers (@str varchar(max)) RETURNS varchar(max) AS BEGIN WHILE @str LIKE '%[^0-9]%' SET @str=replace(@str, substring(@str, patindex('%[^0-9]%',@str),1),''); RETURN @str END GO DECLARE @str varchar(max); SET @str = 'q56--89+9*67qweresr'; select dbo.uf_RemoveNotNumbers (@str) A: A simple version using MySQL: SELECT * FROM `phones` WHERE `phone` LIKE '%8%8%8%8%8%8%8%8%8%8%' Using PHP: // Get all your table rows into $rows using SELECT .. foreach ($rows as $row) { $row['phone'] = preg_replace('/\D/', '', $row['phone']; // Save the row using UPDATE .. } The regular expression \D matches any non-numeric character. See php.net/preg_replace for more information. If you just want to find a row that matches "8888888888", then you could use: if (preg_match('/\D*8\D*8\D*8\D*8\D*8\D*8\D*8\D*8\D*8\D*8\D*/', $row['phone'])) { .. } Which could simplify/abstract to: $match = '8888888888'; if (preg_match('/' . preg_replace('/(\d)/', '\D*$1', $match) . '\D*/', $row['phone'])) { .. } A: Why not write a php script that would do it for you? ex. get all rows -> replace -> update A: heres the query that might work on MSSQL. create FUNCTION dbo.Only_Numbers ( @string VARCHAR(8000) ) RETURNS VARCHAR(8000) AS BEGIN DECLARE @IncorrectCharLoc SMALLINT SET @IncorrectCharLoc = PATINDEX('%[^0-9]%', @string) WHILE @IncorrectCharLoc > 0 BEGIN SET @string = STUFF(@string, @IncorrectCharLoc, 1, '') SET @IncorrectCharLoc = PATINDEX('%[^0-9]%', @string) END SET @string = @string Return @string END GO select dbo.Only_Numbers('888*88-88/2') A: You can try this code: $query="select * from tablename"; $result=mysql_query($query); while($row=mysql_fetch_array($result)) { $str = preg_replace('[\D]', '', $row['phone']); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7523872", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can I debug a windows service without Visual Studio? (on a client's machine) I have a .net windows service I have developed and I am familiar with how to debug it using Visual Studio and attaching the debugger to the process. I also have the service writing to log files throughout its processing to assist in debugging. The problem I am running into is that when some users install my service and try to start it, it gives some generic error saying it couldn't start. I have extensive logging in the start up processes in the service, but not a single one gets written even though I have one before anything else. Here is relevant service code: static void Main(string[] args) { ServiceBase.Run(new OSAEService()); } public OSAEService() { AddToLog("Service Starting"); if (!EventLog.SourceExists("OSAE")) EventLog.CreateEventSource("OSAE", "Application"); this.ServiceName = "OSAE"; this.EventLog.Source = "OSAE"; this.EventLog.Log = "Application"; // These Flags set whether or not to handle that specific // type of event. Set to true if you need it, false otherwise. this.CanHandlePowerEvent = true; this.CanHandleSessionChangeEvent = true; this.CanPauseAndContinue = true; this.CanShutdown = true; this.CanStop = true; } protected override void OnStart(string[] args) { AddToLog("OnStart"); //All the rest of my start up processes } public void AddToLog(string audit) { lock (logLocker) { string filePath = _apiPath + "/Logs/" + _parentProcess + ".log"; System.IO.FileInfo file = new System.IO.FileInfo(filePath); file.Directory.Create(); StreamWriter sw = File.AppendText(filePath); sw.WriteLine(System.DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss.fff tt") + " - " + audit); sw.Close(); } } Neither the "Service Starting" or the "OnStart" logs get written and I am sure it isn't a problem with permission for the log directory. My question is this. Are there other ways to figure out what is causing my service not to start? A: Please check the Microsoft Visual Studio 2010 Remote Debugger to help you debug this service.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523875", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Learning raw PHP/MySQL, are databases supposed to be confusing? I'm fairly new to programming, and I'm teaching myself PHP and MySQL from scratch. I'm beginning to understand how databases work: you have tables, and you have unique ids for all of your subjects for your website. However, this seems rather tedious, as you don't always know how much content you want to have on your site. And the concept of relational databases seems a bit confusing. My question is, once you reach object oriented programming with PHP and/or frameworks like codeigniter, does it simplify these concepts? I'm trying to cram raw php down right now so I can understand the foundations of the language, but it seems rather tough going so far. A: The answer is no, you need to have a knowledge of database design and SQL (and a little bit about DBMS like MySQL, SQL Server, Access or whatever) to design websites that rely on databases. However, basic database design and SQL are extremely easy to learn. And you can learn enough to get moving in a weekend (or less). Grab a book about the DBMS you like (it looks like it's MySQL in this case) and skim through it. They generally have a chapter about database design and a chapter about SQL queries. A: Working with SQL databases is a separate discipline. I disagree that it's tedious -- in fact as someone who developed procedural database code once upon a time, requiring manual creation of data structures, application of indexes, locking and typically hundreds of lines of code to do even the simplest thing, relational databases were a huge improvement and time timesaver, considering all the problems they solve. Since they are non-procedural and based on set theory, there is a learning curve but one that is well worth the effort. With that said, one of the solutions for working with them is "Object - relational mapping" libraries, that are aimed at automating the process of interacting with a sql database, and can be used to eliminate the need for writing sql. Doctrine, Propel and Zend_db_table are a few different takes on ORM in PHP. The problem is, that ORM's are really made for people who already understand relational databases and how they are designed. You typically have to configure the ORM, and in the case of mysql, its default "engine" named myisam doesn't support the storage of relationships between tables. ORM's often have the ability to figure out relationships using "reflection" by reading the data dictionary, but with mysql/myisam it is not possible to determine the relationships between tables, and this is something you need to configure when you setup the orm for a project. If you don't understand how to relate and join tables, and the ins and outs of database design, you will undoubtedly be very confused. Learning the basics of SQL is not that difficult, and for most web developers it's an important skillset to have. Even with an ORM there are times when you need to drop down to raw sql for efficiency or expediency.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523876", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Use the value entered in a JSF page for Java Applet I have created a JSF page which asks the user to enter a value, and this value is being processed via Applet and create a barcode image based on the inputted value. My problem is how can i get the value from the JSF Page and use it in my Applet.. Thanks! A: Use JavaScript. E.g. <h:inputText ... onchange="updateBarcodeApplet(this.value)" /> ... <applet id="barcodeApplet" ...></applet> with this JS <script> function updateBarcodeApplet(value) { var barcodeApplet = document.getElementById("barcodeApplet"); barcodeApplet.updateValue(value); } </script> and in Applet public void updateValue(String value) { // Do your business here. } (yes, all Applet's public methods are just available as is in JS) Needless to say, using an applet for this job is pretty clumsy. Not all clients support or even appreciate applets. I'd also opt for a simple <img> element with a servlet which returns the image as suggested by Denisk. You just have to update the <img src> by JSF or JavaScript. A: Why do you do it in a hard way? You don't really want an applet here, create the image on server, serialize it to response stream and display it as plain image.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523877", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Flex Async Madness - Any way to wait for a rpc.Responder to get a response before going to the next statement? I feel like I must be doing this wrong. I've got a function that is supposed to construct a query based on an API's description of available fields. Here's what I've got: var query_fields = getQueryFieldsFor(sobject_name); // Need query fields for the next statement, which actually does the query public function getQueryFieldsFor(sObject:String):String{ //helper function to get queryfields for given sobject var queryFields:String = ''; app.connection.describeSObject(sObject, new mx.rpc.Responder( function(result:DescribeSObjectResult):void{ var returnFields:String = ''; for ( var field:Field in result.fields ){ if(field.active){ returnFields.concat(field.name+',') } } returnFields.slice(0, returnFields.length-1); //remove last comma queryFields = returnFields; }, function(error):void{ Alert.show('error in getQueryFieldsFor function'); }) ); return queryFields; } I know this doesn't work, and I think I understand why. However, I keep running into this type of issue and I believe I'm just thinking about it/designing it wrong. So what's a better pattern here? Would really appreciate any insight on this. Many thanks in advance. A: It would be better to externalize your functions and execute your next line of code after the fact: public function getQueryFieldsFor(sObject:String):String { var responder:Responder = new Responder( onResult, onFault); app.connection.describeSObject(sObject, responder); } private function onResult(result:DescribeSObjectResult):void { var returnFields:String = ''; for ( var field:Field in result.fields ){ if(field.active){ returnFields.concat(field.name+',') } } returnFields.slice(0, returnFields.length-1); //remove last comma queryFields = returnFields; } Your main problem though is not the code, but a lack of thinking asynchronously. You cannot have a function called "getQueryFields" that will return it instantly. What you want to do is think in the request/response way. You're trying to get some data, a request is made to a service, gets the data back, updates a property which is then binded to a view which gets redrawn. This is the proper way to do any webapp. It might be beneficial for you to also look at application frameworks like RobotLegs and Parsley since it helps you manage these situations. Parsley also has a task library which lets you perform several asynchronous task one after another.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523879", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Return a boolean value from a list comprehension I'm brand new to haskell and am working through some tutorial problems for a functional programming course I am taking. There is one problem that I am completely stumped on. Define a function that returns whether a given string contains all numerical values or not (i.e. "123" => True, "1a3" => False). The function must use a list comprehension. It's this last part that is killing me. It's easy to write without a list comprehension. It's also easy to write a list comprehension with a predicate to ensure that you only put numerical chars into a new list. isNum = [ x | x <- xs, x `elem` ['0'..'9'] ] However I'm not sure how to then compare the new list to the original list to check for equality since this is the entire function definition. A: hint: use a list comprehension, not consist only of a list comprehension. is there some list you can generate, and then run some further processing on to get the answer you need? A: If I were you, I'd just check that the list [x | x <- xs, not (elem x ['0'..'9'])] is empty. A: As small a hint as I can think of for the solution that first comes to my mind: x elem ['0'..'9'] is useful for this, but not as a guard. A: I guess the homework requires a list comprehension, but the idiomatic way to do this would be: import Data.Char isNum = all isDigit as a joke, if you want to think outside the box, you could throw in a list comprehension, but ignore it! isNum = let unnecessaryListComprehension = [x | x <- [0..]] in all isDigit or using a Monoid import Data.Monoid isNum xs = getAll $ mconcat [All $ isDigit x | x <- xs] A: Is this homework? Since the list comprehension will only include characters that are numerals, if there are any non-numeric elements, the resulting list will be shorter. Another approach is to put isNum xs = [ elem x ['0'..'9'] | x <- xs ]. Then you have a list of Boolean values telling you whether each character was a numeral. You can use a Prelude function to tell you whether all the values were True or not. EDIT: more efficiently, there is also a Prelude function that can tell you whether any of the elements was False, indicating a non-numeric element. A: Although there is an answer marked as correct, I think the complete implementation will be like this: isNum xs = foldr (&&) True [x `elem`['0'..'9'] | x <- xs] -- or isNum xs = foldl (&&) True [x `elem`['0'..'9'] | x <- xs] -- or isNum xs = and [x `elem`['0'..'9'] | x <- xs] -- Thanks for the comment of hammar isNum "123" -- returns True isNum "1a3" -- returns False A: isNum xs = null [ x | x <- xs, x notElem ['0'..'9'] ] Just check the list is empty or not .. A: You can use this partial function: isNum :: [Char] -> Bool isNum = foldl (\acc x -> acc && x `elem` ['0'..'9']) True Example: Prelude> isNum "111" True Prelude> isNum "111aaa" False
{ "language": "en", "url": "https://stackoverflow.com/questions/7523881", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using regular expression in ruby I am trying to strip all the <br>'s in a given string. def extract(a) a=a.delete("/ (\<br\>)+ /") puts a end extract("e<gr>y<br>t<gh>hello") is giving egytghhello as output. Why is the <r> of <gr> and <> of gh not getting printed? A: String.delete doesn't take a regular expression as an argument, it takes a set of letters, all of which will be deleted from the string it's called on. So, your code is saying: delete any of <, >, b, r, (, ), +, space, and /. You'd use String.gsub if you wanted to use a regex to remove parts of a string (or gsub! to do the replacing in-place). The usual caveats about the unreliability of using regular expressions to deal with HTML apply: consider using something like Nokogiri, particularly if you have any parsing or manipulation requirements above and beyond this. A: This should account for <br>, <br /> and <br/> just in case. str = "Hi and <gr>y<br>t<gh>hello<br />bla<br/> some moar" puts str.gsub(/<br ?\/?>/,'') Or using a method like your example: def extract(str) str.gsub(/<br ?\/?>/,'') end puts extract("Hi and <gr>y<br>t<gh>hello<br />bla<br/> some moar") Personally I think is better to have the method return a string and then do puts extract() than having the puts inside the method. A: Try the following: a = a.gsub(/<br>/, '')
{ "language": "en", "url": "https://stackoverflow.com/questions/7523884", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }