text
stringlengths
8
267k
meta
dict
Q: What are good ruby-debug alternatives? I'd heard some discussion on a Ruby podcast about a debugger that allowed you to use linux style commands to traverse through an object. Like for example you have a object, with attributes foo and bar, you can actually cd to foo, ls to view it's attributes, cd to another object, etc etc. But I can't find this for the life of me!!! Does anyone know the name of this debugger, or any other good alternatives? A: I believe you're talking about pry which was discussed a while back here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7620926", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Aggregate 3rd dimension of a 3d array for the subscripts of the first dimension I have a 3 Dimensional array Val 4xmx2 dimension. (m can be variable) Val{1} = [1, 280; 2, 281; 3, 282; 4, 283; 5, 285]; Val{2} = [2, 179; 3, 180; 4, 181; 5, 182]; Val{3} = [2, 315; 4, 322; 5, 325]; Val{4} = [1, 95; 3, 97; 4, 99; 5, 101]; I have a subscript vector: subs = {1,3,4}; What i want to get as output is the average of column 2 in the above 2D Arrays (only 1,3 an 4) such that the 1st columns value is >=2 and <=4. The output will be: {282, 318.5, 98} This can probably be done by using a few loops, but just wondering if there is a more efficient way? A: Here's a one-liner: output = cellfun(@(x)mean(x(:,1)>=2 & x(:,1)<=4,2),Val(cat(1,subs{:})),'UniformOutput',false); If subs is a numerical array (not a cell array) instead, i.e. subs=[1,3,4], and if output doesn't have to be a cell array, but can be a numerical array instead, i.e. output = [282,318.5,98], then the above simplifies to output = cellfun(@(x)mean(x(x(:,1)>=2 & x(:,1)<=4,2)),Val(subs)); cellfun applies a function to each element of a cell array, and the indexing makes sure only the good rows are being averaged.
{ "language": "en", "url": "https://stackoverflow.com/questions/7620929", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Eclipse features in Aptana? It seems to me that most of Eclipse's features do not work for me in Aptana. For instance, when editing Java in Eclipse one can press F3 when the cursor is in a class name to jump to the class definition. When editing PHP files in Aptana this does not work. Is it supposed to work, or must it be enabled somehow? Thanks. A: It is likely that your project is not marked as PHP project. Please try the steps here to change the nature associated with your project: http://wiki.appcelerator.org/pages/viewpage.action?pageId=12452389#ChangingYourProject%27s%22Type%22-ChangingProjectNatures
{ "language": "en", "url": "https://stackoverflow.com/questions/7620931", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using a scroll in jQueryMobile + PhoneGap I've seen some ScrollView examples on the JqueryMobile website. I tried to dowload the required additional css and js files, reference them, and setup a scrollviewer, but it doesn't work (actually, all my website stops working, showing only a white-empty page). Any idea or alternative? Thanks! A: As alternatives, you can have a look at iscroll and a jquery plugin touch-scroll.
{ "language": "en", "url": "https://stackoverflow.com/questions/7620933", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CUDA-GDB: Setting Up the Debugger Environment I'm following the CUDA-GDB guide (page 10, getting started) on Ubuntu Linux and got this: antonio@antonio-desktop:~$ export PATH=/usr/local/cuda/bin:$PATH antonio@antonio-desktop:~$ export LD_LIBRARY_PATH=/usr/local/cuda/lib64:/usr/local/cuda/ antonio@antonio-desktop:~$ lib:$LD_LIBRARY_PATH bash: lib:/usr/local/cuda/lib64:/usr/local/cuda/: No such file or directory Well, how do I fix this? I have the current toolkit. A: You have broken a line in two - it should be: $ export PATH=/usr/local/cuda/bin:$PATH $ export LD_LIBRARY_PATH=/usr/local/cuda/lib64:/usr/local/cuda/lib:$LD_LIBRARY_PATH You probably got confused by the line wrap in the nVidia PDF.
{ "language": "en", "url": "https://stackoverflow.com/questions/7620935", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: calling method in a separate class I have my main class setup and a worker thread, one of my early requests that I make in run() is to call my second class called login. I do this like so: login cLogin = new login(); cLogin.myLogin(); class login looks like this: package timer.test; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Bundle; import android.widget.Toast; public class login extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // setContentView(R.layout.main); } public void myLogin() { // prepare the alert box AlertDialog.Builder alertbox = new AlertDialog.Builder(this); // set the message to display alertbox.setMessage(this.getString(R.string.intro)); // add a neutral button to the alert box and assign a click listener alertbox.setNeutralButton("Register New Account", new DialogInterface.OnClickListener() { // click listener on the alert box public void onClick(DialogInterface arg0, int arg1) { // the button was clicked } }); // add a neutral button to the alert box and assign a click listener alertbox.setNegativeButton("Login", new DialogInterface.OnClickListener() { // click listener on the alert box public void onClick(DialogInterface arg0, int arg1) { // the button was clicked } }); // show it alertbox.show(); } 10-01 14:33:33.028: ERROR/AndroidRuntime(440): java.lang.RuntimeException: Unable to start activity ComponentInfo{timer.test/timer.test.menu}: java.lang.IllegalStateException: System services not available to Activities before onCreate() I put onCreate in but still having the same problem. How can I fix this? A: You have a couple of options: 1) Move your public void myLogin() {..} to your main activity. I recommend this solution since you don't need another activity for your purposes. 2) Call startActivity on your login class before calling the myLogin(). Since you inherite from Activity onCreate needs to be called before you call anything else. That's why you get the exception. startActivity is called like this: Intent i = new Intent(this, login.class); startActivity(i); A: You cannot do it this way simply because you are using the context AlertDialog.Builder alertbox = new AlertDialog.Builder(this); //this is the activity context passed in.. The context is not available until Activity onCreate is called via startActivity. and not by constructing an new instance of the login object, you can try passing in an context from the activity calling this method public void myLogin(Context context) { // prepare the alert box AlertDialog.Builder alertbox = new AlertDialog.Builder(context); //blah blah blah... } yes and never construct an activity instance via the constructor.. -.-
{ "language": "en", "url": "https://stackoverflow.com/questions/7620940", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to get the link from a RSS Feed? I am trying to get the post link of a RSS feed. I load all the posts in an array correctly ( I successfully echo the content and other tags) but I have a problem to get the link. In the feed, the link can be found by two ways 1. <link rel="alternate" type="text/html" href="this is the address I want" title="here goes the title" /> and tried <?php echo $post->link[href]; ?> but because there are a lot of link tags in a content, it must echo the one that has rel="alternate" 2. <feedburner:origLink>this is the address</feedburner:origLink> and tried <?php echo $post->feedburner:origLink; ?> My question is how to get the link ? I prefer the 2nd way because it does not go through the feedburner link. Note: I use two RSS XML structures in the array so what I will use is something like this ($post->description)?$post->description:$post->content) as I do for the description/content A: 1. rel=alternate $links = $post->xpath('link[@rel="alternate" and @type="text/html"]'); $link = (string) $links[0]['href']; See http://php.net/simplexmlelement.xpath and http://php.net/simplexml.examples-basic (Example #5) 2. feedburner:origLink $links = $post->xpath('feedburner:origLink'); $link = (string) $links[0]; // or $link = (string) $post->children('feedburner', TRUE)->origLink; See http://php.net/simplexmlelement.children A: I had the same problem but I solved it with the follow: $link = $xml->entry[$i]->link[2]->attributes()->href; //the feed-blog has 3 type of links where probably $xml is $post for you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7620942", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: .htacces rewrite condition not hitting? Lets say I have a two websites www.sample.com and files.sample.com. In an .htaccess file within the webroot of www.sample.com, I have the following: <IfModule mod_rewrite.c> RewriteEngine on RewriteCond %{QUERY_STRING} ^files\/uploads [NC] RewriteRule ^(.*)$ http://files.website.com/$1 [NC,L] </IfModule> The desired result is to have all requests of www.sample.com/files/uploads/file.xml or www.sample.com/files/uploads/subfolder/file.json get 302 redirected to files.sample.com/files/uploads/file.xml and www.sample.com/files/uploads/subfolder/file.json, respectively. However, I can't get the rule to fire. The directory "files" does not exist on the www.sample.com website at all. Could anyone give me a little help as to why the A: You probably want REQUEST_URI not QUERY_STRING. RewriteCond %{REQUEST_URI} ^/files\/uploads [NC] Also note the leading slash. A: Did you turn on mod_rewrite in your apache config? Also yor change '^files/uploads' to ^/files/uploads and QUERY_STRING to PATH_INFO. QUERY_STRING - this is all data after '?' character.
{ "language": "en", "url": "https://stackoverflow.com/questions/7620951", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How To Get Google Maps link From Current location? I need to get the google maps link by pressing a button from the iPhone. I already know how to get the coordinate long/lang. Now I need to convert it to a link. I am working with CLLocation & MKMapview Can anyone help me with that? A: Read the "Apple URL Schemes" documentation. Everything about map links is detailed in this page. A: http://maps.google.com/maps?f=q&q=38.323480,26.767732 You can change those variables at the end and the link will open the google maps app no need for complicated programming
{ "language": "en", "url": "https://stackoverflow.com/questions/7620952", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Json Returning [object object] instead of array I have json data being fed into a Sencha touch app. Here's the json: http://pastie.org/2622260 - (modified for an example, of course) When I return the "images" and console.log it, it returns the following: images: "[object Object],[object Object],[object Object],[object Object],[object Object]" Rather than the URLs. My json encoder looks like this (I'm pulling the data out of a Wordpress site): case 'posts': foreach(get_posts('numberposts=50&category=') as $post) { $count = 0; $imgurl = array(); foreach( get_group('Photo', $post->ID) as $images){ $count++; $imgurl[] = array( 'count'=>$count, 'imageurl'=>get('photo_image_file', $count, 1, false, $post->ID), ); } $json['posts'][] = array( 'id'=>$post->ID, 'title'=>$post->post_title, 'body'=>apply_filters('the_excerpt', $post->post_content), 'date'=>$post->post_date, 'user'=>get_userdata($post->post_author)->user_firstname, 'images'=>$imgurl ); } } header('Content-type: application/json'); echo json_encode($json); exit(); What I am looking for it to do is to return the array of image urls, rather than the [object object] that I am currently getting. EDIT: Here is the sencha code I'm using to try to pull the imageurl out: console.log(this.record.data); console.log(this.record.data.images); console.log(this.record.data.images.length); var numberOfPages = this.record.data.images.length; // Create pages for the carousel var pages = []; for (var i=0; i<numberOfPages; i++) { pages.push(new Ext.Component({ id: 'page'+i, cls: 'page', tpl: '<tpl for=".">{imageurl}</tpl>', //html:'test', })); } // Create the carousel this.carousel = new Ext.Carousel({ id: 'carousel', title:'Gallery', iconCls:'photos2', defaults: { cls: 'card' }, items: pages, }); A: Associative arrays in PHP encoded as JSON become objects in JavaScript when decoded. What you're seeing is correct and normal. Access them as you would any other object in JavaScript. A: Update: Sorry, for the irrelevant example I had given Where is your pages[i].update(this.record.data.images); ? You can try the following - var numberOfPages = this.record.data.length; // Create pages for the carousel var pages = []; for (var i=0; i<numberOfPages; i++) { var tmp = new Ext.Component({ id: 'page'+i, cls: 'page', tpl: '<tpl for=".">{imageurl}</tpl>' }); tmp.update(this.record.data[i].images); pages.push(tmp); } A: Found the answer, gave it to Rifat because his answer was the springboard. I had the [object object]'s coming through as a literal string of characters. I wrote a quick test.php outside Sencha touch and was able to get the actual array to work. My first issue was the json itself - It needed to be validated. You guys were all correct and thank you for that clue. Second, once I got the test.php document working, I realized it had to be within Sencha itself. The nagging feeling that the string of characters had something to do with it sat in my head. Finally, I went to my model and found how I was pulling the images: {name: "images", type: "string"}, I saw string, and the aha moment hit! This fixed it and gave me my URL's: {name: "images"}, Can't thank Ignacio and Rifat enough. You guys hung in there with me and got the answer to (eventually) appear. Thanks again, and hope this helps anyone else that may run into a similar issue. A: I had a similar issue once, in the javascript backend. Here is an answer for people using JS: Make sure to stringify your object arrays before sending them: JSON.stringify(array[i]); Unless ofcourse you are ONLY sending JSON, which in that case sending regular JSON should work fine :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7620953", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to resize the Expander.Content? <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="*" /> <ColumnDefinition Width="auto"/> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <!-- … --> </Grid.RowDefinitions> <TextBlock Grid.Column="0"> This should be allways visible, even if the expander isn’t expanded! </TextBlock> <Expander ExpandDirection="Left" Grid.Column="1"> <Expander.Header> <!-- … --> </Expander.Header> <TreeView MinWidth="50"/> </Expander> <!-- … --> </Grid> I want the user to be able to resize the TreeView. I tried to warp the TreeView in a Grid with 2 columns and a GridSplitter in the first column, but that didn't work. Does anybody have an idea how to make that work? P.S.: A XAML-only answer would be great. A: You may solve your problem using Expander.Collapsed and Expander.Expanded events as Attached Event. I do not have the idea about only using Xaml now, but the following code works well in my case. Xaml <Window x:Class="WpfApplication1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow"> <Grid Expander.Collapsed="Grid_Collapsed" Expander.Expanded="Grid_Expanded"> <Grid.ColumnDefinitions> <ColumnDefinition Width="*" /> <ColumnDefinition Width="auto"/> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <!-- … --> </Grid.RowDefinitions> <TextBlock Grid.Column="0" TextWrapping="Wrap"> This should be allways visible, even if the expander isn’t expanded! </TextBlock> <GridSplitter HorizontalAlignment="Right" VerticalAlignment="Stretch" Width="2" /> <Expander Background="Yellow" ExpandDirection="Left" Grid.Column="1"> <Expander.Header>test</Expander.Header> <TreeView MinWidth="50"/> </Expander> <!-- … --> </Grid> </Window> Codebehinde public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private GridLength _rememberWidth = GridLength.Auto; private void Grid_Collapsed(object sender, RoutedEventArgs e) { var grid = sender as Grid; if(grid != null) { _rememberWidth = grid.ColumnDefinitions[1].Width; grid.ColumnDefinitions[1].Width = GridLength.Auto; } } private void Grid_Expanded(object sender, RoutedEventArgs e) { var grid = sender as Grid; if (grid != null) { grid.ColumnDefinitions[1].Width = _rememberWidth; } } } A: You just need to add another column to the wrapping grid in order for it to work. Here is a XAML sample that worked for me: <Grid x:Name="LayoutRoot"> <toolkit:Expander ExpandDirection="Left" Header="ImLeftExpandedExpander"> <Grid ShowGridLines="True" Background="White" > <Grid.RowDefinitions> <RowDefinition /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition MinWidth="50" /> <ColumnDefinition Width="Auto"/> <ColumnDefinition Width="Auto"/> </Grid.ColumnDefinitions> <sdk:TreeView Background="BurlyWood"> <sdk:TreeViewItem Header="Root"> <sdk:TreeViewItem Header="bla1"/> <sdk:TreeViewItem Header="bla2"/> <sdk:TreeViewItem Header="bla3"/> </sdk:TreeViewItem> </sdk:TreeView> <sdk:GridSplitter x:Name="grsplSplitter" Grid.Row="0" Grid.Column="1" VerticalAlignment="Stretch" HorizontalAlignment="Center" Background="Red" Width="5"></sdk:GridSplitter> <Grid Background="#CCCC66" Grid.Column="2"> <TextBlock FontSize="22" Text="This column can be left empty, its just so the GridSplitter will have space to expand to" TextWrapping="Wrap"/> </Grid> </Grid> </toolkit:Expander> </Grid> And the result: A: Is this what you want? Notice the GridSplitter property ResizeBehavior. <Grid > <Grid.ColumnDefinitions> <ColumnDefinition Width="5*"/> <ColumnDefinition Width="auto"/> <ColumnDefinition Width="2*"/> </Grid.ColumnDefinitions> <TreeView> <TreeViewItem Header="1"> <TreeViewItem Header="2"> <TreeViewItem Header="3"/> </TreeViewItem> <TreeViewItem Header="3"> <TreeViewItem Header="4"/> </TreeViewItem> <TreeViewItem Header="5"/> <TreeViewItem Header="6"/> </TreeViewItem> </TreeView> <GridSplitter Grid.Column="1" Width="10" ResizeDirection="Columns" ResizeBehavior="PreviousAndNext"/> <Canvas Grid.Column="2" Background="LightGray"/> </Grid> Edit: Here is a working example, showing both approaches. If this is not what you want, then please say so. <Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" x:Class="WpfApplication1.MainWindow" Title="MainWindow" d:DesignWidth="516" d:DesignHeight="310"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="*"/> <ColumnDefinition Width="*"/> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="auto"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <Label Content="Change size of content"/> <Border BorderBrush="Black" BorderThickness="1" Grid.Row="1" Margin="10"> <Expander Header="Expander" > <Grid > <Grid.ColumnDefinitions> <ColumnDefinition Width="5*"/> <ColumnDefinition Width="auto"/> <ColumnDefinition Width="2*"/> </Grid.ColumnDefinitions> <TreeView> <TreeViewItem Header="1"> <TreeViewItem Header="2"> <TreeViewItem Header="3"/> </TreeViewItem> <TreeViewItem Header="3"> <TreeViewItem Header="4"/> </TreeViewItem> <TreeViewItem Header="5"/> <TreeViewItem Header="6"/> </TreeViewItem> </TreeView> <GridSplitter Grid.Column="1" Width="10" ResizeDirection="Columns" ResizeBehavior="PreviousAndNext"/> <Canvas Grid.Column="2" Background="LightGray"/> </Grid> </Expander> </Border> <Label Content="Change size of expander" Grid.Column="1"/> <Border BorderBrush="Black" BorderThickness="1" Grid.Row="1" Grid.Column="1" Margin="10"> <Grid > <Grid.ColumnDefinitions> <ColumnDefinition Width="5*"/> <ColumnDefinition Width="auto"/> <ColumnDefinition Width="2*"/> </Grid.ColumnDefinitions> <Expander> <TreeView> <TreeViewItem Header="1"> <TreeViewItem Header="2"> <TreeViewItem Header="3"/> </TreeViewItem> <TreeViewItem Header="3"> <TreeViewItem Header="4"/> </TreeViewItem> <TreeViewItem Header="5"/> <TreeViewItem Header="6"/> </TreeViewItem> </TreeView> </Expander> <GridSplitter Grid.Column="1" Width="10" ResizeDirection="Columns" ResizeBehavior="PreviousAndNext"/> <Canvas Grid.Column="2" Background="LightGray"/> </Grid> </Border> </Grid> </Window>
{ "language": "en", "url": "https://stackoverflow.com/questions/7620954", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: PHP Simple HTML DOM Parser Dies I am screen scraping page with a bunch of subpages using Simple HTML DOM Parser. For some reason it parses the first 40 subpages just fine but when it comes to number 41 it dies with no error. I have made this test page and tried to log everything I do in my script aswell as some of the venets in the Simple HTML DOM Parser but I haven't been able to find the error. Does anyone have an idea why it does when parsing URL number 41? Or does anyone know of some cases Simple HTML DOM Parser will fail? My test page: http://snuzzer.dk/pub/shdp/parse.php This is my script and I use a non-modified version of Simple HTML DOM Parser. The interesting stuff happens in get_lections() and I have markede where I call Simple HTML DOM Parser. define("LECTION_STATUS_REGULAR", 0); define("LECTION_STATUS_CHANGED", 1); define("LECTION_STATUS_CANCELLED", 2); define("LECTION_DOCUMENTS_NONE", 0); define("LECTION_DOCUMENTS_TRUE", 1); define("AMOUNT_OF_WEEKS_IN_A_YEAR", 52); include_once("simple_html_dom.php"); function clean_text($text) { $text = trim($text); $text = strip_tags($text); $text = html_entity_decode($text, ENT_QUOTES, "UTF-8"); $text = utf8_decode($text); return $text; } function get_links_for_lections($weeks) { echo "Finding links<br /><textarea style=\"width:70%;height:150px;\">"; foreach($weeks as $week) { // ** // // THIS IS WHERE I CALL SIMPLE HTML DOM PARSER // // ** echo " * Retrieving HTML...\n"; $html = file_get_html("http://www.lectio.dk/lectio/285/SkemaNy.aspx?type=elev&elevid=2444366210&week=" . $week['week'] . $week['year']); echo " * HTML retrieved...\n"; $lections_regular = $html->find('a[class="s2skemabrik s2bgbox s2withlink"]'); $lections_changed = $html->find('a[class="s2skemabrik s2bgbox s2changed s2withlink"]'); $lections_cancelled = $html->find('a[class="s2skemabrik s2bgbox s2cancelled s2withlink"]'); $lections = array_merge($lections_regular, $lections_changed, $lections_cancelled); foreach($lections as $lection) { $links[] = "http://www.lectio.dk" . $lection->href; } } echo "</textarea> <hr />"; return $links; } function get_lections($links) { // Create array to hold lections $lections = array(); // Loop through links $num = 1; foreach($links as $link) { echo $num . ". " . $link . "<br /> <textarea style=\"width:70%;height:150px;\">"; // Initialize lection $lection = array(); $lection['status'] = LECTION_STATUS_REGULAR; $lection['documents'] = LECTION_DOCUMENTS_NONE; echo " * Retrieving HTML...\n"; $html = file_get_html($link); echo " * HTML retrieved\n"; // Loop through rows foreach($html->find("tr") as $row) { echo " * New cell\n"; // Get name of row $row_name = $row->find("th"); $row_name = $row_name['0']->innertext; echo " - Row name: \"" . $row_name . "\"\n"; if ($row_name == "Type:") { echo " - Checking type...\n"; // Row tells what type it is $cell = $row->find("td"); $content = $cell['0']->innertext; $lection['type'] = clean_text($content); echo " - Type checked\n"; } else if ($row_name == "Titel:") { echo " - Checking title...\n"; // Row tells the title $cell = $row->find("td"); $content = $cell['0']->innertext; $lection['title'] = clean_text($content); echo " - Title checked\n"; } else if ($row_name == "Hold:") { echo " - Checking subject...\n"; // Row tells what the subject is $cell = $row->find("td"); $content = $cell['0']->innertext; $lection['subject'] = clean_text($content); echo " - Subject checked\n"; } else if ($row_name == "Lærere:") { echo " - Checking teachers...\n"; // Row tells who the teacher is $cell = $row->find("td"); $content = $cell['0']->innertext; $lection['teachers'] = clean_text($content); echo " - Teachers checked\n"; } else if ($row_name == "Lokaler:") { echo " - Checking location...\n"; // Row tells the location $cell = $row->find("td"); $content = $cell['0']->innertext; $lection['location'] = clean_text($content); echo " - Location checked\n"; } else if ($row_name == "Note:") { echo " - Checking note...\n"; // Row contains a note $cell = $row->find("td"); $content = $cell['0']->innertext; $lection['note'] = clean_text($content); echo " - Note checked\n"; } elseif ($row_name == "Dokumenter:") { echo " - Checking documents...\n"; // Row contains the documents $cell = $row->find("td"); $content = $cell['0']->plaintext; $content = clean_text($content); if ($content) { // We can't get the titles of the documents as we are not logged in // Instead we tell the user that there are documents available $lection['documents'] = LECTION_DOCUMENTS_TRUE; } echo " - Documents checked\n"; } else if ($row_name == "Lektier:") { echo " - Checking homework...\n"; // Row contains the homework $cell = $row->find("td"); $content = $cell['0']->innertext; $lection['homework'] = clean_text($content); echo " - Homework checked\n"; } else if ($row_name == "Vises:") { echo " - Checking status (part 1)...\n"; // Row tells where the lection is shown $cell = $row->find("td"); $content = $cell['0']->plaintext; $content = clean_text($content); if (strstr($content, ",")) { // If the above is true, the lection is NOT REGULAR // Now we know that the lection is either changed or cancellde // We assume it is changed // Below we check if the lection is cancelled (Where $row_namme == "Status:") $lection['status'] = LECTION_STATUS_CHANGED; } echo " - Status (part 1) checked\n"; } } // Add lection to array of lections $lections[] = $lection; print_r($lection); echo " - Lection added!</textarea><br /><br />"; $num += 1; } return $lections; } function get_weeks($amount_of_weeks) { $weeks = array(); // Current week $week_now = date('W'); $year_now = date('Y'); // Demo $week_now = 44; // Last week to fetch $last_week = $week_now + $amount_of_weeks; // Add weeks to array for ($i = $week_now; $i <= $last_week; $i++) { $week = array(); if ($i > AMOUNT_OF_WEEKS_IN_A_YEAR) { // Week is next year $week['week'] = $i - AMOUNT_OF_WEEKS_IN_A_YEAR; $week['year'] = $year_now + 1; } else { // Week is in this year $week['week'] = $i; $week['year'] = $year_now; } // Add week to weeks $weeks[] = $week; } return $weeks; } $weeks = get_weeks(5); $links = get_links_for_lections($weeks); $lections = get_lections($links); echo "<hr />"; print_r($lections); echo "<hr />"; A: I ran this and it worked fine, I got up to 96. If I had to guess I'd say you reached max excution time. Try adding this at the top: set_time_limit(0); Otherwise try changing your error reporting and post any errors here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7620955", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: LINQ - The difference between .Select(n => n.Name) and .Select(n => new { n.Name } ); I am completely new to Linq and wondering if you can help me understand the difference between the following Linq? For example... //normal select var contacts = entity.Contacts.Select(n => n.FirstName); //select new var contacts2 = entity.Contacts.Select(n => new { n.FirstName }); //normal select output foreach (var c in contacts) Response.Write(c + "<br/>"); //select new output foreach (var c in contacts2) Response.Write(c.FirstName + "<br/>"); The only difference I can see is that in the normal select, the firstname (string) is stored in the collection, whereas in the select new, a contact object is stored in the collecton and the firstname being accessed by its property. Also the select new returns the properties only selected in the statement. Another difference I noticed is that you can return multiple specific properties in the select new. In what scenario would you choose one over the other? Thanks for the help. A: To support Richard Ev's answer: If you are not familiar with Anonymous types, crack up ildasm and give your exe as an input to it. You will get something like this: The thing that you see starting with <>f_AnonymousType() is the one that Richard Ev is talking about. Your syntax of new got translated into a new class (the name was decided by compiler). That is why var keyword is so helpful working with anonymous type. A: n => n.FirstName gives you a string n => new { n.FirstName } gives you an anonymous type, with one string property called FirstName In general, an anonymous type with just one property is probably not what you're looking for, so I'd go for the first option.
{ "language": "en", "url": "https://stackoverflow.com/questions/7620957", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Storyboards with bound properties (custom control: animate colour change) To put it simply, I have this within a ControlTemplate.Triggers condition EnterAction: <ColorAnimation To="#fe7" Storyboard.TargetProperty="Background.Color" Duration="00:00:00.1" Storyboard.TargetName="brd"/> But I want the 'to' colour (#fe7) to be customisable. This is a control derived from ListBox. I can create a DependencyProperty, but of course, I cannot bind the To property of the ColorAnimation to it because the Storyboard has to be frozen and you can't freeze something with bindings (as I understand it). I tried using a {StaticResource} within the To, then populating the resource in the code-behind when the DependencyProperty was changed, by setting this.Resources["ItemColour"] = newValue; for instance. That didn't work perhaps obviously, it's a static resource after all: no new property values were picked up. DynamicResource gave the same problem relating to inability to freeze. The property is only set once when the control is created, I don't have to worry about it changing mid-animation. Is there a nice way of doing this? Do I have to resort to looking for property changes myself, dynamically invoking and managing storyboards at that point? Or overlaying two versions of the control, start and end colour, and animating Opacity instead? Both seem ludicrous.. A: Kieren, Will this serve your purpose? I have extended the Grid class called CustomGrid and created a TestProperty whose value when changed will change the background color of Grid: public class CustomGrid : Grid { public bool Test { get { return (bool)GetValue(TestProperty); } set { SetValue(TestProperty, value); } } public static readonly DependencyProperty TestProperty = DependencyProperty.Register("Test", typeof(bool), typeof(CustomGrid), new PropertyMetadata(new PropertyChangedCallback ((obj, propChanged) => { CustomGrid control = obj as CustomGrid; if (control != null) { Storyboard sb = new Storyboard() { Duration = new Duration(TimeSpan.FromMilliseconds(500)) }; Random rand = new Random(); Color col = new Color() { A = 100, R = (byte)(rand.Next() % 255), G = (byte)(rand.Next() % 255), B = (byte)(rand.Next() % 255) }; ColorAnimation colAnim = new ColorAnimation(); colAnim.To = col; colAnim.Duration = new Duration(TimeSpan.FromMilliseconds(500)); sb.Children.Add(colAnim); Storyboard.SetTarget(colAnim, control); Storyboard.SetTargetProperty(colAnim, new PropertyPath("(Panel.Background).(SolidColorBrush.Color)")); sb.Begin(); } } ))); } This is the button click event that changes the color: private void btnClick_Click(object sender, RoutedEventArgs e) { gridCustom.Test = (gridCustom.Test == true) ? false : true; } I am changing the background color of Grid because I don't have your Listbox. Finally this is the xaml: <Grid x:Name="grid" Background="White"> <local:CustomGrid x:Name="gridCustom" Background="Pink" Height="100" Margin="104,109,112,102" > </local:CustomGrid> <Button Content="Click Me" x:Name="btnClick" Height="45" HorizontalAlignment="Left" Margin="104,12,0,0" VerticalAlignment="Top" Width="145" Click="btnClick_Click" /> </Grid> Will this serve your purpose? Let me know or I misunderstood the question? EDIT: See this code: ColorAnimation's To property cannot be bound as you probably guessed. But that doesn't mean you can't change it's value. You can always get a reference to the ColorAnimation and change it's To value and it will all work out well. So from WPF world of binding we need to change a bit and bind the data how we used to do it in Winforms :). As an example see this: This is the xaml: <Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:Microsoft_Windows_Themes="clr-namespace:Microsoft.Windows.Themes;assembly=PresentationFramework.Aero" x:Class="ControlTemplateTriggers.MainWindow" Title="MainWindow" Height="350" Width="525"> <Window.Resources> <Storyboard x:Key="Storyboard"> <ColorAnimation From="Black" To="Red" Duration="00:00:00.500" Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)" Storyboard.TargetName="gridCustom" /> </Storyboard> </Window.Resources> <Grid x:Name="grid" Background="White"> <Grid x:Name="gridCustom" Background="Pink" Height="100" Margin="104,109,112,102" /> <Button Content="Click Me" x:Name="btnClick" Height="45" HorizontalAlignment="Left" Margin="104,12,0,0" VerticalAlignment="Top" Width="145" Click="btnClick_Click" /> </Grid> </Window> This is the code behind: using System.Windows; using System.Windows.Media.Animation; using System.Windows.Media; using System; namespace Sample { public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); this.DataContext = this; } private void btnClick_Click(object sender, RoutedEventArgs e) { Storyboard sb = this.Resources["Storyboard"] as Storyboard; if (sb != null) { ColorAnimation frame = sb.Children[0] as ColorAnimation; Random rand = new Random(); Color col = new Color() { A = 100, R = (byte)(rand.Next() % 255), G = (byte)(rand.Next() % 255), B = (byte)(rand.Next() % 255) }; frame.To = col; sb.Begin(); } } } } As you can see I am getting a reference to the storyboard and changing it's To property. Your approach to StaticResource obviously wouldn't work. Now what you can do is, in your DependencyProperty callback somehow get a reference to the Timeline that you want to animate and using VisualTreeHelper or something and then set it's To property. This is your best bet. Let me know if this solved your issue :) A: can u put multiple DataTriggers with each having respective color for the "To" property... A: Surely not.. What i understood is that u want color A on the Condition A and Color B on some other condition B....so if there's a property with multiple options u can put datatriggers for those condition only...like if Job done = Red, Half done = Green like wise.. If i misunderstood the problem please correct me.. I think i got ur question ...UR control is user configurable so what ever user select , control's background needs to be set to that color with animation right? A: It turns out this is simply not possible.
{ "language": "en", "url": "https://stackoverflow.com/questions/7620958", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: JSON to setAttribute() I've almost got the following working, but have run across many confusing approaches. The desire is using the key:value in the attr{} for the setAttribute() method properties, WITHOUT a framework. Please lend a slim solution: testDiv = document.getElementById("testDiv"); attr = { align:"center", title:"The Test Div" }; //Possible converting JSON to String, the use in setAttribute? for(var x in attr) alert(x + " , " + attr[ x ] ); testDiv.setAttribute( x , attr[ x ]); A: You don't have JSON there, you have an object literal. Anyway, if I understand you correctly you want to set all of the specified attributes for one particular element? A loop in a function should do it easily enough if you want something re-usable: function setMultipleAttributes(el, attributes) { for (var attr in attributes) el.setAttribute(attr, attributes[attr]); } var testDiv = document.getElementById("testDiv"); setMultipleAttributes(testDiv, { align : "center", title : "The Test Div" }); A: Your problem has nothing to do with “JSON” (actually just a JavaScript object literal) or setting attributes. It's this: for(var x in attr) alert(x + " , " + attr[ x ] ); testDiv.setAttribute( x , attr[ x ]); Since you do not use braces with the for loop, only the statement immediately following it is executed. If I add braces, the above code looks like this: for(var x in attr){ alert(x + " , " + attr[x] ); } testDiv.setAttribute( x , attr[x]); setAttribute isn’t called in the loop — it’s just called once at the end. Instead, you probably want… for(var x in attr){ alert(x + " , " + attr[x] ); testDiv.setAttribute( x , attr[x]); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7620963", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: NHibernate + SQLite issues in .NET 3.5 I'm having a problem working in SharpDevelop using NHibernate and SQLite. I've seen people having my exact problem in Visual Studio 2010 working with .NET 4.0, but I'm working in .NET 3.5 and I've never had these problems earlier. I'm doing some unit testing and whenever I'm trying to open a connection to the DB through NHibernate the following exception is thrown: SetUp : StructureMap.StructureMapException : StructureMap Exception Code: 207 Internal exception while creating Instance '55c9fa8e-fa79-4698-8d06-7e305e73ac49' of PluginType SimplEconomics.Data.NHibernate.UnitOfWork.INHibernateUnitOfWork. Check the inner exception for more details. ----> FluentNHibernate.Cfg.FluentConfigurationException : An invalid or incomplete configuration was used while creating a SessionFactory. Check PotentialReasons collection, and InnerException for more detail. ----> NHibernate.HibernateException : Could not create the driver from NHibernate.Driver.SQLite20Driver, NHibernate, Version=2.1.2.4000, Culture=neutral, PublicKeyToken=aa95f207798dfdb4. ----> System.Reflection.TargetInvocationException : Exception has been thrown by the target of an invocation. ----> NHibernate.HibernateException : The IDbCommand and IDbConnection implementation in the assembly System.Data.SQLite could not be found. Ensure that the assembly System.Data.SQLite is located in the application directory or in the Global Assembly Cache. If the assembly is in the GAC, use <qualifyAssembly/> element in the application configuration file to specify the full name of the assembly. - d:\Builds\FluentNH\src\FluentNHibernate\Cfg\FluentConfiguration.cs:93 I think it's the last line that's most specific and the weird thing is that I first had my project in .NET 4.0 (using the latest version of Sharpdevelop, 4) and with that I could understand that there were some issue with the latest SQLite release, but this is with .NET 3.5, I've used it before. Anyone have any ideas? Here's my spec btw: * *SharpDevelop 3.2.1 *SQLite 1.0.74.0 *NHibernate 2.1.2.4000 *.NET 4.0 installed, and 3.5 *Windows Vista (if that matters) This is driving me completely insane... EDIT: I should add that I have tried the following solution without success: A similar stackoverflow-thread A: Make sure your SQLite DLL is copied to your /bin directory. Also, be warned, that SQLite is not Win OS agnostic and there are both 32-bit and 64-bit versions available and use the appropriate version on the OS that it's used on. SQLite home.
{ "language": "en", "url": "https://stackoverflow.com/questions/7620964", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: JavaScript program, what's wrong? Okay, I don't know where to look. Actually, my interpreter isn't giving me anything back. I'm not getting an alert or anything. var string, output = ""; var counter = number(prompt("Where to start?"); while(; ; counter++){ if(counter < 0){ alert("Error."); break; } else if(counter => 0 >= 10){ string += string; output += string + "\n"; } else{ alert("Too much.") break } } alert(output); A: 1) To type cast to a number, you need to used a capitol N like the class "Number" 2) Take out the "; ;" for your while loop. 3) Semicolons are needed where lines close (good practice). var string, output = ""; var counter = Number(prompt("Where to start?")); while(counter++){ if(counter < 0){ alert("Error."); break; } else if(counter >= 0 >= 10){ string += string; output += string + "\n"; } else{ alert("Too much."); break; } } alert(output); gl A: Your code has a number of syntax errors (as mentioned by others), and is also a little unusually-written. * *A while loop just takes one argument, it looks like you intended to use a for loop *The variable string isn't needed *Number will return NaN if the argument passed to it cannot be evaluated as a number. The code should check for this as well *Your validation code is inside the loop. It would make more sense for this to be outside of the loop *output will end up with a trailing newline. This probably isn't desirable. To avoid this you can build up output as an array of values, and then join them with newlines at the end How about changing your code to this? var counter = Number(prompt("Where to start?", "0")); if (isNaN(counter)) { alert("You needed to enter a number"); } else if (counter < 0) { alert("Error."); } else if (counter > 10) { alert("Too much."); } else { var output = []; for ( ; counter <= 10; counter++) { output.push(counter); } alert(output.join("\n")); } Edit You mentioned that you've not yet learned about JavaScript arrays, so here's an alternative code snippet for the else block that is closer to your original approach, of building up the string step-by-step. var output = ""; for ( ; counter <= 10; counter++) { output += counter + "\n"; } alert(output); A: Perhaps you meant else if(counter => 0 && counter <= 10) { since you have no condition that will get you to your else statement.
{ "language": "en", "url": "https://stackoverflow.com/questions/7620967", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: How to test against a DOM object in qUnit? I'm testing some JavaScript with qUnit. In one object I pass a DOM element, and some methods will change some properties of the element. How can I mock a DOM object in qUnit? I'd like to use a solution browser independent, as I test also XUL applications. A: You can always create an element in JavaScript. If you don't append it (e.g. to the body), it won't be visible, so you could call it a mock element: document.createElement('div'); // 'div' will create a '<div>' So you can use this in a qUnit test function just as well: http://jsfiddle.net/LeMFH/. test("test", function() { expect(1); var elem = document.createElement("div"); elem.style.position = "absolute"; equals(elem.style.position, "absolute"); }); A: I had this situation where I wanted to create a unit test for a JQuery plugin I wrote that provides simple basic tree expansion capability. I found a way to create dummy line item (“LI” element) using the QUnit “ok” method and inject the test DOM as a child of this list item, in this way the resulting manipulated DOM can be examined by expanding the test. Also if the test failed, the manipulated DOM elements will automatically be displayed by the QUnit system. The resulting QUnit output looks like the following: My solution to this problem was to create a function called “testSpace” where the line item text and test HTML can be defined so the QUnit test commands can check the resulting DOM. The following is the test code that uses this feature: test("$.fn.tocControl", function () { var sTest = "<div>" + "<ul>" + "<li>item1</li>" + "<li>item2" + "<ul>" + "<li>s1item1</li>" + "<li>s1item2" + "<ul>" + "<li>s2item1</li>" + "<li>s2item2" + "</li>" + "<li>s2item3</li>" + "<li>s2item4</li>" + "</ul>" + "</li>" + "<li>s1item3</li>" + "<li>s1item4</li>" + "</ul>" + "</li>" + "<li>item3</li>" + "<li>item4</li>" + "<li>item5</li>" + "</ul>" + "</div>"; // Create the test HTML here. var jqTest = testSpace("$.fn.tocControl.test", sTest); // Invoke the JQuery method to test. jqTest.find("ul").tocControl(); // QUnit tests check if DOM resulting object is as expected. equal(jqTest.find("ul.ea-toc-control").length, 1, '$("div#testSpace ul.tocControl").length'); equal(jqTest.find("ul:first").hasClass("ea-toc-control"), true, '$("div#testSpace ul:first").hasClass("tocControl")'); }); The “testSpace” function defines the line item using the QUnit “ok” method, but initially constructs the DOM objects in a temporary location until the QUnit system defines the line item. This function is defined as follows: function testSpace(sName, sHTML) { ok(true, sName); var jqTestItem = $("ol#qunit-tests > li:last"); jqTestItem.append('<div id="testSpaceContainer" style="display:none;">' + sHTML + '</div>'); var jqTestSpace = jqTestItem.children("div#testSpaceContainer:first"); var moveTestSpaceStart = $.TimeStamp(); var moveTestSpace = function () { var jqTestArea = jqTestItem.find("ol > li:contains(" + sName + ")").filter(function () { return $(this).text() == sName; }); if (jqTestArea.length <= 0) { if (!$.HasTimedOut(moveTestSpaceStart, 5000)) setTimeout(moveTestSpace, 200); return false; } var oTestSpace = jqTestSpace.detach(); jqTestArea.append(oTestSpace); jqTestArea.find("div#testSpaceContainer").show(); return true; } moveTestSpace(); return jqTestSpace.children().first(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7620971", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: ActionSheet within UISplitViewController acts different in Portrait Mode than Landscape Mode I created a new application using the Split View-based Application template. I then added an Action Button to the rootViewController navigation controller called actionButton. When the button is pressed, I display an ActionSheet like this: UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:@"Admin Functions", @"Refresh Data", nil]; [actionSheet showFromBarButtonItem:actionButton animated:YES]; [actionSheet release]; After I press the button when in landscape mode it displays the action sheet in a popover which is pointing to the button (as I expected it to): However, in Portrait mode it looks completely different and the menu comes up from the bottom of the rootViewController popover just like it does on the iPhone: My question is, how do I make the ActionSheet appear at the top while in portrait mode, just like it does when in landscape mode? Since this is a "utility menu", it isn't really tied directly to the data being displayed so it shouldn't be part of the popover. A: This behaviour is by design, if it were a popover in portrait mode you would then have 2 levels of popover. This is technically possible by implementing your own version of UIPopover or using one someone has already written (WEPopover). However, this is a poor design choice. You say that the functions aren't related to the data, however one is 'refresh data'. I would replace the action button with a refresh icon such as the one Apple uses in 'Find my Friends': The other, 'Admin Functions', if not directly related to the data in the list, perhaps needs a new home, maybe with the main view of your app? It's hard to say where is best to put it without knowing more about the structure. A: Another possibility is that you could move the action button from right edge of the root view controller's bar to the left edge of the detail view controller's bar. For example, if the action button were located just to the right of the vertical bar in your first screen shot (meaning it's at the left edge of the detail view controller's bar), then when you rotate to portrait mode it would appear just to the right of the Events button in your second screen shot. You could still call UIActionSheet's showFromBarButtonItem:animated method, which would display your action sheet in popup mode. There's still the question of whether you really want two popovers on the screen at the same time. But if you do, this is how to do it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7620972", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Scan list in prolog I want to scan a list in Prolog. In particular, I want to write a predicate scan_list (list), and I want to make it check to see if the current element is a positive integer and if so print it. Thank's. A: If this is homework, be assured that the only way to learn any programming language is to practice it and think about the assignments. However, here is a version that might be, what you want scan_list([]). scan_list([H|T]) :- H > 0,!, print(H),nl,scan_list(T). scan_list([_|T]) :- scan_list(T). It works like that: ?- scan_list([1,-2,7,9,0,-1,14]). 1 7 9 14 yes A: In SWI-Prolog there is include/3, e.g. you can write ?- include(<(0), [1, -2, 7, 9, 0, -1, 14, 0.8], L). L = [1, 7, 9, 14, 0.8]. (Warning: this particular code accepts more numbers than positive integers.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7620973", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Odd CONCAT Error with Select/Insert Any reason why this will return rows: select users.user_fullname,concat(persons.first_name,' ',persons.last_name) from users, persons where users.user_id = persons.user_id and users.user_fullname = '0' Yet this throws a syntax error? update users set users.user_fullname = concat(persons.first_name,' ',persons.last_name) from users, persons where users.user_id = persons.user_id and users.user_fullname = '0' A: It has nothing to do with CONCAT. The problem is that you should not have a FROM clause in an UPDATE statement. UPDATE users, persons SET users.user_fullname = CONCAT(persons.first_name,' ',persons.last_name) WHERE users.user_id = persons.user_id AND users.user_fullname = '0'
{ "language": "en", "url": "https://stackoverflow.com/questions/7620975", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What is wrong my code (trying to abbreviate)? I am using irb/ruby1.9.1. 1st step I wrote the code below: def isUppercase self>= ?A && self<= ?Z end class String def abbreviate abbr = "" each_byte do |c| if c.isUppercase abbr += c.chr end end abbr end end 2nd step I am evaluating the code below which I expected to be "UFO". "Unidentified Flying Object".abbreviate However, errors occcured. How do I correct it? the error is here. irb(main):044:0> load("abbrevi.rb") => true irb(main):045:0> "Unidentified Flyng Object".abbreviate ArgumentError: comparison of Fixxnum with String failed from C:/Ruby192/lib/ruby/1.9.1/abbrevi.rb:4:in >=' from C:/Ruby192/lib/ruby/1.9.1/abbrevi.rb:4:in isUppercase' from C:/Ruby192/lib/ruby/1.9.1/abbrevi.rb:12:in block in abbreviate' from C:/Ruby192/lib/ruby/1.9.1/abbrevi.rb:11:in each_byte' from C:/Ruby192/lib/ruby/1.9.1/abbrevi.rb:11:in abbreviate' from (irb):45 from C:/Ruby192/bin/irb:12:in <main> A: Try this: class Fixnum def isUppercase self.chr >= ?A && self.chr <= ?Z #note use of `chr` to avoid error that occurs when #comparing a Fixnum to a String end end class String def abbreviate abbr = "" each_byte do |c| if c.isUppercase abbr += c.chr.to_s #note this usage as well end end abbr end end Note that you cannot add a string to a number, or compare, so the below will generate errors: irb> 1 >= "A" # => ArgumentError: comparison of Fixnum with String failed UPDATE: @coreyward's answer is the better way to do what you're doing overall, but my answer is only pointing out how to fix your code and the reason for you error. A yet better way might be to use Regular Expressions. A: I don't see why you're checking if a byte is uppercase, rather than a character (there are multi-byte characters), but this sidesteps your issue entirely: class String def abbreviate each_char.reduce('') do |abbr, c| abbr += c if ('A'..'Z').include?(c) abbr end end end This still doesn't really take non A-Z letters/characters into account, though.
{ "language": "en", "url": "https://stackoverflow.com/questions/7620976", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: My app working on android 2.2 and android 2.3.3 emulators but not on my phone galaxy s android 2.3.5 / Read facebook,twitter contacts? i have a problem with my app , In egypt they are going to add extra digit to mobile numbers to expand , so i made an app to modify the existing numbers to the new one. So basically i read all phone numbers , based on some conditions i manipulate them and save the new data, Iam working on eclipse with adt plugin , i have tried the app on emulator 2.2 , and emulator 2.3 and is working very fine and modify all contacts. but when i transfered on my mobile galaxy s android 2.3.5 , it runs without saving the new contact data , i even debugged to see the flow , it works normal gets all numbers modify them and save them without errors , but contacts are not updated. Is there a certain reason , can you give me more ideas ? i want to provide some more info , i have installed froyo 2.2 on my mobile and still won't save the new contact number , although it is working very good on the emulator, i save the contact this way : ContentResolver cr2 = getContentResolver(); String where = Data.RAW_CONTACT_ID + " = ? AND " + String.valueOf(Phone.TYPE) + " = ? "; String[] params = new String[] { id, String.valueOf(type) }; ArrayList<ContentProviderOperation> ops=new ArrayList<ContentProviderOperation>(); ops.add(ContentProviderOperation .newUpdate(Data.CONTENT_URI) .withSelection(where, params) .withValue( ContactsContract.CommonDataKinds.Phone.DATA, phoneNumber).build()); try { cr2.applyBatch(ContactsContract.AUTHORITY,ops); } catch (RemoteException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (OperationApplicationException e) { // TODO Auto-generated catch block e.printStackTrace(); } Ok Guys , Sorry iam just new to android , but i found the mistake and i modified the code to be : ContentResolver cr2 = getContentResolver(); String where = Data.CONTACT_ID + " = ? AND " +Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'" + " AND " + String.valueOf(Phone.TYPE) + " = ? "; String[] params = new String[] { id, String.valueOf(type) }; // Cursor phoneCur = managedQuery(Data.CONTENT_URI, // null, where, params, null); ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(); ops.add(ContentProviderOperation .newUpdate(Data.CONTENT_URI) .withSelection(where, params).withValue( Phone.NUMBER, phoneNumber).build()); try { cr2.applyBatch(ContactsContract.AUTHORITY, ops); count++; System.out.println(phoneNumber); } catch (RemoteException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (OperationApplicationException e) { // TODO Auto-generated catch block e.printStackTrace(); } So Technincally i added the mimetype , and i used to update phone.data so i changed that also to phone.number , now it is working ok on 2.2 / 2.3.5 , so i guess this question is closed , but i have one more thing to ask , the read contacts doesn't include facebook or twitter contacts , is there anyway to read all contacts to update them all including facebook and twitter ???? A: You can do one thing: just change the project-properties file and edit target=android-10 and then try...
{ "language": "en", "url": "https://stackoverflow.com/questions/7620977", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Will Paginate: Limit number of results Im using the will paginate gem for ruby. I am using will paginate to get a bunch of people and sorting on a field. What I want is only the first 100 of those. Essentially the top people. I cant seeem to do this. How would i go about it? Thanks A: As far as my knowledge goes will_paginate doesn't provide an option for this, I just had a root around in its source too to check, but if you don't mind having a subquery in your conditions it can be done... people = Person.paginate(page: 10).where('people.id IN (SELECT id FROM people ORDER BY a_field LIMIT 100)').per_page(5) people.total_pages => 20 Replace a_field with the field your sorting on, and this should work for you. (note, the above uses the current version of will_paginate (3.0.2) for its syntax, but the same concept applies to older version as well using the options hash) A: will_paginate gem will take total_entries parameter to limit the number of entries to paginate. @problems = Problem.paginate(page: params[:page], per_page: 10, total_entries: 30) This gives you 3 pages of 10 records each. A: people = Person.limit(100).paginate(:per_page => 5)
{ "language": "en", "url": "https://stackoverflow.com/questions/7620978", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: What language(s) are programs like ActiveInbox written in? I want to write something similar to ActiveInbox. In addition to original ActiveInbox, I need to add logic that will perform some actions on the emails that come. What language(s) are programs like ActiveInbox written in? Thank you A: Activeinbox is a browser plugin, written in Javascript. It's easy to have a look inside: download the xpi (the Firefox version of the plugin). An xpi file is a zipfile, so open it with your zipfile manager of choice. After that you should head over to Mozilla's developer site or a Chrome extension development tutorial to learn how to wite a Firefox/Chrome plugin. A: Extensions can be written in pure Javascript on Chrome and Firefox.
{ "language": "en", "url": "https://stackoverflow.com/questions/7620988", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to insert image between layers in html5 canvas I need to be able to layer image in canvas... how it is possible to insert image between two, or order the image, more like layer in photoshop... on top or below. In fact, i alredy draw many images, i need to be able to inser one between those, or just use a dummy and change it later, i dont know what is the way to do that ? A: The easiest way to do this is to just stack all of your elements inside a parent container and adjust the z-index CSS property of each layer. The higher the z-index, the closer the layer is to the top of the stack. Elements with lower z-index values are obstructed by elements with higher values. Note that you'll likely have to set position: absolute; on each layer within the container and then align them to, say, the top left corner of the parent element. Otherwise they won't overlap one another. Alternatively, you can manage the layers based on their position within the DOM tree. The later the element is defined in the DOM, the closer it will be to the top of your layer stack (CSS properties aside, of course). So, you could theoretically use insertBefore() or a homespun insertAfter() to place your layers in the required location within the DOM and avoid z-index manipulation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7620994", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jQuery round / circle thermometer possible? Possible Duplicate: Circular progress indicator with jQuery I've been hunting around on the net for hours now trying to find a jquery solution for a round progress meter / thermometer style plugin i need to set a target say 2000 and then pass amount raised such as 100, it would then work out the % difference and show the progress on the image i attached, i.e the red lines would be the progress with 100% being all red like in image but if 50% for exmaple would be half red half black. does anyone have any ideas if something liek this is floating around?
{ "language": "en", "url": "https://stackoverflow.com/questions/7620995", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Trying to receive text via a socket I'm trying to do a simple test off sending data to a socket where the server program then sends data back. I can send the data but don't seem to receive data back. I have checked the server program and I receive the data successfully and used wireshark to watch the traffic and the server program is sending data but my client isn't able to get the data. I have hidden the ip address and port for obvious reasons. Socket echoSocket = null; PrintWriter out = null; BufferedReader in = null; try { //TODO Need filshills public ip address echoSocket = new Socket("xxxxxx",xx); } catch (UnknownHostException e) { System.err.println("Don't know about host."); } catch (IOException e) { System.err.println("Couldn't get I/O for " + "the connection to host."); } PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(echoSocket.getOutputStream())), true); //PrintWriter pw = new PrintWriter(echoSocket.getOutputStream(), true); pw.flush(); pw.print("MS01,test,06,000027,01\r\n"); pw.close(); try{ BufferedReader stdIn = new BufferedReader(new InputStreamReader(echoSocket.getInputStream())); String check = stdIn.readLine(); check = check + ""; //BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in)); String userInput; while ((userInput = stdIn.readLine()) != null) { out.println(userInput); System.out.println("echo: " + in.readLine()); stdIn.close(); } }catch ( Exception e) { String neil = e.getMessage(); neil = neil + ""; } out.close(); in.close(); echoSocket.close(); A: Try to not close PrintWriter, according to getOutputStream, close will close socket: Closing the returned OutputStream will close the associated socket.
{ "language": "en", "url": "https://stackoverflow.com/questions/7620996", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Struct Alignment with PyOpenCL update: the int4 in my kernel was wrong. I am using pyopencl but am unable to get struct alignment to work correctly. In the code below, which calls the kernel twice, the b value is returned correctly (as 1), but the c value has some "random" value. In other words: I am trying to read two members of a struct. I can read the first but not the second. Why? The same issue occurs whether I use numpy structured arrays or pack with struct. And the _-attribute__ settings in the comments don't help either. I suspect I am doing something stupid elsewhere in the code, but can't see it. Any help appreciated. import struct as s import pyopencl as cl import numpy as n ctx = cl.create_some_context() queue = cl.CommandQueue(ctx) for use_struct in (True, False): if use_struct: a = s.pack('=ii',1,2) print(a, len(a)) a_dev = cl.Buffer(ctx, cl.mem_flags.WRITE_ONLY, len(a)) else: # a = n.array([(1,2)], dtype=n.dtype('2i4', align=True)) a = n.array([(1,2)], dtype=n.dtype('2i4')) print(a, a.itemsize, a.nbytes) a_dev = cl.Buffer(ctx, cl.mem_flags.WRITE_ONLY, a.nbytes) b = n.array([0], dtype='i4') print(b, b.itemsize, b.nbytes) b_dev = cl.Buffer(ctx, cl.mem_flags.READ_ONLY, b.nbytes) c = n.array([0], dtype='i4') print(c, c.itemsize, c.nbytes) c_dev = cl.Buffer(ctx, cl.mem_flags.READ_ONLY, c.nbytes) prg = cl.Program(ctx, """ typedef struct s { int4 f0; int4 f1 __attribute__ ((packed)); // int4 f1 __attribute__ ((aligned (4))); // int4 f1; } s; __kernel void test(__global const s *a, __global int4 *b, __global int4 *c) { *b = a->f0; *c = a->f1; } """).build() cl.enqueue_copy(queue, a_dev, a) event = prg.test(queue, (1,), None, a_dev, b_dev, c_dev) event.wait() cl.enqueue_copy(queue, b, b_dev) print(b) cl.enqueue_copy(queue, c, c_dev) print(c) The output (I had to reformat while cut+pasting, so may have messed up line breaks slightly; I've also added comments indicating what the various print values are): # first using struct /home/andrew/projects/personal/kultrung/env/bin/python3.2 /home/andrew/projects/personal/kultrung/src/kultrung/test6.py b'\x01\x00\x00\x00\x02\x00\x00\x00' 8 # the struct packed values [0] 4 4 # output buffer 1 [0] 4 4 # output buffer 2 /home/andrew/projects/personal/kultrung/env/lib/python3.2/site-packages/pyopencl/cache.py:343: UserWarning: Build succeeded, but resulted in non-empty logs: Build on <pyopencl.Device 'Intel(R) Core(TM)2 CPU T5600 @ 1.83GHz' at 0x1385a20> succeeded, but said: Build started Kernel <test> was successfully vectorized Done. warn("Build succeeded, but resulted in non-empty logs:\n"+message) [1] # the first value (correct) [240] # the second value (wrong) # next using numpy [[1 2]] 4 8 # the numpy struct [0] 4 4 # output buffer [0] 4 4 # output buffer /home/andrew/projects/personal/kultrung/env/lib/python3.2/site-packages/pyopencl/__init__.py:174: UserWarning: Build succeeded, but resulted in non-empty logs: Build on <pyopencl.Device 'Intel(R) Core(TM)2 CPU T5600 @ 1.83GHz' at 0x1385a20> succeeded, but said: Build started Kernel <test> was successfully vectorized Done. warn("Build succeeded, but resulted in non-empty logs:\n"+message) [1] # first value (ok) [67447488] # second value (wrong) Process finished with exit code 0 A: In the OpenCL program, try the packed attribute on the struct itself, instead of one of the members: typedef struct s { int4 f0; int4 f1; } __attribute__((packed)) s; It might be that because you only had the packed attribute on a single member of the struct, it might not have been packing the entire structure. A: ok, i don't know where i got int4 from - i think it must be an intel extension. switching to AMD with int as the kernel type works as expected. i'll post more at http://acooke.org/cute/Somesimple0.html once i have cleaned things up.
{ "language": "en", "url": "https://stackoverflow.com/questions/7620999", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Use ajax to call a php method Hi i would like to use ajax in my website where all requests pass are loaded in index.php (i use htacess for rewriting urls) so when i use ajax i always reload the current page and then use if(expressio) to check if the user has called a function with ajax but this cause that all the page is reloaded each time i use ajax. I was wondering if there is a method to call a specific php method/function or property in the current page with ajax without reloading all the page. I'm using the jquery library for ajax If someone knows some other ways is ok! A: A main use of ajax is that you call asynchronously something. Most often functions-methods that are called with ajax do rely on the same php file (if not then it's okay) with other stuff that you do not need to call asynchronously. For example you have a method that is called via ajax to autocomplete a text field (like google search) in a file that there is other stuff you don't want to execute too. If you are under some mvc then you have controller check this out and make sure that only the requested method is called (I've done it successfully). So it is easier controlled under an mvc, all things are in classes... If not under mvc then I guess you have to implement something like controller in order to call only the methods you like. However there is a conition that should be espected, no code should be found out of classes cause it would be executed on "include", it would go like this: file ajax handler 1.Check if an ajax call 2.if check false return; 3.if true then get the name of the class file 4. call the desired method (or methods, you have an execution flow predefined during to your needs) So it can be done. It is important not to execute code that is not supposed to be executed since then undesired results (or errors) would occur. A: in ajax i use the current url as the action of the request but this cause the re-load of the whole page. Since you have your own mvc it could go like this index.php/rt=request/action where request=the name of the controller (which in the end is a class), and action is the name of the action (which in the end is a method inside the class-controller you are requesting) for example mysite.com/rt=user/create My point is that you don't care what the current url is, all you care is to call the right method(=action) of the right class(=controller). The login class is istantiater in all pages because it check if a user is logged; I don't really understand this (when you say pages you mean php files?), whatever it is I suggest (if haven't done already) to follow the single entry point (no need to do this for ajax calls) where every request hits only to index.php like I showed you above. Then a few lines of code on the very top can do the login check. And a last thing what kind of ajax is this that reloads all the page, this an example how I do ajax for autocomplete in a text field: put this as it is in head-script-javascript to make the connection var request = false; try { request = new XMLHttpRequest(); } catch (trymicrosoft) { try { request = new ActiveXObject("Msxml2.XMLHTTP"); } catch (othermicrosoft) { try { request = new ActiveXObject("Microsoft.XMLHTTP"); } catch (failed) { request = false; } } } if (!request) alert("Error initializing XMLHttpRequest!"); or even better you can have it in a separate file and include it wherever you need it then I use a function to do the asunchronous call, what I am doing is similar to your needs because I too get data from html and pass it to php (read the comments) and then execute sql. function getMatch() { //get the form values, I have one value here, you get as need as many as you need var str = document.getElementById("categ_name").value ; var url = "internal.php";//php file to execute //now pass the html form parameters to php //do you see here controller is defined, it is named asynch //then see the action (method of controller class) it is called getMatch //then see how I pass the html form data with str, it is the string to match //comcateg is the mysql table to get the match var params = "rt=asynch/getMatch&data=" + (str)+"&from=comcateg"; request.open("POST", url, true);//use post for connect harder to attack, lots of data transfer //Some http headers must be set along with any POST request. request.setRequestHeader("Content-type", "application/x-www-form-urlencoded;charset=utf-8"); request.setRequestHeader("Content-length", params.length); request.setRequestHeader("Connection", "close"); request.onreadystatechange = updatePage; request.send(params); }//////////////////// Then when the answear will be back this function will be called because we defined so above in the code function updatePage() { if (request.readyState == 4) { if (request.status == 200) { //test var r=request.responseText.split("$$"); alert(r[1]); } else{ //alert("status is " + request.status); } } } I think now you can do it without problem, remeber whatever would be echoed by php even errors all of them will come back in the request.responseText. This is a tutorial among others about mvc that I like, https://sites.google.com/site/mhabipi/php-reading-material/superMVC.htm?attredirects=0&d=1 it's written by Kevin Waterson but sadly phpro.org does not work anymore.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621000", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Atom feed basics I want to provide a atom feed. My HttpServlet writes the following stuff (copied from wikipedia): <?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom"><author><name>Autor des Weblogs</name></author><title>Titel des Weblogs</title><id>urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6</id><updated>2003-12-14T10:20:09Z</updated><entry><title>Titel des Weblog-Eintrags</title><link href="http://example.org/2003/12/13/atom-beispiel"/><id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id><updated>2003-12-13T18:30:02Z</updated><summary>Zusammenfassung des Weblog-Eintrags</summary><content>Volltext des Weblog-Eintrags</content></entry></feed> I'm writing this stuff directly with response.getOutputStream().write(message.getBytes()); with message being the string above. In Internet explorer a special feed reader page is opened but with firefox the raw xml is displayed. Is this a firefox issue, or am I missing to pass some encoding,header, mime type or other information that all browsers see that a atom is coming? A: Did you use the correct response header for your atom feed. You need to set "Content-Type:application/rss+xml" in your response header for this to properly work in firefox. A: You need to set the correct content type, which for Atom is application/atom+xml because this is what your browser uses to decide what plugin or app to launch.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621004", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to load a a collection of users\factories? I am using Ruby on Rails 3.1.0, rspec-rails 2 and Factory gems. In order to test a controller index action I would like to load a collection of users\factories. Example (the following code doesn't work): describe "GET index" do let(:users) { 3.times(Factory(:user)) } it "should ..." do users.should ... end end Using the above code I get the following error: Failure/Error: let(:users) { 3.times(Factory(:user)) } ArgumentError: wrong number of arguments(1 for 0) What can I do to load factories in to users variable? UPDATE ... and if in the above code I have Factory(:user, :account => Factory.build(:account)) instead of Factory(:user) how can I load factories? A: Try let(:users) { FactoryGirl.create_list(:user, 3) }
{ "language": "en", "url": "https://stackoverflow.com/questions/7621013", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Triple colon Scala I'm trying to pick up some scala. Reading through examples I came across this impossible-to-google nugget: case 3 => l ::: List(3) What does the triple colon accomplish? A: Concatenates two lists - javadoc A: To add to gkamal's answer, it's important to understand that methods whose names end in a colon are right-associative. So writing l ::: List(3) is the same as writing List(3).:::(l). In this case it doesn't matter since both operands are lists, but in general you'll need this knowledge to find such methods in the scaladocs. It also helps to know that the scaladocs have a comprehensive index of all methods (and classes, etc) with symbolic names. You can reach it by clicking on the # in the upper-left corner.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621014", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "61" }
Q: Showing Google Maps Marker infoname on Mouseover of a Dynamically Generated DIV I want to introduce a functionality which allows a marker's infoname to appear or disappear upon mouseover or mouseout of a corresponding DIV element generated from jQuery. However, I am getting a "a is undefined" error on line 19 of main.js. After extensive testing on my script, I realise that this has something to do with the marker in the newly added lines as commented below: function addMarker(A) { var point = new google.maps.LatLng(A.lat, A.lng); var image = new google.maps.MarkerImage('images/r.png', new google.maps.Size(30, 30), new google.maps.Point(0, 0), new google.maps.Point(0, 30)); marker = new google.maps.Marker({ map: map, position: point, icon: image, }); } function addInfoName(A) { var infoname = new infoName; // custom object google.maps.event.addListener(marker, 'mouseover', function(event) {infoname.show();}); google.maps.event.addListener(marker, 'mouseout', function(event) {infoname.hide();}); infoname.open(map, marker); } function showResult(A) { $('#results').append('<DIV id=' + A.pid + '>{Blah Blah Blah}</DIV>'); return document.getElementById(A.pid); } function process(json) { $('#results').empty(); total = json.details.length; for(i=0; i<total; i++) { var detail = json.details[i]; var marker; addMarker(detail); addInfoName(detail); // these new lines are added var listDisplay = showResult(detail); listDisplay.onmouseover = function(){google.maps.event.trigger(marker, 'mouseover');}; listDisplay.onmouseout = function(){google.maps.event.trigger(marker, 'mouseout');}; } } google.maps.event.addListener(map, 'idle', function () {$.getJSON(query, process);}); The error disappears if I merge the function addInfoName into process. However, all the DIVs will point to the last marker if I do so. My question is, how do I modify my script to achieve the functionality mentioned above? A: The "a is undefined" error is probably because you are trying to create the map before the dom is ready. At least, that's the only time I have seen it. I can't tell from your code where you're creating it, but make sure that the map div is ready. You either have to place the call to your initialize function at the bottom of the page or in an page load listener. Here's one way you can do that (this can go anywhere in the page): function initialize() { var map = new google.maps.Map(document.getElementById("map_canvas"), { zoom: 6, mapTypeId: google.maps.MapTypeId.ROADMAP }); google.maps.event.addListener(map, 'idle', function () { $.getJSON(query, process); }); } google.maps.event.addDomListener(window, 'load', initialize); Also notice that your idle listener goes in that init function, too, since it won't be able to run until the map has been created. If that's not causing the "a is undefined" error, then I can't see it in the code you've posted. I do, however, see some other problems with your code. So maybe that is actually what's causing it. First, the var marker; definition in process doesn't do anything. Here you are creating a local variable, but that local variable never gets defined. Then addMarker you are creating a global variable by defining marker without the var. So the marker in addInfoname always refers to the global marker, which will always be the last marker defined. So that's why the divs are always showing up with the last marker. I would put a return before marker = ... in addMarker, and use it to set the marker variable like this: var marker = addMarker(detail); In process, of course. Then you also have to send this to addInfoname as a parameter so it gets the correct one. A: Currently you've got a variable marker declared local to the process function, but you're trying to read and write to it from other functions. In particular, addMarker writes to marker without var, which causes an accidental global variable to be created. Meanwhile process is not actually writing to the marker local it has declared, so it contains undefined, which will trip the Google Maps code up when you pass that in. (Tools like jslint, or ECMAScript 5 Strict Mode can catch accidental globals for you. Note total and i are also accidental globals.) It looks like addMarker and addInfoname have been hacked out of the body of process without tying up the variables from process that both of them used. If they were included in the body of process it would work, but you'd get the described behaviour where the same marker value was used for every div because of the Closure Loop Problem. This problem occurs in languages with closures and function-level scope, which includes JavaScript, Python and others. In these languages any variables defined by or inside a for loop are local to the containing function, not reallocated every time you go around the loop. So if you make a closure referring to i in the first iteration of the loop, it's the same variable i as you refer to in the second iteration of the loop; every instance of the function has a closure over the same variable i so every function will see the same value. The same would be true of marker. The Closure Loop Problem can be avoided through use of a second closure that keeps the loop variable in an argument, or, more cleanly, using a closure-based loop mechanism instead of the C-like for loop. ECMAScript 5 offers array.forEach() for this purpose and jQuery offers $.each(): function process(json) { $('#results').empty(); var gev= google.maps.event; $.each(json.details, function(detaili, detail) { var marker= addMarker(detail.lat, detail.lng); $('#results').append($('<div>', { text: detail.name, mouseover: function() { gev.trigger(marker, 'mouseover'); }, mouseout: function() { gev.trigger(marker, 'mouseout'); } })); var infoname= new InfoName(); gev.addListener(marker, 'mouseover', function() { infoname.show(); }); gev.addListener(marker, 'mouseout', function() { infoname.hide(); }); infoname.open(map, marker); }); } function addMarker(lat, lng) { return new google.maps.Marker({ map: map, position: new google.maps.LatLng(lat, lng), icon: new google.maps.MarkerImage( 'images/r.png', new google.maps.Size(30, 30), new google.maps.Point(0, 0), new google.maps.Point(0, 30) ) }); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7621016", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Use nwalign() with any type of sequence I require an approximate string matching function for Matlab. I found out that the Bioinformatics toolbox has the Needleman–Wunsch algorithm by calling nwalign(). The only problem is that it only works with amino acid sequences. So when I try compare strings with numbers and other symbols, I get an error saying: "Both sequences must be amino acids." Is there a way to allow the nwalign() function to accept any type sequence or is there another matlab function which can perform approximate string matching which is not limited to bioinformatics? A: This has been discussed in this thread It explains how to use a non-documented function to perform alignments with symbols other than aminoacids or nucleotides. A: Have a look at python's nwalign() . http://pypi.python.org/pypi/nwalign It seems to take strings as arguments (yet to look at the source), so if you have numpy sequences or lists, you may need to convert them. A: You can try in this way : [Score,Align] =nwalign(Seq1,Seq2,'Alphabet','NT') In this way you can align two nucleotidic sequences. Which kind of scoring matrix are you going to use?
{ "language": "en", "url": "https://stackoverflow.com/questions/7621017", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Start & Stop PHP Script from Backend Administrative Webpage I'm trying to create a webpage that will allow me to start and stop of a PHP script. The script is part of the backend of a site, and will need to access, read data from, process that data, and update a database on the same server the script exists on. Additionally, I'd like the webpage to allow an administrator to view the current status (running or stopped), and even link to logs created by the script. I'm starting to go down the path of learning about PHP's exec, passthru, and related functions. Is this the correct path to take? Are there other ways to do this that would be more suitable? Is it possible to do this in a platform agnostic way? I'm developing on a LAMPP+CakePHP stack in Windows, and would like the functionality to exist on any webhost I choose. A: I've done this in a recent job but it's probably overkill for you. I did a job processor and it basically sets 2 tables in the database, 2 objects at a minimum and 2 controllers at a minimum. The first part is the job processing unit, it is composed of a job processor controller that manages the request to start or continue a job and it comes with two activerow models JobQueue and Job. You can remove the queue, but it's always practical to have queing in such systems so you can say that 2,3,4 jobs could execute at once. The queue is only that, it's a slot that gets several jobs attached to it and it has a queue status to determine if it is running right now or not. The job is a virtual object that maps to a job table describing what has to be done. In my implementation, i have created an interface that must be implemented into the called controller and a field + a type in the database. The Job instanciates the controller class to call (not the job processor controler, another controler that manages the operation to do) and calls a method in it to start the task processing. Now, to get tricky, i forced my system to run on a dedicated server just for that portion because i didn't want the task to load the main server or jam the processing queue of Apache. So i had two servers and my Queue class was in charge of calling via an ip address a page on another server to run the job on that server specifically. When the job was done, it called itself back using a HTTP request to restart processing and do the next task. If no task was left, then it would simply die normally. The advantage of doing it this way is that it doesn't require a cronjob (as long as your script is super stable and cannot crash) because it gets triggered by you when you want it and then you can let it go and it calls itself back with a fsockopen to trigger another page view that triggers the next job. Work units It is important to understand that if your jobs are very large, you should segment them. I used the principle of a "work unit" to describe 1 part the job has to do any number of times. Then the Queue Processor became a time manager too so that he could detect if a job took more than X seconds, it would simply defer the rest of the steps for later and call itself back and continue were he was at. That way, you don't need to "set time limit" and you don't jam your server while a 30s script gets executed. I hope this helps! A: To run a script which run continually, you need think to that: * *Your php script should be launched as CLI (command line) by a job scheduler like cron or something else. Don't forget that your web server configuration defined a timeout on executed script. *To run 24h a day, maybe you imagine to implement an infinite loop. In that case, you can write a test like jobIsActive which read in a file or in the database every loop if the job should be executed or not. If you click on the button just change the job status (update file, db ...). Your both button can stop the treatment or activate it but doesn't stop the infinite loop. *An infinite loop isn't the most elegant solution, why don't you write an entry in the cron tab to execute the job each night and a click on a button can fired it manually.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621025", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What's the reason of disappearing of information on project's natures? I'm seeing strange behavior in Eclipse (I'm using INDIGO, Version: 3.7.1, Build id: M20110909-1335). Information on project's natures (Project/Properties/Project Natures) is not always visible. I can't find any pattern when it's visible and when it's not. I'm observing this for C/C++ nature (provided by CTD) as well as for Python nature (provided by PyDev). I know a project has appropriate nature because for example in project's properties there are entries specific to that nature (like C/C++ Build or PyDev - Interpreter/Grammar) What's the reason of this strange behavior? A: I know that sometimes the place that'll show the properties page may customize it, so, depending on the place (i.e.: project explorer, pydev package explorer or simply using it in the menu project > properties) may yield different results. So, probably if you use it from the menu bar: project > properties (while having the proper project selected) should work always the same way...
{ "language": "en", "url": "https://stackoverflow.com/questions/7621027", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Partial database recovery on Heroku Thankfully this is a hypothetical, planning-ahead sort of a question. Can you restore part of a database using Heroku's backup addon, or otherwise? So, for instance, only restore records in all tables which have a client_id of 5? A: No, that does not appear to be a feature included in the PG Backups addon provided by Heroku: http://devcenter.heroku.com/articles/pgbackups#restoring_from_a_backup
{ "language": "en", "url": "https://stackoverflow.com/questions/7621031", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Algorithm to output the initials of a name I have just started the java programming and at the moment I am doing the basic things. I came across a problem that I can't solve and didn't found any answers around so I thought you might give me a hand. I want to write a program to prompt the user to enter their full name (first name, second name and surname) and output their initials. Assuming that the user always types three names and does not include any unnecessary spaces. So the input data will always look like this : Name Middlename Surname Some of my code that I have done and stuck in there as I get number of the letter that is in the code instead of letter itself. import java.util.*; public class Initials { public static void main (String[] args) { //create Scanner to read in data Scanner myKeyboard = new Scanner(System.in); //prompt user for input – use print to leave cursor on line System.out.print("Please enter Your full Name , Middle name And Surname: "); String name = myKeyboard.nextLine(); String initials1 = name.substring(0, 1); int initials2 = name. //output Initials System.out.println ("Initials Are " + initials1 + initials2 + initials3); } } A: Users will enter a string like "first middle last" so therefore you need to get each word from the string. Loot at split. After you get each word of the user-entered data, you need to use a loop to get the first letter of each part of the name. A: First, the nextLine Function will return the full name. First, you need to .split() the string name on a space, perhaps. This requires a correctly formatted string from the user, but I wouldn't worry about that yet. Once you split the string, it returns an array of strings. If the user put them in correectly, you can do a for loop on the array. StringBuilder builder = new StringBuilder(3); for(int i = 0; i < splitStringArray.length; i++) { builder.append(splitStringArray[i].substring(0,1)); } System.out.println("Initials Are " + builder.toString()); A: Use the String split() method. This allows you to split a String using a certain regex (for example, spliting a String by the space character). The returned value is an array holding each of the split values. See the documentation for the method. Scanner myKeyboard = new Scanner(System.in); System.out.print("Please enter Your full Name , Middle name And Surname: "); String name = myKeyboard.nextLine(); String[] nameParts = name.split(" "); char firstInitial = nameParts[0].charAt(0); char middleInitial = nameParts[1].charAt(0); char lastInitial = nameParts[2].charAt(0); System.out.println ("Initials Are " + firstInitial + middleInitial + lastInitial); Note that the above assumes the user has entered the right number of names. You'll need to do some catching or checking if you need to safeguard against the users doing "weird" things.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621034", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: WebSockets with node.js I'm trying an example of WebSocket to develop a simple chat. server.js: var app = require('http').createServer(handler) , io = require('socket.io').listen(app) , fs = require('fs') app.listen(8080); function handler (req, res) { fs.readFile(__dirname + '/test.html', function (err, data) { if (err) { res.writeHead(500); return res.end('Error loading index.html'); } res.writeHead(200); res.end(data); }); } and test.html: <script src="/socket.io/socket.io.js"></script> <script> var socket = io.connect('http://localhost'); socket.on('connect', function() { alert('<li>Connected to the server.</li>'); }); socket.on('message', function(message) { alert(message); }); socket.on('disconnect', function() { alert('<li>Disconnected from the server.</li>'); }); function sendF(){ var message = "Test"; socket.send(message); alert('Test Send'); } In test.html I have also a simple button that onClick call sendF. If I try it I see on my browser an alert when I CONNECT, SEND, and DISCONNCT, and if I check in console, I see the message. But I cannot receive the same message in response from server, to show it in my browser! I think socket.on('message'... is not working for me! A: Your server.js is missing event listeners. It's also missing where you are doing the send of the message to be displayed in the browser. io.sockets.on('connection', function (socket) { console.log('user connected'); socket.send('hello world'); socket.on('disconnect', function () { console.log('user disconnected.'); }); socket.on('message', function (data) { console.log(data); }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7621035", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How could I detect if a character close to another character on a QWERTY keyboard? I'm developing a spam detection system and have been alerted to find that it can't detect strings like this - "asdfsdf". My solution to this involves detecting if the previous keys were near the other keys on the keyboard. I am not getting the input (to detect spam from) from the keyboard, I'm getting it in the form of a string. All I want to know is whether a character is one key, two keys or more than two keys away from another character. For example, on a modern QWERTY keyboard, the characters 'q' and 'w' would be 1 key away. Same would the chars 'q' and 's'. Humans can figure this out logically, how could I do this in code? A: You could simply create a two-dimensional map for the standard qwerty keyboard. Basically it could look something like this: map[0][0] = 'q'; map[0][1] = 'a'; map[1][0] = 'w'; map[1][1] = 's'; and so on. When you get two characters, you simply need to find their x, and y in the array 'map' above, and can simply calculate the distance using pythagoras. It would not fill the requirement you had as 'q' and 's' being 1 distance away. But rather it would be sqrt(1^2 + 1^2) approx 1.4 The formula would be: * *Characters are c1 and c2 *Find coordinates for c1 and c2: (x1,y1) and (x2,y2) *Calculate the distance using pythagoras: dist = sqrt((x2-x1)^2 + (y2-y1)^2). *If necessary, ceil or floor the result. For example: Say you get the characters c1='q', and c2='w'. Examine the map and find that 'q' has coordinates (x1,y1) = (0, 0) and 'w' has coordinates (x2,y2) = (1, 0). The distance is sqrt((1-0)^2 + (0-0)^2) = sqrt(1) = 1 A: Well, let's see. That's a tough one. I always take the brute-force method and I stay away from advanced concepts like that guy Pythagoras tried to foist on us, so how about a two-dimensional table? Something like this. maybe: +---+---+---+---+---+---+--- | | a | b | c | d | f | s ... +---+---+---+---+---+---+--- | a | 0 | 5 | 4 | 2 | 4 | 1 ... | b | 5 | 0 | 3 | 3 | 2 | 4 ... | c | 4 | 3 | 0 | 1 | 2 | 2 ... | d | 2 | 3 | 1 | 0 | 1 | 1 ... | f | 3 | 2 | 2 | 1 | 0 | 2 ... | s | 1 | 4 | 2 | 1 | 2 | 0 ... +---+---+---+---+---+---+--- Could that work for ya'? You could even have negative numbers to show that one key is to the left of the other. PLUS you could put a 2-integer struct in each cell where the second int is positive or negative to show that the second letter is up or down from the first. Get my patent attorney on the phone, quick! A: Build a map from keys to positions on an idealized keyboard. Something like: 'q' => {0,0}, 'w' => {0,1}, 'a' => {1,0}, 's' => {1,1}, ... Then you can take the "distance" as the mathematical distance between the two points. A: The basic idea is to create a map of characters and their positions on the keyboard. You can then use a simple distance formula to determine how close they are together. For example, consider the left side of the keyboard: 1 2 3 4 5 6 q w e r t a s d f g z x c v b Character a has the position [2, 0] and character b has the position [3, 4]. The formula for their distance apart is: sqrt((x2-x1)^2 + (y2-y1)^2); So the distance between a and b is sqrt((4 - 0)^2 + (3 - 2)^2) It'll take you a little bit of effort to map the keys into a rectangular grid (my example isn't perfect, but it gives you the idea). But after that you can build a map (or dictionary), and lookup is simple and fast. A: I developed a function for the same purpose in PHP because I wanted to see whether I can use it to analyse strings to figure out whether they're likely to be spam. This is for the QWERTZ keyboard, but it can easily be changed. The first number in the array $keys is the approximate distance from the left and the second is the row number from top. function string_distance($string){ if(mb_strlen($string)<2){ return NULL; } $keys=array( 'q'=>array(1,1), 'w'=>array(2,1), 'e'=>array(3,1), 'r'=>array(4,1), 't'=>array(5,1), 'z'=>array(6,1), 'u'=>array(7,1), 'i'=>array(8,1), 'o'=>array(9,1), 'p'=>array(10,1), 'a'=>array(1.25,2), 's'=>array(2.25,2), 'd'=>array(3.25,2), 'f'=>array(4.25,2), 'g'=>array(5.25,2), 'h'=>array(6.25,2), 'j'=>array(7.25,2), 'k'=>array(8.25,2), 'l'=>array(9.25,2), 'y'=>array(1.85,3), 'x'=>array(2.85,3), 'c'=>array(3.85,3), 'v'=>array(4.85,3), 'b'=>array(5.85,3), 'n'=>array(6.85,3), 'm'=>array(7.85,3) ); $string=preg_replace("/[^a-z]+/",'',mb_strtolower($string)); for($i=0;$i+1<mb_strlen($string);$i++){ $char_a=mb_substr($string,$i,1); $char_b=mb_substr($string,$i+1,1); $a=abs($keys[$char_a][0]-$keys[$char_b][0]); $b=abs($keys[$char_a][1]-$keys[$char_b][1]); $distance=sqrt($a^2+$b^2); $distances[]=$distance; } return array_sum($distances)/count($distances); } You can use it the following way. string_distance('Boat'); # output 2.0332570942187 string_distance('HDxtaBQrGkjny'); # output 1.4580596252044 I used multibyte functions because I was thinking about extending it for other characters. One could extend it by checking the case of characters as well.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621043", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: jScrollPane Trouble I have used jScrollPane on my site. I'm also using ajax to update the data on the same div where the jScrollPane is used. Now, when i append the returned data to the div, the scrollbar is not visible on the appended text. It may because the jQuery function is called when the document loads but now any ideas to solve this problem? I read the article here here http://jscrollpane.kelvinluck.com/auto_reinitialise.html but i'm not being able to solve this problem. Here's the code: function scrollfunction($value){ var ajaxRequest; // The variable that makes Ajax possible! try{ // Opera 8.0+, Firefox, Safari ajaxRequest = new XMLHttpRequest(); } catch (e){ // Internet Explorer Browsers try{ ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try{ ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e){ // Something went wrong alert("Your browser broke!"); return false; } } } // Create a function that will receive data sent from the server ajaxRequest.onreadystatechange = function(){ if(ajaxRequest.readyState == 4){ $(ajaxRequest.responseText).appendTo(".div1"); } } ajaxRequest.open("GET", "process.php" , true); ajaxRequest.send(null); } $("document").ready(function() { $(".div1").jScrollPane(); }); A: $("document").ready(function() { $(".div1").jScrollPane({autoReinitialise: true}); }); Is there a good reason for not using jQuery's $.ajax, as I believe all the handlers and functions you are creating in your function is already built in to $.ajax. $.ajax({ type: "GET", url: "process.php", dataType: "text", success: function(data){ $(data).appendTo(".jspPane"); } }); jspPane is normally the container created by jScrollPane, try appending directly to that container.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621048", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Better way to write this Regex? Negative Lookahead I think I've got this working for the most part, but was wondering if there is a better way to write it: /\b(Word)(?!.*?<\/a>)(?!.*?>)\b/ I'm trying to match Word when it's NOT linked, and it's NOT part of HTML tags (like <a href="" title="Word"> should not match). From what I understand, it's better to use negated character classes if possible rather than making it lazy. I tried doing that but couldn't figure it out. I don't even know if it's possible with this, but I thought I'd throw it out there. A: The negated character class you are looking for is [^<>]*. That will skip any tag boundaries. /\b(Word) (?! [^<>]*<\/a> | [^<]*>) \b/x Note that looking for </a> will allow the regex to match should the link have further markup in it; for example a bolded <a>..<b>Word</b>..</a> word would not be skipped. (Checking for such things requires far more effort than a lookahead.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7621053", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Regex to add a space after each comma in Javascript I have a string that is made up of a list of numbers, seperated by commas. How would I add a space after each comma using Regex? A: Use String.replace with a regexp. > var input = '1,2,3,4,5', output = input.replace(/(\d+,)/g, '$1 '); > output "1, 2, 3, 4, 5" A: Those are all good ways but in cases where the input is made by the user and you get a list like "1,2, 3,4, 5,6,7" ..In which case lets make it idiot proof! So accounting for the already formatted parts of the string, the solution: "1,2, 3,4, 5,6,7".replace(/, /g, ",").replace(/,/g, ", "); //result: "1, 2, 3, 4, 5, 6, 7" //Bingo! A: Simplest Solution "1,2,3,4".replace(/,/g, ', ') //-> '1, 2, 3, 4' Another Solution "1,2,3,4".split(',').join(', ') //-> '1, 2, 3, 4' A: var numsStr = "1,2,3,4,5,6"; var regExpWay = numStr.replace(/,/g,", "); var splitWay = numStr.split(",").join(", "); A: Don't use a regex for this, use split and join. It's simpler and faster :) '1,2,3,4,5,6'.split(',').join(', '); // '1, 2, 3, 4, 5, 6' A: I find important to note that if the comma is already followed by a space you don't want to add the space: "1,2, 3,4,5".replace(/,(?=[^\s])/g, ", "); > "1, 2, 3, 4, 5" This regex checks the following character and only replaces if its no a space character. A: As I came here and did not find a good generic solution, here is how I did it: "1,2, 3,4,5".replace(/,([^\s])/g, ", $1"); This replaces comma followed by anything but a space, line feed, tab... by a comma followed by a space. So the regular expression is: ,([^\s]) and replaced by , $1 A: Another simple generic solution for comma followed by n spaces: "1,2, 3, 4,5".replace(/,[s]*/g, ", "); > "1, 2, 3, 4, 5" Always replace comma and n spaces by comma and one space.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621066", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "25" }
Q: How to paste xml to C++ (Tinyxml) I'm currently working on a project in C++ where I need to read some things from a xml file, I've figured out that tinyxml seams to be the way to go, but I still don't know exactly how to do. Also my xml file is a little tricky, because it looks a little different for every user that needs to use this. The xml file I need to read looks like this <?xml version="1.0" encoding="utf-8"?> <cloud_xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx xmlns:d="http://www.kuju.com/TnT/2003/Delta" d:version="1.0"> <cCareerModel d:id="154964152"> <ScenarioCareer> <cScenarioCareer d:id="237116344"> <IsCompleted d:type="cDeltaString">CompletedSuccessfully</IsCompleted> <BestScore d:type="sInt32">0</BestScore> <LastScore d:type="sInt32">0</LastScore> <ID> <cGUID> <UUID> <e d:type="sUInt64">5034713268864262327</e> <e d:type="sUInt64">2399721711294842250</e> </UUID> <DevString d:type="cDeltaString">0099a0b7-e50b-45de-8a85-85a12e864d21</DevString> </cGUID> </ID> </cScenarioCareer> </ScenarioCareer> <MD5 d:type="cDeltaString"></MD5> </cCareerModel> </cloud_xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx> Now the goal of this program is to be able to insert some string (via. a variable) and serch for the corresponding "cScenarioCarrer d:id" and read the "IsComplete" and the "BestScore". Those strings later need to be worked with in my program, but that I can handle. My questions here are A. How do I go by searching for a specific "cScenarioCareer" ID B. How do I paste the "IsComplete" and "BestScore" into some variables in my program. Note: The xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx string is unique for every user, so keep in mind it can be anything. If anyone out there would like to help me, I'd be very graceful, thank you. PS. I'd like to have some kind of understanding for what I'm doing here, all though "paste this code into your program" answers are acceptable, I think it would be much better if you can tell me how and why it works. A: Since you're doing this in C++ I'll make this example using the ticpp interface to TinyXml that available at ticpp.googlecode.com. Assumptions: * *A given xml file will contain one <cloud> tag and multiple <cCareerModel> tags. *Each <cCareerModel> contains a single <ScenarioCareer> tag which in turn contains a single <cScenarioCareer> tag *You've parsed the xml file into a TiXmlDocument called xmlDoc *You don't need to examine the data type attributes *You don't mind using exceptions I'll also assume that you have a context variable somewhere containing a pointer to the <cloud> tag, like so: ticpp::Element* cloud = xmlDoc.FirstChildElement("cloud"); Here's a function that will locate the ticpp::Element for the cScenarioCareer with the given ID. ticpp::Element* findScenarioCareer(const std::string& careerId) { try { // Declare an iterator to access all of the cCareerModel tags and construct an // end iterator to terminate the loop ticpp::Iterator<ticpp::Element> careerModel; const ticpp::Iterator<ticpp::Element> modelEnd = careerModel.end(); // Loop over the careerModel tags for (careerModel = cloud->FirstChildElement() ; careerModel != modelEnd ; ++careerModel) { // Construct loop controls to access careers ticpp::Iterator<ticpp::Element> career; const ticpp::Iterator<ticpp::ELement> careerEnd = career.end(); // Loop over careers for (career = careerModel->FirstChildElement("ScenarioCareer").FirstChildElement() ; career != careerEnd ; ++career) { // If the the d:id attribute value matches then we're done if (career->GetAttributeOrDefault("d:id", "") == careerId) return career; } } } catch (const ticpp::Exception&) { } return 0; } Then to get at the information you want you'd do something like: std::string careerId = "237116344"; std::string completion; std::string score; ticpp::Element* career = findScenarioCareer(careerId); if (career) { try { completion = career->FirstChildElement("IsCompleted")->GetText(); score = career->FirstChildElement("BestScore")->GetText(); } catch (const ticpp::Exception&) { // Handle missing element condition } } else { // Not found } Naturally I haven't compiled or tested any of this, but it should give you the idea.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621067", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: AjaxControlToolkit requires ASP.NET Ajax 4.0 scripts AjaxControlToolkit requires ASP.NET Ajax 4.0 scripts. Ensure the correct version of the scripts are referenced. If you are using an ASP.NET ScriptManager, switch to the ToolkitScriptManager in AjaxControlToolkit.dll. Izvorna datoteka: http://dostavahrane.si/ScriptResource.axd?d=OdsYNSuXxjlt8rcl-C-veHyjBYioAGFje3gsHih3su6oLU1jX125fdCipsztHIubjtFptWsSrTvzlMvPBfnnMGfz62_ByInZiFjjOCVmrpHz8bozy1q4kx6vPqQyelCTItLxGQ2&t=245582f9 i am using AjaxControlToolkit for .net 3.5 in VS 2008. Why i get this error. Must i downgrade it? I downlaod it from here: http://www.asp.net/ajaxlibrary/AjaxControlToolkitSampleSite/ A: I got such error once in one of my projects and since I didn't find a cause, I did what the exception message says - instead of ASP.NET ScriptMessage, I've put Toolkit's Script Manager on the page. It probably is only a workaround but follow it if you won't find any other solution.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621072", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Indexing and searching a MS excel using Lucene 3.1 I have a MS Excel sheet, with following columns title,cast,director,genre. The Excel sheet is parsed using jxl library. The indexing is working properly, but when I search I always get 0 hits found.I don't know where I am going wrong. The code is below : import java.io.File; import java.io.IOException; import jxl.Cell; import jxl.Sheet; import jxl.Workbook; import jxl.read.biff.BiffException; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.index.CorruptIndexException; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.queryParser.ParseException; import org.apache.lucene.queryParser.QueryParser; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.TopScoreDocCollector; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.util.Version; public class ExcelParser { Directory index; Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_31); IndexWriterConfig c = new IndexWriterConfig(Version.LUCENE_31, analyzer); public void parse(String filePath) throws IndexOutOfBoundsException, BiffException, IOException { index = FSDirectory.open(new File("d:\\index")); Sheet contentSheet = Workbook.getWorkbook(new File(filePath)).getSheet( 0); indexDocs(contentSheet); } void indexDocs(Sheet contentSheet) throws CorruptIndexException, IOException { String currentColumn = ""; IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_31, analyzer); IndexWriter writer = new IndexWriter(index, iwc); for (int i = 0; i < contentSheet.getColumns(); i++) { Cell[] xlCells = contentSheet.getColumn(i); currentColumn = xlCells[0].getContents(); StringBuffer sb = new StringBuffer(); for (int j = 1; j < xlCells.length; j++) { sb.append(xlCells[j].getContents() + " "); } addDoc(writer, sb.toString(), currentColumn); } writer.close(); } void searcher(String querystr, String onField) throws ParseException, CorruptIndexException, IOException { IndexSearcher searcher = new IndexSearcher(FSDirectory.open(new File( "d:\\index"))); Query q = new QueryParser(Version.LUCENE_31, onField, analyzer) .parse(querystr); int hitsPerPage = 2; TopScoreDocCollector collector = TopScoreDocCollector.create( hitsPerPage, true); searcher.search(q, collector); ScoreDoc[] hits = collector.topDocs().scoreDocs; System.out.println("Found " + hits.length + " hits."); for (int i = 0; i < hits.length; ++i) { int docId = hits[i].doc; Document d = searcher.doc(docId); System.out.println((i + 1) + ". " + d.get("title")); } searcher.close(); } private static void addDoc(IndexWriter w, String value, String fieldName) throws IOException { Document doc = new Document(); doc.add(new Field(fieldName, value, Field.Store.YES, Field.Index.ANALYZED)); w.addDocument(doc); } public static void main(String[] args) throws IndexOutOfBoundsException, BiffException, IOException { ExcelParser p = new ExcelParser(); p.parse("d:\\movieList.xls"); try { p.searcher("the", "title"); } catch (ParseException e) { e.printStackTrace(); } } } A: You are searching for the term the which is in default stop filter list. Change Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_31); to Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_31, new HashSet()); to clear stopword list. see: http://lucene.apache.org/java/3_0_1/api/core/org/apache/lucene/analysis/standard/StandardAnalyzer.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7621073", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Error signing user in with Umbraco Membership After setting the auth ticket from a successful login with the umbraco membership provider, the Page.User.Identity.IsAuthenticated remains false. if (Membership.ValidateUser(uname, pwd)) { FormsAuthentication.SetAuthCookie(uname, true); } Config: <add name="UmbracoMembershipProvider" type="umbraco.providers.members.UmbracoMembershipProvider" enablePasswordRetrieval="false" enablePasswordReset="false" requiresQuestionAndAnswer="false" defaultMemberTypeAlias="WebsiteUser" passwordFormat="Hashed" /> A: Just started working after rebooting the server... mystery...
{ "language": "en", "url": "https://stackoverflow.com/questions/7621075", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: difference between SDO and JDO in java what is the difference between JDO (JSR 243) and SDO (JSR 235) in Java; what set of open source providers are available for these java specifications A: From this article: [...] JDO looks at the persistence issue only [...] whereas SDO is more general and represents data that can flow between any J2EE tier, such as between a presentation and business tier. EclipseLink is one SDO provider, Apache's DB project is one JDO implementation. A: For an excerpt you can read the "Request" part on the appropriate JSR pages for JDO and SDO. In practice and for quick starters: JDO is the father of JPA. * *JPA is actually used and usable (this is not for granted in the Java EE world), Hibernate and EclipseLink are two well known opensource implmenetations of JPA. *SDO: I have neither seen it in any project I've been, nor have I heard about it so far. Reading the Blurb on the JCP Page made me feel that this is one of those overgeneralized and clumsy Java EE standards not designed for real life. Feel free to ignore SDO for now while digging into JPA a bit.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621077", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: C# return type of function What does GetNode return, a copy or a reference to the real value? public GraphNode GetNode(int idx) { return Nodes[idx]; } In other words will this code change the real value or it will change a copy returned from GetNode? GetNode(someIndex).ExtraInfo = something; Thanks A: Depending on wherever GraphNode is a class or struct. In case of a class you'll be changing "real" value. Struct is the opposite. A: It depends on your definition of GraphNode. If it is a class (by reference) it will return the same instance; or if it is a struct (value-type) then you'll get a new instance. A: In other words will this code change the real value or it will change a copy returned from GetNode? GetNode(someIndex).ExtraInfo = something; If GetNode() returns a struct / value type you will actually get a compilation error in C#: Cannot modify the return value of 'GetNode(someIndex)' because it is not a variable This is exactly because the compiler is trying to protect you from changing a copied value that goes nowhere. Your example makes only sense if GetNode() returns a reference type. The only way to get the example to compile for a value type is by separating retrieval of the return value from the property assignment: var node = GetNode(someIndex); node.ExtraInfo = something; In this case as other posters have mentioned it does depend on whether GetNode() returns a reference type or a value type. For a reference type you are changing the original class instance that GetNode() returns a reference to, for a value type you are modifying a new, copied instance. A: The way classes work in C# is that they can be passed around as pointers. You can set the values inside it, like you have in your example, and it will change the original. Setting the actual class itself cannot be done without a wrapper though. A: It will return a reference (in case GraphNode is a class) to a GraphNode object, so the original object will be altered.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621083", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Getting 'index 0 beyond bounds for empty array' error on non-empty array I have this code to add a row to a table view in the root view controller of my application: NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0]; NSArray *myArray = [NSArray arrayWithObject:indexPath]; NSLog(@"count:%d", [myArray count]); [self.tableView insertRowsAtIndexPaths:myArray withRowAnimation:UITableViewRowAnimationFade]; [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES]; When it is run with the simulator I get this output: count:1 * Terminating app due to uncaught exception 'NSRangeException', reason: '* -[NSMutableArray objectAtIndex:]: index 0 beyond bounds for empty array' This is occurring at the [self.tableView insertRowsAtIndexPaths:myArray withRowAnimation:UITableViewRowAnimationFade]; line, but the NSLog statement shows that the NSArray called myArray is not empty. Am I missing something? Has anyone ever encountered this before? A: In the line before the log statement, you're creating a new array that's only valid in the scope of this method. The array you're using for the table view's data source methods is a different one, so the number of objects in this array doesn't matter at all, even if it has (as I suspect) the same name. A: Calling insertRowsAtIndexPaths triggers your UITableViewController delegate/datasource methods to be called. This is so that the UITableView can obtain the data for the new row. You need to insert data into your data model and make sure numberOfRowsInSection is returning the new increased value. The NSRangeException error is referring to whatever NSMutableArray you are using to store your data for table rows rather than the array of index paths.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621085", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: synchronization of several remote git repositories We have: * *Remote repository with some project. *Several remote repositories, which I want to synchronize with previous one. When something pushed in first project (1), I need to pull these changes to other remote repositories (2). I can pull from first repo and push to destination repositories. What is the simplest way to do this ? Thanks. A: You could clone a new bare mirror repository from the upstream repository that you have no control over, e.g. with: git clone --bare --mirror git://github.com/whoever/whatever.git (In fact, --mirror implies --bare, so --bare isn't strictly necessary.) The --mirror option says that rather than just take the local branches from the remote and make them remote-tracking branches, git should mirror all the branches from the remote repository with the same names. Then, you can set up a frequent cron job that runs the following commands in that repository: git remote update git push --mirror --force repo1 git push --mirror --force repo2 This assumes that you've added repo1 and repo2 as remotes, and that they point to bare repositories that you're only wanting to use as mirrors. (The latter requirement is because you're using --force, so if other people are pushing their work to repo1 or repo2, it'll get overwritten by the automated mirror pushes.) A: You could set up a post-receive hook in the first remote repository that then pushes from your first remote repository to each of the others.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621086", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: MSVCRT: Where is the implement (source code) of sin, cos et al? I wonder where the implemention of basic trigonometric functions can be found in the Visual C++ CRT. Find in files for "sin" in C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\crt shows the definition in math.h but nothing more (except a mention in the EXPORTS section of some def file). To the best of my knowledge, sin is not a keyword that the compiler translates itself to machine code. So there must be an implementation somewhere, even if that implementation boils down to some straight assembly code. What am I missing here? Where'z teh codez? EDIT: Obviously, I was not clear enough: I'm looking for the source code, not compiled lib or dll A: It's in MSVCR90.DLL: C:\WINDOWS\WinSxS\x86_Microsoft.VC90.CRT_...>dumpbin /exports msvcr90.dll | findstr sin 74 48 0007ABA0 _CIasin = __CIasin 84 52 0007B5C0 _CIsin = __CIsin 85 53 0007AF38 _CIsinh = __CIsinh 159 9D 000236AB __get_flsindex = ___get_flsindex 160 9E 000236AB __get_tlsindex = ___get_flsindex 177 AF 0007CE73 __libm_sse2_asin = ___libm_sse2_asin 178 B0 0007D2C1 __libm_sse2_asinf = ___libm_sse2_asinf 192 BE 0007FE7C __libm_sse2_sin = ___libm_sse2_sin 193 BF 00080039 __libm_sse2_sinf = ___libm_sse2_sinf 696 2B7 0002E27A _mbsinc = __mbsinc 697 2B8 0002E24E _mbsinc_l = __mbsinc_l 1211 4BA 0007AB60 asin = _asin 1349 544 0007B580 sin = _sin 1350 545 0007AF20 sinh = _sinh Update: The source isn't provided. The library supplying the functions in the CRT source provided seems to be in crt\src\intel\mt_lib\tran.lib: C:\...\crt\src\intel\mt_lib> lib /list tran.lib : : : f:\dd\vctools\crt_bld\SELF_X86\crt\prebuild\build\INTEL\mt_obj\_sincosf_sse2_.obj f:\dd\vctools\crt_bld\SELF_X86\crt\prebuild\build\INTEL\mt_obj\_sincos_sse2_.obj f:\dd\vctools\crt_bld\SELF_X86\crt\prebuild\build\INTEL\mt_obj\_sinf_sse2_.obj f:\dd\vctools\crt_bld\SELF_X86\crt\prebuild\build\INTEL\mt_obj\_sin_sse2_.obj f:\dd\vctools\crt_bld\SELF_X86\crt\prebuild\build\INTEL\mt_obj\_tanf_sse2_.obj f:\dd\vctools\crt_bld\SELF_X86\crt\prebuild\build\INTEL\mt_obj\_tan_sse2_.obj : : : A: It's in libc. If you are building statically, its in libc.lib. If you are building dynamically, then its in msvcrt.dll
{ "language": "en", "url": "https://stackoverflow.com/questions/7621089", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Web development for a user profile enabled website I am developing a website that will contain user profiles with significant amount of their data. Beyond the general user profile information, I will also need to store their settings, interaction history with other users, and actions they've taken on my website(i.e. purchased an item). I am largely unfamiliar with web development on an enterprise level. Is there a more efficient way to store user profiles than using a relational database (oracle, mysql, ingres, etc)? Obviously within that realm there are multiple optimizations possible, but outside the scope of a relational database, is there a more modern and better solution? A: No. How else do you want to store the user profiles and interactions without using a database? MySQL can be used for very small to large scale web applications plus it's free, has a wide support and its quite easy to learn. I would suggest you use a DB. You can check out Cloud Computing A: You should use a relational database for storing user profile and user activity information. The "more modern solution" would be a non-relational database. Such databases are good at storing large amounts of loosely structured information. For well-structured transactional data like user profile and messages and purchases, relational database is the best choice. RDBMS is designed specifically to efficiently store and retrieve well structured transactional data.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621094", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Jquery change div background inside tr I have been trying to get this to work for quite some time now. I am looking for a way to change the background of a div inside a tr onclick with jquery. What I mean by this is that when the tr (which is named by class) is clicked, then the div with a class name (that is inside the tr) changes color. The problem that I have been having is that I can set the color of all the divs with the specified class name but not just the one that I clicked it's tr. I would think the code would look something like this: $('.backpack_row').click( function(){ if ($(this).css('background-color') != 'rgb(255, 255, 204)') { $(this .divClassname).css('background-color', '#000000'); $(this).css('background-color', '#ffffcc'); } else { $(this).css('background-color', '#ffffff'); $(this .divClassname).css('background-color', '#ffffff'); } }); Here is the HTML: <table> <tr class="backpack_row"><td><div class="divClassname"></div></td><td>Other Stuff</td><td></td></tr> </table> Thanks, Ian A: Fixed your code. A JQuery selector call should be in this format: * *$("selector") *$("selector", context) (where context is this, in this case) $('.backpack_row').click( function(){ if ($(this).css('background-color') != 'rgb(255, 255, 204)') { $(".divClassname", this).css('background-color', '#000000'); $(this).css('background-color', '#ffffcc'); } else { $(this).css('background-color', '#ffffff'); $(".divClassname", this).css('background-color', '#ffffff'); } A: Your selectors are a bit off, and you're making this harder for yourself. Instead of checking for background colors, check for class existence: $(".backpack_row").click(function () { if (!$(this).hasClass("highlighted")) { $(this).find(".divClassname").addClass("divHighlighted"); $(this).addClass("highlighted"); } else { $(this).find(".divClassname").removeClass("divHighlighted"); $(this).removeClass("highlighted"); } }); A: Try this: $('.backpack_row').click( function(){ if ($(this).css('background-color') != 'rgb(255, 255, 204)') { $(this).find(.divClassname).css('background-color', '#000000'); $(this).css('background-color', '#ffffcc'); } else { $(this).css('background-color', '#ffffff'); $(this).find(.divClassname).css('background-color', '#ffffff'); } }); You need to use the el.find() function. It will find an element based on a selector within the el. For documentation, here
{ "language": "en", "url": "https://stackoverflow.com/questions/7621096", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: facebook "like box" for page I set up my website's facebook account as a Page on my facebook account (this was probably incorrect, but I didn't know better at the time). I have switched my account to Use Facebook as a Page. I am trying to create a like box with avatars for my website (www.zealforadeal.com). I get the error code: To access this page, you'll need to switch from using Facebook as your page to using Facebook as yourself. How can I create a Like Box for my page (http://www.facebook.com/zealforadeal) ? (I never use my facebook account for anything other than the Page) A: I think you are confused about the purpose of the 'Like box'. The 'like box' shows the people who have 'Liked' your Facebook page,and your Facebook page status updates.https://developers.facebook.com/docs/reference/plugins/like-box/ A: Just go to the like box page and paste your url (http://www.facebook.com/zealforadeal) into Facebook Page URL field.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621099", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: TableView Sliding in Code How can I make the tableview to stop sliding initially? But it should slide when keyboard is visible. I have written code for keyboarddidshow and hide methods, but it doesn't work if I deselect enable sliding option in IB. A: you can set the propery of setcontentOffset to the table A: i used tableView.scrollEnabled = NO; in ViewDidLoad and tableView.scrollEnabled = YES; in textFieldDidBeginEditing
{ "language": "en", "url": "https://stackoverflow.com/questions/7621101", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: easy_install downloading directory I'm trying to install a python script packaged in egg format using easy_install. The problem is that easy_install downloads dependencies to /tmp. However, my tmp dir only has 4mb of free space (I am working with a NAS drive, set up this way). Is there a way of specifying the download directory? --help doesn't seem to throw up anything useful. Edit: Some more details: I'm running python 2.5.6 and setuputils 0.6c11-2 installed from optware. The NAS is ARM based (specifically the DNS-320 with fun_plug installed). Please let me know if you'd like any more specific info. When I use the -b option, the file is still downloaded to /tmp. It is in fact the extraction process which which uses the remaining space in tmp: easy_install-2.5 -b /mnt/HD/HD_a2/ffp/home/root SQLAlchemy==0.7.2 Searching for SQLAlchemy==0.7.2 Reading http://pypi.python.org/simple/SQLAlchemy/ Reading http://www.sqlalchemy.org Best match: SQLAlchemy 0.7.2 Downloading http://pypi.python.org/packages/source/S/SQLAlchemy/SQLAlchemy-0.7.2.tar.gz#md5=b84a26ae2e5de6f518d7069b29bf8f72 Processing SQLAlchemy-0.7.2.tar.gz error: No space left on device I know the file is downloaded into /tmp by running ls -l /tmp/ while the download is happening: ls -l /tmp/easy_install* total 891 -rw-r--r-- 1 root root 901120 Oct 1 20:35 SQLAlchemy-0.7.2.tar.gz df -h output: Filesystem Size Used Avail Use% Mounted on rootfs 9.7M 4.8M 4.5M 52% / /dev/root 9.7M 4.8M 4.5M 52% / /dev/loop0 23M 23M 0 100% /usr/local/modules /dev/mtdblock5 5.0M 464K 4.6M 10% /usr/local/config /dev/sda4 485M 16M 469M 4% /mnt/HD_a4 /dev/sdb4 485M 11M 474M 3% /mnt/HD_b4 /dev/sda2 1.8T 213G 1.6T 12% /mnt/HD/HD_a2 /dev/sdb2 1.8T 69G 1.8T 4% /mnt/HD/HD_b2 /dev/sda2 1.8T 213G 1.6T 12% /opt Thanks, Jack A: Well here's the solution if anyone's interested. Edit line 412 of /opt/lib/python2.5/site-packages/setuptools/command/easy_install.py from: tmpdir = tempfile.mkdtemp(prefix="easy_install-") to: tmpdir = tempfile.mkdtemp(prefix="easy_install-",dir="/opt/tmp") This works, as /opt is mounted to the HDD and has plenty of free space. I'm no python expert (never programmed with it), but it seems like the -b option has no bearing on where the file is downloaded to. A: easy_install -b wherever or easy_install --build-directory wherever A: Set TMPDIR environment variable such as following: export TMPDIR="/opt/tmp" I think this is a better way than rewriting the easy_install.py. You need to ensure the path exists. A: hmmmmm, you may soft symlink that /tmp/easyinstall to another location before starting the process? I am not a pro in the tool so it's an idea to get going, not a solution
{ "language": "en", "url": "https://stackoverflow.com/questions/7621103", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Adapters not working with datamapper I have the following code: require 'sinatra' require 'datamapper' DataMapper.setup :default, "postgres://localhost/mydb" However, when I try and run it, I get: LoadError: no such file to load -- dm-postgres-adapter /Library/Ruby/Site/1.8/rubygems/custom_require.rb:53:in `gem_original_require' /Library/Ruby/Site/1.8/rubygems/custom_require.rb:53:in `require' /Library/Ruby/Gems/1.8/gems/dm-core-1.1.0/lib/dm-core/adapters.rb:163:in `load_adapter' /Library/Ruby/Gems/1.8/gems/dm-core-1.1.0/lib/dm-core/adapters.rb:133:in `adapter_class' /Library/Ruby/Gems/1.8/gems/dm-core-1.1.0/lib/dm-core/adapters.rb:13:in `new' /Library/Ruby/Gems/1.8/gems/dm-core-1.1.0/lib/dm-core.rb:219:in `setup' These are the gems I have installed: * LOCAL GEMS * abstract (1.0.0) actionmailer (3.0.9, 3.0.5, 2.3.5, 1.3.6) actionpack (3.0.9, 3.0.5, 2.3.5, 1.13.6) actionwebservice (1.2.6) activemodel (3.0.9, 3.0.5) activerecord (3.0.9, 3.0.5, 2.3.5, 1.15.6) activeresource (3.0.9, 3.0.5, 2.3.5) activesupport (3.0.9, 3.0.5, 2.3.5, 1.4.4) acts_as_ferret (0.4.3) addressable (2.2.6, 2.2.5) arel (2.0.10, 2.0.9) autotest (4.4.6) autotest-fsevent (0.2.4) autotest-growl (0.2.9) autotest-rails-pure (4.1.2) bcrypt-ruby (2.1.4) builder (2.1.2) bundler (1.0.10) capistrano (2.5.2) cgi_multipart_eof_fix (2.5.0) configuration (1.2.0) daemons (1.0.10) data_objects (0.10.6) datamapper (1.1.0) diff-lcs (1.1.2) dm-aggregates (1.1.0) dm-constraints (1.1.0) dm-core (1.2.0.rc2, 1.1.0) dm-do-adapter (1.2.0.rc2, 1.1.0) dm-migrations (1.1.0) dm-postgres-adapter (1.2.0.rc2, 1.1.0) dm-serializer (1.1.0) dm-sqlite-adapter (1.2.0.rc2, 1.1.0) dm-timestamps (1.1.0) dm-transactions (1.1.0) dm-types (1.1.0) dm-validations (1.1.0) dnssd (0.6.0) do_postgres (0.10.6) do_sqlite3 (0.10.6) erubis (2.6.6) eventmachine (0.12.10) ezcrypto (0.7.2) faraday (0.6.1) faraday_middleware (0.6.3) fastercsv (1.5.4) fastthread (1.0.1) fcgi (0.8.7) ferret (0.11.6) gem_plugin (0.2.3) hashie (1.0.0) heroku (1.18.1) highline (1.5.0) hpricot (0.8.4, 0.6.164) i18n (0.5.0) json (1.5.1, 1.4.6) launchy (0.3.7) less (1.2.21) libxml-ruby (1.1.2) liquid (2.2.2) mail (2.2.19, 2.2.15) mime-types (1.16) mocha (0.9.12) mongrel (1.1.5) multi_json (0.0.5) multi_xml (0.2.2) multipart-post (1.1.0) mutter (0.5.3) needle (1.3.0) net-scp (1.0.1) net-sftp (2.0.1, 1.1.1) net-ssh (2.0.4, 1.1.4) net-ssh-gateway (1.0.0) nokogiri (1.4.4) oauth (0.4.5, 0.4.4) polyglot (0.3.1) rack (1.2.1, 1.0.1) rack-mount (0.6.14, 0.6.13) rack-test (0.5.7) rails (3.0.9, 3.0.5, 2.3.5, 1.2.6) railties (3.0.9, 3.0.5) rake (0.8.7, 0.8.3) rant (0.5.7) rash (0.3.0) rdoc (3.9.2) RedCloth (4.1.1) rest-client (1.6.1) roauth (0.0.3) rspec (2.6.0, 2.5.0) rspec-core (2.6.4, 2.5.1) rspec-expectations (2.6.0, 2.5.0) rspec-mocks (2.6.0, 2.5.0) rspec-rails (2.6.1, 2.5.0) ruby-openid (2.1.2) ruby-yadis (0.3.4) rubygems-update (1.6.0) rubynode (0.1.5) sequel (3.20.0) shotgun (0.9) simple_oauth (0.1.4) sinatra (1.2.3, 1.0) spork (0.9.0.rc4) sqlite3 (1.3.3) sqlite3-ruby (1.2.4) stringex (1.2.2) sys-uname (0.8.5) taps (0.3.23) termios (0.9.4) thor (0.14.6) tilt (1.2.2) treetop (1.4.9, 1.4.5) tweetstream (1.0.4) twitter (1.4.0) twitter-stream (0.1.10) twitter4r (0.7.0) twitter_oauth (0.4.3) tzinfo (0.3.24) uuidtools (2.1.2) visionmedia-growl (1.0.3) webrat (0.7.1) xmpp4r (0.4) ZenTest (4.5.0) A: You should use dm-core instead of datamapper in your require line. Are you using Bundler? Provided you have bundler set up correctly, it should already be loaded for you. A: Uninstalling dm-postgres-adapter 1.2.0.rc2 fixed it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621106", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: PHP: Cookie not unsetting <? if($_POST["Login"]) { if (GetRightPassword($_POST["emaillogin"],$_POST["passwordlogin"])) { $_SESSION["email"] = $_POST["emaillogin"]; $_SESSION["password"] = $_POST["passwordlogin"]; echo "Keeping logged in: ".$_POST["keeploggedin"]; if ($_POST["keeploggedin"]) { setcookie("email", $_POST["emaillogin"], time()+60*60*24*365); setcookie("password", $_POST["passwordlogin"], time()+60*60*24*365); } } else { echo "Invalid username/password!"; } } if($_POST["Logout"]) { $_SESSION["email"] = null; $_SESSION["password"] = null; setcookie("email", "", time()-900000); setcookie("password", "", time()-900000); } echo $_COOKIE["email"]; ?> That's the only code (As far as I can find, I coded it 6 months ago minimum but I'm prety sure there's no more) that writes to cookies or session. When I click logout, it nulls the session variables, so when the page loads, I'm logged off- Change page again or refresh though, and I'm logged back in again. Any ideas why? Login isn't being sent when I change page, so I have no idea why. If it helps, the echo $_COOKIE["email"]; line echos your email even when it's just set it to "". Edit I just found more code related to this. This code is ran before that code. if(isset($_COOKIE["email"])) { $_SESSION["email"] = $_COOKIE["email"]; $_SESSION["password"] = $_COOKIE["password"]; } A: set in all your cookies the path and domain. This ensures it's not something like a with and withoud www. Check the documentation how to do this: http://nl2.php.net/setcookie This might be the root cause for your problem
{ "language": "en", "url": "https://stackoverflow.com/questions/7621115", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CoffeeScript + KnockoutJS Function Binding I'm using CoffeeScript and KnockoutJS and have a problem getting the values of my view model from within a function. I have a view model: window.Application || = {} class Application.ViewModel thisRef = this searchTerm: ko.observable("") search: -> alert @searchTerm Which compiles to: window.Application || (window.Application = {}); Application.ViewModel = (function() { var thisRef; function ViewModel() {} thisRef = ViewModel; ViewModel.prototype.searchTerm = ko.observable(""); ViewModel.prototype.search = function() { return alert(this.searchTerm); }; return ViewModel; })(); This view model is part of a parent view model which exposes it as field. The problem is that I can't get a reference to the child view model. In the search function 'this' is a instance of the parent, which I don't want. A: In the search function 'this' is a instance of the parent... That depends on how you call it. If you do m = new Application.ViewModel m.search() then this will be m; if you write obj = {search: m.search} obj.search() then this will be obj. Anyway, just use CoffeeScript's => operator: search: => alert @searchTerm That way, this/@ within search will point to the ViewModel instance. thisRef will, as Travis says, just point to the class, not the instance. A: You already have a thisRef object hanging around, use thisRef.searchTerm instead of @searchTerm. I often have that happen when using jQuery... doSomething = -> target = $(@) $("#blah").click -> target.doSomethingElse() Since @doSomethingElse() would be bound to the DOM element the click was executed for. Not what I want.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621116", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Jump to line in vim with relativenumber on In a normal situation it's possible to look at the line number and use [number]G to goto that line. But I like to work with the setting relativenumber on. The disadvantage is that I can't jump to lines anymore by looking at the displayed line number. Is it possible to redefine the behavior of [number]G to fix this? Also, would it be possible to make the current line number 1 instead of 0 with relativenumber on? And how? A: You can simply [number]j or [number]k to do this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621117", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "31" }
Q: Play splash movie every time app launch (with multi-task support) the app I'm working on supports iOS multi-task feature by default, and I want to stick with this. Upon app launch, a splash movie clip is played (code is in AppDelegate), after user hits the home button, and re-launches the app, I want to the same splash movie be played before showing the last view where use was. I know by switching off the multi-task support, I can achieve this, but in the meanwhile, I'm losing the multi-task support feature, and I need to write code to save/resume user states. So, is there any workaround for this? thanks! A: You could try the app delegate's applicationDidBecomeActive: method but quite frankly I'd consider this to be user hostile behaviour. Who wants to see a movie every time they switch between apps? The point of multitasking on the iPhone is to quickly change between apps and this violates that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621130", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get the functions (adresses) from a .DLL (Windows) to call them from Masm32 Im writing a Compiler for a Pascal-like language which converts the program in Masm32 (and then to a .exe). My goal is to let the coder include Windows Libraries (.DLL). So I need to read out the functionnames and the jump adresses first for correct compiler warnings. (function not defined...) Is there a way to do this? I heard that each Win32 function has a magic number (0xXXXXXXXX) which is the adress to it which then can be called with call 0xXXXXXXXX A: Masm32 comes with .inc files that include most of the Windows API functions and structures. Perhaps you can leverage those?
{ "language": "en", "url": "https://stackoverflow.com/questions/7621134", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Single page design using Orchard CMS I have a client who want's a single page design for his site where the content for each "page" is shown/hidden using javascript as the user navigates the site. I'm not sure on the best way to approach this using Orchard. One option would be to have the content all on a single page content item but then you lose the ability to use the navigation features of Orchard and can't let the client think about administration in terms of pages. Does anyone have ideas or experiences on how best to set this up in Orchard CMS? Here's the solution I used based on Bertrand's advice: public ActionResult Display(int id) { var contentItem = _contentManager.Get(id, VersionOptions.Published); dynamic model = _contentManager.BuildDisplay(contentItem); var ctx = _workContextAccessor.GetContext(); ctx.Layout.Metadata.Alternates.Add("Layout_Null"); return new ShapeResult(this, model); } I created a new module with a controller containing the action method above. The action method takes a parameter for the content part id. The _contentManager and _workContextAccessor objects are being injected into the controller. The Layout.Null.cshtml view was created exactly like Bertrand suggested. A: Here's what I would do to achieve that sort of very polished experience without sacrificing SEO, client performance and maintainability: still create the site "classically" as a set of pages, blog posts, etc., with their own URLs. It's the home page layout that should then be different and bring the contents of those other pages using Ajax calls. One method that I've been using to display the same contents as a regular content item, but from an Ajax call (so without the chrome around the content, without bringing the stylesheet in, as it's already there, etc.) is to have a separate controller action that returns the contents in a "null layout": var ctx = _workContextAccessor.GetContext(); ctx.Layout.Metadata.Alternates.Add("Layout_Null"); return new ShapeResult(this, shape); Then, I have a Layout.Null.cshtml file in my views that looks like this: @{ Model.Metadata.Wrappers.Clear(); } @Display(Model.Content) Clearing the wrappers removes the rendering from document.cshtml, and the template itself is only rendering one zone, Content. So what gets rendered is just the contents and nothing else. Ideal to inject from an ajax call. Does this help? A: Following along the lines of Bertrand's solution, would it make more sense to implement this as a FilterProvider/IResultFilter? This way we don't have to handle the content retrieval logic. The example that Bertrand provided doesn't seem to work for List content items. I've got something like this in my module that seems to work: public class LayoutFilter : FilterProvider, IResultFilter { private readonly IWorkContextAccessor _wca; public LayoutFilter(IWorkContextAccessor wca) { _wca = wca; } public void OnResultExecuting(ResultExecutingContext filterContext) { var workContext = _wca.GetContext(); var routeValues = filterContext.RouteData.Values; if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest()) { workContext.Layout.Metadata.Alternates.Add("Layout_Null"); } } public void OnResultExecuted(ResultExecutedContext filterContext) { } } A: Reusing Rahul's answer with added code to answer @tuanvt's question. I'm honestly not sure what your question is but if seems like you want to access the data sent with the ajax request. If it's JSON you're sending set contentType: "application/json" on the request, JSON.stringify() it , then access it in Rahul's proposed ActionFilter by extracting it from the request stream. Hope it helps in any way. public class LayoutFilter : FilterProvider, IResultFilter { private readonly IWorkContextAccessor _wca; public LayoutFilter(IWorkContextAccessor wca) { _wca = wca; } public void OnResultExecuting(ResultExecutingContext filterContext) { var workContext = _wca.GetContext(); var routeValues = filterContext.RouteData.Values; if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest()) { workContext.Layout.Metadata.Alternates.Add("Layout_Null"); if (filterContext.HttpContext.Request.ContentType.ToLower().Contains("application/json")) { var bytes = new byte[filterContext.HttpContext.Request.InputStream.Length]; filterContext.HttpContext.Request.InputStream.Read(bytes, 0, bytes.Length); filterContext.HttpContext.Request.InputStream.Position = 0; var json = Encoding.UTF8.GetString(bytes); var jsonObject = JObject.Parse(json); // access jsonObject data from ajax request } } } public void OnResultExecuted(ResultExecutedContext filterContext) { } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7621135", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Can't add an IntPtr and an Int I have this lines in C# Visual Studio 2010: IntPtr a = new IntPtr(10); IntPtr b = a + 10; And it says: Operator '+' cannot be applied to operands of type 'System.IntPtr' and 'int'. MSDN says that this operation should work. A: If you are targetting .net 4 then your code will work. For earlier versions you need to use IntPtr.ToInt64. IntPtr a = new IntPtr(10); IntPtr b = new IntPtr(a.ToInt64()+10); Use ToInt64 rather than ToInt32 so that your code works for both 32 and 64 bit.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621140", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Incorporate PHP Into HTML Form I wonder whether someone may be able to help me please. I'm trying to put together functionality which allows an administrator to search for user details in a mySQL database using the email address as the search criteria. Once the search has taken place I would like the 'first' and 'surname' fields in my form to be completed with the record retrieved. I think the search is working as the form refreshes but it doesn't retrieve any visible information. I just wondered whether it would be at all possbible please that someone could take a look at my code below and let me know where I've gone wrong. Many thanks <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <?php require("phpfile.php"); // Opens a connection to a MySQL server $connection=mysql_connect ("hostname", $username, $password); if (!$connection) { die('Not connected : ' . mysql_error());} // Set the active MySQL database $db_selected = mysql_select_db($database, $connection); if (!$db_selected) { die ('Can\'t use db : ' . mysql_error()); } $email = $_POST['email']; $result = mysql_query("SELECT * FROM userdetails WHERE emailaddress like '%$email%'"); ?> <title>Map!</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script src="js/gen_validatorv4.js" type="text/javascript"></script> </head> <h1>&nbsp;</h1> <form name="userpasswordreset" id="userpasswordreset" method="post"> <div class="container"> <p align="justify">&nbsp;</p> <div class="title1"> <h2>User Details </h2> </div> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="26%" height="25"><strong>Email Address</strong></td> <td width="4%">&nbsp;</td> <td width="70%"><input name="email" type="email" id="email" size="50" /></td> </tr> <tr> <td height="25"><strong>Confirm Email Address </strong></td> <td>&nbsp;</td> <td><input name="conf_email" type="email" id="conf_email" size="50" /></td> </tr> <tr> <td height="25"><label> <input type="submit" name="Submit" value="Search" /> </label></td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td height="25">&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td height="25"><strong>First Name </strong></td> <td>&nbsp;</td> <td><input name="fname" type="text" id="fname" size="30" value="<?php echo $row['forename']; ?>" /> </td> </tr> <tr> <td height="25"><strong>Last Name </strong></td> <td>&nbsp;</td> <td><input name="lname" type="text" id="lname" size="30" value="<?php echo $row['surname']; ?>" /></td> </tr> <tr> <td height="25">&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td height="25"><strong>Password</strong></td> <td>&nbsp;</td> <td><input name="pass" type="password" id="pass" size="30" /></td> </tr> <tr> <td height="25"><strong>Confirm Password </strong></td> <td>&nbsp;</td> <td><input name="conf_pass" type="password" id="conf_pass" size="30" /></td> </tr> <tr> <td height="25">&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td height="25"><strong>Password Hint </strong></td> <td>&nbsp;</td> <td><input name="hint" type="text" id="hint" size="30" /></td> </tr> <tr> <td height="25">&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td height="25">&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> </table> </div> </form> <script language="JavaScript" type="text/javascript"> // Code for validating the form var frmvalidator = new Validator("userpasswordreset"); frmvalidator.addValidation("email","req","Please provide your email address"); frmvalidator.addValidation("email","email","Please enter a valid email address"); frmvalidator.addValidation("conf_email","eqelmnt=email", "The confirmed email address is not the same as the email address"); </script> </div> </body> </html> UPDATED CODE <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <?php require("phpfile.php"); // Opens a connection to a MySQL server $connection=mysql_connect ("hostname", $username, $password); if (!$connection) { die('Not connected : ' . mysql_error());} // Set the active MySQL database $db_selected = mysql_select_db($database, $connection); if (!$db_selected) { die ('Can\'t use db : ' . mysql_error()); } $email = mysql_real_escape_string($_POST['email']); // make the value safe for in the query $result = mysql_query("SELECT * FROM userdetails WHERE emailaddress like '%$email%'"); $rows = array(); while ($row = mysql_fetch_assoc($result)) { $rows[] = $row; } // $rows is now a multi dimensional array with values found by the query ?> <title>Map</title> <script src="js/gen_validatorv4.js" type="text/javascript"></script> <h1>&nbsp;</h1> <form name="userpasswordreset" id="userpasswordreset" method="post"> <p align="justify">&nbsp;</p> <div class="title1"> <h2>Your Details </h2> </div> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="26%" height="25"><strong>Email Address </strong></td> <td width="4%">&nbsp;</td> <td width="70%"><input name="email" type="email" id="email" size="50" /></td> </tr> <tr> <td height="25"><strong> Confirm Email Address </strong></td> <td>&nbsp;</td> <td><input name="conf_email" type="email" id="conf_email" size="50" /></td> </tr> <tr> <td height="25"><label> <input type="submit" name="Submit" value="Search" /> </label></td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td height="25"><strong>First Name </strong></td> <td>&nbsp;</td> <td><input name="fname" type="text" id="fname" size="30" /></td> </tr> <tr> <td height="25"><strong>Last Name</strong></td> <td>&nbsp;</td> <td><input name="lname" type="text" id="lname" size="30" /></td> </tr> <tr> <td height="25">&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td height="25">&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td height="25"><strong>Password</strong></td> <td>&nbsp;</td> <td><input name="pass" type="password" id="pass" size="30" /></td> </tr> <tr> <td height="25"><strong>Confirm Password </strong></td> <td>&nbsp;</td> <td><input name="conf_pass" type="password" id="conf_pass" size="30" /></td> </tr> <tr> <td height="25">&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td height="25"><strong>Password Hint </strong></td> <td>&nbsp;</td> <td><input name="hint" type="text" id="hint" size="30" /></td> </tr> <tr> <td height="25">&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td height="25">&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> </table> </form> <script language="JavaScript" type="text/javascript"> // Code for validating the form // Visit http://www.javascript-coder.com/html-form/javascript-form-validation.phtml // for details var frmvalidator = new Validator("userpasswordreset"); frmvalidator.addValidation("email","req","Please provide your email address"); frmvalidator.addValidation("email","email","Please enter a valid email address"); frmvalidator.addValidation("conf_email","eqelmnt=email", "The confirmed email address is not the same as the email address"); </script> </body> </html> A: Aren't you missing the step where you actually run the mysql_fetch_assoc function against your query? Just assigning the result of mysql_query to the variable $result is not enough! Add something like this after your call to mysql_query: if($result) { $row = mysql_fetch_assoc($result)); } Edit: mysql_fetch_assoc PHP documentation A: To get all the rows resulted with the query you would need to use a mysql fetch function (there are several). The preffered method is definitly mysql_fetch_assoc The relevant part of your code would look something like this: $email = mysql_real_escape_string($_POST['email']); // make the value safe for in the query $result = mysql_query("SELECT * FROM userdetails WHERE emailaddress like '%$email%'"); $rows = array(); while ($row = mysql_fetch_assoc($result)) { $rows[] = $row; } // $rows is now a multi dimensional array with values found by the query A: Just going over your code breifly, I dont think your passing the value of the email to in your sql query correctly. try using this. $result = mysql_query("SELECT * FROM userdetails WHERE emailaddress like '%" . $email . "%'");
{ "language": "en", "url": "https://stackoverflow.com/questions/7621141", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Google API - Static Maps Frankly, I'm not sure what I'm doing wrong. This is my code, but for some reason, the map is outputting a blank iFrame with a source URL that if I click will send me to the proper map, so the URL is being input correctly, but it's not actually being displayed on my website. <?php $addressStr ="516 East Liberty Street, Ann Arbor, MI 48104"; ?> <iframe width="206" height="175" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="<?php echo "http://maps.googleapis.com/maps/api/staticmap?center={$addressStr}&zoom=15&size=204x173&markers=color:orange|{$addressStr}&sensor=true&output=embed"; ?>"></iframe> A: It's not an iframe. You need a standard <img> tag ?
{ "language": "en", "url": "https://stackoverflow.com/questions/7621146", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Auto deletion from memory after indexing with solr because of lack memory i want to force solr to write the index into hard space and does not keep the file opened in memory,How can i do that in solrj? i add the solr.commit() after each document indexed but it does not work A: Few pointers :- To immediately commit data use - req.setAction( UpdateRequest.ACTION.COMMIT, false, false ); or solr.commit(false, false) The arguments are waitFlush and waitSearcher which are true by default and needs to be set to false. Also revisit the configurations for maxBufferedDocs & ramBufferSizeMB in solrconfig.xml
{ "language": "en", "url": "https://stackoverflow.com/questions/7621153", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to create a shortcut which copy line where cursor on Possible Duplicate: Eclipse copy/paste entire line keyboard shortcut I want to create an eclipse shortcut. Wherever line cursor on (without selection) when pressed Ctrl+C, eclipse will copy the whole line to clipboard. Is this possible? A: Key bindings can be associated with commands, but this operation would be 3 commands - Line Start, Select Line End, Copy. You'd have to implement your own command to execute all the three (id = org.eclipse.ui.edit.text.goto.lineStart, id = org.eclipse.ui.edit.text.select.lineEnd and id = org.eclipse.ui.edit.copy). But setting Ctrl+C as key binding would conflict with existing binding - Copy.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621157", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Getting User's name from table when they login with e-mail The user table is setup as: ID | Name | Email | Password and they login with: Email | Password I'm wondering how I can display their 'Name' when they login with their e-mail. What I have so far that works with email is: session_start(); if (!isset($_SESSION['email'])) { header('location: '); } include_once('config.php'); $email = $_SESSION['email']; <!doctype html> <body> <p><?php echo $email; ?> and that works, but when I try something like $sql = "SELECT name FROM $table WHERE email='$_SESSION["email"]'"; $result = mysql_query($sql); <!doctype html> <body> <p><?php echo $result; ?></p> that doesn't work. Any help is appreciated A: tyou did not fetch the result from database use the following line mysql_result($result ,0); You can use above function .see the php manual to fetch result from database A: You really should include more information, for example what error you're presented with when you attempt the code you included. However, It would look like you have not correctly escape the string $sql. Try something like: $sql = "SELECT name FROM $table WHERE email='" . $_SESSION["email"] . "'"; Note the dot (.) which concatenates strings instead of evaluating inside a string as you attempted to do. If you really want to input an array index into the string, you could enclose the variable using {} $sql = "SELECT name FROM $table WHERE email='{$_SESSION["email"]}'"; A: mysql_query() only returns a resource, this needs to be passed to mysql_fetch_array() to deal with the returned records; http://php.net/manual/en/function.mysql-query.php has some examples A: Do it like this: $sql = "SELECT name FROM $table WHERE email=".$_SESSION['email']; $result = mysql_query($sql); $row = mysql_fetch_assoc($result); $name = $row['name']; <!doctype html> <body> <p><?php echo $name; ?></p> Regards, Akke
{ "language": "en", "url": "https://stackoverflow.com/questions/7621159", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to dynamically set variable value with C#? For example, PHP code: $test = "hello"; ${$test} = $test; echo $hello; // return hello How to do this in C#? Thanks in advance. UPD: Dynamic variable in C#? - here is an answer. A: This isn't supported in C#. You could use an ExpandoObject and set a member on it, but it's not quite the same as the PHP code. You'll still need to refer to the ExpandoObject by a variable name. dynamic myObject = new ExpandoObject(); string test = "Hello"; ((IDictionary<string, object>)myObject).Add(test, test); Console.WriteLine(myObject.Hello); Nonetheless, this doesn't help with code clarity. If all you want to do is map a name to a value you can use a Dictionary, which is really what ExpandoObject uses internally, as demonstrated by the cast in the code above. A: C# is not designed for that sort of thing at the language level. You will have to use reflection to achieve that, and only for fields, not local variables (which cannot be accessed via reflection). A: Such dynamic access to class members can be achieved via reflection. class Foo { string test; string hello; void Bar() { test = "hello"; typeof(Foo).InvokeMember( test, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.SetField, null, this, new object[] { "newvalue" } ); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7621169", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can you solve equations in PHP? I'm looking for a generalized equation solver in PHP. This could either be in the form of in-built functionality, a library, or even integration with another language if it comes to it. I am even comfortable with a joint solution that involves some combination of the above. I need this for an educational website on which I am working. Let me give a series of equations that I would ideally expect such a solver to deal with: x+5=8 => x=3 x^2=5 => x=+/-sqrt(5) [exact solution in terms of sqrt, ln, or whatever] AND x=+/-2.236 [approximate solution to certain number of digits] x+y=-3 [solve in terms of y] => y=-x-3 x^2=-5 => x=+/5i x+y=3 and x-y=3 => x=3, y=0 I hope this is not a bridge too far. If so, I'll build the functionality as each problem comes in-house, but if anyone knows of the proper library for such a set of problems, I would greatly appreciate it. A: First: your math solutions are wrong. * *x+5=8 evaluates to x=3 *x+y=-3, y evaluates to -x-3 etc. To do the math: make an API call to Wolfram|Alpha. Seeing as this is an educational venture, I would highly suggest that you do not create your own product and rely on third-party software. I would personally go with Wolfram Mathematica, and probably their pre-college solutions or go with Web Mathematica for web interfaces. Note about Web Mathematica: it uses JSP or Java Servlets for it's back-end technology. More about specific technical details for Web Mathematica will be helpful. A: Check out Sage, from their website: Sage is a free open-source mathematics software system licensed under the GPL. It combines the power of many existing open-source packages into a common Python-based interface. Mission: Creating a viable free open source alternative to Magma, Maple, Mathematica and Matlab. Sage has an AJAX-based notebook interface, that is probably as good as an API that you can use from PHP.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621171", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Exiting for-loop in c++ I have at least 2 problems with the code but I will start with this one. The following code does not seem to work correctly: cout<<"Vill du mata in en post till? (ja/nej)"<<endl; //I'm asking if the user wants to run the for-loop one more time or brake with ja(yes) or nej(no). cin>>svar; if (svar == ja) { return 0; } The problem is that if the user answers no it does not brake but instead runs trough the for-loop without "running" or "executing" the cin>> lines. I did some troubleshooting and found that if I change if (svar == ja) to if (svar != nej) it brakes the for-loop, but the problem is it does so even if I put in ja(yes) or anything else... Heres is the full code, thank you for any help you can provide: #include <cstdlib> #include <iostream> #include <string> using namespace std; struct telefonbok { string namn; string nummer; }; int main() { int ja, nej; telefonbok post[10]; bool svar; //behövs för frågan om man vill fortsätta. for (int i=0; i<10; i++) { cout<<"Lagg till en post i telefonboken."<<endl; cout<<"Ange personens namn: "<<endl; cin>>post[i].namn; cout<<"Ange personens nummer :"<<endl; cin>>post[i].nummer; cout<<"Vill du mata in en post till? (ja/nej)"<<endl; cin>>svar; if (svar == ja) //stoppar slingan om man svarar nej { return 0; } } system("PAUSE"); return 0; } A: The variable ja and nej are not initialized. Comparing svar to them is futile. A: Svar should be a string (since you are expecting the user to enter a string "ja" or "nej", and not an integer which the code expects), and you should probably check for "nej" instead of "ja" considering the question you ask. If you only want to exit the loop and not the function use break: // ... string svar = ""; for (int i=0; i<10; i++) { // ... cout<<"Vill du mata in en post till? (ja/nej)"<<endl; cin >> svar; if (svar == "nej") { return 0; // If you only want to exit the loop and not the function you can use: // break; } } A: Looking at your code, it's immediately clear that you are attempting to compare a string to an uninitialized int called ja. If you want to compare svar to something that will return a meaningful value, you will want to compare a string to a string, i.e. if (svar == "ja") instead of if (svar == ja). I can't see anywhere else in the code where the ints "ja" and "nej" are used. What is their purpose?
{ "language": "en", "url": "https://stackoverflow.com/questions/7621175", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Real Time Image Processing in Android using the NDK Using an Android (2.3.3) phone, I can use the camera to retrieve a preview with the onPreviewFrame(byte[] data, Camera camera) method to get the YUV image. For some image processing, I need to convert this data to an RGB image and show it on the device. Using the basic java / android method, this runs at a horrible rate of less then 5 fps... Now, using the NDK, I want to speed things up. The problem is: How do I convert the YUV array to an RGB array in C? And is there a way to display it (using OpenGL perhaps?) in the native code? Real-time should be possible (the Qualcomm AR demos showed us that). I cannot use the setTargetDisplay and put an overlay on it! I know Java, recently started with the Android SDK and have zero experience in C A: Have you considered using OpenCV's Android port? It can do a lot more than just color conversion, and it's quite fast. A: A Google search returned this page for a C implementation of YUV->RGB565. The author even included the JNI wrapper for it. A: You can also succeed by staying with Java. I did this for the imagedetectíon of the androangelo-app. I used the sample code which you find here by searching "decodeYUV". For processing the frames, the essential part to consider is the image-size. Depending on the device you may get quite large images. i.e. for the Galaxy S2 the smallest supported previewsize is 640*480. This is a big amount of pixels. What I did, is to use only every second row and every second column, after yuvtorgb decoding. So processing a 320*240 image works quite well and allowed me to get frame-rates of 20fps. (including some noise-reduction, a color-conversion from rgb to hsv and a circledetection) In addition You should carefully check the size of the image-buffer provided to the setPreview function. If it is too small, the garbage-collection will spoil everything. For the result you can check the calibration-screen of the androangelo-app. There I had an overlay of the detected image over the camera-preview.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621178", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Django form multiple select box size in template I have a template: ... <form action="/reportform/" method="post"> <p><label>Aircraft system:</label> <br>{{ Querry.system }} ... it looks like this How can I set a Size option for this box? for example, 10. A: Use the attrs attribute to define the size. class MyForm(forms.Form): system = forms.ChoiceField(choices=SYSTEM_CHOICES, widget=forms.SelectMultiple(attrs={'size':'40'})) Sometimes, it is useful to override the widget in the forms init method. class MyForm(forms.Form): <snip> def __init__(self, *args, **kwargs): super(MyForm, self).__init__(*args, **kwargs) self.fields['system'].widget = forms.SelectMultiple(attrs={'size':'40'}))
{ "language": "en", "url": "https://stackoverflow.com/questions/7621184", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: RewriteRule & Header set Expires : how to I'm using rewrite rules to create a /fr /en on my website and does folder don't exist, therefore if I try to use <Directory /fr> ExpiresDefault "access plus 1 day" </Directory> Apache complain because the folder does not exist, can't find a way to do it in the http.conf If I use Header set Expires "access plus 1 day" in the .htaccess, can see the header showing Expires: access plus 1 day instead of the date + 1 day, if i remove it I can see Expires: Thu, 19 Nov 1981 08:52:00 GMT Also if I use ExpiresDefault "access plus 1 day" It does not work... Can you please tell how to get this right? Also I believe that Safari (and only safari) keep on reloading the page every minutes because of that, is that correct or just another issue? Thx for your help! A: Directory instructions are working on real filesystem paths. So a Directory setting should looks like : <Directory /var/www/foo/bar/fr > (...) </Directory> Instead, if you prefer working with url path you must use Location directives: <Location /fr > (...) </Location> This should at least fix your inexistents directories problems (if I understand your first sentence, which is quite strange)
{ "language": "en", "url": "https://stackoverflow.com/questions/7621185", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Vertical Scroll Content within DIvs - Reload to top I'm using the simplest HTML 'overflow: scroll' type mark-up for creating a scroll bar within multiple div containers to display text and image content within the scroll. I have it setup within tabbed content areas, that are pulled together calling divs within the tab links. I'm trying to figure how, if possible, that when a user browses to a different tab and then back - to allow that scroll bar to reload to the top, ready to scroll downward again. Pretty much, the mark-up; <li class="newtab"> <!--JS Rollover Button for Tab--> <a href=#tab13 onMouseOver= "if (document.images) document.tab_recordedattack_off1.src= 'img/Btns/tab_recordedattack_on1.png';" onMouseOut= "if (document.images) document.tab_recordedattack_off1.src= 'img/Btns/tab_recordedattack_off1.png';"><img src="img/Btns/tab_recordedattack_off1.png" name=tab_recordedattack_off1 border=0></a> <!--End JS Rollover Button for Tab--> </li> </ul> <div class="tab_container"> <div id="tab13" class="tab_content"> <div class="tabright"> <div style="border:0px solid black;width:500px;height:400px;overflow:scroll;overflow-y:scroll;overflow-x:hidden;"> I've been thinking about trying to set a simple html anchor point at the top of scroll areas and somehow call to it within the tab links - but can't figure out how to do that. Any suggestions? - How can I point the tabbed links to the content and the anchor point? A: You can use jQuery to reset the scroll: http://jsfiddle.net/Cqhch/ $("button").click(function(){ $("div:first").scrollTop(0); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7621196", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: lockfile purpose in init.d daemon scripts (linux) When looking at various daemon scripts in /etc/init.d/, I can't seem to understand the purpose of the 'lockfile' variable. It seems like the 'lockfile' variable is not being checked before starting the daemon. For example, some code from /etc/init.d/ntpd: prog=ntpd lockfile=/var/lock/subsys/$prog start() { [ "$EUID" != "0" ] && exit 4 [ "$NETWORKING" = "no" ] && exit 1 [ -x /usr/sbin/ntpd ] || exit 5 [ -f /etc/sysconfig/ntpd ] || exit 6 . /etc/sysconfig/ntpd # Start daemons. echo -n $"Starting $prog: " daemon $prog $OPTIONS RETVAL=$? echo [ $RETVAL -eq 0 ] && touch $lockfile return $RETVAL } What is the 'lockfile' variable doing? Also, when writing my own daemon in C++ (such as following the example at the bottom of http://www.itp.uzh.ch/~dpotter/howto/daemonize), do I put the compiled binary directly in /etc/init.d/ or do I put a script there that calls the binary. (i.e. replacing the 'daemon $prog' in the code above with a call to my binary?) A: The whole thing is a very fragile and misguided attempt to keep track of whether a given daemon is running in order to know whether/how to shut it down later. Using pids does not help, because a pid is meaningless to any process except the direct parent of a process; any other use has unsolvable and dangerous race conditions (i.e. you could end up killing another unrelated process). Unfortunately, this kind of ill-designed (or rather undesigned) hackery is standard practice on most unix systems... There are a couple approaches to solving the problem correctly. One is the systemd approach, but systemd is disliked among some circles for being "bloated" and for making it difficult to use a remote /usr mounted after initial boot. In any case, solutions will involve either: * *Use of a master process that spawns all daemons as direct children (i.e. inhibiting "daemonizing" within the individual daemons) and which thereby can use their pids to watch for them exiting, keep track of their status, and kill them as desired. *Arranging for every daemon to inherit an otherwise-useless file descriptor, which it will keep open and atomically close only as part of process termination. Pipes (anonymous or named fifos), sockets, or even ordinary files are all possibilities, but file types which give EOF as soon as the "other end" is closed are the most suitable, since it's possible to block waiting for this status. With ordinary files, the link count (from stat) could be used but there's no way to wait on it without repeated polling . In any case, the lockfile/pidfile approach is ugly, error-prone, and hardly any better than lazy approaches like simply killall foobard (which of course are also wrong). A: The rc scripts keep track of whether or not it is running and don't bother stopping what is not running. A: What is the 'lockfile' variable doing? It could be nothing or it could be eg. injected into $OPTIONS by this line . /etc/sysconfig/ntpd The daemon takes the option -p pidfile where $lockfile could go. The daemon writes its $PID in this file. do I put the compiled binary directly in /etc/init.d/ or do I put a script there that calls the binary The latter. There should be no binaries in /etc, and its customary to edit /etc/init.d scripts for configuration changes. Binaries should go to /(s)bin or /usr/(s)bin.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621203", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Sort NULL values to the end of a table Is there a way with PostgreSQL to sort rows with NULL values in fields to the end of the selected table? Like: SELECT * FROM table ORDER BY somevalue, PUT_NULL_TO_END A: Does this make the trick? ORDER BY somevalue DESC NULLS LAST Taken from: http://www.postgresql.org/docs/9.0/static/sql-select.html A: NULL values are sorted last in default ascending order. You don't have to do anything extra. The issue applies to descending order, which is the perfect inverse and thus sorts NULL values on top. PostgreSQL 8.3 introduced NULLS LAST: ORDER BY somevalue DESC NULLS LAST For PostgreSQL 8.2 and older or other RDBMS without this standard SQL feature: ORDER BY (somevalue IS NULL), somevalue DESC FALSE sorts before TRUE, so NULL values come last, just like in the example above. See: * *Sort by column ASC, but NULL values first? *The manual on SELECT
{ "language": "en", "url": "https://stackoverflow.com/questions/7621205", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "125" }
Q: Problematic make file for java JFLAGS = -d bin -cp lib/slick.jar:lib/lwjgl.jar JC = javac .SUFFIXES: .java .class .java.class: $(JC) $(JFLAGS) src/$*.java CLASSES = \ Game.java \ Block.java \ BlockMap.java \ default: classes classes: $(CLASSES:.java=.class) clean: $(RM) bin/*.class My source files are in src/ and I want to the compiled files to be in bin/ . When I run make, it gives me this error makefile:7: *** multiple target patterns. Stop. A: The problem is here: .java.class: $(JC) $(JFLAGS) src/$*.java and here: clean: $(RM) bin/*.class These are no rules but commands. And commands must be on its own lines with a tab at the beginning of the line. .java.class: $(JC) $(JFLAGS) src/$*.java clean: $(RM) bin/*.class Not that this are all problems with Makefiles and Java in general and this Makefile in particular. A: Since you don't know how to manage a Makefile there is no reason NOT to use a better tool. Here is a minimal Ant file which should do the job. And because Ant is designed for Java, most of the directory handling problems of Make simply don't exist. As a bonus you can ask any Java developer for more help. Java developers and Makefile experts are a quite uncommon match in these days. <project name="Game" default="classes"> <target name="classes"> <mkdir dir="bin" /> <javac srcdir="src" destdir="bin" classpath="lib/slick.jar;lib/lwjgl.jar" includeantruntime="false"/> </target> <target name="clean"> <delete dir="bin" /> </target> </project>
{ "language": "en", "url": "https://stackoverflow.com/questions/7621208", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How should platformer game's solid objects be implemented efficiently? I have been trying to write a platformer engine for a few times now. The thing is I am not quite satisfied with my implementation details on solid objects. (wall, floor, ceiling) I have several scenario I would like to discuss. For a simple platformer game like the first Mario, everything is pretty much blocks. A good implementation should only check for necessary collision, for instance, if Mario is running and at the end of the way, there is a cliff, how should we check for collision efficiently? Should we always check on every step Mario is taking to see whether his hitbox is still on the ground? Or is there some other programming way that allows us to not handle this every frame? But blocks are boring, let's put in some slopes. Implementation details-wise, how should slopes be handled? Some games such as Sonic, have this loop structure that the character can go "woohoo" in the loop and proceed. Another scenario is "solid" objects (floor, ceiling, wall) handling. In Megaman, we can see that the player can make himself go through the ceiling by using a tool to go into the solid "wall". Possibly, the programming here is to force the player to go out of the wall so that the player is not stuck, by moving the player quickly to the right. This is an old "workaround" method to avoid player stucking in wall. In newer games these days, the handle is more complex. Take, for instance, Super Smash Brawl, where players can enlarge the characters (along with their hitbox) The program allows the player to move around "in" the ceiling, but once the character is out of the "solid" area, they cannot move back in. Moreover, sometimes, a character is gigantic that they go through 3 solid floors of a scene and they can still move inside fine. Anybody knows implementation details along these lines? So here, I know that there are many implementation possible, but I just wanna ask here that are there some advanced technical details for platformer game that I should be aware of? I am currently asking for 3 things: * *How should solid collision of platformer game be handled efficiently? Can we take lesser time to check whether a character has ran and completely fell off a platform? *Slope programming. At first, I was thinking of physics engine, but I think it might be overkill. But in here, I see that slopes are pretty much another types of floor that "push" or "pull" the character to different elevation. Or should it be programmed differently? *Solid objects handling for special cases. There might be a time where the player can slip into the solid objects either via legal game rules or glitches, but all in all, it is always a bad idea to push the player to some random direction if he is in a wall. A: * *For a small number of objects, doing an all-pairs collision detection check at each time step is fine. Once you get more than a couple hundred objects, you may want to start considering a more efficient method. One way is to use a binary space partitioning (BSP) to only check against nearby objects. Collision detection is a very well researched topics and there are a plethora of resources describing various optimizations. *Indeed, a physics engine is likely overkill for this task. Generally speaking, you can associate with each moving character a "ground" on which he is standing. Then whenever he moves, you simply make him move along the axis of the ground. *Slipping into objects is almost always a bad idea. Try to avoid it if possible.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621211", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Getting variables by scope Is it possible for a function in C++ to find the addresses of all variables in a certain scope? I'm talking about methods such as scanning the memory used by the program, or looking at a compiler's parse tree. Maybe there's even a mechanism added for it in C++11. This is something I've been wondering about for a few time now, some good answers will be appreciated. Thanks. note: the code should be called from inside the program. A: This is something that all debuggers can do, so I think it would be possible for a program to get that level of introspection if it is compiled with debug information and can somehow parse its own symbol table. This project implemented debug info parsing to generate class introspection for C++. I guess the same approach would work for your purposes. Also, I doubt this will be possible if you compile with optimizations, since the optimizer may change your code enough that a mapping from individual variables in the source code to memory locations does not exist.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621212", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java Regex Understanding I need help to understand regex. For some reason, i'v read lots of tutorials and lots of questions here on sof, and cannot manage to understand it. I want to use String.split function like in here: Java string.split - by multiple character delimiter. But i cant understand this part: String[] parts = input.split("[,\\s\\-:\\?]"); Lets supose i want to make a split with this following delimiters: " " (space), "." (full stop), "," (coma), "!", "»", "«", etc. How can i get this with regex? I want understand what this characters in here: ("[,\s\-:\?]") are. What does "\s", why is it needed. A: \s is "any single whitespace character". So it represents a space, newline, tab, or other such. Note that the regex could actually be written more compactly in this case: String[] parts = input.split("[,\\s:?-]"); (? doesn't need to be escaped when inside [], and - doesn't either if it's the last thing.) For more details about character classes, see http://www.regular-expressions.info/charclass.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7621214", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: json_decode variables php I'm simply trying to extract variables from a json_decode the resulting decoded code (a snippet of) is: auth_info: array(4) { ["profile"]=> array(13) { ["name"]=> array(3) { ["givenName"]=> string(6) "John" ["familyName"]=> string(7) "Doe" ["formatted"]=> string(14) "John Doe" } } } I'm trying all things such as: echo "\n\nMy name is ".$auth_info['profile']->name->givenName; But all to no avail..ideas please? Many thanks as always Darren A: They are all arrays, try this. $auth_info['profile']['name']['givenName']
{ "language": "en", "url": "https://stackoverflow.com/questions/7621218", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery .css('right') not working I am making a simple game in jQuery. I am having trouble turning the spider image to north east. I have it working fine with north west but for some reason north east does not seem to be working. Here is my init code: // JavaScript Document function init(){ angel = $('<img class="spider">').attr({ 'src': 'img/spider.png' }).css({ width: "125px", height: "125px;", 'position': 'absolute', top: -10, left: -10 }); //append it to body $(document.body).append(angel); //start dreaming do_dream(); } Here is my part of the code that is responsible for turning it north east or north west. Like I said earlier, north west seems to work perfectly fine but when the same code is used for turning it north east, it does not work. // turn north west if (parseInt(dream.css('top')) < parseInt(angel.css('top')) && parseInt(dream.css('left')) < parseInt(angel.css('left'))) { $('.spider').attr('src', 'img/spider_nw.png'); } // turn north east if (parseInt(dream.css('top')) < parseInt(angel.css('top')) && parseInt(dream.css('right')) < parseInt(angel.css('right'))) { $('.spider').attr('src', 'img/spider_ne.png'); } A: "Right" isn't working, because the CSS attribute for right is set to "auto". You have to calculate the right offset, using (replace your current right-compare expression by this): (dream.parent().width() - dream.width() - dream.offset().left) < (angel.parent().width() - angel.width() - angel.offset().left) A: @rob-w had explained the reason and also had given a way to solve it. Another way is, you can always set all the four properties- left, right, top, bottom. Don't need to set height and width then. Like - //width: "200px", //height: "200px;", 'position': 'absolute', top: y - 100, left: x - 100, right: x + 100, //(x - 100 + 200) bottom: y + 100, //(y - 100 + 200) A: At a guess, it's because a DOM element will only have the "bottom" and "right" attributes if it's been positioned with them. That is, the browser / jQuery will not automatically compute the distance from the right edge of the window / document for you when you do .css('right'). If what you want to find is the position of the right edge of the element, try adding the position of the left edge and the width.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621223", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Delphi inline assembler pointer to structure Hi people is there a way i can access a pointer to a structure member directly from in line assembler i tried this procedure test(eu:PImageDosHeader);assembler; asm push eu._lfanew end; It won't compile but if i use this procedure test(eu:Pointer); var xx:TImageDosHeader; begin xx:=TImageDosHeader(eu^); asm push xx._lfanew end; end; It works great.Any idea how can i access a structure trough a pointer in inline asm? is a matter of optimizing the code A: The following works: type PMyStruct = ^TMyStruct; TMyStruct = record A, B: cardinal; end; procedure ShowCard(Card: cardinal); begin ShowMessage(IntToHex(Card, 8)); end; procedure test(Struct: PMyStruct); asm push ebx // We must not alter ebx mov ebx, eax // eax is Struct; save in ebx mov eax, TMyStruct(ebx).A call ShowCard mov eax, TMyStruct(ebx).B call ShowCard pop ebx // Restore ebx end; procedure TForm6.FormCreate(Sender: TObject); var MyStruct: TMyStruct; begin MyStruct.A := $22222222; MyStruct.B := $44444444; test(@MyStruct); end; A: I would write it like this: procedure test(const eu: TImageDosHeader); asm push TImageDosHeader([EAX])._lfanew end; The pertinent documentation is here. A: Yet another workaround: procedure test(eu:PImageDosHeader); asm push eu.TImageDosHeader._lfanew end;
{ "language": "en", "url": "https://stackoverflow.com/questions/7621224", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Font not well rendered with freetype and Opengl ES 2 (IPhone device) I'm using freetype for writing text in an IPhone device, the result are rare. As you can see in the image same characters(like 'b', 'n' or 'u') aren't rendered equally. The texture is always the same. Any idea where is the problem or what's going on? http://craneossgd.files.wordpress.com/2011/10/image_freetype1.png Code: FT_New_Face(getFTLibrary(), _filename, 0, &(_face)) FT_Select_Charmap( _face, FT_ENCODING_UNICODE ); FT_Set_Char_Size( _face, _pt<<6,_pt<<6, _dpi, _dpi); for (i=0; i<255; i++) { if (!createGlyphTexture(i)) { clean(); } } ..... createGlyphTexture(unsigned char ch){ .... FT_Load_Glyph(_face, FT_Get_Char_Index(_face,ch), FT_LOAD_DEFAULT) FT_Get_Glyph(_face->glyph, &glyph) .... // *** Transform glyph to bitmap FT_Glyph_To_Bitmap(&glyph, FT_RENDER_MODE_NORMAL, 0, 1); // *** Get bitmap and glyph data bitmap_glyph = (FT_BitmapGlyph)glyph; bitmap = bitmap_glyph->bitmap; // *** width = pow2(bitmap.width); height = pow2(bitmap.rows); // *** Alloc memory for texture expanded_data = (GLubyte *)malloc( sizeof(GLubyte)*2*width*height ); for (j=0; j<height;j++) { for (i=0; i<width; i++) { if ( (i>=(CRuint)bitmap.width) || (j>=(CRuint)bitmap.rows) ){ expanded_data[2*(i+j*width)] = 0; expanded_data[2*(i+j*width)+1] = 0; } else { expanded_data[2*(i+j*width)] = bitmap.buffer[i+bitmap.width*j]; expanded_data[2*(i+j*width)+1] = bitmap.buffer[i+bitmap.width*j]; } } } // *** Load texture into memory glBindTexture(GL_TEXTURE_2D, _textures[ch]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_LUMINANCE_ALPHA, width, height, 0, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, expanded_data); .... } Thanks!! A: In freetype reference: http://www.freetype.org/freetype2/docs/reference/ft2-base_interface.html FT_LOAD_TARGET_LIGHT. A lighter hinting algorithm for non-monochrome modes. Many generated glyphs are more fuzzy but better resemble its original shape. A bit like rendering on Mac OS X. As a special exception, this target implies FT_LOAD_FORCE_AUTOHINT. FT_RENDER_MODE_LIGHT.This is equivalent to FT_RENDER_MODE_NORMAL. It is only defined as a separate value because render modes are also used indirectly to define hinting algorithm selectors. See FT_LOAD_TARGET_XXX for details. It works using next configuration: FT_Load_Glyph(_face, FT_Get_Char_Index(_face,ch), FT_LOAD_TARGET_LIGHT) ... FT_Glyph_To_Bitmap(&glyph, FT_RENDER_MODE_NORMAL, 0, 1);
{ "language": "en", "url": "https://stackoverflow.com/questions/7621227", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is drawrect more efficient for coregraphcs drawing than using core graphics in touches moved? My whole app uses touchesMoved for drawing (Coregraphics). Should I be calling [self setNeedsDisplay] from within touchesMoved instead of performing the drawing code in there? Would that stop some lag that I am experiencing? The only reason I didn't try this before posting is because it is going to take me a few hours to convert all drawing to within drawRect and I wanted to know if it would be more would efficient than drawing in touchesMoved? A: Yes. You should always keep your drawing in drawRect and use setNeedsDisplay to trigger the actual drawing. This is key to the rendering of views in Cocoa Touch. For example, if you didn't use this method, you could potentially have drawing code scattered around your class in multiple methods. In addition, this also ensures that your drawing code executes only once during a render cycle. Essentially, calling setNeedsDisplay triggers an invalidation flag that lets your UIView know to redraw itself. Without this, you could be performing extra drawing operations that aren't actually needed due to the render cycle. A: You should not do drawing inside a UI callback. It will slow down or freeze the UI responsiveness, and you won't have the proper drawing context if you want to draw directly into a UIView. Instead save, schedule or queue the information required for drawing for later, either into your own bitmap drawing context, or during the drawRect callback for that view. Depending on the frame rate required, you many not even need to do a setNeedsDisplay on every touchesMoved event, but can queue the data and set a flag for an animation rate timer or CADisplayLink callback to do the setNeedsDisplay at a more constant rate (say only 15 or 30 frames per second). This will also help eliminate extra drawing operations.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621229", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Check if my app has permissions to read process info and read/write to files and directories How to check in my C# application if I have Permissions to get process list, kill processes, get directories, get files in directories, read and write files and etc? Thanks! A: If your has permission can do the operation without issue, if there is a lack of permission you can catch the exception and handle it(UnauthorizedAccessException etc). A: In .NET there are two ways to do this. The System.Security.Permissions namespace has attributes and classes you need. You can use the attributes and write declarative code, or use the classes with imperative code. As an example, for FileIO you would do this Declarative : Typically you annotate a method, and based on the SecurityAction exceptions are thrown is the current or calling code doesn't have the said permission [FileIOPermissionAttribute(SecurityAction.PermitOnly, ViewAndModify = "C:\\example\\sample.txt")] Imperative: Here you can programatically check for permissions FileIOPermission f = new FileIOPermission(PermissionState.None); f.AllLocalFiles = FileIOPermissionAccess.Read; try { f.Demand(); } catch (SecurityException s) { Console.WriteLine(s.Message); } Imperative or declarative, your code has to react to an exception. The SecurityAction enum explains how these work, some check if the current code has permission, some check the calling code too. This enum has the same corresponding methods (Deny,Assert,etc) which can be used in imperative code. Lastly, the System.Security.Permissions namespace doesn't have anything for processes, so I assume you can't really check for permissions here. Although it's for .NET 1.1 this security article is pretty relevant. (Doesn't have coloured code though =(
{ "language": "en", "url": "https://stackoverflow.com/questions/7621230", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can i call a richfaces component from xhtml page I am including jasper report's exported xhtml to a jsf page. I want to put some export option to jasper report template and when user viewing report on browser if he click this option(pdf image) i want to pop up a pane and get export options (page ranges) and then call a jsf bean metod.I am using jsf 1.2 and richfaces so I need to know how i can call a
{ "language": "en", "url": "https://stackoverflow.com/questions/7621234", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there a C++ allocator that prevent an STL container from being swapped? Has anyone seen an allocator that calls mlock(2) to prevent an STL container's contents from being swapped to disk? There is afaik only one tricky part to writing such an allocator, namely minimizing the number of mlocked pages by clustering allocations to be mlocked. Ergo, one should probably start by modifying some shared memory allocator? A: If I wanted to implement this (which is difficult to imagine, because I find it hard to believe it's the right solution to any problem :^), I'd try to do it by using a boost::pool_allocator (which provides a standard library compatible Allocator from a pool) and then - I forget the details; think it'll involve the RequestedSize template argument to singleton_pool and a user_allocator ? - there will be some way of having that sit on top of a pool which requests bigger chunks of memory by the mechanism of your choice which in your case would be allocation of mlocked pages.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621243", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Wait for file to be unlocked - Windows I'm writing a TFTP server program for university, which needs exclusive access to the files it opens for reading. Thus it can be configured that if a file is locked by another process that it waits for the file to become unlocked. Is there any way on Win32 to wait for a file become unlocked without creating a handle for it first? The reason I ask, is that if another process calls CreateFile() with a dwShareMode that is incompatible to the one my process uses, I won't even be able to get a file handle to use for waiting on the lock using LockFileEx(). Thanks for your help in advance! A: As tools from MS like OH and Process Explorer do it, it is definitely possible to get all the handles opened by a process. From there to wait on what you'd like the road is still long, but it is a beginning :) If you have no success with the Win32 API, one place to look at is for sure the NT Native API http://en.wikipedia.org/wiki/Native_API You can start from here http://msdn.microsoft.com/en-us/library/windows/desktop/ms724509%28v=vs.85%29.aspx and see if it works with the SystemProcessInformation flag. Look also here for a start http://nsylvain.blogspot.com/2007/09/how-list-all-open-handles.html The native API is poorly documented, but you can find resources online (like here http://www.osronline.com/article.cfm?id=91) As a disclaimer, I should add that the Native API is somehow "internal", and therefore subject to change on future versions. Some functions, however, are exposed also publicly in the DDK, at kernel level, so the likelihood of these functions to change is low. Good luck! A: If you take a look at the Stack Overflow questions What Win32 API can be used to find the process that has a given file open? and SYSTEM_HANDLE_INFORMATION structure, you will find links to code that can be used to enumerate processes and all open handles of each running process. This information can be used to obtain a HANDLE to the process that has the file open as well as its HANDLE for the file. You would then use DuplicateHandle() to create a copy of the file HANDLE, but in the TFTP process' handle table. The duplicated HANDLE could then be used by the TFTP process with LockFileEx(). This solution relies on an internal function, NtQuerySystemInformation(), and an undocumented system information class value that can be used to enumerate open handles. Note that this feature of NtQuerySystemInformation() "may be altered or unavailable in future versions of Windows". You might want to use an SEH handler to guard against access violations were that to happen.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621248", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: opening files from a website I asked a similar question yesterday but I included some code that basically took my question on a different tangent than I had intended. So I shall try again. I am rewriting a python script that crawls a website to find a few hundred text files, I have no interest in any content of the text file beyond the second line of the file. Previously I would download all of the files then loop through them all to extract the second line. I would now like to open each file as my script discovers it, grab the second line, and close it without downloading to my harddrive then opening it. So basically is there a way I can open a file that is at www.example.com/123456.txt and take the second line from that file copy it to an array or something without downloading it and then opening it. A: Well, you could use urllib2.urlopen() to just get the file contents into memory, extract the second line, and then immediately discard the file from memory, if you wanted, without ever hitting your disk. You are going to have to download the contents over the internet, though. A: You could try something like urllib2.urlopen('url').read().splitlines()[1] but I guess that would download the entire file to memory A: You can't retrieve the fist N lines (or perform a line seek) but if the web server supports the Range header you could retrieve the first N bytes of the file (byte seek). If you know the maximum length of a line, you could do this: >>> import urllib2 >>> maxlinelength = 127 # nb: in terms of bytes >>> myHeaders = {'Range':'bytes=0-'+str(maxlinelength)} # from byte 0 to maxlinelength >>> req = urllib2.Request('http://www.constitution.org/gr/pericles_funeral_oration.txt', headers=myHeaders) >>> partial = urllib2.urlopen(req) >>> partial.readline() # first line discarded >>> yourvar = partial.readline() >>> yourvar # this is the second line: 'from Thucydides (c.460/455-399 BCE), \r\r\n'
{ "language": "en", "url": "https://stackoverflow.com/questions/7621249", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Symfony2 file and directory convention Am learning Symfony2 framework. the structure of files and directories make me very annoyed. It make me really hard to follow things ej: routing_dev.yml //use underscore AppCache.php // use camel case there is no unique convention. Can anyone tell me when to use camel case and when to use underscore-separator in the framework ? A: PHP files containing classes follow camel case convention as they follow PSR-0 standard. All the other files, like configurations or scripts, are lower cased. Somehow I never found it confusing.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621250", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to make a resizable JDialog? I'm using JOptionPane.showOptionDialog to show a JDialog. I would like to know how: * *set the dimension of the dialog (for now I'm using setPreferredSize() method on the given panel but I know that such method shouldn't be used). *make the showed dialog resizable. My code looks like: JPanel panel; //my JPanel built with dialog contents int ret = JOptionPane.showOptionDialog(myFrame, panel, "titel", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[1]); I know that I could obtain the desired result building a JDialog this way: JDialog dialog = new JDialog(panel); dialog.setResizable(true); dialog.setSize(800,600); dialog.setVisible(true); The problem with the last solution is that I can't get the return value. EDIT: in response to @camickr observations: Why do you need to set the preferred size? If you build the panel properly is should be displayed at its preferred size. I'm not sure of having fully understood Swing on this point. The problem is, for example, that I'm displaying through a JDialog a ChartPanel built with JFreeChart. Now, I suppose that panel has it's own preferred size, but I want to see it bigger. How can I do that without explicitly use setPreferredSize()? Read the JOptionPane API. Search for "Direct Use". It shows you how to directly access the dialog used by the option pane and you can I read it but I can't find the right method to understand which button (Ok or Cancel) has been pressed on the JDialog. A: This hack using a HierarchyListener to get access to the JOptionPane's also works: http://blogs.oracle.com/scblog/entry/tip_making_joptionpane_dialog_resizable // TIP: Make the JOptionPane resizable using the HierarchyListener pane.addHierarchyListener(new HierarchyListener() { public void hierarchyChanged(HierarchyEvent e) { Window window = SwingUtilities.getWindowAncestor(pane); if (window instanceof Dialog) { Dialog dialog = (Dialog)window; if (!dialog.isResizable()) { dialog.setResizable(true); } } } }); A: * *Why do you need to set the preferred size? If you build the panel properly is should be displayed at its preferred size. *Read the JOptionPane API. Search for "Direct Use". It shows you how to directly access the dialog used by the option pane and you can With you second approach why are you setting the size? Again just pack() the dialog and it will be displayed at the panels preferred size. What do you mean you can't get the return value? You have access to any method of your custom panel. So you can just invoke the getXXX() method when you receive control again. Just make sure the dialog is modal and the code after the setVisible(true) will block until the dialog is closed. A: If you want to go the second way completely, you have to create and position your own "YES" and "NO" buttons somewhere (since a raw JDialog is just an empty modable frame). Therefore, you need to attach a MouseListener to both buttons and handle click events. On a click, you will know what button was pressed, and you'll just have to call dispose() on the dialog to close it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621255", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Hadoop 0.20.2 reducer throws ArrayIndexOutOfBoundsException when iterating values I am fairly new to hadoop, however, I've been reading "Hadoop: The definitive guide", so I think I have an understanding of the basic concepts. I used Hadoop 0.20.2 to run a fairly simple job, but I get the following exception: java.lang.ArrayIndexOutOfBoundsException: 4096 at java.io.ByteArrayInputStream.read(ByteArrayInputStream.java:127) at java.io.DataInputStream.readInt(DataInputStream.java:373) at com.convertro.mapreduce.WritableHit.readFields(Unknown Source) at org.apache.hadoop.io.serializer.WritableSerialization$WritableDeseria lizer.deserialize(WritableSerialization.java:67) at org.apache.hadoop.io.serializer.WritableSerialization$WritableDeseria lizer.deserialize(WritableSerialization.java:40) at org.apache.hadoop.mapreduce.ReduceContext.nextKeyValue(ReduceContext. java:116) at org.apache.hadoop.mapreduce.ReduceContext$ValueIterator.next(ReduceCo ntext.java:163) at com.convertro.mapreduce.HitConvertingIterable$HitConvertingIterator.n ext(HitConvertingIterable.java:35) at com.convertro.mapreduce.HitConvertingIterable$HitConvertingIterator.n ext(HitConvertingIterable.java:1) at com.convertro.naive.NaiveHitReducer.reduce(Unknown Source) at com.convertro.mapreduce.HitReducer.reduce(Unknown Source) at com.convertro.mapreduce.HitReducer.reduce(Unknown Source) at org.apache.hadoop.mapreduce.Reducer.run(Reducer.java:176) at org.apache.hadoop.mapred.ReduceTask.runNewReducer(ReduceTask.java:566 ) at org.apache.hadoop.mapred.ReduceTask.run(ReduceTask.java:408) at org.apache.hadoop.mapred.LocalJobRunner$Job.run(LocalJobRunner.java:2 This happens during the reading of the WritableHit class (the input value to the reduce phase). Below is the WritableHit class code: public class WritableHit implements WritableComparable<WritableHit> { private Hit hit; public WritableHit() { this(null); } public WritableHit(Hit hit) { this.hit = hit; } @Override public void readFields(DataInput input) throws IOException { String clientName = input.readUTF(); String clientSiteId = input.readUTF(); String eventUniqueId = input.readUTF(); String eventValue = input.readUTF(); String pageRequested = input.readUTF(); String refererUrl = input.readUTF(); String uniqueHitId = input.readUTF(); String userAgent = input.readUTF(); String userIdentifier = input.readUTF(); String userIp = input.readUTF(); int timestamp = input.readInt(); int version = input.readInt(); hit = new Hit(version, uniqueHitId, clientName, clientSiteId, timestamp, userIdentifier, userIp, pageRequested, refererUrl, userAgent, eventUniqueId, eventValue); } @Override public void write(DataOutput output) throws IOException { output.writeUTF(hit.getClientName()); output.writeUTF(hit.getClientSiteId()); output.writeUTF(hit.getEventUniqueId()); output.writeUTF(hit.getEventValue()); output.writeUTF(hit.getPageRequested()); output.writeUTF(hit.getRefererUrl()); output.writeUTF(hit.getUniqueHitId()); output.writeUTF(hit.getUserAgent()); output.writeUTF(hit.getUserIdentifier()); output.writeUTF(hit.getUserIp()); output.write(hit.getTimestamp()); output.write(hit.getVersion()); } public Hit getHit() { return hit; } @Override public int compareTo(WritableHit o) { return hit.getUniqueHitId().compareTo(o.getHit().getUniqueHitId()); } } Any help would be much appreciated. Thanks A: I figured it out. Apparently, when you implement a Writable object, you should use the writeInt method, and not the write method. Once I did that, it worked like a charm.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621257", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Solution for Visual Studio shows message "Error while trying tu run project:" after un signing assemblies? a couple of days ago I signed my assemblies to test ClickOnce deployment. All worked fine until I cannot deserialize my old binary-serialized-files, so I had to revert the code-signing of the assemblies. That's ok, I will not use ClickOnce, it was just a test. The problem now is that Visual Studio shows the message "Error while trying to run project:" (whithout giving any more information about why that happens and with that very annoyig sound) when starting to debug. Then I must try again and the debug starts as usual unless, of course, you edit the code. Is there a solution for that appart from re-installing VS? Note: I tried deleting the .SUO file but the problem persists. A: Solved! The problem was that, after removing code signing (uncheck the signing options on the project properties), there was .pfx file remaining. Just deleting that .pfx file stops the "Error while trying to run project" message. A: Error comes because recently you might have un-installed Internet Browsers. This error will come Because of not assigning the default Browser for the project. In Visual Studio,Right click on the Project and set Internet Explorer as your Default Browser.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621258", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Move an image across a web page How can I move an image element across a page? As an example, Vimeo does this with an image of a cloud: http://www.vimeo.com/log_in A: They're just changing the position with JavaScript. You can do this yourself easily with jQuery .animate(). A: Place an absolutely-positioned image on your page with a style that looks like: style="position: fixed; top: 40%; right: 0px; Then, using a window timer, increase the right style attribute every 50 milliseconds. So 100 milliseconds in, the same style looks like this: style="position: fixed; top: 40%; right: 2px; You have to make sure the background of the cloud is transparent as well so that it can "float across" stuff that is "behind it" Here's the exact image they use: http://www.vimeo.com/assets/images/land_cloud.png You can't see anything because it's a white cloud with a transparent background. Use "Save As" on your browser to download it. A: The code: function cloud () { var cloud = new Element('img', { 'src':'/assets/images/land_cloud.png', 'styles': { 'position':'fixed', 'top':'40%', 'right':'40px' } }).inject(document.body); var cloud_style = (function () { var right = this.getStyle('right'); right = right.substr(0,right.indexOf('px')); this.setStyle('right', right.toInt()+1+'px'); }); cloud_style.periodical('100',cloud); } A: You could do it with css3 animation. Or you could do it with plain ol' Javascript: Call SetInterval( ) with an appropriate value for the interval; then, in the interval-timeout handler, change the x-origin of the cloud image to move the thing left or right. Set up the z-index of the cloud and the hill so that the cloud is hidden by the hill.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621259", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: protecting C++ code in program I realize this must be a somewhat naive question, but I have written C++ program for a client. He needs the program installed on his machine, but I don't want to give him the code obviously. How can I protect the code so he doesn't have access to the source code? any suggestions to help me get started would be appreciated. thanks! A: Compile the program, and give him the compiled version? Like most computer programs? Beyond that, I refer you to Protecting executable from reverse engineering? A: You don't have to give your customer the source code of your program. Generally speaking, he should only need the executable program. A: C++ is a compiled language. That means that after compilation, the compiler will generate a binary file which contains machine code - for example, a dll, a lib or an exe file under Windows. In windows, all you have to do is deliver the exe's and associated dll's, if they are not already present on the client's machine. There can be different versions of the binaries (depending on platforms, e.g. 32bit vs 64bit compilations) so you might have to run more compilations and let an installer utility handle the distribution.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621263", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }