text
stringlengths
8
267k
meta
dict
Q: How do I draw a rotating prism in OpenGL? I'm trying to draw a simple crystal that rotates on its axis. I can get the shape right easily enough by drawing a pyramid and then drawing it again upside down, but I've got two problems. First off, even though I draw everything in the same color, two of the faces come out a different color as the other two. Second, it's placing a "bottom" on each pyramid that's visible through the translucent walls of the crystal, which ruins the effect. Is there any way to get rid of it? Here's the code I'm using to set up and draw the GL scene. There's a lot more OpenGL code than this, of course, but this is the relevant part. procedure Initialize; begin glShadeModel(GL_SMOOTH); glClearColor(0.0, 0.0, 0.0, 0.5); glClearDepth(1.0); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glHint(GL_PERSPECTIVE_CORRECTION_HINT,GL_NICEST); end; procedure Draw; //gets called in a loop begin glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT); glLoadIdentity(); glTranslatef(-1.5,-0.5,-6.0); glRotatef(rotation,0.0,1.0,0.0); glBegin(GL_TRIANGLE_FAN); glColor4f(0, 0, 1, 0.2); glVertex3f(0, 3.4, 0); glVertex3f(-1, 0, -1); glVertex3f(-1, 0, 1); glVertex3f(1, 0, 1); glVertex3f(1, 0, -1); glVertex3f(-1, 0, -1); glEnd; glBegin(GL_TRIANGLE_FAN); glVertex3f(0, -3.4, 0); glVertex3f(-1, 0, -1); glVertex3f(-1, 0, 1); glVertex3f(1, 0, 1); glVertex3f(1, 0, -1); glVertex3f(-1, 0, -1); glEnd; rotation := rotation + 0.02; end; Anyone know what I'm doing wrong and how to fix it? A: I'm trying to draw a simple crystal Stop. Crystals are translucent, and the moment you start drawing translucent objects, you can basically discard any notion of the effect being "simple". Rendering a true prism (which refracts different wavelengths of light differently) is something that requires raytracing of some form to get right. And there are many ray tracers that can't even get it right, since they only trace R, G and B wavelengths, whereas you need to trace many wavelengths to approximate the refraction and light splitting pattern of a prism. The best you're going to get is on a rasterizer like OpenGL some level of fakery. I can't explain what's going on with the faces, but the problem with seeing through to the other polygons is simple: you're not using backface culling. Unless you want to see the back faces of transparent objects, you need to make sure that backface culling is active.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548488", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Enable and Disable Textboxes jquery I have enabled mutiple textboxes with jQuery. But I am not sure how to re-enable them if it the radio button is not selected. What modifications would I have to make to my current code? <script type="text/javascript"> $(document).ready(function() { $(":radio[id^=check]").click(function() { var textId = "#" + this.id.replace("check", "text"); $(textId).removeAttr("disabled", "disabled").css('background-color', '#99FF66') }); //alert("test"); }); </script> A: Replace $(textId).removeAttr("disabled", "disabled") by $(textId).removeAttr("disabled") It is quite obvious if you read the docs, removeAttr doesn't take two arguments A: You could use a single handler to do both -- disable when the radio button isn't checked, enable when it is. Using @AlienWebGuy's observation that you can use the checked test for the value of the property, this can be done as: $(":checkbox[id^=check]").click(function() { $("#" + this.id.replace("check", "text")) .prop("disabled", $(this).filter(':checked').length == 0); }); when coupled with this CSS <style> input:disabled { background-color: #99ff66; } </style> A: You want to manipulate the property, not the attribute: $(textId).prop('disabled',true); and $(textId).prop('disabled',false'); A: I was able to complete the task doing it this way. Baiscally, I have id on my textbox and radio buttons. That go radio button id="check1" textbox id="text1", radio button id="check2" textbox id="text2". Then in my decline id i have radio button id="checker1" and textbox id="text1", etc. So based on which one the choose it will enable it and turn it green, or disable and turn it red. Here is the code. <script type="text/javascript"> $(document).ready(function() { //Goes through each and if click adds css and removes disable $(":radio[id^=check]").click(function() { var textId = "#" + this.id.replace("check", "text"); $(textId).removeAttr("disabled").css('background-color', '#99FF66').css('color', '#000') }); //Goes through each and if checked adds disabled and turns red $(":radio[id^=checker]").click(function() { var textId = "#" + this.id.replace("checker", "text"); $(textId).attr("disabled", "disabled").css('background-color', '#FF0033').css('color', '#FFFFFF') }); //alert("test"); }); </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/7548498", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Export a java library in a .jar file I'm still pretty new to java and I'm VERY new to exporting .jar files. I've got a little game that I want to send to some friends and I was told in another question that I should export it to an executable jar file. Well I finally got that working on my computer but when I send it to other people it doesn't work because they don't have the library. I'm importing the objectdraw library and without that my program won't run at all! So basically I need to find a way to export the object draw library as part of my .jar file so that they can use it too. Do I simply include it in the included files part of the jar command? ex: jar cmf MANIFEST.mf Archery.jar * /System/Library/Java/Extensions/objectdraw.jar or what? I'm working out of the command line right now. A: The simplest way is to send the JAR library file too and add a Class-Path entry to the manifest. This entry would look like: Class-Path: objectdraw.jar You could also set the CLASSPATH environment variable manually. Alternatively, you can unpack the library and add all (or just the required files) to your final jar. This doesn't always work though, because some libraries rely on the integrity of teir JAR file. Finally, it is possible to include the dependency in the main JAR, but it would require a custom class loader. A: Turns out the best way I've found to do this is to unpack the library and then put all the resulting files in with your final archive. This way it actually works on other computers. jar xf library_wanted.jar; jar cvmf MANIFEST.mf end_result.jar *.class library_wanted/
{ "language": "en", "url": "https://stackoverflow.com/questions/7548499", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: 'Confirmation token is invalid' when testing with Cucumber I'm trying to get a sign up form working with Devise; I'm testing it with Cucumber. When a user signs up, I send a confirmation e-mail. Something goes wrong when running my test, though. This is my scenario: Scenario: Signing in via confirmation Given there are the following users: | email | password | unconfirmed | | user@ticketee.com | password | true | And "user@ticketee.com" opens the email with subject "Confirmation instructions" And they click the first link in the email Then I should see "Your account was successfully confirmed." And I should see "Signed in as user@ticketee.com" However, I get the following error: expected there to be content "Your account was successfully confirmed. You are now signed in." in "\n Ticketee\n \n\nTicketee\nSign up\n Sign in\nResend confirmation instructions\n\n\n \n 1 error prohibited this user from being saved:\n Confirmation token is invalid\n\n\n Email\n\n \n\n Sign inSign upForgot your password?" (RSpec::Expectations::ExpectationNotMetError) I guess the important part here is: 1 error prohibited this user from being saved:\n Confirmation token is invalid I have tested this manually (went to sign up and clicked the confirmation link in the e-mail) and this works fine.. It's only when I test through Cucumber that I get the 'Confirmation token is invalid' message. Anyone know how I can fix this? I'd like to see my tests pass.. Thanks a lot. EDIT: Steps asked for in the comments: When /^(?:I|they|"([^"]*?)") opens? the email with subject "([^"]*?)"$/ do |address, subject| open_email(address, :with_subject => subject) end Clicking link: When /^(?:I|they) click the first link in the email$/ do click_first_link_in_email end I just looked at the confirmation email I got and my e-mail address is parsed as a mailto: link; I changed the first link step to this: And they follow "Confirm my account" in the email but that didn't work either.. I'm still getting the invalid token error message. A: So.. I wasted two hours on this. I had a typo. I have the following line: unconfirmed = attributes.delete("unconfirmed") == "true" I forgot to put the quotes around true. Without the quotes, the test passes.. Jeez. Thanks to everyone who put some time in helping me :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7548504", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Rails, Alphanumeric validation in the controller In my app I let users select a username, just like the twitter signup page: https://twitter.com/signup When the user starts typing a username, I want in real-time to let the user know if the username is available & valid. The regex I've been using to validate the username is alphanumeric is: /^[a-z0-9]+[-a-z0-9]*[a-z0-9]+$/i Given params[:username] In the controller, how can I validate if the username is alphanumeric or not. Note, I'm not saving the record here just validation. so a model validation wouldn't work. Ideas? Thanks A: You'd still want to use model validations. Something like this perhaps: class User validates :username, :format => { :with => /your regex/ }, :uniqueness => true end # then in some controller action or rack app def test_username user = User.new(:username => params[:username]) # Call user.valid? to trigger the validations, then test to see if there are # any on username, which is all you're concerned about here. # # If there are errors, they'd be returned so you can use them in the view, # if not, just return success or something. # if !user.valid? && user.errors[:username].any? render :json => { :success => false, :errors => user.errors[:username] } else render :json => { :success => true } end end A: r = /^[a-z0-9]+[-a-z0-9]*[a-z0-9]+$/i unless your_string.match(r).nil? # validation succeeded end A: I think your regex is a little overly verbose. I'd actually try the following regex for the alphanumeric validation: /\A[A-Z0-9]+\z/i
{ "language": "en", "url": "https://stackoverflow.com/questions/7548507", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: what is the order of source operands in AT&T syntax compared to Intel syntax? The Intel ISA reference documentation for this instruction is clear: VPBLENDVB xmm1, xmm2, xmm3/m128, xmm4 Select byte values from xmm2 and xmm3/m128 using mask bits in the specified mask register, xmm4, and store the values into xmm1. xmm1 is the destination, xmm2/3/4 are source operands So what does this become using AT&T syntax? We know that the destination register must be last, but what is the order of source operands? vpblendvb $xmm2, $xmm3, $xmm4, $xmm1 or vpblendvb $xmm4, $xmm3, $xmm2, $xmm1 or something else? A: Assembling (note GAS uses % instead of $ to denote registers) the following: vpblendvb %xmm4, %xmm3, %xmm2, %xmm1 with the GNU assembler (version 2.21.0.20110327 on x86_64 2.6.38 linux) and then disassembling yields: $ objdump -d a.out 0: c4 e3 69 4c cb 40 vpblendvb %xmm4,%xmm3,%xmm2,%xmm1 in intel syntax (as the manual shows): $ objdump -d -M intel a.out 0: c4 e3 69 4c cb 40 vpblendvb xmm1,xmm2,xmm3,xmm4 So it looks like the order of all the arguments is reversed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548509", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: How do I reflect changes made to ViewModels for other windows? My app contains the following moduls: SystemModel --> SystemViewModel --> SystemWindow SettingsModel --> SettingsViewModel --> SettingsWindow My SystemViewModel contain SettingsViewModel and other things. In my SystemViewModel I create some Instance that its ctor receives SettingsViewModel. If i want to update the settings I opened new SettingsWindow as ShowDialog with SettingsViewModel as him DataContext. If the user click "ok" I update the settings else I don't update. My problem is that I dont know how to update the Settings in the Instance that I created in the SystemViewModel (Instance that received SettingsViewModel in his ctor). Any idea? A: Can you create only one instance of settings view model, maybe residing in a common view model that serves kind of a root for the view model and providing the glue that binds the models together? Something like a view model controller, even if this sound a bit strange. This root view model could react to events from the view models and then can do everything that is required to update the other settings. Another approach is a messaging based approach like the one that is implemented by MVVM Light Toolit. I have used this once and after the project got rather big this approach was kind of complicated regarding maintenance. Update: You can find information about MVVM Light Toolkit here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548512", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How I can convert my json data to html? I have get $.getJSON('ajax/ajax-test.php', function( data ) { .... }); json data I am trying view: { "1": { "section":"painting", "category": { "1":"african", "2":"modern art" } }, "2": { "section":"antiques", "category": { "3":"ikons" } } } How I can convert my json data to html to look like: painting african modern art antiques ikons I tried $.each(data, function(i, section_obj){ $.each(section_obj, function(section, category_arr){ content += category_arr+'<br />'; }); and $.getJSON('ajax/ajax-test.php, function( data ) { var content = ''; $.each(data, function(i, section_obj) { $.each(section_obj, function(section, section_name) { content += section_name+'<br />'; $.each(section_obj.category, function(category, category_arr){ content += category_arr+'<br />'; }); }); }); $('#content-test').empty().append(content).css({ 'display':'block' }).show('slow'); }); but it not working! A: First of all, make sure that you can access data, exmp: alert(data[1].section). if not then use: var data = $.parseJSON(data) And only then try to use: $.each(data, function(i, section_obj){ $.each(section_obj.category, function(section, category_arr){ content += category_arr+'<br />'; });
{ "language": "en", "url": "https://stackoverflow.com/questions/7548513", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: problem with 2 elements in android layout I have the following layout for two things -> a back button and a title text view.the back button is supposed to to align to the left of the parent while the text is supposed to be at the centre. Somehow, its not working and I dont have any clue why. Can anyone kindly help me out ? Thanks. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center_horizontal" android:orientation="horizontal"> <ImageButton android:src="@drawable/backtap" android:background="@null" android:layout_width="wrap_content" android:layout_height="match_parent" android:paddingLeft="5dip" android:paddingRight="5dip" android:id="@+id/back_button3" android:layout_alignParentLeft="true"/> <TextView android:layout_width="wrap_content" android:layout_height="match_parent" android:paddingTop="10dip" android:paddingLeft="10dip" android:paddingRight="10dip" android:layout_centerHorizontal="true" android:id="@+id/title_text_view_success3"/> </RelativeLayout> A: I changed it to a linear layout, changed layout_width+layout_height to wrap_content (instead of match_parent) and changed gravity to layout_gravity. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal"> <ImageButton android:src="@drawable/backtap" android:background="@null" android:layout_width="wrap_content" android:layout_height="match_parent" android:paddingLeft="5dip" android:paddingRight="5dip" android:id="@+id/back_button3" android:layout_alignParentLeft="true"/> <TextView android:layout_width="wrap_content" android:layout_height="match_parent" android:paddingTop="10dip" android:paddingLeft="10dip" android:paddingRight="10dip" android:layout_centerHorizontal="true" android:text="text here" android:id="@+id/title_text_view_success3"/> </LinearLayout> Seems to work Hope it helps. EDIT After re-reading your question, this might be of more help: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content"> <ImageButton android:src="@drawable/backtap" android:background="@null" android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingLeft="5dip" android:paddingRight="5dip" android:id="@+id/back_button3" android:layout_alignParentLeft="true"/> <TextView android:layout_width="fill_parent" android:layout_height="match_parent" android:paddingTop="10dip" android:paddingLeft="10dip" android:paddingRight="10dip" android:gravity="center_horizontal" android:text="text here" android:id="@+id/title_text_view_success3"/> </LinearLayout> A: Try using a LinearLayout. Also try removing android:gravity from the parent layout. A: Thanks for your help/efforts. I took into considerations all your tricks and tips and made some changes to my layout and it works nicely now. Thanks once again.:) <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:layout_gravity="center_horizontal"> <ImageButton android:src="@drawable/backtap" android:background="@null" android:layout_width="wrap_content" android:layout_height="match_parent" android:paddingLeft="5dip" android:paddingRight="5dip" android:id="@+id/back_button3" android:layout_alignParentLeft="true"/> <TextView android:layout_width="wrap_content" android:layout_height="match_parent" android:paddingTop="10dip" android:paddingLeft="10dip" android:paddingRight="10dip" android:layout_centerHorizontal="true" android:id="@+id/title_text_view_success3"/> </RelativeLayout>
{ "language": "en", "url": "https://stackoverflow.com/questions/7548517", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Finding line number of a word in a text file using java I require searching a word in a text file and display the line number using java. If it appears more than once I need to show all the line numbers in the output. Can anyone help me please? A: Read the text file using Java class LineNumberReader and call method getLineNumber to find the current line number. http://docs.oracle.com/javase/7/docs/api/java/io/LineNumberReader.html A: You can store this information manually. Whenever you are invoking readline() of your BufferedReader, if you're using such, you can also increment a counter by one. E.g., public int grepLineNumber(String file, String word) throws Exception { BufferedReader buf = new BufferedReader(new InputStreamReader(new DataInputStream(new FileInputStream(file)))); String line; int lineNumber = 0; while ((line = buf.readLine()) != null) { lineNumber++; if (word.equals(line)) { return lineNumber; } } return -1; } A: Something like this might work: public ArrayList<Integer> find(String word, File text) throws IOException { LineNumberReader rdr = new LineNumberReader(new FileReader(text)); ArrayList<Integer> results = new ArrayList<Integer>(); try { String line = rdr.readLine(); if (line.indexOf(word) >= 0) { results.add(rdr.getLineNumber()); } } finally { rdr.close(); } return results; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7548519", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: apache SSLEngine On, in separate Vhost, or mix with :80? I'm unsure if I should create a separate Vhost in apache for HTTPS purposes. I need to pass the "SSLEngine" option and I'm wondering if that would hurt performance on normal http-requests? Does it matter if I use SSLEngine On inside a *:80 Vhost, like so: <VirtualHost *:80 *:443> DocumentRoot /var/www/html/ ServerName *.domain.com SSLEngine On SSLCertificateFile /current-certificate SSLCertificateKeyFile /current-key </VirtualHost> A: With that block you are running SSL on 80 and 443, prob not what you want. You need a separate vhost entry. One for regular http and the other for SSL. And yes it would degrade performance. But check out SSL persistent connections. Most of the SSL overhead is from the handshake not the actual transfer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548521", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Trouble getting a list of cities from LS I'm struggling getting an array of LS cities... file_get_contents() returns an empty dropdown on their roadblock requiring you to select cities. Unfortunately it's empty... so then I thought it was coming from an ajax request. But looking at the page I don't see any ajax requests on the page. Then I tried CURL, thinking that maybe simulating a browser would help... the below code had no affect. $ch = curl_init("http://www.URL.com/"); curl_setopt($ch, CURLOPT_VERBOSE, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)'); $result=curl_exec($ch); var_dump($result); Does anyone have any ideas on how I can get a solid list of available areas? A: I have found out how they populate the list of cities and created some sample code below you can use. The list of cities is stored as a JSON string in one of their javascript files, and the list is actually populated from a different javascript file. The names of the files appear to be somewhat random, but the root name remains the same. An example of the JS file with the city JSON is hXXp://a3.ak.lscdn.net/deals/system/javascripts/bingy-81bf24c3431bcffd317457ce1n434ca9.js The script that populates the list is hXXp://a2.ak.lscdn.net/deals/system/javascripts/confirm_city-81bf24c3431bcffd317457ce1n434ca9.js but for us this is inconsequential. We need to load their home page with a new curl session, look for the unique javascript URL that is the bingy script and fetch that with curl. Then we need to find the JSON and decode it to PHP so we can use it. Here is the script I came up with that works for me: <?php error_reporting(E_ALL); ini_set('display_errors', 1); // debugging // set up new curl session with options $ch = curl_init('http://livingsocial.com'); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.2.13) Gecko/20101206 Ubuntu/10.10 (maverick) Firefox/3.6.13'); $res = curl_exec($ch); // fetch home page // regex string to find the bingy javascript file $matchStr = '/src="(https?:\/\/.*?(?:javascripts)\/bingy-?[^\.]*\.js)"/i'; if (!preg_match($matchStr, $res, $bingyMatch)) { die('Failed to extract URL of javascript file!'); } // this js file is now our new url $url = $bingyMatch[1]; curl_setopt($ch, CURLOPT_URL, $url); $res = curl_exec($ch); // fetch bingy js $pos = strpos($res, 'fte_cities'); // search for the fte_cities variable where the list is stored if ($pos === false) { die('Failed to locate cities JSON in javascript file!'); } // find the beginning of the json string, and the end of the line $startPos = strpos($res, '{', $pos + 1); $endPos = strpos($res, "\n", $pos + 1); $json = trim(substr($res, $startPos, $endPos - $startPos)); // snip out the json if (substr($json, -1) == ';') $json = substr($json, 0, -1); // remove trailing semicolon if present $places = json_decode($json, true); // decode json to php array if ($places == null) { die('Failed to decode JSON string of cities!'); } // array is structured where each country is a key, and the value is an array of cities foreach($places as $country => $cities) { echo "Country: $country<br />\n"; foreach($cities as $city) { echo ' ' ."{$city['name']} - {$city['id']}<br />\n"; } echo "<br />\n"; } Some important notes: If they decide to change the javascript file names, this will fail to work. If they rename the variable name that holds the cities, this will fail to work. If they modify the json to span multiple lines, this will not work (this is unlikely because it uses extra bandwidth) If they change the structure of the json object, this will not work. In any case, depending on their modifications it may be trivial to get working again, but it is a potential issue. They may also be unlikely to make these logistical changes because it would require modifications to a number of files, and then require more testing. Hope that helps! A: Perhaps a bit late, but you don't need to couple to our JavaScript to obtain the cities list. We have an API for that: https://sites.google.com/a/hungrymachine.com/livingsocial-api/home/cities
{ "language": "en", "url": "https://stackoverflow.com/questions/7548524", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I make this REGEX ignore = in a tag's attribute? Alan Moore was very helpful in solving my earlier problem, but I didn't realise until just now that the REGEX he wrote for pulling out all of a tag's attributes will break prematurely if there's an equal sign in a URL. I've spent a good while on this, trying different modifications with lookaheads and behinds, to no avail. I need this regex to break on: space + word + = , but it's breaking even if there's no space, only a letter and an =. This is mainly only an issue when I'm formatting a tag that has an onclick event with Javascript, such as opening a window or calling a a script (form action). Regex: #(\s+[^\s=]+)\s*=\s*([^\s=]+(?>\s+[^\s=]+)*(?!\s*=))#i Code to check on: onClick=window.open('http%3A%2F%2Fwww.stackoverflow.com%2Ffakeindex.php%3Fsomevariable%3Dsomevalue','popup','scrollbars=yes,resizable=yes,width=716,height=540,left=0,top=0,ScreenX=0,ScreenY=0'); class=someclass What it does: The above will break on the letter prior to the =, so in this case that the URL is encoded, it breaks on "s" in "scrollbars=yes". I can encode the URL to get around the =, but the rest of the javascript makes it still a problem since there are variables and values which require the =. If the REGEX forced it to allow = and only break on spaces followed by a word followed by that = like is should be doing, then I should be able to have the javascript work in the custom tags since the entire onClick string would be captured as the value. A: Disclaimer: As others have already stated/emphasized, using regex with HTML is fraught with potential gotcha's. Doing so with a mix of two intermingled markup languages, like you have here, is even more perilous. There are lots of ways for this solution (and any like it) to fail. That said... Answering this question requires an understanding of your preceding question (PHP PREG_REPLACE Returning wrong result depending on order checked). Note that I added an answer to that question as well with a solution consisting of minimal change to the original code. What follows is another answer with a somewhat improved solution. (Both of these answers fix both specific problems.) Some random comments on your original code: * *The expression: [^\s]+ can be shortened to: \S+ *With the foreach statement, the order of processing is not guaranteed. (And the order is important here - although this is probably not an issue since the array is declared all at once so should have the correct order.) *You are using ([^\[]+) to capture the attribute value. I think you meant to use ([^\]]+) (but even that is not the best expression). *Using ([^\[]+) (or ([^\]]+)) to capture the attribute value does not allow for square brackets to appear within the value. *The regexes are not written in free spacing mode and contain no comments. *Having unquoted attribute values with multiple words introduces quite a bit of potential ambiguity. What if you wanted to have a title attribute like this: title="CSS class is specified: class=myclass"? You should really be delimiting these attribute values. A (somewhat) better solution: Assumptions: * *All Ltags will be well formed. *Ltags are never nested. *Ltag attributes are separated by a "SPACE+WORD+=" sequence. *Other [specialtags] may appear anywhere inside an Ltag except within the "SPACE+WORD+=" attribute separator sequences. *All Ltag attribute values never contain: "SPACE+WORD+=" sequence. This includes multi-word titles and Javascript snippets inside an onClick. I assume you know precisely what will be occurring within the Ltag attributes and that they will conform to the above requirements. Here is a somewhat improved version of replaceLTags(), which uses a callback function to parse and wrap each attribute value with double quotes. The complex regexes are fully commented. // Convert all Ltags to HTML links. function replaceLTags($str){ // Case 1: No URL specified in Ltag open tag: "[l]URL[/l]" $re1 = '%\[l\](.*?)\[/l\]%i'; $str = preg_replace($re1, '<a href="$1">$1</a>', $str); // Case 2: URL specified in Ltag open tag: "[l=URL attr=val]linktext[/l]" $re2 = '% # Match special Ltag construct: [l=url att=value]linktext[/l] \[l= # Literal start-of-open-Ltag sequence. (\S+) # $1: link URL. ( # $2: Any/all optional attributes. [^[\]]* # {normal*} = Zero or more non-[] (?: # "Unroll-the-loop" (See: MRE3) \[[^[\]]*\] # {special} = matching [square brackets] [^[\]]* # More {normal*} = Zero or more non-[] )* # End {(special normal*)*} construct. ) # End $2: Optional attributes. \] # Literal end-of-open-Ltag sequence. (.*?) # $3: Ltag link text contents. \[/l\] # Literal close-Ltag sequence. %six'; return preg_replace_callback($re2, '_replaceLTags_cb', $str); } // Callback function wraps values in quotes and converts to HTML. function _replaceLTags_cb($matches) { // Wrap each attribute value in double quotes. $matches[2] = preg_replace('/ # Match one Ltag attribute name=value pair. (\s+\w+=) # $1: Space, attrib name, equals sign. ( # $2: Attribute value. (?: # One or more non-start-of-next-attrib (?!\s+\w+=) # If this char is not start of next attrib, . # then match next char of attribute value. )+ # Step through value one char at a time. ) # End $2: Attribute value. /sx', '$1"$2"', $matches[2]); // Put humpty back together again. return '<a href="'. $matches[1] .'"'. $matches[2] .'>'. $matches[3] .'</a>'; } The main function regex, $re2, matches an Ltag element, but does not attempt to parse individual open tag attributes - it globs (and captures into group $2) all the attributes into one substring. This substring containing all the attributes is then parsed by the regex in the callback function, which uses the desired "SPACE+WORD+=" expression as a separator between name=value pairs. Note that this function can be passed a string containing multiple Ltags and all will be processed in one go. It will also correctly handle IPv6 literal URL addresses such as: http://[::1:2:3:4:5:6:7] (which contain square brackets). If you insist on going down this road, I would recommend using a delimiter for the attribute values. I know you said that you can't use the double quote for some reason, but you could use a special character such as '\1' (ASCII 001), then replace that with double quotes in the callback function. This would dramatically cut down on the list of possible ways for this to fail. A: If you can guarantee that the pattern will never occur inside an attribute value, you could split the string on this regex: \s+(?=\w+=) That actually simplifies the problem quite a bit. The code below assumes the URL (which may contain custom [fill] tags) ends at the first whitespace (if present) or at the closing bracket of the [l] tag. Everything after the first whitespace is assumed to be a series of whitespace-separated name=value pairs, where the name always matches ^\w+$ and the value never contains a match for \s+\w+=. Values may also contain [fill] tags. function replaceLTags($originalString) { return preg_replace_callback( '#\[l=((?>[^\s\[\]]++|\[\w+\])+)(?:\s+((?>[^\[\]]++|\[\w+\])+))?\](.*?)\[/l\]#', replaceWithinTags, $originalString); } function replaceWithinTags($groups) { $result = "<a href=\"$groups[1]\""; $attrs = preg_split('~\s+(?=\w+=)~', $groups[2]); foreach ($attrs as $a) { $result .= preg_replace('#\s*(\w+)=(.*)#', ' $1="$2"', $a); } $result .= ">$groups[3]</a>"; return $result; } demo I'm also assuming there are no double-quotes in the attribute values. If there are, the replacement will still work but the resulting HTML will be invalid. If you can't guarantee the absence of double-quotes, you may have to URL-encode them or something before doing these replacements.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548526", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how do I reload a div with a rails partial is there a way in rails to reload a div with a partial Controller def home @events = [] end def ajax_load_events ... @band = Band.find_by_name(@artist) begin artist = Bandsintown::Artist.new({ :name => @artist }) @events = artist.events rescue Bandsintown::APIError @events = [] #this will ensure that if an error happens from the bandsintown api, we'll catch the error end end HTML <div class="field disable_color"> <label for="search">Select a Song</label> <input type="search" name="request[song]" id="request_song" value="" /> </div> <tbody class="load_events"> <%= render :partial => 'event', :collection => @events %> </tbody> partial <% @events.each_with_index do |event, index| %> <tr class="gradeU"> <td><%= check_box_tag "instance_selected#{index}", "2"%></td> <td><%= event.datetime.strftime("%B %d, %Y") %></td> <td><%= "#{event.venue.name} - #{event.venue.city}, #{event.venue.country}" %></td> </tr> <% end %> jQuery $("#request_song").autocomplete({ source: function(req, add){ $.getJSON('/song_ajax/trackName/'+ $("#request_artist").val() + '', req, function(data) { var suggestions = data.suggestions; add(suggestions); }); }, change: function() { var artist_url = encodeURIComponent($('#request_artist').val().replace(/\./g, "")); $.getJSON('/ajax_load_events/'+ artist_url + '', function(data) { }); }, }); Basically i need the div #load_events be refreshed with the @events array that is populated with the ajax_load_events action ...any ideas what i am missing A: In your controller: def ajax_load_events respond_to do |format| format.js end end ajax_load_events.js.erb $("#load_events").html('<%= escape_javascript(render :partial => "your_partial", :locals => { :events => @events}) %>'); Update: routes.rb get "/ajax_load_events" => "your_controller#ajax_load_events" in your .js $.get("/ajax_load_events/", {}, null, "script");
{ "language": "en", "url": "https://stackoverflow.com/questions/7548531", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: JQuery mobile: reading from $.mobile.changePage I'm using jquery mobile 1.0b3 and i'm creating two pages where one page has to send data to the second page with a button. I know that a "a href" element could be rendered with a button but if i want to send some custom data from a page to another i can "override" mobile.changePage. This is the element <a href="#" id="save" data-role="button">Save</a> and this is the jquery function ('m trying to override the internal call to change page, is it correct ?) $('#save').live( 'click', function() { $.mobile.changePage( "index.html", { transition: "$.mobile.defaultPageTransition", data: $('#form').serialize()}); } ); the transition works fine but how can i read the data in the new page ? I need to read the values the user entered in the other form but i don't know how. The documentation gives mention to mobile.changePage but i haven't found how to read the data. Is it correct to read it in the "pageInit" ? Thanks A: Good question. I don't think you can do it. The data gets sent via Ajax to your server, but is not passed in any of the standard events. However you can do something like this: <script> var data; $('#save').live( 'click', function() { data = "some value you compute"; $.mobile.changePage("index.html"); } $("#index").live("pagebeforecreate", function() { // do something with data to change the DOM for #index } </script> This takes advantage of the fact that you're using Ajax and not loading a different URL when you change pages.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548532", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to find apostrophe in string using PHP? I can't get to detect an apostrophe (') in a string. I tried if (strpos($username, chr(39)) > 0 ) if (strpos($username, '\') > 0 ) if (strpos($username, "'") !== FALSE)) without luck. What's the right way of doing it? A: you listed this one, and it should work: if (strpos($username, "'") !== FALSE) A: Single-quote is a special character. So if you want to use a single-quote within the single quoted string you have to escape the single-quote with a backslash \ symbol. int singleQuotePosition = strpos($username, '\''); OR int singleQuotePosition = strpos($username, "'"); PHP Manual: Strings A: Just another random guess: Maybe your single quote isn't really a single quote. If so, you might want to try mb_strpos or preg_match to find the UTF-8 variations of that character: preg_match("/'/u", $string); Or even test with /\p{Pi}/u to see if it's another type of single quote doppelganger. Another tip: instead of strpos and boolean result fiddling, try strstr if you just want to test for a character presence.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548533", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to utilise google maps to replicate functionality similar to rightmoves' draw-a-search? I know this will be a complex solution. I would appreciate it if you could push me in the right direction. Please have a look at http://www.rightmove.co.uk/draw-a-search.html. I am interested in finding out how this is possible. what steps do I have to take to achieve this? A: There's quite a few things going on here. You need to have event listeners for when the user clicks on the map. You need to place markers where they click. You need to draw two types of polylines; the static type connecting two markers, and the dynamic dotted line as they move the cursor or drag a marker. When you've closed up the polygon, you need to make your search only return properties inside that shape (although they're actually doing it within X miles radius from that shape). They're also inserting markers half-way along the lines that you can drag - this will require the geographical library, using the interpolate function.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548544", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Winform DataGridView Control With Extended Capabilities I am looking for a DataGridView control for Winforms which has the following capabilities with little or no programming (once the the control is bound to datasource). * *Disconnected Search/Filtering *Pagination *Backend/Frontend Column Groupping *Exporting Data *Print Preview It doesn't matter the control be commercial, free, or open source. A: You might want to try the Telerik GridView it pretty much does all you want except for the Print preview.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548545", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: python: class attributes and instance attributes I'm new to python and learned that class attributes are like static data members in C++. However, I got confused after trying the following code: >>> class Foo: ... a=1 ... >>> f1=Foo(); >>> f2=Foo() >>> f1.a 1 >>> f1.a=5 >>> f1.a 5 >>> f2.a 1 Shouldn't f2.a also equal 5? If a is defined as a list instead of an integer, the behavior is expected: >>> class Foo: ... a=[] ... >>> f1=Foo(); >>> f2=Foo() >>> f1.a [] >>> f1.a.append(5) >>> f1.a [5] >>> f2.a [5] I looked at Python: Difference between class and instance attributes, but it doesn't answer my question. Can anyone explain why the difference? Thanks A: You're not doing the same thing in your second example. In you first example, you are assigning f1.a a new value: f1.a = 5 In your second example, you are simply extending a list: f1.a.append(5) This doesn't change what f1.a is pointing to. If you were instead to do this: f1.a = [5] You would find that this behaves the same as your first example. But consider this example: >>> f1=Foo() >>> f2=Foo() >>> Foo.a = 5 >>> f1.a 5 >>> f2.a 5 In this example, we're actually changing the value of the class attribute, and the change is visible in all instances of the class. When you type: f1.a = 5 You're overriding the class attribute with an instance attribute. A: >>> class Foo: ... a=1 ... >>> f1=Foo() >>> f2=Foo() >>> f1.a # no instance attribute here in f1, so look up class attribute in Foo 1 >>> f1.a=5 # create new instance attribute in f1 >>> f1.a # instance attribute here. Great, let's use this. 5 >>> f2.a # no instance attribute in f2, look up class attribute in Foo 1 >>> >>> class Foo: ... a=[] ... >>> f1=Foo() >>> f2=Foo() >>> f1.a # no instance attribute - look up class attribute in Foo [] >>> f1.a.append(5) # no instance attribute, modify class attribute in-place >>> f1.a # no instance attribute - look up class attribute in Foo [5] >>> f2.a # same here [5] A: My advice: to understand such cases, do tests using id, and __dict__ too : class Foo: a=1 # Foo.a == 1 # id(Foo.a) == 10021840 # Foo.__dict__ == {'a': 1, '__module__': '__main__', '__doc__': None} f1 = Foo() # f1.a == 1 # id(f1.a) == 10021840 # f1.__dict__ == {} f2 = Foo() # f2.a == 1 # id(f2.a) == 10021840 # f2.__dict__ == {} f1.a = 5 # f1.a == 5 # id(f1.a) == 10021792 # f1.__dict__ == {'a': 5} # f2.a == 1 # id(f2.a) == 10021840 # f2.__dict__ == {} This shows that as long as the instruction f1.a = 5 has not been executed, the instance f1 doesn't have a personal attribute a. Then, why does the instruction print f1.a executed before f1.a = 5 produce 1? That's because: A class instance has a namespace implemented as a dictionary which is the first place in which attribute references are searched. When an attribute is not found there, and the instance’s class has an attribute by that name, the search continues with the class attributes. http://docs.python.org/reference/datamodel.html#the-standard-type-hierarchy A: Python's class attributes and object attributes are stored in separate dictionaries. For the object f1, these can be accessed via, respectively, f1.__class__.__dict__ and f1.__dict__. Executing print f1.__class__ is Foo will output True. When you reference the attribute of an object, Python first tries to look it up in the object dictionary. If it does not find it there, it checks the class dictionary (and so on up the inheritance heirarchy). When you assign to f1.a, you are adding an entry to the object dictionary for f1. Subsequent lookups of f1.a will find that entry. Lookups of f2.a will still find the class attribute — the entry in the class attribute dictionary. You can cause the value of f1.a to revert to 1 by deleting it: del f1.a This will remove the entry for a in the object dictionary of f1, and subsequent lookups will continue on to the class dictionary. So, afterwards, print f1.a will output 1. A: What happens is the following: When you instantiate a new object f1 = Foo(), it does not have any attributes of its own. Whenever you try to access for example f1.a, you get redirected to the class’s Foo.a: print f1.__dict__ {} print f1.a 1 However, if you set f1.a = 5, the instance gets a new attribute of that value: print f1.__dict__ {'a': 5} The class definition is untouched by this, as are any other instances. In the second example, you do not reassign anything. With append you are only using that very same list which was defined in the class. Therefore, your instance still refers to that list, as do all other instances. A: When you assign an attribute in python, it doesn't matter where that attribute might already be defined, the new assignment is always applied to the object assigned to. When you say >>> f1.a=5 The object that has the attribute here is the instance, so it's the instance that gets the new value.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548546", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Javascript oop-like fail(?!?) Consider this: function f2(x) { return x+1; }; X = function(){ this.f1=function (x) { return 2*f2(x); } return this; }; then x = new X(); x.f1(1) works fine. But when i want to do this: X = function(){ this.f2 = function(x) { return x+1; }; this.f1=function (x) { return 2*f2(x); } return this; }; The same statement will complain that it can't find f2. In, for example c#, you can say class X { int f2(int x){return x+1;} int f1(int x){return 2*f2(x);} } and this will work X x=new X(); x.f1(1) Why? A: because you forgot this.f2. Javascript don't see class variables without this A: You need to reference the f2 with the this keyword explicitly. X = function(){ this.f2 = function(x) { return x+1; }; this.f1=function (x) { return 2*this.f2(x); } return this; }; A: Javascript doesn't have the implicit this that you get in C#. You need to add the this in: X = function(){ this.f2 = function(x) { return x+1; }; this.f1=function (x) { return 2*this.f2(x); }; return this; }; A: X = function(){ this.f2 = function(x) { return x+1; }; this.f1=function (x) { return 2*this.f2(x); // <-- Need this here since it is not implicit } return this; }; A: To reference f2 in your second code block, you'll need to use this.f2. this references the context in which the function is being executed. Since you call f1 in the following way: x.f1(); ... the context is set to the instance, x. JavaScript does not make instance variables available to the scope in the same way as scope variables, i.e. those directly available: X = function(){ var f2 = 123; this.f2 = function(x) { return x+1; }; this.f1=function (x) { console.log(f2); // => 123 console.log(this.f2); // => function(){} return 2 * this.f2(x); }; return this; };
{ "language": "en", "url": "https://stackoverflow.com/questions/7548552", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is it possible to have OpenGL draw on a memory surface? I am starting to learn OpenGL and I was wondering if it is possible to have it draw on a video memory buffer that I've obtained through other libraries? A: For drawing into video memory you can use framebuffer objects to draw into OpenGL textures or renderbuffers (VRAM areas for offscreen rendering), like Stefan suggested. When it comes to a VRAM buffer created by another library, it depends what library you are talking about. If this library also uses OpenGL under the hood, you need some insight into the library to get that "buffer" (be it a texture, into which you can render directly using FBOs, or a GL buffer object, into which you can read rendered pixel data using PBOs. If this library uses some other API to interface the GPU, there are not so many possibilities. If it uses OpenCL or CUDA, these APIs have functions to directly use their memory buffers or images as OpenGL buffers or textures, which you can then render into with the mentioned techniques. If this library uses Direct3D under the hood, it gets a bit more difficult. But at least nVidia has an extension to directly use Direct3D 9 surfaces and textures as OpenGL buffers and textures, but I don't have any experience with this and neither do I know if this is widely supported. A: You cannot let OpenGL draw directly to arbitrary memory, one reason is that in most implementations OpenGL drawing happens in video RAM, not system memory. You can however draw to an OpenGL offscreen context and then read back the result to any place in system memory. A web search for framebuffer objects (FBOs) should point you to documentation and tutorials. If the memory you have is already in VRAM, for example decoded by hardware acceleration, then you might be able to draw to it directly if it is available as an OpenGL texture - then you can use some render to texture techniques that will save you transferring data from and to VRAM.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548556", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Programmatically prevents battery charge Some computers (e.g. Dell, Vaio) come with software that prevents a battery from charging. This functionality allows me to use my laptop with battery (protected from power outage) and keep my battery from charging until it's down to, at most, 50% battery/charge remaining. I want do write some code to automate this task. I searched Dell Support Center for a solution, and I searched Google, too - no luck with either. I thought about downloading the program and debugging it, but I couldn't find it. Has anyone ever seen something like this? Thanks PS: I want to do this on a Dell Inspiron, and the code can be in C++/C# (or something) A: I've never heard of a program that disables battery charging. (Why on earth would you want this?) If such programs exist, I imagine that they interact with the firmware or hardware at a very primitive level. One thing you can try is a busy loop (burning power like mad) that checks the battery level and sleeps for a bit once it gets down to the target level. This won't do good things to the cpu temperature, however. A: Some laptops come with battery charge limiting functionality - it is not via software though, but via firmware plus dedicated internal hardware I guess. Some Lenovo and Acer have such capability. The logic is not in software as the charge limiter kicks in even when the laptop is off. The reason is that battery degrade when kept at 100% - as it is the case with laptops that are always plugged in. The new Acer Swift would limit at 80%, some Lenovo let one input a particular value. If interested I can provide you with the software side - it works on Windows and Linux but can easily be available on MacOS. It works in conjunction with external hardware - i.e. a homeplug. The code works but it's by no means production ready. It would need a bit of tweaking for a particular operating system and homeplug. Let know if interested. Available on github: Charge Limiter
{ "language": "en", "url": "https://stackoverflow.com/questions/7548559", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: why would spaces in a Python tuple matter? I've been getting weird results and I finally noticed that my habit of putting spaces in a tuple is causing the problem. If you can reproduce this problem and tell me why it works this way, you would be saving what's left of my hair. Thanks! jcomeau@intrepid:/tmp$ cat haversine.py #!/usr/bin/python def dms_to_float(degrees): d, m, s, compass = degrees d, m, s = int(d), float(m), float(s) float_degrees = d + (m / 60) + (s / 3600) float_degrees *= [1, -1][compass in ['S', 'W', 'Sw']] return float_degrees jcomeau@intrepid:/tmp$ python Python 2.6.7 (r267:88850, Jun 13 2011, 22:03:32) [GCC 4.6.1 20110608 (prerelease)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from haversine import * >>> dms_to_float((111, 41, 0, 'SW')) 111.68333333333334 >>> dms_to_float((111,41,0,'Sw')) -111.68333333333334 With spaces in the tuple, the answer is wrong. Without, the answer is correct. A: The spaces should make no difference. The difference is due to the case: SW vs Sw. You don't check for SW here: compass in ['S', 'W', 'Sw']] Perhaps change it to this: compass.upper() in ['S', 'W', 'SW']] A: Presuming that the "degrees" relate to degrees of latitude or longitude, I can't imagine why "SW" is treated as a viable option. Latitude is either N or S. Longitude is either E or W. Please explain. Based on your sample of size 1, user input is not to be trusted. Consider checking the input, or at least ensuring that bogus input will cause an exception to be raised. You appear to like one-liners; try this: float_degrees *= {'n': 1, 's': -1, 'e': 1, 'w': -1}[compass.strip().lower()]
{ "language": "en", "url": "https://stackoverflow.com/questions/7548562", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: float <-> std::string conversion alternative? is there any alternative to atof, strtod, lexical_cast, stringstream or sprintf? that is: * *fast *C++ way (std::string instead of char*) *safe (no buffer overrun risk) *valid (return NaN if conversion couldn't be made) *no external library (independent) I prefer more like this , a simple function, optimized, and to the point reason : * *atof and strtod is C function and they are not returning NaN upon failure, I prefer working on std::string, so I just asking if anyone already writing some wrapper to std::string that I can use (if you don't mind). *lexical_cast has boost dependency *stringstream is slow *sprintf has buffer overflow risk and its C function A: I'd look at Boost Spirit * *http://www.boost.org/doc/libs/1_47_0/libs/spirit/doc/html/spirit/qi/reference/numeric/real.html At least the benchmarks of the formatters (that is float -> string) consistently turn out as top-of-the-bill*1* Also the exact input format specification and semantics when parsing can be configured very nicely using a policy class. Here is my absolute min-dependency use of qi::any_real_parser<> and the list of dependendencies it touches: #include <boost/spirit/include/qi_real.hpp> namespace qi = boost::spirit::qi; int main() { const char input[] = "3.1415926"; const char *f(input); const char *l(f+strlen(input)); qi::any_real_parser<double> x; double parsed; x.parse(f, l, qi::unused, qi::unused, parsed); return 0; } * *boost/concept *boost/config *boost/detail *boost/exception *boost/fusion *boost/iterator *boost/math *boost/mpl *boost/optional *boost/preprocessor *boost/proto *boost/range *boost/regex *boost/spirit *boost/typeof *boost/type_traits *boost/utility *boost/variant aligned_storage.hpp,assert.hpp,blank_fwd.hpp,blank.hpp,call_traits.hpp,checked_delete.hpp,concept_check.hpp,config.hpp,cstdint.hpp,current_function.hpp,foreach_fwd.hpp,foreach.hpp,get_pointer.hpp,implicit_cast.hpp,iterator.hpp,limits.hpp,math_fwd.hpp,next_prior.hpp,noncopyable.hpp,none.hpp,none_t.hpp,optional.hpp,ref.hpp,static_assert.hpp,swap.hpp,throw_exception.hpp,type.hpp,utility.hpp,variant.hpp,version.hpp 1 e.g. http://www.boost.org/doc/libs/1_47_0/libs/spirit/doc/html/spirit/karma/performance_measurements/numeric_performance/double_performance.html A: If you want to convert from numerical types to std::string there's a std::to_string function available in the latest standard. Unfortunately as I've found out recently, in Visual Studio 2010 it is somewhat limited because there are only three overloads available for it; long double, long long, and unsigned long long. This causes issues when trying to use them from within templates. A: The fast format library should be able to do the kinds of transformations you're looking for, at least for writing a float out. It does not handle parsing of a float, however.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548564", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Question Regarding Getters & Setters I know this might be a stupid question to many but I usually like to stick to correct/better implementation. In Java, when writing a getter/setter, would it be better to refer to the instance variable with this or access it directly? Thanks A: When writing a setter you are typically forced to refer to the instance variable (not the local variable) using this in order to differentiate between the instance variable and the parameter; e.g. public void setFoo(int foo) { this.foo = foo; } However, when writing a getter method there is typically no need to prefix the instance variable with this: public int getFoo() { return foo; } A: It does not really matter as long as you refer to the proper variables. Yet, it is a common practice to refer to the local fields with this so that you do not mix them up with local variables: public void setField(int field)[ this.field = field; } A: That is simply a matter of taste, although it has some particular use cases. When subclassing, this keyword can be used for routines and variables to stress that they actually belong to super class (or this class) and not e.g., statically imported. It's also commonly used to disambiguate parameters from local variables. E.g., private Foo foo; public void setFoo(Foo foo) { this.foo = foo; } A: Specifying this tends to alleviate any variable scope problems you might encounter later on. It's not necessary, though.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548568", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: "Error: attempt to index local 'self' (a nil value)" in string.split function Quick facts, I got this function from http://lua-users.org/wiki/SplitJoin at the very bottom, and am attempting to use it in the Corona SDK, though I doubt that's important. function string:split(sSeparator, nMax, bRegexp) assert(sSeparator ~= '') assert(nMax == nil or nMax >= 1) local aRecord = {} if self:len() > 0 then local bPlain = not bRegexp nMax = nMax or -1 local nField=1 nStart=1 local nFirst,nLast = self:find(sSeparator, nStart, bPlain) while nFirst and nMax ~= 0 do aRecord[nField] = self:sub(nStart, nFirst-1) nField = nField+1 nStart = nLast+1 nFirst,nLast = self:find(sSeparator, nStart, bPlain) nMax = nMax-1 end aRecord[nField] = self:sub(nStart) end return aRecord end The input: "1316982303 Searching server" msglist = string.split(msg, ' ') Gives me the error in the title. Any ideas? I'm fairly certain it's just the function is out of date. Edit: lots more code Here's some more from the main.lua file: multiplayer = pubnub.new({ publish_key = "demo", subscribe_key = "demo", secret_key = nil, ssl = nil, -- ENABLE SSL? origin = "pubsub.pubnub.com" -- PUBNUB CLOUD ORIGIN }) multiplayer:subscribe({ channel = "MBPocketChange", callback = function(msg) -- MESSAGE RECEIVED!!! print (msg) msglist = string.split(msg, ' ') local recipient = msglist[0] --Get the value table.remove(msglist, 0) --Remove the value from the table. local cmdarg = msglist[0] table.remove(msglist, 0) arglist = string.split(cmdarg, ',') local command = arglist[0] table.remove(arglist, 0) argCount = 1 while #arglist > 0 do argname = "arg" .. argCount _G[argname] = arglist[0] table.remove(arglist, 0) argCount = argCount + 1 end Server.py: This is the multiplayer server that sends the necessary info to clients. import sys import tornado import os from Pubnub import Pubnub ## Initiat Class pubnub = Pubnub( 'demo', 'demo', None, False ) ## Subscribe Example def receive(message) : test = str(message) msglist = test.split() recipient = msglist.pop(0) msg = msglist.pop(0) id = msglist.pop(0) if id != "server": print id print msg commandHandler(msg,id) return True def commandHandler(cmd,id): global needOp needOp = False global matchListing if server is True: cmdArgList = cmd.split(',') cmd = cmdArgList.pop(0) while len(cmdArgList) > 0: argument = 1 locals()["arg" + str(argument)] = cmdArgList.pop(0) argument += 1 if cmd == "Seeking": if needOp != False and needOp != id: needOp = str(needOp) id = str(id) pubnub.publish({ 'channel' : 'MBPocketChange', #Message order is, and should remain: #----------Recipient, Command,Arguments, Sender 'message' : needOp + " FoundOp," + id + " server" }) print ("Attempting to match " + id + " with " + needOp + ".") needOp = False matchListing[needOp] = id else: needOp = id pubnub.publish({ 'channel' : 'MBPocketChange', #Message order is, and should remain: #----------Recipient, Command,Arguments, Sender 'message' : id + ' Searching server' }) print "Finding a match for: " + id elif cmd == "Confirm": if matchListing[id] == arg1: pubnub.publish({ 'channel' : 'MBPocketChange', #Message order is, and should remain: #----------Recipient, Command,Arguments, Sender 'message' : arg1 + ' FoundCOp,' + id + ' server' }) matchListing[arg1] = id else: pass #Cheater. elif cmd == "SConfirm": if matchListing[id] == arg1 and matchListing[arg1] == id: os.system('python server.py MBPocketChange' + arg1) #Here, the argument tells both players what room to join. #The room is created from the first player's ID. pubnub.publish({ 'channel' : 'MBPocketChange', #Message order is, and should remain: #----------Recipient, Command,Arguments, Sender 'message' : id + ' GameStart,' + arg1 + ' server' }) pubnub.publish({ 'channel' : 'MBPocketChange', #Message order is, and should remain: #----------Recipient, Command,Arguments, Sender 'message' : arg1 + ' GameStart,' + arg1 + ' server' }) else: pass #hax else: pass def connected(): pass try: channel = sys.argv[1] server = False print("Listening for messages on '%s' channel..." % channel) pubnub.subscribe({ 'channel' : channel, 'connect' : connected, 'callback' : receive }) except: channel = "MBPocketChange" server = True print("Listening for messages on '%s' channel..." % channel) pubnub.subscribe({ 'channel' : channel, 'connect' : connected, 'callback' : receive }) tornado.ioloop.IOLoop.instance().start() A: This error message happens if you run: string.split(nil, ' ') Double check your inputs to be sure you are really passing in a string. Edit: in particular, msglist[0] is not the first position in the array in Lua, Lua arrays start at 1. As an aside, this function was written when the intention that you'd use the colon syntactic sugar, e.g. msglist=msg:split(' ')
{ "language": "en", "url": "https://stackoverflow.com/questions/7548571", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I keep the number pad always appear in uiview? I am making an uivivewcontroller which I want the number pad always appear like this. How can I make that? Plus, why the upper view which looks like a uitableviewcontroller seems unscrollable? Is that not a uitableview, how can it be made? All in all, I'd like to make a view which looks very similar to this page. What approach is best for me? add subview? Thanks for any help! A: To make your screen to looks like that page, the easiest way is just to design your screen in IB with the the navigation bar, image, button and all. Then, add your text field and called yourTextField.setDelegate = self; yourTextField.keyboardType = UIKeyboardTypeNumberPad; [yourTextField becomeFirstResponder]; A: In any UITextField you use on your UIViewController, just call [myTextField becomeFirstResponder];
{ "language": "en", "url": "https://stackoverflow.com/questions/7548575", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JQuery script not working with IE8 I am using this marquee plugin for JQuery: http://www.givainc.com/labs/marquee_jquery_plugin.htm This creates a streaming ticker out of ul and li elements. I am using imbedded Ruby (Ruby on Rails) to provide the data. This works on the Mac using Safari and Firefox, and on Windows using Firefox, but does not work with Windows on IE8. I'm having similar problems on another page that is using JQuery. Basically, it is not functional in Internet Explorer 8. I've researched this but can't seem to find the specific answer I need to make this work. One post I read suggested using $(window).load(function) { instead of $(document).ready(function) { I appreciate the help. I'm fairly new to JQuery. Here is the relevant portion of my code: <script type="text/javascript"> $(document).ready(function (){ $("#marquee").marquee(); $("#marquee").marquee("update"); }); </script> <div id="prayers"> <!-- this loop is necessary to iterate through the array passed in @prayers --> <ul id="marquee" class="marquee"> <% @prayers.each do |prayer| %> <li><%= prayer.first_name %> from <%= prayer.city %> prays: "<%= prayer.request %>"</li> <% end %> <li>This is a scrolling prayer. Check it out</li> </ul> </div> A: I downloaded the plugin and tested in FF, IE and Chrome and it was working fine for me. One thing I did noticed though is that the plugin would not work if you do not add the css file to your page (jquery.marquee.css). <link href="Styles/jquery.marquee.css" rel="stylesheet" type="text/css" /> After I added that the plugin worked everywhere. If it does not work for you maybe check IE's Security Tab and make sure you can run Javascript from it. Good luck.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548576", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: adding class in jQuery not working in IE9 I am working on a menu for a WordPress theme. I am trying to style the menu such that on hover, menu items that don't have a submenu look one way, and menu items that DO have a submenu look a different way. I have the following jQuery $(document).ready(function(){ $('.menu li').has('ul').addClass('submenu'); }); And I have styled this in my CSS file. Main menu items on hover get 4 rounded borders and main menu items on hover that have a submenu get only the upper rounded borders. This works great in Firefox, Chrome and Safari but not in IE9. Anyone have any ideas how to get this jQuery function to be accepted by IE9? The WordPress theme in progress is at WordPress theme A: border-top-left-radius: 10px 10px 0 0; That is the offending line. You only want border-radius, since that's what you put for the -moz-, -webkit- and other prefixes.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548579", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Update text with submitted data w/jQuery I have a form on a page. I have a link acting as submit button. The value is sent to a php page via ajax where the value is set into a session. After submit I swap the form with text field where the text is displayed. How do I use the text from the submitted form to display withing <pre></pre> tags? $("#btnPreview").click(function() { var custM = $("#inviteMsg").val(); $.ajax({ url: "ajax.php", type: "POST", data: "msg="+custM }); }); <div id="customMsgPreview"> <div class="rollSec"> <pre> // SUBMITTED TEXT NEEDS TO APPEAR HERE '.$tstLnk.' </pre> </div> A: You can pass success callback: success: function (text) { $('#customMsgPreview pre').html(text); } A: Use $.ajax's success callback. var custM = $("#inviteMsg").val(); $.ajax({ url: "ajax.php", type: "POST", data: "msg="+custM, success: function(response){ $('#customMsgPreview').find('pre').html(custM); } }); You can also put response from the ajax page in the pre tag as well.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548588", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to search for string in file How could I search for string in text file in java? Would it have to be in a text file or could it read a .ini or some other file type example sound = off opengl = on openal = off I tried searching for it on google but I couldnt really find anything. Thanks in advance A: It looks like you want to use a Properties file. You can load one using Properties.load(String path); A: If your file is a properties file or an ini file (key = value), you may want to use the Apache Commons Configuration API. It is much better than the Properties class from the JDK. A: There are tons of information with those typical of questions. Here you have two easy examples: * *Loading Java Properties Files http://viralpatel.net/blogs/2009/10/loading-java-properties-files.html *How do I load property settings with the Properties class? http://www.jguru.com/faq/view.jsp?EID=581608 In short it is easy to load a file into a Properties object, for example to obtain, in your case, the sound value in a example.properties file: Properties props = new Properties(); props.load(new FileInputStream("example.properties")); String isOnOrOff = props.getProperty("sound");
{ "language": "en", "url": "https://stackoverflow.com/questions/7548590", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Trying to post date via php with mySQL... Need help I'm trying to post the date and time at the time I create a new record. The record is created but the 'add_time' column is blank in mySQL. What's wrong with it? $date = date("Y-m-d G:i:s") ; $order = "INSERT INTO cartons_added (add_time, type, part_no, add_type, add_qty, add_ref, add_by, add_notes) VALUES ('$_POST[date]', '$_POST[type]', '$_POST[part_no]', '$_POST[add_type]', '$_POST[add_qty]', '$_POST[add_ref]', '$_POST[add_by]', '$_POST[add_notes]')"; $result = mysql_query($order); A: You're never using the $date variable you created. You probably meant to use that instead of $_POST[date]. A: I believe instead of: VALUES ('$_POST[date]', '$_POST[type]', '$_POST[part_no]', '$_POST[add_type]', '$_POST[add_qty]', '$_POST[add_ref]', '$_POST[add_by]', '$_POST[add_notes]')"; You mean to use // Use your $date variable VALUES ('$date', '$_POST[type]', '$_POST[part_no]', '$_POST[add_type]', '$_POST[add_qty]', '$_POST[add_ref]', '$_POST[add_by]', '$_POST[add_notes]')"; All of this needs a great deal of treatment for protection against SQL injection. The easiest path to take is to surround all $_POST vars in mysql_real_escape_string(): "... VALUES ('$date', '" . mysql_real_escape_string($_POST['type']) ."', '" . mysql_real_escape_string($_POST['part_no']) ."', '" . mysql_real_escape_string($_POST['add_type']) ."', '" . mysql_real_escape_string($_POST['add_qty']) ."', '" . mysql_real_escape_string($_POST['add_ref']) ."', '" . mysql_real_escape_string($_POST['add_by']) ."', '" . mysql_real_escape_string($_POST['add_notes']) ."')"; A: Try this: date('Y-m-d H:i:s'); A: You have to fix that SQL-injection hole: There's also a syntax error, it's not $_POST[add_ref], but $_POST['add_ref'] You can write '$_POST[name]' (bad) instead of $_POST['name'], (good) but don't it's bad practice. Change the code to: $query = "INSERT INTO cartons_added (add_time, type, part_no, add_type, add_qty, add_ref, add_by, add_notes) VALUES ('$date', '{mysql_real_escape_string($_POST['type'])}', '{mysql_real_escape_string($_POST['part_no'])}', '{mysql_real_escape_string($_POST['add_type'])}', '{mysql_real_escape_string($_POST['add_qty'])}', '{mysql_real_escape_string($_POST['add_ref'])}', '{mysql_real_escape_string($_POST['add_by'])}', '{mysql_real_escape_string($_POST['add_notes'])}') "; Never ever ever insert a $_POST, $_GET, $_SESSION and alike stuff directly into a query. See: How does the SQL injection from the "Bobby Tables" XKCD comic work?
{ "language": "en", "url": "https://stackoverflow.com/questions/7548591", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Emacs like strict auto-indent in vim Emacs, while editing a C file, forces me to follow a particular indentation. When I press tab on an incorrectly indented line, it corrects the indentation. I want this behaviour from my vim editor. Till now I have done the following : set cindent set smartindent set autoindent set expandtab set tabstop=2 set shiftwidth=2 set cinkeys=0{,0},:,0#,!,!^F in my .vimrc file. However, I am not achieving the same emacs-like forced effect as I want. Is it possible at all in vim ? A: The == command is what you want, if I understand you correctly. It reindents the current line according to syntax rules. As for binding it to tab, that's certainly possible, but I have not done that and am not completely sure as to how you can catch the right moment when it should actually insert the tab and when it should reindent. Personally, I find it less confusing to just press ==. = accepts a range even, so you can go into visual mode, make a selection and tap = and the region will be reindented. A: 'smartindent' is obsolete. There's really no reason you need to have that in your vimrc. 'cindent' overrules 'smartindent', so setting both in your vimrc is pointless. Setting 'cindent' in your vimrc isn't very useful either, since it only really works well on C-like languages. filetype indent on will enable the filetype-specific indentation plugins (c.f., the indent directory under $VIMRUNTIME). That paired with 'autoindent' at least gives you basic automatic indentation support regardless of what filetype you're editing. If you want to add indent settings for a specific filetype, you can create your own indent script in ~/.vim/indent/<filetype>.vim, or ~/.vim/after/indent/<filetype>.vim if you're augmenting an existing system-wide indent script. As the settings you posted show, pressing Ctrlf in insert mode will do what Emacs does when you press Tab. This is described at :help indentkeys-format. 'cinkeys' is used when 'cindent' is enabled and 'indentexpr' is empty. 'indentkeys' is for the reverse. It's just a slight change to modify the setting so Tab can be used in place of/in addition to Ctrlf. On a final note, I'd recommend learning your way around Vim's help. It's very thorough and easy to use once you figure things out. :help usr_toc is a good place to start for user-level documentation. :help describes some of the basic about navigating the help, how to search for topics, etc.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548606", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: redirect with .htaccess a dynamic URL to a new static page How can I redirect with .htaccess a dynamic URL to a new static page, i.e. pages like: /page2.php?view=preview&image=33&category=2 /page2.php?view=thumbnailList&category=1 /page2.php?view=thumbnailList&category=3 etc, to: /index.php/photo-gallery There are many pages like the 3 examples on top (and theyt are indexed by Google) and I would like to redirect all the pages which start with /page2.php? to the new location. A: You are looking for mod_rewrite (if you use apache).
{ "language": "en", "url": "https://stackoverflow.com/questions/7548607", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Help with php function zip_open It's now 5am, and as much as I try to research, I can't find much information on this function set. Here's the code I have (shortened slightly): <?php $source = $_FILES["restore_file"]["tmp_name"]; $zip = zip_open($source); while ($zip_entry = zip_read($zip)) { echo zip_entry_name($zip_entry).'\n'; } ?> which when I upload my example zip out puts: example/ example/index.php example/file1.csv example/file2.csv example/file3.csv etc. I need to know how to access the contents of those files though, and also be able to specify which file I am accessing exactly. For example, before going through the csv files, I need to check a php variable in the index.php file of the archive, to make sure it is correct. Is using the ZipArchive class a better idea instead of the zip functions perhaps? I was under the impression though that using the zip functions would be better as it can access the files on the fly (without having to transfer the files to a new directory). A: Use ZipArchive::getFromName(). Example from the PHP manual adapted to your case: $zip = new ZipArchive(); if ($zip->open($_FILES["restore_file"]["tmp_name"]) === true) { echo $zip->getFromName('example/index.php'); $zip->close(); } else { echo 'failed'; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7548610", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Manually Triggering Form Validation using jQuery I have a form with several different fieldsets. I have some jQuery that displays the field sets to the users one at a time. For browsers that support HTML5 validation, I'd love to make use of it. However, I need to do it on my terms. I'm using JQuery. When a user clicks a JS Link to move to the next fieldset, I need the validation to happen on the current fieldset and block the user from moving forward if there is issues. Ideally, as the user loses focus on an element, validation will occur. Currently have novalidate going and using jQuery. Would prefer to use the native method. :) A: You can't trigger the native validation UI (see edit below), but you can easily take advantage of the validation API on arbitrary input elements: $('input').blur(function(event) { event.target.checkValidity(); }).bind('invalid', function(event) { setTimeout(function() { $(event.target).focus();}, 50); }); The first event fires checkValidity on every input element as soon as it loses focus, if the element is invalid then the corresponding event will be fired and trapped by the second event handler. This one sets the focus back to the element, but that could be quite annoying, I assume you have a better solution for notifying about the errors. Here's a working example of my code above. EDIT: All modern browsers support the reportValidity() method for native HTML5 validation, per this answer. A: var field = $("#field") field.keyup(function(ev){ if(field[0].value.length < 10) { field[0].setCustomValidity("characters less than 10") }else if (field[0].value.length === 10) { field[0].setCustomValidity("characters equal to 10") }else if (field[0].value.length > 10 && field[0].value.length < 20) { field[0].setCustomValidity("characters greater than 10 and less than 20") }else if(field[0].validity.typeMismatch) { field[0].setCustomValidity("wrong email message") }else { field[0].setCustomValidity("") // no more errors } field[0].reportValidity() }); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="email" id="field"> A: In some extent, You CAN trigger HTML5 form validation and show hints to user without submitting the form! Two button, one for validate, one for submit Set a onclick listener on the validate button to set a global flag(say justValidate) to indicate this click is intended to check the validation of the form. And set a onclick listener on the submit button to set the justValidate flag to false. Then in the onsubmit handler of the form, you check the flag justValidate to decide the returning value and invoke the preventDefault() to stop the form to submit. As you know, the HTML5 form validation(and the GUI hint to user) is preformed before the onsubmit event, and even if the form is VALID you can stop the form submit by returning false or invoke preventDefault(). And, in HTML5 you have a method to check the form's validation: the form.checkValidity(), then in you can know if the form is validate or not in your code. OK, here is the demo: http://jsbin.com/buvuku/2/edit A: TL;DR: Not caring about old browsers? Use form.reportValidity(). Need legacy browser support? Read on. It actually is possible to trigger validation manually. I'll use plain JavaScript in my answer to improve reusability, no jQuery is needed. Assume the following HTML form: <form> <input required> <button type="button">Trigger validation</button> </form> And let's grab our UI elements in JavaScript: var form = document.querySelector('form') var triggerButton = document.querySelector('button') Don't need support for legacy browsers like Internet Explorer? This is for you. All modern browsers support the reportValidity() method on form elements. triggerButton.onclick = function () { form.reportValidity() } That's it, we're done. Also, here's a simple CodePen using this approach. Approach for older browsers Below is a detailed explanation how reportValidity() can be emulated in older browsers. However, you don't need to copy&paste those code blocks into your project yourself — there is a ponyfill/polyfill readily available for you. Where reportValidity() is not supported, we need to trick the browser a little bit. So, what will we do? * *Check validity of the form by calling form.checkValidity(). This will tell us if the form is valid, but not show the validation UI. *If the form is invalid, we create a temporary submit button and trigger a click on it. Since the form is not valid, we know it won't actually submit, however, it will show validation hints to the user. We'll remove the temporary submit button immedtiately, so it will never be visible to the user. *If the form is valid, we don't need to interfere at all and let the user proceed. In code: triggerButton.onclick = function () { // Form is invalid! if (!form.checkValidity()) { // Create the temporary button, click and remove it var tmpSubmit = document.createElement('button') form.appendChild(tmpSubmit) tmpSubmit.click() form.removeChild(tmpSubmit) } else { // Form is valid, let the user proceed or do whatever we need to } } This code will work in pretty much any common browser (I've tested it successfully down to IE11). Here's a working CodePen example. A: Somewhat easy to make add or remove HTML5 validation to fieldsets. $('form').each(function(){ // CLEAR OUT ALL THE HTML5 REQUIRED ATTRS $(this).find('.required').attr('required', false); // ADD THEM BACK TO THE CURRENT FIELDSET // I'M JUST USING A CLASS TO IDENTIFY REQUIRED FIELDS $(this).find('fieldset.current .required').attr('required', true); $(this).submit(function(){ var current = $(this).find('fieldset.current') var next = $(current).next() // MOVE THE CURRENT MARKER $(current).removeClass('current'); $(next).addClass('current'); // ADD THE REQUIRED TAGS TO THE NEXT PART // NO NEED TO REMOVE THE OLD ONES // SINCE THEY SHOULD BE FILLED OUT CORRECTLY $(next).find('.required').attr('required', true); }); }); A: I seem to find the trick: Just remove the form target attribute, then use a submit button to validate the form and show hints, check if form valid via JavaScript, and then post whatever. The following code works for me: <form> <input name="foo" required> <button id="submit">Submit</button> </form> <script> $('#submit').click( function(e){ var isValid = true; $('form input').map(function() { isValid &= this.validity['valid'] ; }) ; if (isValid) { console.log('valid!'); // post something.. } else console.log('not valid!'); }); </script> A: Html Code: <form class="validateDontSubmit"> .... <button style="dislay:none">submit</button> </form> <button class="outside"></button> javascript( using Jquery): <script type="text/javascript"> $(document).on('submit','.validateDontSubmit',function (e) { //prevent the form from doing a submit e.preventDefault(); return false; }) $(document).ready(function(){ // using button outside trigger click $('.outside').click(function() { $('.validateDontSubmit button').trigger('click'); }); }); </script> Hope this will help you A: For input field <input id="PrimaryPhNumber" type="text" name="mobile" required pattern="^[789]\d{9}$" minlenght="10" maxLength="10" placeholder="Eg: 9444400000" class="inputBoxCss"/> $('#PrimaryPhNumber').keyup(function (e) { console.log(e) let field=$(this) if(Number(field.val()).toString()=="NaN"){ field.val(''); field.focus(); field[0].setCustomValidity('Please enter a valid phone number'); field[0].reportValidity() $(":focus").css("border", "2px solid red"); } }) A: $('#id').get(0).reportValidity(); This will trigger the input with ID specified. Use ".classname" for classes. A: Another way to resolve this problem: $('input').oninvalid(function (event, errorMessage) { event.target.focus(); }); A: When there is a very complex (especially asynchronous) validation process, there is a simple workaround: <form id="form1"> <input type="button" onclick="javascript:submitIfVeryComplexValidationIsOk()" /> <input type="submit" id="form1_submit_hidden" style="display:none" /> </form> ... <script> function submitIfVeryComplexValidationIsOk() { var form1 = document.forms['form1'] if (!form1.checkValidity()) { $("#form1_submit_hidden").click() return } if (checkForVeryComplexValidation() === 'Ok') { form1.submit() } else { alert('form is invalid') } } </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/7548612", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "125" }
Q: Objective-c How to load a UIViewController in synchronous way my main application view load a UIVIewController for showing a disclaimer, user can or not accept, in a modal way. The disclaimer UIVIewController has 2 buttons, 'agree' and 'disagree'. If user clicks on 'disagree' the application close itself. If user clicks on 'agree' the disclaimer UIVIewController close itself and the main application goes on. The problem is that when i load the disclaimer UIViewController the main application goes on and not wait until the disclaimer UIViewController is discmissed. There is a way to open a modal UIViewController in a 'synchronous way'? Thank you. A: so I am assuming that in your application delegate in the applicationDidFinishLaunching method you have a viewController whos view is automatically added to the window. Well inside the viewController class in the -(void)viewDidLoad method you should allocate the disclaimer controller and present it modally using [self presendModalViewController:my_disclaimer animate:YES]; This will cause the controller to slide up in front of everything. If the user clicks no then simply leave that modal controller display locking them out of the application. so the code inside your viewController -(void)viewDidLoad method should read -(void)viewDidLoad { //Alocate memory MyCustomController *controller = [[MyCustomController alloc] initWithWhatever:arguements_to_get_controller_setup]; //present controller [self presentModalViewController:controller animate:YES]; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7548615", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Spring Jdbc Template returning Int as Long? I have 3 columns in my MySQL table, 2 are INTs and one VARCHAR. I am getting class cast exception: java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer. Heres my code: List<Map<String, Object>> rows = getJdbcTemplate().queryForList(sql); for (Map row : rows) { Customer customer = new Customer(); // throws ClassCastException // customer.setCustId((Integer)(row.get("CUST_ID"))); customer.setCustId((Long)(row.get("CUST_ID"))); // had to change custId field in bean to long customer.setName((String)row.get("NAME")); // work around customer.setAge(((Long)row.get("AGE")).intValue()); customers.add(customer); } My question is why do i have to cast it to Long? Is it because the maximum allowed INT value in MySQL and the maximum allowed int value by java are not same? A: MySQL primary key integers are unsigned, Java ints are signed. Same number of bits, but the unsigned has a full 4G positive range.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548616", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why does KIF UIView:dragFromPoint:toPoint not result in touchesEnded:withEvent being called on my view? This question is about the iOS acceptance testing framework KIF. I have a test step which uses the KIF extension to UIView dragFromPoint:toPoint. I have a custom view class which implements touchesBegan/touchesMoved/touchesEnded/touchesCancelled. From my KIF test step I convert my coordinates to that of my custom view and call dragFromPoint. NSLog & breakpoints tell me that touchesBegan and touchesMoved are being called on my view but touchesEnded is not. Looking at the KIF code I can see that it's posting this event but I can't figure out why it's not being delivered to my view when the other two are. Here is an excerpt of my KIF test step code: // Convert points to coordinate system of the CoinView CGPoint coinCenter = [view convertPoint:view.center fromView:view.superview]; CGPoint coinTarget = [view convertPoint:coinSlotTarget fromView:coinSlotView.superview]; [view dragFromPoint:coinCenter toPoint:coinTarget];
{ "language": "en", "url": "https://stackoverflow.com/questions/7548619", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "26" }
Q: A multi-conditional switch statement? This is something that I haven't seen in the PHPdoc for switch() so I'm not sure if it's possible, but I'd like to have a case which is multi-conditional, such as: switch($this) { case "yes" || "maybe": include "filename.php"; break; ... } Is this valid syntax/is this even possible with a switch() statement? A: Usually you'd just use case fall-through. switch($this) { case "yes": case "maybe": include "filename.php"; break; ... } A: Is this valid syntax/is this even possible with a switch() statement? No and no. The expression will be evaluated as ("yes" or "maybe"), which will result in true. switch will then test against that result. You want to use case "yes": case "maybe": // some code break; A: Should be switch($this) { case "yes": case "maybe": include "filename.php"; break; ... } A: You can do this with fall-through: switch ($this) { case "yes": case "no": include "filename.php"; break; } A: Sure, just specify two cases without breaking the first one, like so: switch($this) { case "yes": case "maybe": include "filename.php"; break; ... } If you don't break a case, then any code for that case is run and continues on to execute additional code until the execution is broken. It will continue through all cases below it until it sees a break.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548623", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: null session on page method I'm using InProc session state and for some odd reason, the session variables are always null when I'm using a page method. If I do this: var test = HttpContext.Current.Session["test"]; it's showing nothing when I'm running on a page method but if I continue debugging and open another page, it's showing its expected result. I can't post all the code of the app so where should I start looking? web.config file looks like this: <sessionState mode="InProc"/> Thanks. A: If you are setting "test " in a masterpage it will be null in the webmethod. A webmethod doesn't know anything about masterpages. [System.Web.Services.WebMethod(EnableSession=true)] public static string Bla(double bla) { //code here var test = HttpContext.Current.Session["test"]; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7548624", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Adding a CADisplayLink to Cocos2D I have Cocos2D in my app and I use it as the game engine for my game. At this point I need to have a game loop fire at the rate the screen refreshes. So this leads me to think that I need to use CADisplayLink. So how would I implement CADisplayLink so that my game loop which will consist of Cocos2D will be called at the rate of the screen refreshing? Thanks! A: Cocos2D has the CADisplayLink object already integrated. In fact, it will be using CCDirectorDisplayLink by default unless you have specified a different director type. Check your project's AppDelegate class, in particular the didFinishLaunching… method.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548627", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I SELECT DISTINCT on one (excluded) column, but include other columns in the query? (ORACLE) So I have data arranged loosely like this: Table 1 - PEOPLE: person_id (primary key), parent_id, child_id, other_parent_fields, other_child_fields Table 2 - PARENTS: parent_id (auto incrementing primary key), other_fields Table 3 - CHILDREN: child_id (auto incrementing primary key), parent_id(foreign key referencing PARENTS) other_fields I want to be able to query for all of the distinct parents from the PEOPLE table, and insert all of the other_parent_fields into the PARENTS table, throwing out the old parent_id from Table 1, in favor of my auto incrementing parent_id in table 2. I also want to do the same for children, but maintain the parent-child relationships, only using my own ids from table 2 and table 3. Essentially, I am trying to change the way that the database is designed. Rather than a whole table for all people, I am creating a PARENTS table and a CHILDREN table, the latter of which refers to PARENTS with a foreign key. The reason I am throwing out the ids from table 1 is because I have no reason to care about them in my new table (i.e. the numbering can start back from one, and additional entries can just auto increment the primary key). However, before discarding these IDs from table 1, I need to capture the parent-child relations that they relay. Is this even possible? How would one go about doing it? we can assume, for simplicity that no children have children i.e. someone cant be a parent and a child A: I did not fully understand your question but it seems that you first query would be this (SQL Server syntax): insert into Parents select other_parent_fields, person_id as legacy_parent_id from (select distinct person_id, other_parent_fields from PEOPLE where parent_id is null) x The trick would be to first group on parent_id, other_parent_fields and then discard the parent_id. (A distinct is equal to a group by *). The above query only works if other_parent_fields is a pure function of parent_id. I interpret your question as an attempt to normalize denormalized data, so I guess this is true. In order to extract the children you can do this: insert into Children select other_child_fields, parent_id as legacy_parent_id from (select distinct person_id, other_child_fields from PEOPLE where parent_id is not null) x Now your tables contain the distinct parents and children as well as their old IDs. You have to write an update query now that assigns the new parent ids into the children table. Then you drop the legacy fields.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548633", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: When I type "rails server", I get an error "Could not find gem 'turn <>=0>' I am totally new to ror. Installed it today. Created the first app following Lynda instructions. Within the app folder, tried to run WEBrick but got this mistake: Could not find gem 'turn<>=0>' in any of the gem sources listed in your Gemfile. Run 'bundle install' to install missing gem. I did run "bundle install", but it didn't help. I get the same error. What should I do? A: For some strange reason not everything is installed by budler. Some gems must be installed as root. Try: sudo gem install turn
{ "language": "en", "url": "https://stackoverflow.com/questions/7548641", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SetTextColor of TextView programmatically I have a ListView with a TextView in each row. I have a default color.xml with is set in the row.xml I have different colors for different states <selector xmlns:android="http://schemas.android.com/apk/res/android" > <!-- pressed --> <item android:color="#ffffff" android:state_pressed="true"/> <!-- focused --> <item android:state_selected="true" android:color="#8b8989"/> <!-- default --> <item android:color="#ffffff"/> </selector> This works like a charm. But when Im trying to change the color for some rows in code, this doesn't seem to work. The second_color.xml looks just the same, but with different colors. The color is changed, but for the other states (not default) nothing changes. I change the color like this: TextView tl = (TextView) v.findViewById(R.id.textlabel); tl.setTextColor(getContext().getResources().getColor(R.color.second_color)); A: Solved it! In order to set this in code it's required to create a ColorStateList. ColorStateList cl = null; try { XmlResourceParser xrp = getResources().getXml(R.color.live_color); cl = ColorStateList.createFromXml(getResources(), xrp); } catch (Exception ex) {} if(cl != null){ tl.setTextColor(cl); } A: if your xml file is saved at /res/row.xml then you reference it with R.color.row TextView tl = (TextView) v.findViewById(R.id.textlabel); tl.setTextColor(R.color.row);
{ "language": "en", "url": "https://stackoverflow.com/questions/7548653", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I create absolute paths for INCLUDEs and REDIRECTs that will work regardless directory nesting level? I have a problem similar to the one mentioned here, except I need a solution for ABSOLUTE PATHs: How to use a PHP includes across multiple directories/sub directories with relative paths The additional bit in my setup is that I have multiple files ("config.php","functions.php",etc) that I'm including in my "header.php" file, then including only "header.php" in my sub-sub-sub-sub-etc folder items. Basically the header file says "if not logged in then redirect to the top level index.php file". The header itself is, however, in it's own subfolder called "common_inc". The problem I'm experiencing comes in when I need to perform a redirect (which is managed in the header) from any non top-level directory. The only solutions that come to mind are to 1) set 'allow_url_include' to true or 2) place all files in a flat directory structure and work from there or 3) remove the redirect from the header and manually place an absolute path redirect in all files. Obviously all of these solutions are undesirable. So can anyone think of a better way to establish ABSOLUTE PATHS (for both includes and redirects) that won't change based on their request location? I'm sure there is something amazingly simple I'm overlooking, but my brain is rather fried atm. Thanks in advance! A: The dirname function may be of use here. It returns the pathname for the current directory. dirname - php manual
{ "language": "en", "url": "https://stackoverflow.com/questions/7548657", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Having an Iframe with `a` tag with some id on it, how to create a new iframe that would follow that `a` url? We have a main web page with Iframe on it. So we have a web page loaded into Iframe. There is a link on it (a tag). We know its id. How to create a new Iframe on our main page that would follow that link? (link is relative to the site we put into our iframe). A: Assuming the iframe and your web page is on the same domain, you get the a's href from the iframe's document. var src = document.getElementById('myframe').contentWindow.document.getElementById('aid').getAttribute('href'); have a look here: http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_iframe_contentdocument A: You'd have to take the full url and past it into your own iframe. If that's not what you meant please provide code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548660", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Git/GitHub can't push to master I am new to Git/GitHub and ran into an issue. I created a test project and added it to the local repository. Now I am trying to add files/project to the remote repository. Here's what I did (and this worked) - git remote add origin git://github.com/my_user_name/my_repo.git Now when I try to push the repository to GitHub, using the following command, I get the following error - git push origin master Error - fatal: remote error: You can't push to git://github.com/my_user_name/my_repo.git Use git@github.com:my_user_name/my_repo.git A: Use Mark Longair's answer, but make sure to use the HTTPS link to the repository: git remote set-url origin https://github.com/my_user_name/my_repo.git You can use then git push origin master. A: GitHub doesn't support pushing over the Git protocol, which is indicated by your use of the URL beginning git://. As the error message says, if you want to push, you should use either the SSH URL git@github.com:my_user_name/my_repo.git or the "smart HTTP" protocol by using the https:// URL that GitHub shows you for your repository. (Update: to my surprise, some people apparently thought that by this I was suggesting that "https" means "smart HTTP", which I wasn't. Git used to have a "dumb HTTP" protocol which didn't allow pushing before the "smart HTTP" that GitHub uses was introduced - either could be used over either http or https. The differences between the transfer protocols used by Git are explained in the link below.) If you want to change the URL of origin, you can just do: git remote set-url origin git@github.com:my_user_name/my_repo.git or git remote set-url origin https://github.com/my_user_name/my_repo.git More information is available in 10.6 Git Internals - Transfer Protocols. A: There is a simple solution to this for someone new to this: Edit the configuration file in your local .git directory (config). Change git: to https: below. [remote "origin"] url = https://github.com/your_username/your_repo A: Mark Longair's solution using git remote set-url... is quite clear. You can also get the same behavior by directly editing this section of the .git/config file: before: [remote "origin"] fetch = +refs/heads/*:refs/remotes/origin/* url = git://github.com/my_user_name/my_repo.git after: [remote "origin"] fetch = +refs/heads/*:refs/remotes/origin/* url = git@github.com:my_user_name/my_repo.git (And conversely, the git remote set-url... invocation produces the above change.) A: I had this issue after upgrading the Git client, and suddenly my repository could not push. I found that some old remote had the wrong value of url, even through my currently active remote had the same value for url and was working fine. But there was also the pushurl param, so adding it for the old remote worked for me: Before: [remote "origin"] url = git://github.com/user/repo.git fetch = +refs/heads/*:refs/remotes/origin/* pushurl = git@github.com:user/repo.git NOTE: This part of file "config" was unused for ages, but the new client complained about the wrong URL: [remote "composer"] url = git://github.com/user/repo.git fetch = +refs/heads/*:refs/remotes/composer/* So I added the pushurl param to the old remote: [remote "composer"] url = git://github.com/user/repo.git fetch = +refs/heads/*:refs/remotes/composer/* pushurl = git@github.com:user/repo.git A: This error occurs when you clone a repo using a call like: git clone git://github.com/....git This essentially sets you up as a pull-only user, who can't push up changes. I fixed this by opening my repo's .git/config file and changing the line: [remote "origin"] url = git://github.com/myusername/myrepo.git to: [remote "origin"] url = ssh+git://git@github.com/myusername/myrepo.git This ssh+git protocol with the git user is the authentication mechanism preferred by Github. The other answers mentioned here technically work, but they all seem to bypass ssh, requiring you to manually enter a password, which you probably don't want. A: The below cmnds will fix the issue. git pull --rebase git push A: If you go to http://github.com/my_user_name/my_repo you will see a textbox where you can select the git path to your repository. You'll want to use this! A: I added my pubkey to github.com and this was successful: ssh -T git@github.com But I received the "You can't push" error after having wrongly done this: git clone git://github.com/mygithubacct/dotfiles.git git remote add origin git@github.com:mygithubacct/dotfiles.git ...edit/add/commit git push origin master Instead of doing what I should have done: mkdir dotfiles cd dotfiles git init git remote add origin git@github.com:mygithubacct/dotfiles.git git pull origin master ...edit/add/commit git push origin master A: To set https globally instead of git://: git config --global url.https://github.com/.insteadOf git://github.com/ A: The fastest way yuo get over it is to replace origin with the suggestion it gives. Instead of git push origin master, use: git push git@github.com:my_user_name/my_repo.git master
{ "language": "en", "url": "https://stackoverflow.com/questions/7548661", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "155" }
Q: Require help understanding a prolog method for appending list elements append([],Xs,Xs). append([Head|Tail],List2,[Head|Tail2]):- append(Tail,List2,Tail2). The upper append method adds elements from first two parameter slots to the third param variable. ?-append([2,1], [3,4], X). ?-X=[2,1,3,4] The way I see it in steps is (which is propably wrong): * *append(2 | [1], [3,4], 2 | X) *append([1], [3,4], X) *append(1 | [], [3,4], 1 | X) *append([], [3,4], [3,4]) And that's it. I can't wrap my head around how it adds together the elements and that's what i could use help with - a clear explanation on how this method works. I just don't understand how the [2,1] array gets added to the final result. A: the X in the recursion is not the same X as in the original call if you rename it in the trace you'll see append(2 | [1], [3,4], 2 | X1) -- X = [2|X1] append([1], [3,4], X1) append(1 | [], [3,4], 1 | X2) -- X1 = [1|X2] append ([], [3,4], [3,4]) -- X2 = [3,4] so X1 = [1,3,4] and X = [2,1,3,4] A: First, you have to understand how a list is implemented in Prolog. It is an essentially recursive data structure. * *The empty list is a list of zero items, represented by the atom []. *Non-empty lists are represented by the structure ./2, consisting of the head of the list (a prolog term), and the tail of the list (another list, consisting of all items save the first). So... * *[] — a list of zero items, is represented as[] *[a] — a list of 1 item, is represented as.(a,[]) *[a,b] — a list of 2 items, is represented as.(a,.(b,[])) *[a,b,c] — a list of 3 items, is represented as .(a,.(b,.(c,[]))) The standard list notation using square brackets is just syntactic sugar on top of this representation. Saying [Head|Tail] is a polite way of saying .(Head,Tail) and saying [X,Y,Z|More] is the polite way of saying .(X,.(Y,.(Z,More))). (You might be noticing a certain....Lisp-ishness...to the internal list notation here.) Understanding how a list is represented, the naive algorithm for appending (concatenating) one list to another is this: First, there are two special cases to consider: * *The result of appending a non-empty list X to an empty list Y is X.Append [1,2,3] to [] and get [1,2,3].Note. This case is can be (is normally) handled by the ordinary case below, though. It's an opportunity for optimization as there's no point in recursing down the entire list, just to replace [] with [] at the end, right?. *The result of appending an empty list X to a non-empty list Y is Y.Append [] to [1,2,3] and you get [1,2,3]. Otherwise, we have the ordinary case: * *Append non-empty list Y to non-empty list X to produce list Z. To do this is trivial: We simply recurse down on list X, popping its head as we go and and prepending that to list Z, the result. You'll notice that as this happens, list Z is a broken list structure, since its last node is always unbound rather than being []. This gets fixed at the very end when the source list, list X, is exhausted and degenerates into the special case of being an empty list. At that point, the unbound last node gets bound as it unifies with list Y (a list of zero or more nodes), leaving us with a correct list structure. The Prolog code for append/3 expresses this algorithm directly. As noted earlier, the first clause is an optional optimization, as that can be handled by the 3rd clause (the ordinary case). It wants a cut, though, as without, backtracking would produce two solutions. append( X , [] , X ) :- !. ; concatenate empty list X to list Y producing Y append( [] , Y , Y ). ; concatenate list X to empty list Y producing X append( [X|Xs] , Y , [X|Zs] ) :- ; anything else append( Xs , Y , Zs ) .
{ "language": "en", "url": "https://stackoverflow.com/questions/7548662", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Email to SMS script I am searching for a script that can forward emails to SMS. By Google'ng I found few PHP script. But I need in ASP.NET Is there any free script that automatically send emails to SMS. Or at least can anybody tell me how to get started to make my own script? A: Best bet would be to use an SMS Gateway, if you find a provider, you can have them transmit the message (http://en.wikipedia.org/wiki/SMS_gateway). Also, if you know the carrier you are sending the message to, you could simply just email back out (http://www.emailtextmessages.com/). A: You can use number@provider as email so this type of service called text@email and you can send sms as normal message.Service provider name
{ "language": "en", "url": "https://stackoverflow.com/questions/7548665", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Xor encryption in PHP I'm new to Xor encryption, and I'm having some trouble with the following code: function xor_this($string) { // Let's define our key here $key = ('magic_key'); // Our plaintext/ciphertext $text =$string; // Our output text $outText = ''; // Iterate through each character for($i=0;$i<strlen($text);) { for($j=0;$j<strlen($key);$j++,$i++) { $outText .= $text{$i} ^ $key{$j}; //echo 'i='.$i.', '.'j='.$j.', '.$outText{$i}.'<br />'; //for debugging } } return $outText; } When I run this it works for normal strings, like 'dog' but it only partially works for strings containing numbers, like '12345'. To demonstrate... xor_this('dog') = 'UYV' xor_this('123') = '' It's also interesting to note that xor_this( xor_this('123') ) = '123', as I expect it to. I'm pretty sure the problem resides somewhere in my shaky understanding of bitwise operators, OR possibly the way PHP handles strings that contain numbers. I'm betting there's someone clever out there that knows exactly what's wrong here. Thanks. EDIT #1: It's not truly 'encryption'. I guess obfuscation is the correct term, which is what I'm doing. I need to pass a code containing unimportant data from a user without them being able to easily tamper with it. They're completing a timed activity off-line and submitting their time to an online scoreboard via this code. The off-line activity will obfuscate their time (in milliseconds). I need to write a script to receive this code and turn it back into the string containing their time. A: How i did it, might help someone ... $msg = 'say hi!'; $key = 'whatever_123'; // print, and make unprintable chars available for a link or alike. // using $_GET, php will urldecode it, if it was passed urlencoded print "obfuscated, ready for url: " . urlencode(obfuscate($msg, $key)) . "\n"; print "deObfuscated: " . obfuscate(obfuscate($msg, $key), $key); function obfuscate($msg, $key) { if (empty($key)) return $msg; return $msg ^ str_pad('', strlen($msg), $key); } A: I think you might have a few problems here, I've tried to outline how I think you can fix it: * *You need to use ord(..) to get the ASCII value of a character so that you can represent it in binary. For example, try the following: printf("%08b ", ord('A')); // outputs "01000001" *I'm not sure how you do an XOR cipher with a multi-byte key, as the wikipedia page on XOR cipher doesn't specify. But I assume for a given key like "123", your key starts "left-aligned" and extends to the length of the text, like this: function xor_this($text) { $key = '123'; $i = 0; $encrypted = ''; foreach (str_split($text) as $char) { $encrypted .= chr(ord($char) ^ ord($key{$i++ % strlen($key)})); } return $encrypted; } print xor_this('hello'); // outputs "YW_]]" Which encrypts 'hello' width the key '12312'. A: There's no guarantee that the result of the XOR operation will produce a printable character. If you give us a better idea of the reason you're doing this, we can probably point you to something sensible to do instead. A: I believe you are faced with console output and encoding problem rather than XOR-related. Try to output results of xor function in a text file and see a set of generated characters. I believe HEX editor would be the best choice to observe and compare a generated characters set. Basically to revert text back (even numbers are in) you can use the same function: var $textToObfuscate = "Some Text 12345"; var $obfuscatedText = $xor_this($textToObfuscate); var $restoredText = $xor_this($obfuscatedText); A: Based on the fact that you're getting xor_this( xor_this('123') ) = '123', I am willing to guess that this is merely an output issue. You're sending data to the browser, the browser is recognizing it as something which should be rendered in HTML (say, the first half dozen ASCII characters). Try looking at the page source to see what is really there. Better yet, iterate through the output and echo the ord of the value at each position. A: Use this code, it works perfect function scramble($inv) { $key=342244; // scramble key $invarr=str_split($inv); for($index=0;$index<=strlen($inv)-1;$index++) { srand($key); $var=rand(0,255); $res=$res.(chr(ord($var)) ^ chr(ord($invarr[$index]))); $key++; } return($res); } A: Try this: $outText .= (string)$text{$i} ^ (string)$key{$j}; If one of the two operands is an integer, PHP casts the other to an integer and XORs them for a numeric result. Alternatively, you could use this: $outText .= chr(ord($text{$i}) ^ ord($key{$j})); A: // Iterate through each character for($i=0; $i<strlen($text); $i++) { $outText .= chr(ord($text{$i}) ^ ord($key{$i % strlen($key)))}; } note: it probably will create some weird characters... A: Despite all the wise suggestions, I solved this problem in a much simpler way: I changed the key! It turns out that by changing the key to something more like this: $key = 'ISINUS0478331006'; ...it will generate an obfuscated output of printable characters.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548667", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Zend Framework Bootstrap question I am new to Zend Framework. I have a master layout file and I want to add and remove css/js files dynamically. I plan on creating an XML file which contains which controller/actions should have which files added. I was thinking of having the constructor for the controller read the xml file and add the files as required but this seems a bit bad practice. I am thinking it may be better to have this done in the bootstrap class file. Can anyone tell me if this would be the correct way of doing it and how I may go about doing this please? A: The correct way would be to let your views decide which styles/scripts they need. There are view helpers available for this very purpose. This way you separate your representation logic (views, scripts, css) from your application logic (controllers/bootstrap) and your data logic (database,...). A: Create your own layout plug-in class . Inside its post-dispatch hook code your own logic . A: It is a good idea to load static resources only when you need them! That said, it seems like a contradiction in your question that you're considering loading these view specific resources during bootstrap. That's much too early, your app has no clue yet about what will be needed. With the tought of economic lazyness in the background, you should add resources in your views: if (somecondition) { $this->headScript()->addJavascriptFile($this->baseUrl() . '/path/to/your file'); } else $this->jQuery()->addOnLoad($someShortjQueryScript); } If that's too late for your taste, you can do it in the action too: $this->view->headLink()->appendStyle($someCSS); Check out the view helpers, you can do all kinds of things, append, prepend, addOnLoad, add files, scripts, styles, etc. It doesn't seem like a good idea to me to read a list of files from config. But I may be wrong.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548672", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Load pages using jQuery/Ajax in the same div that loads a page every 6 sec? On my index.php I have a header, sidebar, footer and the main part of it is the <div id="feed"> that loads engine.php every 6000 ms. I have a Contact page ( contact.php ) in my sidebar. Instead of copying my index.php to a new page, with header, sidebar, footer and a main div for the contact content, can I load it in the #feed div of index.php withour refreshing the site in the browser? To summarize it, my question is, is there any way that my pages to be loaded on the same div ( #feed) without refresh and freeze the setTimeout timer? When the user click back on Home, then the engine.php is loaded and reloaded every 6 seconds. Maybe this can be done with Ajax, I don't know... Thank you for this and any examples/codes are highly appreciated. <script language="JavaScript"> $(function () { function loadfeed() { $('#feed') .addClass('loading') .load('engine.php', function () { $(this).removeClass('loading'); setTimeout(loadfeed, 6000); }); } loadfeed(); }); </script> Update Having something like this works, but the engine.php loads after 6 sec. $("#contactBtn").click(function() { $("#feed").load('contact.php'); }); A: Without interrupting the timeout cycle, the contact form will display for a maximum of 6 seconds inside #feed before the next $.load request finishes. If you want to leave the timeout cycle going, rather than putting everything in #feed, you can give it an appropriate sibling: <div id="panels"> <div id="feed"> <!-- ... --> </div> <div id="contact" style="display:none"> <!-- ... --> </div> </div> Then, switch which is currently displaying: $('a.contact').click(function (e) { e.preventDefault(); $('#contact').show(); $('#panels > div:not(#contact)').hide(); }); $('a.feed').click(function (e) { e.preventDefault(); $('#feed').show(); $('#panels > div:not(#feed)').hide(); }); The feed will continue to load into #feed, while the contact page can display uninterrupted. Also, if you supply a clue on your links, you can combine those click handlers with fair ease: <div id="menu"> <a href="feed.php" data-panel="feed">Feed</a> <a href="contact.php" data-panel="contact">Contact</a> </div> <script> $('#menu > a').click(function (e) { e.preventDefault(); var panel = $(this).data('panel'); // or $(this).attr('data-panel') for jQuery 1.4 or older $('#' + panel).show(); $('#panels > div:not(#' + panel + ')').hide(); }); </script> A: I have no way of fully testing this, but you try something like this. <script language="JavaScript"> var timerID; $(function () { function loadfeed() { $('#feed') .addClass('loading') .load('engine.php', function () { $(this).removeClass('loading'); timerID = setTimeout(loadfeed, 6000); }); } $("#contactBtn").click(function() { clearTimeout(timerID); $("#feed").load('contact.php'); $("#feedBtn").bind('click', loadfeed); }); loadfeed(); }); </script> The key here is the use of a global timerID variable and the clearTimeout() function. If this works, you can include a Return to feeds button with id="feedBtn" in contact.php, but you’ll have to bind the loadfeed function to the button’s click event after loading it. A: You can load a file with $.load $("#contactBtn").click(function() { $("#feed").load('contact.html') No need for a callback or the timeout. } Check the jquery docs if you're looking for something more specific. Hope that helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548674", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to update data in a List extends Map> I'm making use of a List<? extends Map<String,?>> that I populated with data. cursor.moveToFirst(); while (cursor.getPosition() < cursor.getCount()) { item.put("ProdName",cursor.getString(2)); item.put("ProdSize", cursor.getString(3)); item.put("ProdPack",cursor.getString(4)); item.put("OrdQty","0"); //list.add(item); list.add(i, item); item = new HashMap<String,String>(); cursor.moveToNext(); i = i + 1; } How do I update a value for example in the OrdQty field? A: Looks like a very bad design to me. Java's an object-oriented language. Why don't you provide a real contract and create Product and Order objects? Give Order a List of Products to maintain. What you're proposing is less self-explanatory and harder to write and maintain. A: @Duffymo is right, you shouldn't use a map as a pseudo-object. This is how to update an object at a specific place (index) in a list. Map<String,?> ugly = list.get(index); Then you can do whatever you want with the object ugly. If you did it properly, it would look like this... Product p = list.get(index); p.setOrderQuantity(17);
{ "language": "en", "url": "https://stackoverflow.com/questions/7548675", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MS Access: Can't change the file type in the Save As dialog box I have an .mdb file created in access 2003 and I'd like to convert it to access 2007 .accdb but when I go to the Save as dialog it lets me save the file only as it's current format(.mdb) and there isn't any additional file formats in the drop down box. same thing happens when I create a new .accdb and try to save it as an 2003 .mdb file. I can't see anything but .accdb in the Save As file format drop down box. I could probably run a VBA code to save as my wanted file format but it isn't optimal. does any one knows what the solution might be? Thank you, Jake A: 'PUT THIS IN A STANDARD CLASS MODULE FIRST Option Compare Database Private mstrFileName As String Private mblnStatus As Boolean 'Declare needed functions Private Declare Function GetOpenFileName Lib "comdlg32.dll" Alias "GetOpenFileNameA" _ (pOpenfilename As OPENFILENAME) As Long Private Declare Function GetSaveFileName Lib "comdlg32.dll" Alias "GetSaveFileNameA" _ (pOpenfilename As OPENFILENAME) As Long 'Declare OPENFILENAME custom Type Private Type OPENFILENAME lStructSize As Long hwndOwner As Long hInstance As Long lpstrFilter As String lpstrCustomFilter As String nMaxCustFilter As Long nFilterIndex As Long lpstrFile As String nMaxFile As Long lpstrFileTitle As String nMaxFileTitle As Long lpstrInitialDir As String lpstrTitle As String Flags As Long nFileOffset As Integer nFileExtension As Integer lpstrDefExt As String lCustData As Long lpfnHook As Long lpTemplateName As String End Type 'Function needed to call the "Save As" dialog Public Function SaveFileDialog(lngFormHwnd As Long, _ lngAppInstance As Long, strInitDir As String, _ strFileFilter As String) As Long Dim SaveFile As OPENFILENAME Dim X As Long If IsMissing(strFileName) Then strFileName = "" With SaveFile .lStructSize = Len(SaveFile) .hwndOwner = lngFormHwnd .hInstance = lngAppInstance .lpstrFilter = strFileFilter .nFilterIndex = 1 .lpstrFile = String(257, 0) 'Use for a Default File SaveAs Name - [UD] '.lpstrFile = "testfile.txt" & String(257 - Len("testfile.txt"), 0) .nMaxFile = Len(SaveFile.lpstrFile) - 1 .lpstrFileTitle = SaveFile.lpstrFile .nMaxFileTitle = SaveFile.nMaxFile .lpstrInitialDir = strInitDir .lpstrTitle = "Enter a Filename to Save As" '[UD] .Flags = 0 .lpstrDefExt = ".xls" 'Sets default file extension to Excel, 'in case user does not type it - [UD] End With X = GetSaveFileName(SaveFile) If X = 0 Then mstrFileName = "none" mblnStatus = False Else mstrFileName = Trim(SaveFile.lpstrFile) mblnStatus = True End If End Function Public Property Let GetName(strName As String) mstrFileName = strName End Property Public Property Get GetName() As String GetName = mstrFileName End Property Public Property Let GetStatus(blnStatus As Boolean) mblnStatus = blnStatus End Property Public Property Get GetStatus() As Boolean GetStatus = mblnStatus End Property 'THEN WE'LL CALL IT LIKE Private Sub cmdTest_Click() On Error GoTo Err_cmdTest_Click Dim cDlg As New CommonDialogAPI 'Instantiate CommonDialog Dim lngFormHwnd As Long Dim lngAppInstance As Long Dim strInitDir As String Dim strFileFilter As String Dim lngResult As Long lngFormHwnd = Me.Hwnd 'Form Handle lngAppInstance = Application.hWndAccessApp 'Application Handle strInitDir = "C:\" 'Initial Directory - [UD] 'Create any Filters here - [UD] strFileFilter = "Excel Files (*.xls)" & Chr(0) & "*.xls" & Chr(0) & _ "ALL Files (*.*)" & Chr(0) & "*.* & Chr(0)" '"Text Files (*.csv, *.txt)" & _ 'Chr(0) & "*.csv; *.txt" & Chr(0) lngResult = cDlg.SaveFileDialog(lngFormHwnd, _ lngAppInstance, strInitDir, strFileFilter) If cDlg.GetStatus = True Then MsgBox "You chose the Filename of: " & cDlg.GetName 'Retrieve Filename - [UD] Else MsgBox "No file chosen." '[UD] End If Exit_cmdTest_Click: Exit Sub Err_cmdTest_Click: MsgBox Err.Description, vbExclamation, "Error in cmdTest_Click()" Resume Exit_cmdTest_Click End Sub
{ "language": "en", "url": "https://stackoverflow.com/questions/7548678", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: My posted date via php is off 1 hour... How to fix? My date is ahead 1 hour when I post to mySQL via php. I'm in Los Angeles. How can i make the time correct? Here is what I currently have: $date = date("m/d/y g:i A") ; A: see date_default_timezone_set like date_default_timezone_set('America/Los_Angeles'); A: First check if servers time is correct ( on linux use date shell command). If yes, you just set the time and you're good. If not you have to change it in php with setlocale() or date_default_timezone_set() function A: Use this to get the time zone PHP is using date_default_timezone_get(); If you're in Los Angeles you can set your time zone temporarily for only the current script date_default_timezone_set('America/Los_Angeles'); http://php.net/manual/en/function.date-default-timezone-set.php Also pass T in the date function: echo date("D M j G:i:s T Y"); outputs Mon May 25 16:23:49 EDT 2009 A: It depends on your specific case, but I had saved the date as UTC / GMT time, so I had to use the gmdate function instead of date. E.g. gmdate("H:i",$time)
{ "language": "en", "url": "https://stackoverflow.com/questions/7548686", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Cakephp mysql connect errors with remote database Just baked an app and got this on my cake homepage Warning (2): mysql_connect() [function.mysql-connect]: Premature end of data (mysqlnd_wireprotocol.c:554) [CORE\cake\libs\model\datasources\dbo\dbo_mysql.php, line 561] Warning (2): mysql_connect() [function.mysql-connect]: OK packet 1 bytes shorter than expected [CORE\cake\libs\model\datasources\dbo\dbo_mysql.php, line 561] Warning (2): mysql_connect() [function.mysql-connect]: mysqlnd cannot connect to MySQL 4.1+ using the old insecure authentication. Please use an administration tool to reset your password with the command SET PASSWORD = PASSWORD('your_existing_password'). This will store a new, and more secure, hash value in mysql.user. If this user is used in other scripts executed by PHP 5.2 or earlier you might need to remove the old-passwords flag from your my.cnf file [CORE\cake\libs\model\datasources\dbo\dbo_mysql.php, line 561] Cake is NOT able to connect to the database. This issue only occurs when connecting to a remote database, connecting to a localhost database gives me no problems. A: http://dev.mysql.com/doc/refman/5.1/en/old-client.html The database is using an old-style of password hash for the user that mysql_connect is trying to login with. The mysql driver in php that you are running is incompatible with the old-style of password hash. As it says, it wants you to regenerate the password using the new-style of hash. This problem isn't really related to cakephp, but rather PDO and its mysql driver.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548690", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C++ operator() optimization on vectors I'm writing numerical code, in which it is useful to define vector operations. E.g if x and y are n-long vectors full of floats, it is nice to have x^y result in a in the ith element of y equaling some arbitary function of the ith element of x. One simple way of doing this is: #include <vector> #include <stdio.h> #include <ctime> using namespace std; template <typename T> void operator^(vector<T> A, vector<T> B){ typename vector<T>::iterator a = A.begin(); typename vector<T>::iterator b = B.begin(); while(a!=A.end()){ *b = 2*(*a); a++; b++; } //for (uint i=0; i<A.size(); i++) //B[i] = 2*A[i]; } int main(int argc, char** argv){ int n = 10000; int numRuns = 100000; vector<float> A; for (int i=0; i<n; i++) A.push_back((float) i); vector<float> B = vector<float>(n); clock_t t1 = clock(); for (int i=0; i<numRuns; i++) for (int j=0; j<n; j++) B[j] = 2*A[j]; clock_t t2 = clock(); printf("Elapsed time is %f seconds\n", double(t2-t1)/CLOCKS_PER_SEC); t1 = clock(); for (int i=0; i<numRuns; i++) B^A; t2 = clock(); printf("Elapsed time is %f seconds\n", double(t2-t1)/CLOCKS_PER_SEC); return 0; } Now, when run on my computer after -O3 compiling, the output is Elapsed time is 0.370000 seconds Elapsed time is 1.170000 seconds If instead I use the commented out lines in the template, the second time is ~1.8 seconds. My question is: how do I speed up the operator call? Ideally it should take the same amount of time as the hand-coded loop. A: You're passing the arguments by value. That makes copies of the vectors. template <typename T> void operator^(vector<T> A, vector<T> B) If you pass them by reference, you may get a speedup. template <typename T> void operator^(vector<T> const& A, vector<T>& B) (A quick test on ideone.com shows even better performance than the hand-written loop, but I don't know what optimizations they enable on the compilation.) On another note, you probably want to overload some other operator. It's bad style to have non-assignment and non-increment operators modifying their arguments (I recommend reading the Operator Overloading FAQ). You should overload operator^= instead. template <typename T> vector<T>& operator^=(vector<T>& B, vector<T> const& A){ typename vector<T>::const_iterator a = A.begin(); typename vector<T>::iterator b = B.begin(); while(a!=A.end()){ *b = 2*(*a); a++; b++; } return B; } A: Another thought is to use valarrays, which were intended expressly for this purpose, and have a large number of operators defined for you already. A description of their usage and operations can be found here: http://www.cplusplus.com/reference/std/valarray/ A discussion of them can be found here indicating some pros and cons: C++ valarray vs. vector
{ "language": "en", "url": "https://stackoverflow.com/questions/7548691", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to grab number after word in python I have a huge file containing the following lines DDD-1126N|refseq:NP_285726|uniprotkb:P00112 and DDD-1081N|uniprotkb:P12121, I want to grab the number after uniprotkb. Here's my code: x = 'uniprotkb:P' f = open('m.txt') for line in f: print line.find(x) print line[36:31 + len(x)] The problem in line.find(x) is 10 and 26, I grab the complete number when it is 26. I'm new to programming, so I'm looking for something to grab the complete number after the word. x = 'uniprotkb:' f = open('m.txt') for line in f: if x in line: print the number after x A: import re regex = re.compile('uniprotkb:P([0-9]*)') print regex.findall(string) A: The re module is quite unnecessary here if x is static and always matches a substring at the end of each line (like "DDD-1126N|refseq:NP_285726|uniprotkb:P00112"): x = 'uniprotkb:' f = open('m.txt') for line in f:   if x in line:     print line[line.find(x)+len(x):] Edit: To answer you comment. If they are separated by the pipe character (|), then you could do this: sep = "|" x = 'uniprotkb:' f = open('m.txt') for line in f:   if x in line:     matches = [l[l.find(x)+len(x):] for l in line.split(sep) if l[l.find(x)+len(x):]] print matches If m.txt has the following line: DDD-1126N|uniprotkb:285726|uniprotkb:P00112 Then the above will output: ['285726', 'P00112'] Replace sep = "|" with whatever the column separator would be. A: Use regular expressions: import re for line in open('m.txt'): match = re.search('uniprotkb:P(\d+)', line) if match: print match.group(1) A: Um, for one thing I'd suggest you use the csv module to read a TSV file. But generally, you can use a regular expression: import re regex = re.compile(r"(?<=\buniprotkb:)\w+") for line in f: match = regex.search(line) if match: print match.group() The regular expression matches a string of alphanumeric characters if it's preceded by uniprotkb:.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548692", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: masking UIImageView when it leaves the UIViewController's frame I have an Advertisement UIViewController class that contains the following code. The frame is the exact dimension of the image. When it animates down I want it to disappear at the 76.0 point. I made the UIViewController's frame the same size as the image too, but it doesn't obscure any of the image when it slides down. How do I make it so that I cannot see the uiimageview when it leaves the UIViewController frame? -(void)viewDidLoad{ UIImageView *ad = [[UIImageView alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 76.0)]; ad.image = [UIImage imageNamed:@"advertisement.jpg"]; [self.view addSubview:ad]; [ad release]; [UIView animateWithDuration:1.0 //animate the content offset delay:6.0 options:UIViewAnimationCurveEaseIn animations:^{ ad.frame = CGRectMake(0.0, 152.0, 320.0, 76.0); } completion:^(BOOL finished){ } ]; } Appdelegate: Advertisement *theAdView = [[Advertisement alloc] init]; theAdView.view.frame = CGRectMake(0.0, self.window.frame.size.height-120.0, 320.0, 76.0); [self.window addSubview:theAdView.view]; A: Set the clipsToBounds property on the view (of the viewcontroller) to YES. Subviews of the view will then be drawn only within the bounds of the view. UIView documentation
{ "language": "en", "url": "https://stackoverflow.com/questions/7548693", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: 2D Circle and rectangle intersection tests What I'm doing is testing to see what the level of intersection between a circle and rectangle. I would like to find whether the rectangle is completely inside the circle, partially intersecting it, or if there is no intersection at all. I've attached the code that I've come up with today, it simply checks the distances from the center of the circle to the corners of the rectangle to determine the level of intersection. What I'm wondering is there a more efficient way of doing this? EDIT: Here is my updated, working code. fullIntersect is my own, I found the partialIntersect snippet on Circle-Rectangle collision detection (intersection). I'm going to leave this open, as I'm still curious as to whether there is a better way of doing this. public boolean fullIntersect(float circleX, float circleY, float radius) { float radsq = radius * radius; double xsq = Math.pow(circleX - xPosition, 2); double xpwsq = Math.pow(circleX - (xPosition + width), 2); double ysq = Math.pow(circleY - yPosition, 2); double yphsq = Math.pow(circleY - (yPosition + height), 2); if(xsq + ysq > radsq || xsq + yphsq > radsq || xpwsq + yphsq > radsq || xpwsq + ysq > radsq) return false; return true; /* this is what the one if statement does double disBotLeft = xsq + ysq; double disTopLeft = xsq + yphsq; double disTopRight = xpwsq + yphsq; double disBotRight = xpwsq + ysq; if(disBotRight > radsq) return false; if(disBotLeft > radsq) return false; if(disTopLeft > radsq) return false; if(disTopRight > radsq) return false; return true; */ } public int intersects(float circleX, float circleY, float radius) { if(!enabled) return 0; double wo2 = width / 2.0d; double ho2 = height / 2.0d; double circleDistanceX = Math.abs(circleX - xPosition - wo2); double circleDistanceY = Math.abs(circleY - yPosition - ho2); if (circleDistanceX > (wo2 + radius)) { return 0; } if (circleDistanceY > (ho2 + radius)) { return 0; } if(fullIntersect(circleX, circleY, radius)) { return 2; } if (circleDistanceX <= (wo2)) { return 1; } if (circleDistanceY <= (ho2)) { return 1; } double cornerDistance_sq = Math.pow(circleDistanceX - wo2,2) + Math.pow(circleDistanceY - ho2,2); return cornerDistance_sq <= (radius*radius) ? 1 : 0; } A: I think your code does not consider these intersections: I'll delete this answer as soon as you enhance your code/question.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548696", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: QuantumGrid VCL - How to change the text of a Hyperlink column in the cell click event? Using: Delphi XE, Devexpress VCL. In the cell click event, I am trying to change the value of a cell in a hyperlink column in Devexpress's QuantumGrid VCL control. The column is a custom column and is not bound to the dataset. The hyperlink column's properties are set as per: Editing := False; ReadOnly := True; SingleClick := True; The following code (grdReprint is the grid's DBTableView, and, grdReprintColumn2 is the Hyperlink column) is ineffective: procedure TfReceiptList.grdReprintCellClick(Sender: TcxCustomGridTableView; ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton; AShift: TShiftState; var AHandled: boolean); var v: integer; c: integer; begin if ACellViewInfo.Item = grdReprintColumn1 then begin v := datamod.uspRECEIPT_LSTRECEIPTID.AsInteger; fMain.PrintReceipt(v); end else if ACellViewInfo.Item = grdReprintColumn2 then begin (* This code is ineffective because the cell contents do not change *) if ACellViewInfo.Text = 'Void' then grdReprint.DataController.SetEditValue(grdReprintColumn2.Index, 'Unvoid', evsValue) else grdReprint.DataController.SetEditValue(grdReprintColumn2.Index, 'Void', evsValue); end; end; If the above isn't the proper way to change the text in the cell, then other ideas are welcome. TIA. A: When the SingleClick property in the hyperlink control is set to TRUE the GridViews CellClick event is not called. (I may be able to further help if I could understand why you a using a hyperlink control for what looks like just text. See my coments below your question.) EDIT: This answer is incorrect if the gridViews Editing property is False as OP indicated. It is does describe the behavior if Editing is True FWIW.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548698", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why broadcastreceiver doesn't receive the broadcast? As mentioned in the question, and the following shows mu code .. AlarmActivity package adham.test; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class AlarmActivity extends Activity { /** Called when the activity is first created. */ Button btnStart,btnStop; Context context; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); btnStart=(Button)this.findViewById(R.id.btnStart); btnStop=(Button)this.findViewById(R.id.btnstop); context = this.getApplicationContext(); startService(new Intent(context,AlarmService.class)); btnStart.setOnClickListener(new OnClickListener(){ @Override public void onClick(View arg0) { startService(new Intent(context,AlarmService.class)); } }); btnStop.setOnClickListener(new OnClickListener(){ @Override public void onClick(View arg0) { stopService(new Intent(context,AlarmService.class)); } }); } } AlarmReceiver package adham.test; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.widget.Toast; public class AlarmReceiver extends BroadcastReceiver { @Override public void onReceive(Context c, Intent i) { try{ Bundle b = i.getExtras(); String msg = b.getString("alarm_message"); Log.d("Receiverr ---","now"); Toast.makeText(c, msg, Toast.LENGTH_LONG).show(); }catch(Exception e){ } } } AlarmService package adham.test; import java.util.Calendar; import android.app.AlarmManager; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.os.IBinder; import android.widget.Toast; public class AlarmService extends Service { private static final String TAG = "MyService"; Context c; @Override public IBinder onBind(Intent arg0) { // TODO Auto-generated method stub return null; } @Override public void onCreate() { Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show(); c= this; } @Override public void onStart(Intent intent, int startid) { Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show(); Calendar cal = Calendar.getInstance(); cal.add(Calendar.SECOND, 10); Intent i = new Intent(c,AlarmReceiver.class); i.putExtra("alarm_message", "Hello, Alarm is running !"); PendingIntent pi= PendingIntent.getActivity(c, 19237, i, PendingIntent.FLAG_UPDATE_CURRENT); AlarmManager am = (AlarmManager)c.getSystemService(ALARM_SERVICE); am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pi); } @Override public void onDestroy(){ Toast.makeText(this, "My Service Destroyed", Toast.LENGTH_LONG).show(); } } AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="adham.test" android:versionCode="1" android:versionName="1.0"> <uses-sdk android:minSdkVersion="9" /> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".TestServicesActivity" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <service android:name=".AlarmService"></service> <activity android:name=".AlarmActivity"></activity> <receiver android:process=":remote" android:name=".AlarmReceiver"></receiver> </application> </manifest> A: I think you never raise any broadcast. Your code shows: Intent i = new Intent(c,AlarmReceiver.class); i.putExtra("alarm_message", "Hello, Alarm is running !"); PendingIntent pi= PendingIntent.getActivity(c, 19237, i, PendingIntent.FLAG_UPDATE_CURRENT); You are calling getActivity but AlarmReceiver is a Broadcast, you need to call getBroadcast(...) instead.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548708", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Regular Expression to match a string, that doesn't end in a certain string I an trying to write a regular expression to be used as part of a replace operation. I have many paths as follows: <ProjectReference Include="..\Common.Workflow\Common.Workflow.csproj"> <ProjectReference Include="..\Common.Workflow\Common.Workflow.Interfaces\Common.Workflow.Interfaces.csproj"> <ProjectReference Include="..\Common.Workflow\Common.Workflow.Persistence\Common.Workflow.Persistence.csproj"> <ProjectReference Include="..\Common.Workflow\Common.Workflow.Process\Common.Workflow.Process.csproj"> I need to replace the Common.Workflow\ in all cases except where the it contains Common.Workflow.csproj. I am moving these files as part of a code clean up. A: Replace Common\.Workflow\\(?!Common\.Workflow\.csproj) with what you need. A: Use a negative look-ahead and a negative look-behind, like this: (?<!.*Common.Workflow.csproj)Common.Workflow\\(?!.*Common.Workflow.csproj) Explanation: * *(?<!.*Common.Workflow.csproj) means "Common.Workflow.csproj must not appear before the match *(?!.*Common.Workflow.csproj) means "Common.Workflow.csproj must not appear after the match" This regex will prevent matching if Common.Workflow.csproj appears anywhere in the input (you didn't specify that the negative match only appears after the search)
{ "language": "en", "url": "https://stackoverflow.com/questions/7548710", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Multi-level navigation menu options? I am doing a small web project for a friend's business. I'm looking for a plug and play navigation menu that I can use that supports multi-level navigation. I'd also like to have as much styling control as possible with the navigation menu. The best free menu I found on the web was jQuery Superfish. It does not seem to of been updated in a while and I am wondering if its still a good choice, or are there better alternatives. I already have jQuery loaded on the site, so I would prefer a plugin that uses jQuery or does not require a lot of additional framework dependencies. Thanks for the input.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548717", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: jQuery UI Autocomplete ignore non alphanumeric letters I want to ignore all non alphanumeric letters from autocomplete input. For example if user inputs K P COLLECTION it can search K. P. COLLECTION. This is my code on http://jsbin.com/usupem Code: var autocomplete_data = data here... $( ".autocomplete" ).autocomplete({ source: function(req, response) { var re = $.ui.autocomplete.escapeRegex(req.term); var matcher = new RegExp( "^" + re, "i" ); response($.grep(autocomplete_data, function(item){return matcher.test(item.label); }) ); }, focus: function( event, ui ) { $( ".autocomplete" ).val( ui.item.label ); return false; }, select: function( event, ui ) { $( ".autocomplete" ).val( ui.item.label ); return false; } }).data( "autocomplete" )._renderItem = function( ul, item ) { return $( "<li></li>" ).data( "item.autocomplete", item ).append( "<a>" + item.label + "<br><small>" + item.desc + "</small></a>" ).appendTo( ul ); }; A: You should strip the non alpha-numeric characters from both the input and the term that you're matching. Try calling something like this on both the req.term and item.label values in your source function: function stripNonAlphaNumeric(string){ var r = string.toLowerCase(); r = r.replace(new RegExp("[^A-z0-9 ]", 'g'), ""); return r; } http://jsbin.com/ufetiq/3
{ "language": "en", "url": "https://stackoverflow.com/questions/7548718", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Base Classes on Proxy Objects I have a webservice that is wrapped up by a data access object and is accessed by many different UI controls. The proxy objects look something like this: Public Class WebProxyObject1 ' Common properties, there are about 10 of these Public Name As String Public Address As String ' Specialized properties there are about 20 of these Public count As Integer End Class The DAL layers look something like this: Public Class DataAccessObject Implements IDataAccessObject ' These are called in MANY, MANY, MANY locations Public Function GetObject(ByVal name As String) As WebProxyObject1 Implements IDataAccessObject.GetObject ' Makes call to a webservice Return New WebProxyObject1 End Function Public Function ListObjects() As System.Collections.Generic.List(Of WebProxyObject1) Implements IDataAccessObject.ListObjects ' Makes call to a webservice Dim list As New List(Of WebProxyObject1) Return list End Function End Class Now, I need to add a 2nd webservice to the mix. The goal is to reuse the UI controls that are currently coded to use the Proxy Objects that come from the first webservice. There are about 10 common properties and about 20 that are different. To add the 2nd webservice, I'd create a 2nd DAL object that implements the same interface. The problem is that it currently returns the proxies from the first webservice. My thought on how to solve this is to extract an interface from each of the proxy objects and mash them together. Then implement the new interface on both proxy objects. That will create a huge class/interface where some properties aren't used. Then have the DAL return the interface. The problem that I'm facing isn't a real bug or an issue, but extracting the 2 interfaces and smashing them together just feels kind of wrong. I think it would technically work, but it kind of smells. Is there a better idea? The resulting interface would look like this: Public Interface IProxyObject ' Common Property Name() As String Property Address() As String ' Specialized Property Count() As Integer Property Foo() As Integer End Interface A: Create a base class for your WebProxyObjects to inherit from. Public MustInherit Class WebProxyObjectBase ' Common properties Public Property Name As String Public Property Address As String End Class Next create your two WebProxyObjects: Public Class WebProxyObject1 Inherits From WebProxyObjectBase ' Specialized properties Public Property count As Integer End Class Public Class WebProxyObject2 Inherits From WebProxyObjectBase ' Specialized properties Public Property foo As Integer End Class Next have your DAL return the Base Class: Public Class DataAccessObject Implements IDataAccessObject ' These are called in MANY, MANY, MANY locations Public Function GetObject(ByVal name As String) As WebProxyObjectBase Implements IDataAccessObject.GetObject ' Makes call to a webservice Return New WebProxyObjectBase End Function Public Function ListObjects() As System.Collections.Generic.List(Of WebProxyObjectBase) Implements IDataAccessObject.ListObjects ' Makes call to a webservice Dim list As New List(Of WebProxyObjectBase) Return list End Function End Class Then when calling your DataAccessObject you'll be able to ctype the return to the proper class: Dim DAO as New DataAccessObject Dim Pxy1 as WebProxyObject1 = TryCast(DAO.GetObject("BOB"), WebProxyObject1) If Pxy1 IsNot Nothing Then 'Do stuff with proxy End If
{ "language": "en", "url": "https://stackoverflow.com/questions/7548720", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Alternate of BufferedImage in C++ I am using BufferedImage in my Java program for storing some information in an image. The problem is that I want to create a similar program in C++ but I can't find an alternate of BufferedImage.. Looking forward to some useful ideas. Thanks A: You can have a look at the cairo library: http://cairographics.org/ In the examples: cairo_surface_t *surface; cairo_t *cr; surface = cairo_image_surface_create (CAIRO_FORMAT_ARGB32, 120, 120); cr = cairo_create (surface);
{ "language": "en", "url": "https://stackoverflow.com/questions/7548722", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: JavaScript timeout on iPad Safari vs. Win 7 Safari I am using the latest version of jqGrid (4.x) for an application displaying local data. * *Win7: All works fine on several browsers (Chrome, FF, IE, Safari). *In iPad's Safari the grid works excellent, but there is one issue: When I unload the grid because I need to redefine its columns, this either takes extremely long or times out. I am using purely local objects - no back-end connectivity involved. Debug console on iPad Safari: JavaScript execution exceeded timeout I have tried both ways: $("#myGrid").GridUnload(); $("#myGrid").GridUnload("#myGrid"); I can reproduce the issue, when I skip the GridUnload part the issue is gone. As said above, on a Win7 Safari this is not problem at all. Any ideas how I could work around the issue? -- UPDATE --- This issue was very hard to trace for me, since I am not aware of how to debug JS code on an iPad. So far, this issue seems not to be specific to jqGrid, but the timeout happens whenever something in JS takes to long. For some reasons I do not understand yet, this seems to be the GridUnload(). Can somebody tell me, whenever this Safari iPad Javascript timeout is happening, I have no idea what triggers it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548728", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Cron job not working in Whenever gem I have an application that contains a bunch of tasks, and every day I want to run a cron job that creates a DayTask for each Task in the database. A Task has_many DayTasks and these daytasks are what users will be checking off every day. I'm using the whenever gem but it doesn't seem to be running at all. Any ideas? config/schedule.rb every 1.day, :at => "12:01am" do runner "Task.generate_tasks_for_day" end Task.rb def generate_tasks_for_day Task.all.each do |task| task.day_tasks.create(:target_date => Date.today) end end result of running the 'whenever command' 1 0 * * * /bin/bash -l -c 'cd /home/grant/rails_projects/GoalTwist && script/rails runner -e production '\''Task.generate_tasks_for_day'\''' Note: I've been changing the times in config/schedule.rb every time I want to test run it. A: You have to actually register the job with the crontab by running: whenever --update-crontab Also if you're trying to get jobs running locally, add :environment => "development" to your task runner "MyTask.some_action", :environment => "development" A: Finally I have solved how to run the gem Whenever. It's working good on production, but not in development mode (I think that to working good in dev mode you must do some tricks). Then, these are the processes to do: * *install the gem *write your scheduler.rb file *push to the remote server *login to the remote server (for example with ssh) *see if whenever is good uploaded by running in terminal: whenever *update whenever crontab by running: whenever --update-crontab *restart the server crontab (for example in Ubuntu server): sudo service cron restart *check if crontab is good implemented on the server: crontab -l That's it! Personally, I prefer to set up my crons directly from the server: * *Edit the crontab: crontab -e *Append my cron (e.g. every day at 5:00 AM - can be little different for not-Linux-based server): 0 5 * * * /bin/bash -l -c 'cd /path_to_my_app/current && RAILS_ENV=production bundle exec rake my_cron_rake' *Check if good implemented: crontab -l *Done A: Try to execute the whenever generated command directly from terminal or add the following line MAILTO=your@emailadress.com to your crontab. A: if whenever command gives you -bash: whenever: command not found, try bundle exec whenever
{ "language": "en", "url": "https://stackoverflow.com/questions/7548730", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "24" }
Q: Validations not done while submitting rails form via jquery I did a simple rails form with two user inputs , name and email. I'm using rails 3.1, so I used :remote => true in my form_for tag. I also created a create.js.erb and added corresponding format.js in the users_controller.rb. I added the following lines in create.js.erb $(document).ready(function(){ $('body').html("<h1>Registration Successful</h1>") }); Now the problem is that when I click the submit button, with empty fields, it does not show validations error messages that I have added in the user.rb model file. Instead, it will show me registration successful message. Is there some easy way to circumvent this problems in rails. Also please note that I'm very bad at javascript, so please be nice to me. controller code for create def create @user = User.new(params[:user]) respond_to do |format| if @user.save #UserMailer.registration_confirmation(@user).deliver format.html { redirect_to @user, notice: 'User was successfully created.' } format.js else format.html { render action: "new" } format.js end end end A: The reason it doesn't show the errors is because you are not telling it to, you are simply telling it to write "Registration Successful". You could try: <% @user.errors.full_messages.each do |error| %> $('body').prepend("<h1><%=error%></h1>"); <% end %> This assumes that your controller has the following or something similar: @user = User.create(params[:user]) Hopefully this is enough to get you started. If not, some controller code will be required to help further.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548735", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: copy rows from srce to dest ignoring records already in dest I have two tables in two seperate databases with slightly different structures: destTable: name, address, city, state, zip, country, email, phone, company srceTable: company, address, city, state, zip, country, name, email, phone When I try to use this statement: INSERT INTO db1.destTable (name, address, city, state, zip, country, email, phone, company) SELECT company, address, city, state, zip, country, name, email, phone FROM db2.srceTable WHERE db2.srceTable.email NOT EXISTS(SELECT email FROM db1.destTable WHERE (db2.srceTable.email=db1.destTable.email) I get this error: #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'EXISTS(SELECT email FROM srceTable' at line 4 I've tried several versions of this and replaced EXISTS with NOT IN and everything produces an error. What's the secret to this copy? (oh, and I only have the email field that I worry about being a dup). Thanks, Pete A: You're missing the last ) from the NOT EXISTS statement. INSERT INTO db1.destTable (name, address, city, state, zip, country, email, phone, company) SELECT company, address, city, state, zip, country, name, email, phone FROM db2.srceTable WHERE db2.srceTable.email NOT EXISTS(SELECT email FROM db1.destTable WHERE (db2.srceTable.email=db1.destTable.email)) A: Maybe you were trying to use NOT IN? INSERT INTO db1.destTable (name, address, city, state, zip, country, company, email, phone) SELECT company, address, city, state, zip, country, name, email, phone FROM db2.srceTable WHERE db2.srceTable.email NOT IN (SELECT email FROM db1.destTable) Also the number of columns in your INSERT and SELECT statements were different. EDIT: OK, so the fields were subtly different in that I failed to notice the name in the SELECT statement. I've edited my statement so now it swaps the name and company, because I still can't understand the ordering in the original statement. A: You could just make a unique index on the email column. Then do INSERT IGNORE INTO ... The records already in the destination will be silently ignored. No need for the where clause. A: you have to remove db2.srceTable.email after WHERE clause and add an ) at the end, also reorder your SELECT fields, you can have mixed data in your columns else INSERT INTO db1.destTable (name, address, city, state, zip, country, email, phone, company) SELECT name, address, city, state, zip, country, email, phone, company FROM db2.srceTable WHERE NOT EXISTS (SELECT email FROM db1.destTable WHERE db2.srceTable.email=db1.destTable.email)
{ "language": "en", "url": "https://stackoverflow.com/questions/7548737", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Countdown with jQuery So, I have this outputted from my DB: 00:01:53 Inside a span tag <span class="jb_timer">00:01:53</span> So my question is, how can I make it countdown with jQuery? Thanks. A: Here's something that should get you started in the right direction: var remaining = $("span.jb_timer").text(), regex = /\d{2}/g, matches = remaining.match(regex), hours = matches[0], minutes = matches[1], seconds = matches[2], remainingDate = new Date(); remainingDate.setHours(hours); remainingDate.setMinutes(minutes); remainingDate.setSeconds(seconds); var intvl = setInterval(function () { var totalMs = remainingDate.getTime(), hours, minutes, seconds; remainingDate.setTime(totalMs - 1000); hours = remainingDate.getHours(); minutes = remainingDate.getMinutes(); seconds = remainingDate.getSeconds(); if (hours === 0 && minutes === 0 && seconds === 0) { clearInterval(intvl); } $("span.jb_timer").text( (hours >= 10 ? hours : "0" + hours) + ":" + (minutes >= 10 ? minutes : "0" + minutes) + ":" + (seconds >= 10 ? seconds : "0" + seconds)); }, 1000); Working Example: http://jsfiddle.net/andrewwhitaker/YbLj4/ Notes: * *First you have to parse the initial hours, minutes, and seconds out of the span's text. Do this using a simple regular expression. *Use setInterval to set up a timer that runs every 1000 milliseconds. *When that timer fires, subtract 1000 ms from the time and update the span's text appropriately. *When the hours, minutes, and seconds reach 0, clear (cancel) the interval. A: Here's a very simple one that seems to accomplish exactly what you're looking for. It doesn't have the bells and whistles of the scripts Hanlet linked to, and I think it's a bit simpler than Andrew's solution (even if there are more lines of code... mine doesn't use regular expressions, nor the Date() object). http://jsfiddle.net/ct3VW/2/ function countDown(timeDiv){ var timeStringArray = timeDiv.text().split(':'); var timeNumberArray = []; //the following loop simply converts the values in timeStringArray to actual numbers for(var i = 0; i < 3; i++){ timeNumberArray.push(parseInt(timeStringArray[i],10)); } timeNumberArray[2]--; //decrement the seconds if(timeNumberArray[2] < 0 && timeNumberArray[1] > 0){ timeNumberArray[1]--; timeNumberArray[2] = 59; } //this if statement won't have any effect because the sample timer doesn't have any hours at the moment if(timeNumberArray[1] < 0 && timeNumberArray[0] > 0){ timeNumberArray[0]--; timeNumberArray[1] = 59; } var newTimeString = (timeNumberArray[0] < 10) ? '0' + timeNumberArray[0] : timeNumberArray[0]; for(var i = 1; i < 3; i++){ var timePart = (timeNumberArray[i] < 10) ? ':0' + timeNumberArray[i] : ':' + timeNumberArray[i]; newTimeString += timePart; } if(timeNumberArray[2] !== 0){ //don't want to call the function again if we're at 0 timeDiv.text(newTimeString); setTimeout( (function(){ countDown(timeDiv) }),1000); }else{ //here's where you could put some code that would fire once the counter reaches 0. } } $(function(){ countDown($('div')); }); A: There are tons of samples and scripts in the Internet. Maybe you will like one of these
{ "language": "en", "url": "https://stackoverflow.com/questions/7548747", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Data Virtualization not working I have been trying to gain performance by implementing virtualization for my ListView. I use the following article to achieve that : WPF: Data Virtualization By Paul McClean http://www.codeproject.com/KB/WPF/WpfDataVirtualization.aspx the problem is that instead of loading just a couple of pages, all the pages are actually loaded which is weird. all the items are loaded when the Control is loaded. Here is my ListView : <ListView ItemsSource="{Binding}" VirtualizingStackPanel.IsVirtualizing="True" VirtualizingStackPanel.VirtualizationMode="Recycling" ScrollViewer.IsDeferredScrollingEnabled="True"> <ListView.ItemsPanel> <ItemsPanelTemplate> <VirtualizingStackPanel> </VirtualizingStackPanel> </ItemsPanelTemplate> </ListView.ItemsPanel> <ListView.View> <GridView> <GridViewColumn Width="250"> <GridViewColumn.Header> <TextBlock Text="Part Number" HorizontalAlignment="Left"></TextBlock> </GridViewColumn.Header> <GridViewColumn.CellTemplate> <DataTemplate> <TextBlock Text="{Binding Part.PartNumber}"></TextBlock> </DataTemplate> </GridViewColumn.CellTemplate> </GridViewColumn> <GridViewColumn Header="Description" Width="250"> <GridViewColumn.CellTemplate> <DataTemplate> <TextBlock Text="{Binding Part.Description}"></TextBlock> </DataTemplate> </GridViewColumn.CellTemplate> </GridViewColumn> <GridViewColumn Header="Current Price" Width="250"> <GridViewColumn.CellTemplate> <DataTemplate> <TextBlock Text="{Binding CurrentPrice}"></TextBlock> </DataTemplate> </GridViewColumn.CellTemplate> </GridViewColumn> <GridViewColumn Header="Old Price" Width="250"> <GridViewColumn.CellTemplate> <DataTemplate> <TextBlock Text="{Binding OldPrice}"></TextBlock> </DataTemplate> </GridViewColumn.CellTemplate> </GridViewColumn> </GridView> </ListView.View> </ListView> A: I just realized that I was using a ScrollViewer (with property ScrollViewer.VerticalScrollBarVisibility="Visible") around my ListView which is why all the items were being loaded at once. I removed it and everything now works fine.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548752", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Second Activity shows blank screen after first Activity starts Intent Hi I'm trying to use an implicit intent to start a second activity. The TextView and Button work for Activity One, but when I click the button to start the second activity, I do not see any of the TextViews in the second activity. All I get is a black blank screen. If I press back, it takes me back to Activity One. I also followed this just as a test: http://mubasheralam.com/tutorials/android/how-start-another-activity And same thing happens. I can see Activity One, but Activity Two is just a blank screen. Here is my code: ActivityOne.java: import android.app.Activity; import android.os.Bundle; import android.widget.TextView; import android.content.Context; import android.content.Intent; import android.widget.Button; import android.view.View.OnClickListener; import android.view.View; import android.widget.LinearLayout; public class ActivityOne extends Activity implements OnClickListener { private TextView mytext; private Button mybutton; private LinearLayout linearlayout; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); linearlayout = new LinearLayout(this); mytext = new TextView(this); mybutton = new Button(this); mybutton.setText("Next Activity"); mybutton.setOnClickListener(this); mytext.setText("Activity1"); linearlayout.addView(mytext); linearlayout.addView(mybutton); setContentView(linearlayout); } public void onClick(View v) { Intent intent = new Intent(); intent.setAction("com.example.hello.SHOW"); intent.putExtra("com.example.hello.Implicit_intent", "This is extras"); startActivity(intent); } } ActivityTwo.java import android.app.Activity; import android.os.Bundle; import android.widget.LinearLayout; import android.widget.TextView; public class ActivityTwo extends Activity { private TextView mytext; private LinearLayout linearlayout; public void OnCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mytext = new TextView(this); linearlayout = new LinearLayout(this); linearlayout.addView(mytext); Bundle extras = getIntent().getExtras(); mytext.setText("Activity One value: " + extras.getString("com.example.hello.Implicit_intent")); setContentView(linearlayout); } } AndroidManifest.xml: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.hello" android:versionCode="1" android:versionName="1.0"> <uses-sdk android:minSdkVersion="10" /> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".ActivityOne" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".ActivityTwo" android:label="@string/app_name"> <intent-filter> <action android:name="com.example.hello.SHOW" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity> </application> </manifest> I'm using Android Emulator 2.3.3, CPU/ABI is ARM A: You could try adding layout params to the textview and linear layout in ActivityTwo like public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ViewGroup.LayoutParams tParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); ViewGroup.LayoutParams lParams = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); mytext = new TextView(this); linearlayout = new LinearLayout(this); mytext.setLayoutParams(tParams); linearlayout.setLayoutParams(lParams); linearlayout.addView(mytext); Bundle extras = getIntent().getExtras(); mytext.setText("Activity One value: " + extras.getString("com.example.hello.Implicit_intent")); setContentView(linearlayout); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7548753", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Set date format with existing records php mySQL. How? I have a mySQL with a table. There are 30 records all with a date column. How do I change all my existing records in my table to have today's date with is format? date_default_timezone_set('America/Los_Angeles'); $date = date("m/d/y g:i A") ; A: Here's the fix for the VARCHAR to DATETIME (this will erease the current value): ALTER TABLE mytable modify column `mycolumn` datetime NOT NULL DEFAULT 0; UPDATE mytable SET mycolumn = NOW() WHERE ...; or UPDATE mytable SET mycolumn = '2011-09-25 17:40:00' WHERE ...; If you want to save the current value use: ALTER TABLE mytable add column `newdate` datetime NOT NULL DEFAULT 0; UPDATE mytable SET newdate = mycolumn; ALTER TABLE mytable DROP COLUMN mycolumn; If you want to select the date in the format you can: SELECT DATE_FORMAT(mycolumn, '%m/%e/%y %h:%i %p') FROM mytable WHERE ... Or in your PHP you can use: date_default_timezone_set('America/Los_Angeles'); // query select ($row = mysql_fetch_assoc($query)... $date = $date = date("m/d/y g:i A", strtotime($row['mycolumn']));
{ "language": "en", "url": "https://stackoverflow.com/questions/7548755", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Android. Launch dialog from context menu I have a listView and want on long press show my custom dialog. How I cat to do this? All my attempts brought nothing to me. Dialog never shows, ANR is occurs. @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); ExpandableListView.ExpandableListContextMenuInfo info = (ExpandableListView.ExpandableListContextMenuInfo) menuInfo; int type = ExpandableListView.getPackedPositionType(info.packedPosition); int group = ExpandableListView.getPackedPositionGroup(info.packedPosition); int child = ExpandableListView.getPackedPositionChild(info.packedPosition); if (type == 1) { menu.add("rating"); } } @Override public boolean onContextItemSelected(MenuItem menuItem) { Handler handler = new Handler() { @Override public void handleMessage(Message msg) { int rating = msg.arg1; System.out.println("Rating = " + rating); } }; System.out.println("Create rating dialog"); Toast.makeText(MyListActivity.this, "Ass", Toast.LENGTH_SHORT).show(); // new RatingDialog(MyListActivity.this, handler).show(); return super.onContextItemSelected(menuItem); } Rating dialog never shows, toast works perfectly. It is necessary to show context menu befor dialog or I can launch my dialog from onCreateContextMenu()? Thanks! A: You may need to show the context menu before the dialog. You could then have an option to rate.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548756", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Seeking advice re: accessing MySql db via Android app I'm looking for some advice on the best approach to access a MySql db from an android app. I am trying to interface with a web site (not written by me) that uses PHP. I have access to the developer of the web site, but, he does not know android. The web site is structured so that the content is dynamic (ie. news, notices, etc.) once you log on. At the moment, I've written code that can successfully log onto the web site. My next step is to obtain the data and display it on a mobile device. Here's my dilemma. I don't know if it is better to try and use an SQL API to access the data base directly, or, go through the existing PHP forms to access the data. Any and all advice would be greatly appreciated. A: You should not connect directly to database from mobile devices for reasons stated here: Why is the paradigm of "Direct Database Connection" not welcomed by Android Platform? Build a REST layer on you server, where you authenticate users and perform authorization and business logic. A: I recommend the developer (or you) implement RESTful web services in PHP that provide you access to the data you need. JSON is a good data format that's easily processed in Android and easily generated in PHP (or RoR if you go that way). On top of this RESTful layer, you should implement user-based authentication to ensure security and traceability of the api usage. Here's a link to a couple REST libraries for PHP: https://stackoverflow.com/questions/238125/best-framework-for-php-and-creation-of-restful-based-web-services And Android JSON parsing: http://developer.android.com/reference/org/json/package-summary.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7548758", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: generate a date string in HTTP response date format in C I'm trying to generate a date string from current time to put into HTTP response header. It looks like this: Date: Tue, 15 Nov 2010 08:12:31 GMT I only have the default C library to work with. How do I do this? A: Use strftime(), declared in <time.h>. #include <stdio.h> #include <time.h> int main(void) { char buf[1000]; time_t now = time(0); struct tm tm = *gmtime(&now); strftime(buf, sizeof buf, "%a, %d %b %Y %H:%M:%S %Z", &tm); printf("Time is: [%s]\n", buf); return 0; } See the code "running" at codepad. A: Check if your platform has strftime : http://pubs.opengroup.org/onlinepubs/007908799/xsh/strftime.html . A: Another solution is to avoid strftime() as it is impacted by locales and write your own function: void http_response_date(char *buf, size_t buf_len, struct tm *tm) { const char *days[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; const char *months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; snprintf(buf, buf_len, "%s, %d %s %d %02d:%02d:%02d GMT", days[tm->tm_wday], tm->tm_mday, months[tm->tm_mon], tm->tm_year + 1900, tm->tm_hour, tm->tm_min, tm->tm_sec); } int http_response_date_now(char *buf, size_t buf_len) { time_t now = time(NULL); if (now == -1) return -1; struct tm *tm = gmtime(&now); if (tm == NULL) return -1; http_response_date(buf, buf_len, tm); return 0; } Example output as of the time of writing: Tue, 20 Oct 2020 22:28:01 GMT. The output length will be 28 or 29 (if the month day >= 10), so a 30 char buffer is enough. A: Use gmtime(3) + mktime(3). You will end up with a struct tm that has all that information. struct tm { int tm_sec; /* seconds */ int tm_min; /* minutes */ int tm_hour; /* hours */ int tm_mday; /* day of the month */ int tm_mon; /* month */ int tm_year; /* year */ int tm_wday; /* day of the week */ int tm_yday; /* day in the year */ int tm_isdst; /* daylight saving time */ };
{ "language": "en", "url": "https://stackoverflow.com/questions/7548759", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Data driven unit tests problem I'm having some troubles getting my unit tests to be setup to use an Excel .xlsx data source. My App.config file: <?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="microsoft.visualstudio.testtools" type="Microsoft.VisualStudio.TestTools.UnitTesting.TestConfigurationSection, Microsoft.VisualStudio.QualityTools.UnitTestFramework, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/> </configSections> <connectionStrings> <add name="TestData" connectionString="Dsn=Excel Files;dbq=TestData.xlsx;defaultdir=.; driverid=790;maxbuffersize=2048;pagetimeout=5" providerName="System.Data.Odbc" /> </connectionStrings> <microsoft.visualstudio.testtools> <dataSources> <add name="GetAllCellNamesTest" connectionString="TestData" dataTableName="GetAllCellNamesTest$" dataAccessMethod="Sequential"/> </dataSources> I have verified that it is finding TestData.xlsx, and there is a sheet named GetAllCellNamesTest. In my unit test class, I have the following setup: [TestMethod()] [DeploymentItem("TestProject\\TestData.xlsx")] [DataSource("GetAllCellNamesTest")] public void GetAllCellNamesTest() { // ... test code TestData.xlsx is being copied to the test results directory and all the unit tests which don't try to reference the data source are passing. However, this one test is failing with the following message: The unit test adapter failed to connect to the data source or to read the data. For more information on troubleshooting this error, see "Troubleshooting Data-Driven Unit Tests" (http://go.microsoft.com/fwlink/?LinkId=62412) in the MSDN Library. Error details: ERROR [42S02] [Microsoft][ODBC Excel Driver] The Microsoft Access database engine could not find the object 'GetAllCellNamesTest$'. Make sure the object exists and that you spell its name and the path name correctly. If 'GetAllCellNamesTest$' is not a local object, check your network connection or contact the server administrator. I'm really not sure where in my setup is wrong, I followed this walkthrough on MSDN to get setup: Walkthrough: Using a Configuration File to Define a Data Source. Note that I did change the section version to 10.0.0.0 because I am using .net 4.0 (per the note at the bottom of the page). edit: oh, and all files are located locally on my computer. A: Have you tried using a full file path? Is the file readonly? A: You could also specify the files/directory you want to deploy as a part of your TestSettings. This will save you the effort of having to put the DeploymentItem attribute for every test method. A: you use configuration after; <configSections> <section name="microsoft.visualstudio.testtools" type="Microsoft.VisualStudio.TestTools.UnitTesting.TestConfigurationSection, Microsoft.VisualStudio.QualityTools.UnitTestFramework, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/> </configSections>
{ "language": "en", "url": "https://stackoverflow.com/questions/7548761", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Call an access function outside access with VB NET I would like to call a custom created function in access from VB NET. For example I created a myRoundNumber function in Access when i create a query in access with that function it works but outside it doesn't. A: You cannot use custom Access functions in a query outside of Access.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548762", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Show different message to the hours | php here is my code, where i make mistake? Btw my time ZONE is UTC + 2:00. Thanks for answers in advance. <?php $current_time = date('H'); if ($current_time >18) { echo "Good night"; } if ($current_time <12) { echo "Good morning"; } if (($current_time >=12) && ($current_time <17)) { echo "Good day"; } ?> A: $current_time = date('H'); if ($current_time >18) { echo "Good night"; } else if ($current_time <12) { echo "Good morning"; } else { echo "Good day"; } A: Your last test should check for $current_time <=17. Note the less than or equal to... if (($current_time >=12) && ($current_time <=17)) @Ernestas Stankevičius has a nice clean solution though. A: Try doing var_dump($current_time);. That way, you will understand what it contains and where you are making a mistake. A: As predicted, the problem is in time zone. <?php date_default_timezone_set('Europe/Sofia'); $current_time =date('H'); echo "$current_time"; if ($current_time >'18') { echo "Good night"; } if ($current_time <'12') { echo "Good morning"; } if (($current_time >='12') && ($current_time <='17')) { echo "Good day"; } ?>
{ "language": "en", "url": "https://stackoverflow.com/questions/7548765", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Are there any difference between aspx and code behind when assigning text values asp.net 4.0 c# This is code behind assigning aspx.cs if (srLang == "tr") { lblUnWantedPrivateMessages.Text = "Özel Mesaj Almak İstemediğiniz Oyuncular"; lblPmBlockUserNameTitle.Text = "Oyuncu Adı:"; } else { lblUnWantedPrivateMessages.Text = "Players That You Don't Want To Receive PM"; lblPmBlockUserNameTitle.Text = "Player Name:"; } and this is aspx assigning <% if (srLang == "tr") { lblUnWantedPrivateMessages.Text = "Özel Mesaj Almak İstemediğiniz Oyuncular"; lblPmBlockUserNameTitle.Text = "Oyuncu Adı:"; } else { lblUnWantedPrivateMessages.Text = "Players That You Don't Want To Receive PM"; lblPmBlockUserNameTitle.Text = "Player Name:"; } %> Are there any performance difference between these 2 ? A: Both will compile into equivalent code, and there will be no performance difference. Placing significant code in the code behind file allows for a separation of responsibilities (display markup in the aspx file, logic in the code behind file) and leads to code that is easier to maintain.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548768", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Any good simple DirectX samples for Windows 8 (Developer preview)? Are there any good tutorials on how to draw a simple triangle in DirecX for Windows 8 Developer preview? The game sample is too complex to understand the "basic" workings of the new DirectX version (which seems to be completely different from DirectX 9). A: The point of the sample is the Windows 8, not the DirectX. You need to learn DirectX11 before doing it with Windows 8. You're trying to read a sample on interoperation between two technologies, neither of which you understand. The point of Windows 8 Dev Preview is not to teach DirectX. A: Figured it out. See code below. Only thing that doesn't work is the texture (it shows as white instead of displaying the image, but at least it displays the triangle!) (This code isn't obviously the whole program. Turns out it involves quite a lot of complex code to just draw a triangle these days!) using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using ManagedDirectX; using Windows.Storage; using Windows.Storage.Streams; namespace TestProgram { public sealed class EntryPoint { public void NtfyExecutionAbrt() { } public EntryPoint() { beginexecblock(); } void onrenderframe() { if(vertcount>0) { maincontext.Draw(vertcount); } } int vertcount = 0; Shader defaultshader; RenderContext maincontext; async void beginexecblock() { if ((await Windows.Storage.ApplicationData.Current.RoamingFolder.GetFilesAsync()).Count == 0) { await ApplicationData.Current.RoamingFolder.CreateFileAsync("testfile.txt"); ApplicationData.Current.SignalDataChanged(); Windows.UI.Popups.MessageDialog tdlg = new Windows.UI.Popups.MessageDialog("Roaming file creation success", "Sync status"); await tdlg.ShowAsync(); } try { DateTime started = DateTime.Now; RenderContext mtext = new RenderContext(); maincontext = mtext; StorageFolder folder = Windows.ApplicationModel.Package.Current.InstalledLocation; StorageFile file = await folder.GetFileAsync("DXInteropLib\\VertexShader.cso"); var stream = (await file.OpenAsync(FileAccessMode.Read)); Windows.Storage.Streams.DataReader mreader = new Windows.Storage.Streams.DataReader(stream.GetInputStreamAt(0)); byte[] dgram = new byte[file.Size]; await mreader.LoadAsync((uint)dgram.Length); mreader.ReadBytes(dgram); file = await folder.GetFileAsync("DXInteropLib\\PixelShader.cso"); stream = await file.OpenAsync(FileAccessMode.Read); mreader = new Windows.Storage.Streams.DataReader(stream.GetInputStreamAt(0)); byte[] mgram = new byte[file.Size]; await mreader.LoadAsync((uint)file.Size); mreader.ReadBytes(mgram); try { defaultshader = mtext.CreateShader(dgram, mgram); mtext.InitializeLayout(dgram); defaultshader.Apply(); mtext.OnRenderFrame += onrenderframe; } catch (Exception er) { Windows.UI.Popups.MessageDialog mdlg = new Windows.UI.Popups.MessageDialog(er.ToString(),"Fatal error"); mdlg.ShowAsync().Start(); } IStorageFile[] files = (await folder.GetFilesAsync()).ToArray(); bool founddata = false; foreach (IStorageFile et in files) { if (et.FileName.Contains("rawimage.dat")) { stream = await et.OpenAsync(FileAccessMode.Read); founddata = true; } } int width; int height; byte[] rawdata; if (!founddata) { file = await folder.GetFileAsync("TestProgram\\test.png"); stream = await file.OpenAsync(FileAccessMode.Read); var decoder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(stream); var pixeldata = await decoder.GetPixelDataAsync(Windows.Graphics.Imaging.BitmapPixelFormat.Rgba8, Windows.Graphics.Imaging.BitmapAlphaMode.Straight, new Windows.Graphics.Imaging.BitmapTransform(), Windows.Graphics.Imaging.ExifOrientationMode.IgnoreExifOrientation, Windows.Graphics.Imaging.ColorManagementMode.DoNotColorManage); width = (int)decoder.PixelWidth; height = (int)decoder.PixelHeight; rawdata = pixeldata.DetachPixelData(); file = await folder.CreateFileAsync("rawimage.dat"); stream = (await file.OpenAsync(FileAccessMode.ReadWrite)); var realstream = stream.GetOutputStreamAt(0); DataWriter mwriter = new DataWriter(realstream); mwriter.WriteInt32(width); mwriter.WriteInt32(height); mwriter.WriteBytes(rawdata); await mwriter.StoreAsync(); await realstream.FlushAsync(); } else { DataReader treader = new DataReader(stream.GetInputStreamAt(0)); await treader.LoadAsync((uint)stream.Size); rawdata = new byte[stream.Size-(sizeof(int)*2)]; width = treader.ReadInt32(); height = treader.ReadInt32(); treader.ReadBytes(rawdata); } Texture2D mtex = maincontext.createTexture2D(rawdata, width, height); List<VertexPositionNormalTexture> triangle = new List<VertexPositionNormalTexture>(); triangle.Add(new VertexPositionNormalTexture(new Vector3(-.5f,-.5f,0),new Vector3(1,1,1),new Vector2(0,0))); triangle.Add(new VertexPositionNormalTexture(new Vector3(0,0.5f,0),new Vector3(1,1,1),new Vector2(1,0))); triangle.Add(new VertexPositionNormalTexture(new Vector3(.5f,-0.5f,0),new Vector3(1,1,1),new Vector2(1,1))); byte[] gpudata = VertexPositionNormalTexture.Serialize(triangle.ToArray()); VertexBuffer mbuffer = maincontext.createVertexBuffer(gpudata,VertexPositionNormalTexture.Size); mbuffer.Apply(VertexPositionNormalTexture.Size); vertcount = 3; Windows.UI.Popups.MessageDialog tdlg = new Windows.UI.Popups.MessageDialog("Unit tests successfully completed\nShader creation: Success\nTexture load: Success\nVertex buffer creation: Success\nTime:"+(DateTime.Now-started).ToString(), "Results"); tdlg.ShowAsync().Start(); } catch (Exception er) { Windows.UI.Popups.MessageDialog tdlg = new Windows.UI.Popups.MessageDialog(er.ToString(), "Fatal error"); tdlg.ShowAsync().Start(); } } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7548770", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Disable or turn off the auto generation of mappings based on the POCO properties I am using the Code First constructs to connect to an existing database (which, I know is not code first technically). I do this so that I can mock out Fake Data Repositories using LINQ to Entities instead of LINQ to SQL. In the CTP3 last year, this worked great - I could create a new Configuration for my table, and explicitly add the properties of the POCO that were mapped to the database. In July 2011, Code First was included in EF4.1 so I thought I would upgrade. Unfortunately, EF is now too smart for my liking. For example, a) all properties of my POCOs are assumed to be mapped to database fields, so for example, a property Person.TempPassword{get;set;} causes the generated SQL to search for a TempPassword column in my Person table; b) if I inherit a class from my POCO (for example, Employee inherits from Person), EF starts generating Discriminator columns etc. I know that I can resolve the former problem using the Ignore() or [NotMapped] attributes, however that is a big hassle and I'd prefer not to do it. The latter problem I cannot resolve. All I need is a way to be able to turn off all these smarts, and just let me explicitly set properties as I used to do. Note that I have tried removing every single one of the constraints as well, for example modelBuilder.Conventions.Remove(); I have also overriden the call to OnModelCreating(), and NOT called base.OnModelCreating(), just included my own Configuration code, as below. An example of my configuration is: public class AddressBookConfiguration : EntityTypeConfiguration<AddressBook>{ public AddressBookConfiguration() { this.HasKey(x => x.AddressBookID); this.ToTable("AddressBook"); this.Property(x => x.AddressBookID); this.Property(x => x.AddressBookName); this.Property(x => x.WhenCreated); this.Property(x => x.TotalItems); } } Thank you. A: The path I usually take when need to expand Entity Framework classes functionality is to generate the Data Model plainly from the database, and than use Extension Methods. I know this is not sufficient, and you can not create Properties this way. However, I'm afraid this might be the best you can get.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548772", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Refresh output line containing download percentage I'm writing a script that has to download several files from the www. To make it more expressive I've just added a download hook to calculate the downloading percentage of the file that has being downloaded. Printing it out on the terminal produces a lot of output because I rewrite the same line each time the percentage counter is incremented, example: 1% - Downloading test.jpg 2% - Downloading test.jpg ... and so on I'd like to obtain something like many bash scripts or programs (such as "apt-get" from ubuntu): refresh the line containing the percentage without have to write several times the same line containing the the updated percentage. How can I do that? Thanks. [edit] I'm using Python3.2 to develop the file downloader. A: You need curses: http://docs.python.org/howto/curses.html A: Use \r (carriage return) and write directly to the terminal with sys.stdout.write: import time import sys for i in range(101): sys.stdout.write('%3d%%\r' % i) time.sleep(.1) Or a little more Python 3-ish: import time for i in range(101): print('{:3}%'.format(i),end='\r') time.sleep(.1)
{ "language": "en", "url": "https://stackoverflow.com/questions/7548775", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: System.Windows.Interactivity: Could not load file or assembly 'System.Windows, Version=2.0.5.0 I am trying to reference System.Windows.Interactivity in order to support IsExpanded behavior command But as soon as i add a reference to this assembly, i get the error loading System.Windows 2.0. This appears to be a known bug, and solution appears to be to just reference that assembly. I downloaded Silverlight SDK, and referenced assembly in question in my project. however, now i am getting lots of conflicts between System.Windows, and WindowsBase.dll. Classes such as RoutedEventHandler exist in both.. Must be a way to fix this, since i see people being successful in using that Interactivity dll with wpf 4.0.. A: You need to reference the dll's in the main project (not just the control libraries). It was the problem in my case. See more info here: Could not load file or assembly 'System.Windows.Interactivity' A: I got this error when running a project built in a previous version of Visual Studio, but I was running it in VS2017. My issue was resolved by opening the VS2017 installer and modifying my install to select the "Blend for Visual Studio SDK for .Net" component in the VS 2017 install. Fissh A: If you have a WPF project you need to use the WPF specific version of that assembly, maybe you took the wrong .dll? Here are the two respective file paths on my system: C:\Program Files (x86)\Microsoft SDKs\Expression\Blend\.NETFramework\v4.0\Libraries\System.Windows.Interactivity.dll C:\Program Files (x86)\Microsoft SDKs\Expression\Blend\Silverlight\v4.0\Libraries\System.Windows.Interactivity.dll A: If one of your projects is targeting the .NET 4.0 Client Profile you might find switching to the full .NET 4.0 framework corrects the issue. A: Sonic, like H.B. said you can't use Silverlight version in WPF. You will need to install different WPF specific Expression Blend SDK instead of Silverlight.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548780", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Windows Media Encoder SDK - Figuring out when conversion is done in native C++ I use the Windows Media Encoder SDK to convert WAV files in the WMA format. It works pretty nice BUT I have a huge problem finding out when the process is done... The funny thign is that I have used parts of code from the SDK itself to get notifications for this but them don't seem to work... :( Here is a piece of my code: class CCallBack : public IDispEventImpl< EVENT_ID, //Thsi is sth I got from the SDK CCallBack, &DIID__IWMEncoderEvents, &LIBID_WMEncoderLib, LIB_VERMAJOR, LIB_VERMINOR > { private: WMENC_ENCODER_STATE m_enumState; WMENC_SOURCE_STATE m_enumSrcState; public: // Define the event sink map which determines the events // that the application receives. BEGIN_SINK_MAP( CCallBack ) SINK_ENTRY_EX( EVENT_ID, DIID__IWMEncoderEvents, DISPID_ENCODEREVENT_STATECHANGE, OnStateChange ) SINK_ENTRY_EX( EVENT_ID, DIID__IWMEncoderEvents, DISPID_ENCODEREVENT_SRCSTATECHANGE, OnSourceStateChange ) END_SINK_MAP() // Implement the event handler for the OnStateChange event. STDMETHOD( OnStateChange )( WMENC_ENCODER_STATE enumState ) { m_enumState = enumState; return S_OK; } // Implement the event handler for the OnSourceStateChange event. STDMETHOD( OnSourceStateChange )( WMENC_SOURCE_STATE enumState, WMENC_SOURCE_TYPE enumType, short iIndex, BSTR bstrSourceGroup ) { m_enumSrcState = enumState; return S_OK; } // Override the base class virtual function to provide information // on the implemented event handlers. HRESULT GetFuncInfoFromId( const IID& iid, DISPID dispidMember, LCID lcid, _ATL_FUNC_INFO& info ) { if( InlineIsEqualGUID( iid, DIID__IWMEncoderEvents ) ) { info.cc = CC_STDCALL; info.vtReturn = VT_ERROR; switch( dispidMember ) { // Descibe the parameters of the // OnStateChange event handler. case DISPID_ENCODEREVENT_STATECHANGE: info.nParams = 1; info.pVarTypes[0] = VT_I4; return S_OK; // Describe the parameters of the // OnSourceStateChange event handler. case DISPID_ENCODEREVENT_SRCSTATECHANGE: info.nParams = 4; info.pVarTypes[0] = VT_I4; info.pVarTypes[1] = VT_I4; info.pVarTypes[2] = VT_I2; info.pVarTypes[3] = VT_BSTR; return S_OK; default: return E_FAIL; } } return E_FAIL; } // Link the events to the encoder instance. HRESULT CCallBack::Init( IWMEncoder* pEncoder ) { if( pEncoder == NULL ) return E_FAIL; HRESULT hr = DispEventAdvise( pEncoder ); if( FAILED( hr ) ) { // TODO: Handle failure condition. } return hr; } // Detach the event sink from the encoder instance. HRESULT CCallBack::Shutdown( IWMEncoder* pEncoder ) { if( pEncoder == NULL ) return E_FAIL; HRESULT hr = DispEventUnadvise( pEncoder ); if( FAILED( hr ) ) { // TODO: Handle failure condition. } return hr; } // Private member variable access functions. WMENC_ENCODER_STATE State() { return m_enumState; } WMENC_SOURCE_STATE SrcState() { return m_enumSrcState; } CCallBack() { _asm nop } }; void Do() // This is my code... { // Declare variables. HRESULT hr; IWMEncoder2* pEncoder = NULL; IWMEncSourceGroupCollection* pSrcGrpColl = NULL; IWMEncSourceGroup2* pSrcGrp = NULL; IWMEncSource* pSrcAud = NULL; IWMEncAudioSource* pAudSrc = NULL; IWMEncAudienceObj* pAudnc = NULL; IWMEncFile2* pFile = NULL; IWMEncAttributes* pAttr = NULL; IWMEncDisplayInfo* pDispInfo = NULL; IErrorInfo* pIErr = NULL; IWMEncStatistics* pStatistics = NULL; IWMEncFileArchiveStats* pFileArchiveStats = NULL; IWMEncOutputStats* pOutputStats = NULL; CComBSTR bstrName; long lCount = 0; CString str; CCallBack EventSink; // Retrieve a pointer to an IWMEncoder2 interface. hr = ::CoCreateInstance(CLSID_WMEncoder, NULL, CLSCTX_INPROC_SERVER, IID_IWMEncoder2, (void**) &pEncoder); if ( FAILED( hr ) ) goto ERR; hr = EventSink.Init( pEncoder ); if( FAILED( hr ) ) goto ERR; // Retrieve the source group collection. hr = pEncoder->get_SourceGroupCollection(&pSrcGrpColl); if ( FAILED( hr ) ) goto ERR; // Add a source group to the collection. hr = pSrcGrpColl->Add(CComBSTR("SG_1"), (IWMEncSourceGroup**)&pSrcGrp); if ( FAILED( hr ) ) goto ERR; hr = pSrcGrp->AddSource(WMENC_AUDIO, (IWMEncSource**)&pAudSrc); if ( FAILED( hr ) ) goto ERR; if(m_cComboContentType.GetCurSel()==0) hr = pAudSrc->put_ContentMode(WMENC_AUDIOCONTENT_NO_MODE); else if(m_cComboContentType.GetCurSel()==1) hr = pAudSrc->put_ContentMode(WMENC_AUDIOCONTENT_SPEECH_MODE); else if(m_cComboContentType.GetCurSel()==2) hr = pAudSrc->put_ContentMode(WMENC_AUDIOCONTENT_MIXED_MODE); else hr = pAudSrc->put_ContentMode(WMENC_AUDIOCONTENT_NO_MODE); if ( FAILED( hr ) ) goto ERR; { int val = m_cCheckBoxUseTwoPassEnc.GetCheck(); //int val = ((CButton*)GetDlgItem(IDC_CHECK1))->GetState(); if(val==BST_CHECKED) hr = pAudSrc->put_PreProcessPass(1); else hr = pAudSrc->put_PreProcessPass(0); if ( FAILED( hr ) ) goto ERR; } // Add audio source to the source group. hr = pAudSrc->SetInput(CComBSTR("D:\\WAVs\\recording_015.wav")); if ( FAILED( hr ) ) goto ERR; hr = pEncoder->get_File((IWMEncFile**)&pFile); if ( FAILED( hr ) ) goto ERR; hr = pFile->put_LocalFileName(CComBSTR("C:\\Users\\Ghost\\Desktop\\OutputFile_+8.wma")); if ( FAILED( hr ) ) goto ERR; // Set the profile in the source group. hr = pSrcGrp->put_Profile(CComVariant(/*(IWMEncProfile*)*/pPro2)); if ( FAILED( hr ) ) goto ERR; hr = pPro2->Validate(); if ( FAILED( hr ) ) goto ERR; // Start the encoding process. hr = pEncoder->PrepareToEncode(VARIANT_TRUE); if ( FAILED( hr ) ) goto ERR; pEncoder->put_AutoStop(VARIANT_TRUE); hr = pEncoder->Start(); if ( FAILED( hr ) ) goto ERR; hr = pEncoder->get_Statistics(&pStatistics); if ( FAILED( hr ) ) goto ERR; WMENC_ENCODER_STATE enumCurState = WMENC_ENCODER_PAUSING; WMENC_ENCODER_STATE enumPrvState; MSG msg; while( TRUE ) { // In order for the events to be triggered correctly, // the windows message queue needs to be processed. while(PeekMessage(&msg,NULL,NULL,NULL,PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); } enumPrvState = enumCurState; enumCurState = EventSink.State(); if( EventSink.SrcState() == WMENC_SOURCE_STOP ) enumCurState = WMENC_ENCODER_STOPPED; if( enumCurState != enumPrvState ) { switch ( enumCurState ) { case WMENC_ENCODER_STARTING: // TODO: Handle encoder starting state. break; case WMENC_ENCODER_RUNNING: // TODO: Handle encoder running state. break; case WMENC_ENCODER_PAUSING: // TODO: Handle encoder pausing state. break; case WMENC_ENCODER_PAUSED: // TODO: Handle encoder paused state. break; case WMENC_ENCODER_STOPPING: // TODO: Handle encoder stopping state. break; case WMENC_ENCODER_STOPPED: // TODO: Handle encoder stopped state. goto EXIT_WAIT; case WMENC_ENCODER_END_PREPROCESS: // TODO: Handle encoder end preprocess state. break; } } } EXIT_WAIT: hr = EventSink.Shutdown( pEncoder ); if ( FAILED( hr ) ) goto ERR; // for(;;) // { // MSG msg; // while(PeekMessage(&msg,NULL,NULL,NULL,PM_REMOVE)) // { // TranslateMessage(&msg); // DispatchMessage(&msg); // } // // pStatistics->get_StreamOutputStats(WMENC_AUDIO, 0, 1, (IDispatch**)&pOutputStats); // if ( FAILED( hr ) ) goto ERR; // pStatistics->get_FileArchiveStats((IDispatch**)&pFileArchiveStats); // if ( FAILED( hr ) ) goto ERR; // WMENC_LONGLONG Dur; // pFileArchiveStats->get_FileDuration(&Dur); // long Dur2; // pAudSrc->get_Duration(&Dur2); // if ( FAILED( hr ) ) goto ERR; // WMENC_ENCODER_STATE EncState; // pEncoder->get_RunState(&EncState); // if ( FAILED( hr ) ) goto ERR; // WMENC_ARCHIVE_STATE ArchState; // pEncoder->get_ArchiveState(WMENC_ARCHIVE_LOCAL, &ArchState); // if ( FAILED( hr ) ) goto ERR; // if(ArchState == WMENC_ARCHIVE_STOPPED && EncState == WMENC_ENCODER_STOPPED) // { // break; // } // Sleep(2000); // } AfxMessageBox(_T("DONE !")); goto END; ERR: ReportError(); END: // Release pointers. ComFree(pSrcGrpColl) ComFree(pSrcGrp) ComFree(pStatistics) ComFree(pFileArchiveStats) ComFree(pAudnc) ComFree(pIErr) ComFree(pFile) ComFree(pSrcAud) ComFree(pAttr) ComFree(pDispInfo) ComFree(pEncoder) } The state of the encoder goes to WMENC_ENCODER_RUNNING and it stays unchanged for ever... As you can probably see I ve tried both : pEncoder->get_RunState(&EncState); ...and the Event Sink the SDK proposes. Yet, nothing seems to work... Ideas anyone ? Another problem that I would be glad I you could help, is that, when I set the IWMEncAudioSource object to use a two-pass encoding, it doesn't. The code for that is above, where I do the : pAudSrc->put_PreProcessPass(1);
{ "language": "en", "url": "https://stackoverflow.com/questions/7548782", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: .Net - LINQ query returning a single object? Is it possible to use a LINQ query to return a single object instead of a list? User user = (from User u in users where u.id == 5 select u); A: Use one of: .Single() // return a single .SingleOrDefault() // return a single or the default value if there are no matches .First() // return the first object it encounters that matches .FirstOrDefault() // return the first object it encounters that matches, or the default value if no matches .Single() and .SingleOrDefault() will throw an exception if there are multiple matches. A: Or to make it even simpler: User user = users.Single(u => u.id == 5); If the query returns more than one, you'll need to use First, as Single throws an exception if there is more than one element in the query. A: Yes, User user = (from User u in users where u.id == 5 select u).Single() This will throw and exception if more than one element is returned by the query. If you only want the first element: User user = (from User u in users where u.id == 5 select u).First() Use SingleOrDefault() and FirstOrDefault() to return null for reference types when no element exists. A: or First and FirstOrDefault. User user = (from User u in users where u.id == 5 select u).FirstOrDefault(); A: dmck is correct -- the Enumerable.Single() method will accomplish this. However, by design it will throw an exception if there is more that one object in the set. If you want to avoid throwing an exception you have several other options: * *The Enumerable.First or Enumerable.Last methods *The Enumerable.ToArray method immediately followed by in indexer, such as: User user = (from User u in users where u.id == 5 select u).ToArray()[0];
{ "language": "en", "url": "https://stackoverflow.com/questions/7548783", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Regex for "AND NOT" operation I'm looking for a general regex construct to match everything in pattern x EXCEPT matches to pattern y. This is hard to explain both completely and concisely...see Material Nonimplication for a formal definition. For example, match any word character (\w) EXCEPT 'p'. Note I'm subtracting a small set (the letter 'p') from a larger set (all word characters). I can't just say [^p] because that doesn't take into account the larger limiting set of only word characters. For this little example, sure, I could manually reconstruct something like [a-oq-zA-OQ-Z0-9_], which is a pain but doable. But i'm looking for a more general construct so that at least the large positive set can be a more complex expression. Like match ((?<=(so|me|^))big(com?pl{1,3}ex([pA]t{2}ern) except when it starts with "My". Edit: I realize that was a bad example, since excluding stuff at the begginning or end is a situation where negative look-ahead and look-behind expressions work. (Bohemian I still gave you an upvote for illustrating this). So...what about excluding matches that contain "My" somewhere in the middle?...I'm still really looking for a general construct, like a regex equivalent of the following pseudo-sql select [captures] from [input] where ( input MATCHES [pattern1] AND NOT capture MATCHES [pattern2] ) If there answer is "it does not exist and here is why..." I'd like to know that too. Edit 2: If I wanted to define my own function to do this it would be something like (here's a C# LINQ version): public static Match[] RegexMNI(string input, string positivePattern, string negativePattern) { return (from Match m in Regex.Matches(input, positivePattern) where !Regex.IsMatch(m.Value, negativePattern) select m).ToArray(); } I'm STILL just wondering if there is a native regex construct that could do this. A: After your edits, its still the negative lookahead, but with an additional quantifier. If you want to ensure that the whole string does not contain "My", then you can do this (?!.*My)^.*$ See it here on Regexr This will match any sequence of characters (with the .* at the end) and the (?!.*My).* at the beginning will fail when there is a "My" anywhere in the string. If you want to match anything that si not exactly "My" then use anchors (?!^My$).* A: This will match any character that is a word and is not a p: ((?=[^p])\w) To solve your example, use a negative look-ahead for "My" anywhere in the input, ie (?!.*My): ^(?!.*My)((?<=(so|me|^))big(com?pl{1,3}ex([pA]t{2}ern) Note the anchor to start of input ^ which is required to make it work. A: I wonder why people try to do complicated things in big monolithic regular expressions? Why can't you just break down the problem into sub-parts and then make really easy regular expressions to match those individually? In this case, first match \w, then match [^p] if that first match succeeds. Perl (and other languages) allows for constructing really complicated-looking regular expressions that allows you to do exactly what you need to do in one big blobby-regex (or, as it may well be, with a short and snappy crypto-regex), but for the sake of whoever it is that needs to read (and maintain!) the code once you've gone you need to document it fully. Better then to make it easy to understand from the start. Sorry, rant over. A: So after looking through these topics on RegEx's: lookahead, lookbehind, nesting, AND operator, recursion, subroutines, conditionals, anchors, and groups, I've come to the conclusion that there is no solution that satisfies what you're asking for. The reason why lookahead doesn't work is because it fails in this relatively simple case: Three words without My included as one. Regex: ^(?!.*My.*)(\b\w+\b\s\b\w+\b\s\b\w+\b) Matches: included as one The first three words fail to match because My happens after them. If "My" is at the end of the entire string, you'll never match anything because every lookahead will fail because they will all see that. The problem appears to be that while lookahead has an implicit anchor as to where it begins its match, there's no way of terminating where lookahead ends its search with an anchor based upon the result of another part of the RegEx. That means you really have to duplicate all of the RegEx into the negative lookahead to manually create the anchor you're after. This is frustrating and a pain. The "solution" appears to be use a scripting language to perform two regex's. One on top of the other. I'm surprised this kind of functionality isn't better built into regular expression engines.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548787", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "37" }
Q: Facebook Cache won't flush? I just renamed my facebook application, but the Like button and the link sharer didn't change, even I used the debug tool (no more Linter tool ??). Any Idea how can I do that? A: you have to clear the facebook cache of your app/url. you can do this on the facebook url linter. http://developers.facebook.com/tools/debug insert the url which you are tring to like, and you will be presented with the info facebook see's. side effect is that its refreshes facebook cache from this url.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548791", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Oracle jdbc creating a table, sequence and trigger I'm trying to create a table with a sequence and with a trigger for that sequence. When I do this within Oracle Express edition I have the following SQL statements. Which DO run correctly inside Oracle Express using the same user I log in with JDBC. CREATE table "TEST" ( "ID" NUMBER(10) NOT NULL, "NAME" VARCHAR2(20), constraint "TEST_PK" primary key ("ID") ) CREATE sequence "TEST_SEQ" CREATE trigger "BI_TEST" before insert on "TEST" for each row begin if :NEW."ID" is null then select "TEST_SEQ".nextval into :NEW."ID" from dual; end if; end; So now what I do is put each of these into a List of Strings and execute 1 by one like this: List<String> commands = new ArrayList<String>(4); commands.add("Create table ..."); commands.add("Create sequence ..."); commands.add("Create trigger..."); st = con.createStatement(); for (String command : commands) { st.execute(command); } etc... But I get an error with the trigger statement. "Error with Oracle command: ORA-00942: table or view does not exist" It seems to me that Oracle has not yet seen the new table at this point. How can I correct this? Should I create multiple statement objects or try committing in-between each command? TIA A: It seems that an error in invoking method execute. Another method Statement#executeUpdate should be used for DDL queries. See official javadoc. Update: Have you tried to use executeBatch method? I'm trying to execute batch using spring jdbc: getJdbcTemplate().batchUpdate(new String[] { createTable, createTrigger, insert }); it works fine for me. A: Check for synonym of the table created. You can not access, if synonym is not created for the user. A: Thanks for the input. I had 2 issues. The "table or view does not exist" error was resolved by creating a new statement for each SQL I ran + using executeUpdate method instead of execute method. Then I had an issue with the trigger being invalid - so I made sure all the trigger/table/index names used upper case.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548793", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: ASP.net Entity-Framework (Basic) Questions (ASP.net MVC 3.0 Razor, EF Code First) My first question is: where do I store my data? in the Initializer or in the .sdf? And my second question is this: I have a class for Songs, and one for Artists. This is from my Initializer: var Artists= new List<Artist>() { new Artist{ Name = "ArtistName", Birthday=DateTime.Parse("4-4-1988")} }; Authors.ForEach(s => context.Authors.Add(s)); context.SaveChanges(); var Songs= new List<Song>() { new Song { Name="SongName", Genre = Genre.GenreTypes.Rock, Artist=Artists[0]} //<-- }; Books.ForEach(s => context.Books.Add(s)); context.SaveChanges(); Where the green arrow is, is the problem. I'm trying to get the artist by the list-index above (where I loaded the artists into the database), but when I test it (item.Artist.Name), I don't get anything. the artist property is null! I don't get it. why? do I even do it correctly? (I'm trying to get the artist's name, that's all) And last question: I also have in the author's class a List (list of his songs). how should I load songs of him there? A: What do you mean? Store your data? Your data is normally saved in a database that you chose in your connectionString. The initializer will take care of the database creation, seeding etc. Selecting a song with his artist You can get the Artist by including him in the query. For example: yourContext.Songs.Include("Artist").toList()' This will return all the songs and the artist will be filled in for each song. Selecting a song with his artist In the same way you fill in the Artist for the song. yourContext.Artists.Include("ListPropertyName").toList() Here is a link that might help you: http://msdn.microsoft.com/en-us/library/bb896272.aspx Saving a song together with his artist. I'm going to show the way I work , Your relationship should be something like this: public class Artist { [Key] public Guid ID { get; set; } //..OtherProperties ... public virtual ICollection<Songs> Songs { get; set; } } public class Song { [Key] public Guid ID { get; set; } //..OtherProperties ... //Foreign Key Stuff [ForeignKey("Artist")] public Guid ArtistId { get; set; } //Relationship public virtual Artist Artist { get; set; } } If you work this way you can just fill in the ArtistId manually in the song. So You will have to do the following: var Artists= new List<Artist>() { new Artist{ Name = "ArtistName", Birthday=DateTime.Parse("4-4-1988"), ID = Guid.NewGuid()} }; Authors.ForEach(s => context.Authors.Add(s)); var Songs= new List<Song>() { new Song { Name="SongName", Genre = Genre.GenreTypes.Rock, ArtistId=Artists[0].ID} //<-- }; Songs.ForEach(s => context.Songs.Add(s)); context.SaveChanges(); Now, what is the advance with separating the ID and the actual Artist. It's very simple, when you make a Artist you can manually set the ID and you can use it later in your code instead of saving the artist first. So first you make your artists and set there Id and then you can directly use it in your song. In your example you actually do Savechanges() twice. If you're using 'my' method you only have to save once. You should really check some tutorials on Entity Framework , google is your friend :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7548798", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Invocation of init method failed; nested exception is java.lang.IncompatibleClassChangeError: Implementing class error message: SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [config/spring/Hibernate-ctx.xml]: Invocation of init method failed; nested exception is java.lang.IncompatibleClassChangeError: Implementing class at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1338) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:473) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409) at java.security.AccessController.doPrivileged(Native Method) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:423) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:728) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:380) at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:255) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:199) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:45) at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4723) at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5226) at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5221) at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334) at java.util.concurrent.FutureTask.run(FutureTask.java:166) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603) at java.lang.Thread.run(Thread.java:722) Caused by: java.lang.IncompatibleClassChangeError: Implementing class at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:791) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142) at org.apache.catalina.loader.WebappClassLoader.findClassInternal(WebappClassLoader.java:2820) at org.apache.catalina.loader.WebappClassLoader.findClass(WebappClassLoader.java:1150) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1645) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1523) at java.lang.Class.getDeclaredConstructors0(Native Method) at java.lang.Class.privateGetDeclaredConstructors(Class.java:2404) at java.lang.Class.getConstructor0(Class.java:2714) at java.lang.Class.getDeclaredConstructor(Class.java:2002) at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:78) at org.springframework.orm.hibernate3.LocalSessionFactoryBean.newConfiguration(LocalSessionFactoryBean.java:772) at org.springframework.orm.hibernate3.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:517) at org.springframework.orm.hibernate3.AbstractSessionFactoryBean.afterPropertiesSet(AbstractSessionFactoryBean.java:211) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1369) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1335) ... 23 more Using tomcat 7 and maven build. mvn dependency:tree -Dverbose gives following message: C:\project>mvn dependency:tree -Dverbose [INFO] Scanning for projects... [INFO] Searching repository for plugin with prefix: 'dependency'. [INFO] ------------------------------------------------------------------------ [INFO] Building home-app [INFO] task-segment: [dependency:tree] [INFO] ------------------------------------------------------------------------ [INFO] [dependency:tree {execution: default-cli}] [INFO] com.home.app:home-app:war:0.0.1 [INFO] +- org.springframework:spring-orm:jar:3.0.5.RELEASE:compile [INFO] | +- org.springframework:spring-beans:jar:3.0.5.RELEASE:compile [INFO] | | \- (org.springframework:spring-core:jar:3.0.5.RELEASE:compile - omitted for duplicate) [INFO] | +- (org.springframework:spring-core:jar:3.0.5.RELEASE:compile - omitted for duplicate) [INFO] | +- org.springframework:spring-jdbc:jar:3.0.5.RELEASE:compile [INFO] | | +- (org.springframework:spring-beans:jar:3.0.5.RELEASE:compile - omitted for duplicate) [INFO] | | +- (org.springframework:spring-core:jar:3.0.5.RELEASE:compile - omitted for duplicate) [INFO] | | \- (org.springframework:spring-tx:jar:3.0.5.RELEASE:compile - omitted for duplicate) [INFO] | \- (org.springframework:spring-tx:jar:3.0.5.RELEASE:compile - omitted for duplicate) [INFO] +- log4j:log4j:jar:1.2.14:runtime (scope not updated to compile) [INFO] +- mysql:mysql-connector-java:jar:5.1.17:compile [INFO] +- org.hibernate:ejb3-persistence:pom:3.3.2.Beta1:compile [INFO] +- org.hibernate:hibernate-core:jar:3.6.7.Final:compile [INFO] | +- antlr:antlr:jar:2.7.6:compile [INFO] | +- commons-collections:commons-collections:jar:3.1:compile [INFO] | +- dom4j:dom4j:jar:1.6.1:compile [INFO] | +- org.hibernate:hibernate-commons-annotations:jar:3.2.0.Final:compile [INFO] | | \- (org.slf4j:slf4j-api:jar:1.5.8:compile - omitted for conflict with 1.6.1) [INFO] | +- org.hibernate.javax.persistence:hibernate-jpa-2.0-api:jar:1.0.1.Final:compile [INFO] | +- javax.transaction:jta:jar:1.1:compile [INFO] | \- (org.slf4j:slf4j-api:jar:1.6.1:compile - omitted for conflict with 1.5.8) [INFO] +- commons-dbcp:commons-dbcp:jar:1.2.2:compile [INFO] | \- commons-pool:commons-pool:jar:1.3:compile [INFO] +- org.springframework:spring-hibernate3:jar:2.0.8:compile [INFO] | +- aopalliance:aopalliance:jar:1.0:compile [INFO] | +- commons-logging:commons-logging:jar:1.1:compile [INFO] | | +- (log4j:log4j:jar:1.2.12:compile - omitted for conflict with 1.2.14) [INFO] | | +- logkit:logkit:jar:1.0.1:compile [INFO] | | +- avalon-framework:avalon-framework:jar:4.1.3:compile [INFO] | | \- (javax.servlet:servlet-api:jar:2.3:compile - omitted for conflict with 3.0-alpha-1) [INFO] | +- org.hibernate:hibernate:jar:3.2.5.ga:compile [INFO] | | +- net.sf.ehcache:ehcache:jar:1.2.3:compile [INFO] | | | +- (commons-logging:commons-logging:jar:1.0.4:compile - omitted for conflict with 1. [INFO] | | | \- (commons-collections:commons-collections:jar:2.1:compile - omitted for conflict w [INFO] | | +- (javax.transaction:jta:jar:1.0.1B:compile - omitted for conflict with 1.1) [INFO] | | +- (commons-logging:commons-logging:jar:1.0.4:compile - omitted for conflict with 1.1) [INFO] | | +- asm:asm-attrs:jar:1.5.3:compile [INFO] | | +- (dom4j:dom4j:jar:1.6.1:compile - omitted for duplicate) [INFO] | | +- (antlr:antlr:jar:2.7.6:compile - omitted for duplicate) [INFO] | | +- (cglib:cglib:jar:2.1_3:compile - omitted for conflict with 2.2.2) [INFO] | | +- (asm:asm:jar:1.5.3:compile - omitted for conflict with 3.3.1) [INFO] | | \- (commons-collections:commons-collections:jar:2.1.1:compile - omitted for conflict wi [INFO] | +- (org.springframework:spring-beans:jar:2.0.8:compile - omitted for conflict with 3.0.5.R [INFO] | +- (org.springframework:spring-context:jar:2.0.8:compile - omitted for conflict with 3.0.5 [INFO] | +- (org.springframework:spring-core:jar:2.0.8:compile - omitted for conflict with 3.0.5.RE [INFO] | +- org.springframework:spring-dao:jar:2.0.8:compile [INFO] | | +- (aopalliance:aopalliance:jar:1.0:compile - omitted for duplicate) [INFO] | | +- (commons-logging:commons-logging:jar:1.1:compile - omitted for duplicate) [INFO] | | +- (org.springframework:spring-beans:jar:2.0.8:compile - omitted for conflict with 3.0. [INFO] | | +- (org.springframework:spring-context:jar:2.0.8:compile - omitted for duplicate) [INFO] | | \- (org.springframework:spring-core:jar:2.0.8:compile - omitted for conflict with 3.0.5 [INFO] | \- (org.springframework:spring-jdbc:jar:2.0.8:compile - omitted for conflict with 3.0.5.RE [INFO] +- org.springframework:spring-expression:jar:3.0.5.RELEASE:compile [INFO] | \- (org.springframework:spring-core:jar:3.0.5.RELEASE:compile - omitted for duplicate) [INFO] +- org.springframework:spring-aop:jar:3.0.5.RELEASE:compile [INFO] | +- (aopalliance:aopalliance:jar:1.0:compile - omitted for duplicate) [INFO] | +- (org.springframework:spring-asm:jar:3.0.5.RELEASE:compile - omitted for conflict with 3 [INFO] | +- (org.springframework:spring-beans:jar:3.0.5.RELEASE:compile - omitted for duplicate) [INFO] | \- (org.springframework:spring-core:jar:3.0.5.RELEASE:compile - omitted for duplicate) [INFO] +- org.springframework:spring-context:jar:3.0.5.RELEASE:compile [INFO] | +- (org.springframework:spring-aop:jar:3.0.5.RELEASE:compile - omitted for duplicate) [INFO] | +- (org.springframework:spring-beans:jar:3.0.5.RELEASE:compile - omitted for duplicate) [INFO] | +- (org.springframework:spring-core:jar:3.0.5.RELEASE:compile - omitted for duplicate) [INFO] | +- (org.springframework:spring-expression:jar:3.0.5.RELEASE:compile - omitted for duplicat [INFO] | \- (org.springframework:spring-asm:jar:3.0.5.RELEASE:compile - omitted for duplicate) [INFO] +- org.springframework:spring-tx:jar:3.0.5.RELEASE:compile [INFO] | +- (aopalliance:aopalliance:jar:1.0:compile - omitted for duplicate) [INFO] | +- (org.springframework:spring-aop:jar:3.0.5.RELEASE:compile - omitted for duplicate) [INFO] | +- (org.springframework:spring-beans:jar:3.0.5.RELEASE:compile - omitted for duplicate) [INFO] | +- (org.springframework:spring-context:jar:3.0.5.RELEASE:compile - omitted for duplicate) [INFO] | \- (org.springframework:spring-core:jar:3.0.5.RELEASE:compile - omitted for duplicate) [INFO] +- org.springframework:spring-core:jar:3.0.5.RELEASE:compile [INFO] | +- (org.springframework:spring-asm:jar:3.0.5.RELEASE:compile - omitted for duplicate) [INFO] | \- (commons-logging:commons-logging:jar:1.1.1:compile - omitted for conflict with 1.1) [INFO] +- cglib:cglib:jar:2.2.2:compile [INFO] | \- asm:asm:jar:3.3.1:compile [INFO] +- org.springframework:spring-test:jar:3.0.6.RELEASE:test [INFO] +- org.springframework:spring-asm:jar:3.0.6.RELEASE:compile [INFO] +- org.slf4j:jcl-over-slf4j:jar:1.5.8:runtime [INFO] | \- (org.slf4j:slf4j-api:jar:1.5.8:runtime - omitted for conflict with 1.6.1) [INFO] +- org.slf4j:slf4j-api:jar:1.5.8:runtime (scope not updated to compile) [INFO] +- org.slf4j:slf4j-log4j12:jar:1.5.8:runtime [INFO] | +- (org.slf4j:slf4j-api:jar:1.5.8:runtime - omitted for duplicate) [INFO] | \- (log4j:log4j:jar:1.2.14:runtime - omitted for duplicate) [INFO] +- junit:junit:jar:4.9:compile [INFO] | \- org.hamcrest:hamcrest-core:jar:1.1:compile [INFO] +- javassist:javassist:jar:3.12.1.GA:compile [INFO] +- com.sun.faces:jsf-impl:jar:2.1.3:compile [INFO] +- com.sun.faces:jsf-api:jar:2.1.3:compile [INFO] +- javax.servlet:jstl:jar:1.2:compile [INFO] +- javax.inject:javax.inject:jar:1:compile [INFO] +- javax.servlet:servlet-api:jar:3.0-alpha-1:provided (scope not updated to compile) [INFO] +- javax.servlet.jsp:jsp-api:jar:2.2.1-b03:provided [INFO] +- com.sun.el:el-ri:jar:1.0:provided [INFO] \- org.springframework:spring:jar:2.5.6.SEC03:compile [INFO] \- (commons-logging:commons-logging:jar:1.1.1:compile - omitted for conflict with 1.1) [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESSFUL [INFO] ------------------------------------------------------------------------ [INFO] Total time: 2 seconds [INFO] Finished at: Sun Sep 25 23:21:18 CEST 2011 [INFO] Final Memory: 16M/39M [INFO] ------------------------------------------------------------------------ This is problem with duplicate of hibernate jar file. But i am not sure which one is duplicating here. My test class is executing fine. ie problem with tomcat. POM.xml: <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.home.app</groupId> <artifactId>home-app</artifactId> <version>0.0.1</version> <packaging>war</packaging> <name>home-app</name> <url>http://maven.apache.org</url> <properties> <org.springframework.version>3.0.5.RELEASE</org.springframework.version> </properties> <dependencyManagement> <dependencies> </dependencies> </dependencyManagement> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.2</version> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>tomcat-maven-plugin</artifactId> <version>1.1</version> <configuration> <url>http://localhost:8080/manager/html</url> <server>myserver</server> <path>/home-app</path> <warFile>${project.build.directory}/${project.build.finalName}.war</warFile> </configuration> </plugin> </plugins> </build> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>3.0.5.RELEASE</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.14</version> <scope>provided</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.17</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>ejb3-persistence</artifactId> <version>3.3.2.Beta1</version> <type>pom</type> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>3.6.7.Final</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.2.2</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-hibernate3</artifactId> <version>2.0.8</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <version>${org.springframework.version}</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>3.0.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${org.springframework.version}</version> <exclusions> <exclusion> <artifactId>commons-logging</artifactId> <groupId>commons-logging</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <type>jar</type> <version>${org.springframework.version}</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>2.2.2</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>3.0.6.RELEASE</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-asm</artifactId> <version>3.0.6.RELEASE</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>jcl-over-slf4j</artifactId> <version>1.5.8</version> <scope>runtime</scope> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.5.8</version> <scope>runtime</scope> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.5.8</version> <scope>runtime</scope> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.14</version> <scope>runtime</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.9</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>javassist</groupId> <artifactId>javassist</artifactId> <version>3.12.1.GA</version> </dependency> <dependency> <groupId>com.sun.faces</groupId> <artifactId>jsf-impl</artifactId> <version>2.1.3</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>com.sun.faces</groupId> <artifactId>jsf-api</artifactId> <version>2.1.3</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>javax.inject</groupId> <artifactId>javax.inject</artifactId> <version>1</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>3.0-alpha-1</version> <type>jar</type> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.2.1-b03</version> <type>jar</type> <scope>provided</scope> </dependency> <dependency> <groupId>com.sun.el</groupId> <artifactId>el-ri</artifactId> <version>1.0</version> <type>jar</type> <scope>provided</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring</artifactId> <version>2.5.6.SEC03</version> <type>jar</type> <scope>compile</scope> </dependency> </dependencies> <repositories> <repository> <id>jboss</id> <name>JBoss repository</name> <url>https://repository.jboss.org/nexus/content/repositories/releases/</url> </repository> </repositories> </project> A: [INFO] +- org.hibernate:hibernate-core:jar:3.6.7.Final:compile [INFO] | +- org.hibernate:hibernate:jar:3.2.5.ga:compile These are (at least) mutually exclusive. I use "at least" since after you have put in place the exclusion rule you need to recheck your dependencies. I would exclude the older 3.2.5.ga. Using the maven exclude mechanism inside the dependency for org.springframework:spring-hibernate3:jar:2.0.8:compile. A: i have the same problem SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [applicationContext.xml]: Invocation of init method failed; nested exception is java.lang.IncompatibleClassChangeError: Implementing class to fix it replace <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate</artifactId> <version>3.2.6.ga</version> </dependency> with <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>3.6.10.Final</version> </dependency>
{ "language": "en", "url": "https://stackoverflow.com/questions/7548810", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Problem with sprite sheet The code below shows how I'm cutting my sprites, but the memory usage grows constantly. How can I fix? CGImageRef imgRef = [imgSprite CGImage]; [imgView setImage:[UIImage imageWithCGImage:CGImageCreateWithImageInRect(imgRef, CGRectMake(column*width, line, width, height))]]; CGImageRelease(imgRef); This code is called by the NSTimer in an interval of 0.1. A: Since you haven’t posted the declaration of imgSprite, I’ll assume that its class follows Cocoa naming conventions. In: CGImageRef imgRef = [imgSprite CGImage]; that method (a non-NARC1 method) returns an object that you do not own, hence you should not release it. In: [imgView setImage:[UIImage imageWithCGImage:CGImageCreateWithImageInRect(imgRef, CGRectMake(column*width, line, width, height))]]; the argument is the expression: CGImageCreateWithImageInRect(imgRef, CGRectMake(column*width, line, width, height)) CGImageCreateWithImageInRect() (a function whose name follows the Create Rule2) returns an image that you do own, hence you should release it, which you don’t. In: CGImageRelease(imgRef); you’re releasing an image that you do not own, so you should not release it. You have two problems: you’re (potentially over)releasing imgRef and you’re leaking the image returned by CGImageCreateWithImageInRect(). You should do the following instead: // you do not own imgRef, hence you shouldn’t release it CGImageRef imgRef = [imgSprite CGImage]; // use a variable for the return value of CGImageCreateWithImageInRect() // because you own the return value, hence you should release it later CGImageRef imgInRect = CGImageCreateWithImageInRect(imgRef, CGRectMake(column*width, line, width, height)); [imgView setImage:[UIImage imageWithCGImage:imgInRect]]; CGImageRelease(imgInRect); You might want to read the Memory Management Programming Guide and the Memory Management Programming Guide for Core Foundation. 1NARC = new, alloc, retain, copy 2The Create Rule states that if you call a function whose name contains Create or Copy then you own the return value, hence you should release it when you don’t need it any longer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548812", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: byte-code: Symbol's value as variable is void: org-babel-tangle-lang-exts I had Emacs working pretty well and then I restarted my computer. Now this block of code prevents me from loading my init-files: (require 'ob-clojure) (org-babel-do-load-languages 'org-babel-load-languages '((emacs-lisp . nil) (R . t) (python . t) (js . t) (scheme . t) (C . t) (clojure . t) (lilypond . t) (octave . t))) I don't know why this would be. I had gotten babel to work fine with R before I restarted. Now I get the message: byte-code: Symbol's value as variable is void: org-babel-tangle-lang-exts I grep'd the directory for anything mentioning org-babel and only the above expression came up. That plus the fact that the rest of my init-files code loaded when I got rid of it makes me think that this code is the problem. But why would org-mode be referring to a function I don't have? Running emacs --debug-init gave: Debugger entered--Lisp error: (void-function org-babel-do-load-languages) (org-babel-do-load-languages (quote org-babel-load-languages) (quote (... ... ... ... ... ... ... ...))) eval-buffer(#load<2>> nil "/home/kca/.emacs.d/init-org.el" nil t) ; Reading at buffer position 3080 load-with-code-conversion("/home/kca/.emacs.d/init-org.el" "/home/kca/.emacs.d/init-org.el" nil nil) load("init-org") eval-buffer(# nil "/home/kca/.emacs.d/init.el" nil t) ; Reading at buffer position 1464 load-with-code-conversion("/home/kca/.emacs.d/init.el" "/home/kca/.emacs.d/init.el" t t) load("/home/kca/.emacs.d/init" t t) #[nil "\205\264 I tried to check if the right org-mode version was loading: M-x load-library org M-x org-version => Org-mode version 7.7 Here is the code in init.el that is loading it: (add-to-list 'load-path (concat conf-dir "org-7.7/lisp")) (add-to-list 'load-path (concat conf-dir "org-7.7/contrib/lisp")) I'm using Emacs 23.2 and Org-7.7. Thanks for your help! A: Try rebooting again. Then read the rest here, if that didn't help... Use binary search of your init file to determine just what code you are loading that is the problem. Make sure you load the source code (*.el, not *.elc) for the problematic code. Set debug-on-error to non-nil, so you get a backtrace that tells you something about the context of the error. If the error is completely contained in some external package, make sure all your files for that package are for the same package version. If the only thing you changed was restarting, then perhaps the problem is in an environment variable. One guess is that for some reason your variable load-path does not have the right value, so it isn't loading all the files you need. Or maybe you moved some of that package's code? HTH. Should get you started toward finding out more about the problem. A: Actually, the trouble was that I didn't understand the org manual instructions. Apparently, I did need to put (require 'org-install) and (require 'ob-tangle) into my init file to get literate programming features. I'm not sure how I got R to work in babel before, though. Oh, well it works now! Hat tip to edenc in the #org-mode irc channel.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548813", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Multiply elements of a matrix along its third dimension For programming in MATLAB, how can I write a function that will take a stack of matrices in a variable (let's say M) and multiply them together and return in answer in an output argument. It would be preferred to put M as an input argument of the function. And it might be easier to use for loops to multiply each layer to the previous. Help would be greatly appreciated, thank you! To help start: M(:,:,1)=[1 2,3 4]; %first layer M(:,:,2)=[5 6,7 8]; %second layer A: That function is called prod. Try this newM = prod(M,3);
{ "language": "en", "url": "https://stackoverflow.com/questions/7548820", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Implementing URL shortener logic in JavaScript As a result of finding this interesting question, I decided to write an example in JavaScript which implemented the logic and contribute it back to the question. The problem is that I'm having some issues implementing the logic. I can speak Ruby which is what I'm basing my implementation on, but I'm having an issue with an endless while loop which I'm having trouble sorting out. I have the whole implementation up on js.do.it here: http://jsdo.it/rfkrocktk/k9Jq function encode(i) { if (i == 0) return DICTIONARY[0]; var result = ''; var base = DICTIONARY.length; while (i > 0) { result += DICTIONARY[i % base]; i = i / base; } result = result.reverse(); return result; } What am I doing wrong here? A: Javascript uses floating point math by default. Use i = Math.floor(i / base);
{ "language": "en", "url": "https://stackoverflow.com/questions/7548823", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What are the functional differences between iODBC and unixODBC? There are two major Open Source platform independent implementation of the ODBC. It is iODBC and unixODBC. Considering Unix as ODBC user platform and feature-wise, what are the real practical differences between these two implementations? A: I finally found some time for a more complete answer... (attn @mloskot -- you can change your accepted answer, if you agree that this one is more accurate and/or complete than the other) iODBC and unixOBDC are basically API equivalent, both being cross-platform implementations of Microsoft's ODBC standard. iODBC's flexible Unicode support includes UCS-2, UTF-8, UCS-4. iODBC libraries are bundled into macOS Panther (10.3.0) through Big Sur (11.2.x), and may be built and/or installed on AIX, Solaris, HP-UX, any Linux distribution, *BSD, other Unix-like OS, and more. iODBC has been thread safe for a very long time, and is actively maintained and supported by OpenLink Software (my employer). The table below covers the most common comparative questions (is there something I should add?), and is based on iODBC 3.52.14, as of February 2021 (reports version 03.52.1421.0217), and unixODBC 2.3.9, as of September 2020. For a somewhat more detailed comparison, and a much more fancy and detailed table, see this spreadsheet feature iODBC UnixODBC Unicode support     UCS-2 YES YES     UCS-4 (a/k/a UTF-32) YES NO     UTF-08 (a/k/a UTF-8) YES NO     UTF-16 YES YES     UTF-32 (a/k/a UCS-4) YES NO Supports drivers and apps developed using other SDKs     Supports drivers developed using iODBC SDK YES NO     Supports apps developed using iODBC SDK YES NO     Supports drivers developed using unixODBC SDK YES YES     Supports apps developed using unixODBC SDK YES YES     Supports drivers developed using DataDirect SDK YES NO     Supports apps developed using DataDirect SDK YES NO OS default DM     macOS YES NO     Linux partial partial     Unix-like partial partial OS support     macOS YES partial     Linux YES YES     Unix-like YES YES User-friendly native GUI Administrator     macOS YES Qt-based     Linux GTK-based and HTML-based Qt-based     Unix-like GTK-based and HTML-based Qt-based Thread Safe YES YES Support     Mailing List(s) YES YES     Forum(s) YES YES     Github repository YES YES     SourceForge repository YES YES Open Source Licensing     GPL NO programs     LGPL YES libraries     BSD YES NO Notes Unicode a/k/a Wide Characters * *iODBC supports and translates between all of UCS-2, UCS-4, UTF-8, UTF-16, UTF-32 *unixODBC follows MDAC, and SQLWCHARs are 2 bytes UCS2 encoded SDK lock-in * *iODBC supports applications and drivers developed using unixODBC SDK and DataDirect SDK as well as those developed using iODBC SDK *unixODBC only supports applications and drivers developed using unixODBC SDK A: Just so you know I use and have contributed to unixODBC and I don't use iODBC. Unicode support unixODBC follows MS ODBC Driver manager and has SQLWCHARs as 2 bytes UCS2 encoded. iODBC I believe uses wchar_t (this is based on attempting to support iODBC in DBD::ODBC) cursor library unixODBC has one, I don't "think" iODBC has. application support A lot of ODBC applications support unixODBC e.g., OpenOffice and ODBC drivers from Oracle, IBM and SAP. I'm not sure about iODBC. OS support iODBC has always been the most used on on Macs since Apple included it (although I believe it is removed from Lion). Both can be built from source and most Linux distributions package both (although not Novell/Suse which only distributes unixODBC). thread safety unixODBC is thread safe and includes flags to protect handles at different levels. This did not used to be the case with iODBC (but that might have changed now). support Both have support forums (unixODBC has 3) although I'd say the unixODBC ones are far more active (I'm on both). Licensing unixODBC is GPL and LGPL. iODBC is LGPL/BSD In practice there is not a lot of difference but I think you'll find unixODBC is more widely used.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548825", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "36" }
Q: how to run a python file on a linux server as a page I want to begin with the fact that I know nothing about linux, and I found a script that I would like to run on my server as a page, but when I goto the .py file it downloads the file!!! how am I suppose to run it?? am I suppose to use a php file and do a command to run the file? Thanks in advance A: This may be quite easy (and there's certainly no need to employ PHP here)! Given a trivial Python script: > cat cgi-bin/test.py #!/usr/bin/env python print '''Content-Type: text/html <html> <head> <title>Hello from Python</title> </head> <body> <h2>Hello from Python</h2> </body> </html>''' You can run a simple CGI HTTP Server from the command-line using Python: > python -m CGIHTTPServer Serving HTTP on 0.0.0.0 port 8000 ... Then in another terminal window: > w3m -dump http://localhost:8000/cgi-bin/test.py Hello from Python This is useful for testing CGI scripts on your local machine. If you want to configure a production HTTP server for serving Python content, then you're best off asking at https://webmasters.stackexchange.com/ . A: This is not an easy task, especially if you are not good with Linux, but take a look at this: http://docs.python.org/library/cgi.html#installing-your-cgi-script-on-a-unix-system A: There are two paths: * *The mod_wsgi plug-in will run a Python script. You need to configure Apache, and install mod_wsgi. *The CGI plug-in will run your Python, also. You need to configure Apache. Note the common theme. You need to configure Apache. This isn't a Python question. It's an Apache question.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548826", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }