text
stringlengths
8
267k
meta
dict
Q: PHP Echo function I'm using a comment script on this page im building. I want for eacht page the comments to say: "Reaction on (each page different name)". So I found the line what says this but it wont grab on to the echo function. This is the line: <H3>{$COM_LANG['header']}</H3> The header is the part of "Reaction on" and I want to echo behind the company name thats different for each page. I tried: <H3>{$COM_LANG['header']} $companyname; </H3> But it wont work... EDIT: Sorry if i'm not clear, maby its because i'm dutch and don't know hoe to explaine something in english. Here a piece of code where this is all about: <div id="usernotes"> <div class="head"> <H3>{$COM_LANG['header']} </H3> <br> </div> EOF; if ($comments_count) { for($i=0; $i<$comments_count; $i++) { if ($dont_show_email[$i] != '1' && $email != '') { $author[$i] = "<a href=\"mailto:{$email[$i]}\">{$author[$i]}</a>"; } $text[$i] = str_replace(chr(13), '<br />', $text[$i]); print<<<EOF <div class="note"> <strong>{$author[$i]}</strong><br /> <small>{$time[$i]}</small> <div class="text"> {$text[$i]} </div> </div> Thanks in advance! A: if <H3>{$COM_LANG['header']}</H3> does output what it's supposed to you can try either <H3>{$COM_LANG['header'] . $companyname}</H3> or <H3>{$COM_LANG['header']} . {$companyname}</H3> Anyway you'd make things easier to everybody showing the PHP code that transforms the above declaration into HTML: is there a template engine, maybe? A: The application might be using a templating language. This on looks like Latte. So you might want this: <H3>{$COM_LANG['header']} {$companyname} </H3>
{ "language": "en", "url": "https://stackoverflow.com/questions/7627834", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Input content into a DIV within an HTML file from a PHP file I'm not sure if this is even possible but if it is I imagine it would be via PHP (which I am a total beginner at). Basically I have an .html file with an empty DIV tag in it and I am hoping to get the content of that DIV tag, which is stored in a .php file, and put it into the DIV. To try and make this a bit clearer... HTML FILE <div id="content"> </div> and... CSS #content { position:relative; width:700px; max-height:550px; min-height:10px; overflow:auto; } #content h1 { font-family:"Kristen ITC"; font-size:20px; font-weight:bold; margin-top:20px; margin-bottom:0px; margin-left:70px; text-align:left; color:#000000; text-decoration:underline; } #content p { font-family:"Bradley Hand ITC"; font-size:22px; font-weight:bold; margin-top:0px; margin-bottom:0px; margin-left:90px; margin-right:130px; text-align:left; color:#000000; text-decoration:none; } And then, I am hoping to have this... <h1>- Chapter 1</h1> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus molestie orci at orci blandit consectetur dapibus elit sollicitudin. Donec diam libero, feugiat vitae egestas eget, pellentesque eget tellus.</p> <h1>- Chapter 2</h1> <p>Phasellus in libero at ligula tincidunt convallis et a libero. Ut elementum molestie enim, vitae consequat mi imperdiet in. Ut metus justo, pharetra vel convallis et, eleifend vitae est. Aenean fringilla tincidunt nunc ac gravida.</p> In a .php file, which I will then link to within the .html file, like this... HTML FILE <div id="content"> (Somehow link the .php. file here to get the <h1> and <p> stuff) </div> I hope this makes sense. I have currently tried (remember I'm a beginner so don't laugh if I'm just being stupid)... HTML FILE <div id="content"> $contents = file_get_contents('current.php'); </div> with the php file being... PHP FILE <?php // print output <h1>- Chapter 1</h1> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus molestie orci at orci blandit consectetur dapibus elit sollicitudin. Donec diam libero, feugiat vitae egestas eget, pellentesque eget tellus.</p> <h1>- Chapter 2</h1> <p>Phasellus in libero at ligula tincidunt convallis et a libero. Ut elementum molestie enim, vitae consequat mi imperdiet in. Ut metus justo, pharetra vel convallis et, eleifend vitae est. Aenean fringilla tincidunt nunc ac gravida.</p> ?> I have no idea what I'm doing, whether I'm relatively close to making this work, completely miles away from achieving it or if it's even possible. In a perfect world where I could just use the .html file and .css file, it would look like this example I made on jsfiddle Can anyone help me with this? A: You're including a file (not 1:1 copy'ing the contents of the file). Try: <div id="content"> <?php include('current.php'); ?> </div> This will strip <?php ... ?> tags, hope it helps. Documentation is available. A: Use this: HTML FILE <div id="content"> <?php echo file_get_contents('current.php'); ?> </div> Get rid of the <?php and ?> in your "php" file, which just contains plain HTML. If you want to add dynamic content, at the server's side, you have to contain PHP code within <?php and ?>. When you're defining plain HTML, do NOT use <?php, because <?php tells the interpreter to parse the contents between <?php and ?> as PHP code. A: you should use the file_get_contents('sourcefile.php') function which allows retrieve the source file content. If the source file includes code , you may use require() or include(). For further information read php.net manual.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627843", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Echo the results of query based on its index This is pretty basic but I can't seem to get it to work I have this query $people = "SELECT name FROM people"; $people = mysql_query($people) or die(mysql_error()); $row_people = mysql_fetch_assoc($people); $totalRows_people = mysql_num_rows($people); I can echo the first result of this query with <?php echo $row_people['name']; ?> I could also create a loop and echo all the results. But I really want to echo the results individually based on its index. I have tried this, but it does not work. <?php echo $row_people['name'][2]; ?> Thanks for your help. A: You can ORDER them by their index and then use a loop. $people = "SELECT name FROM people ORDER by index"; A: You can fetch them by their index using a WHERE clause. $people = sprintf("SELECT name FROM people WHERE index='%d'", $index); If you want to query all rows, you could store them into an array while looping over them: $people = "SELECT name FROM people"; $people = mysql_query($people) or die(mysql_error()); $totalRows_people = mysql_num_rows($people); $rows_people = array(); while($row_people = mysql_fetch_assoc($people)) { $rows_people[] = $row_people; } You might want to add the primary key to the returned fields and use it as the array index probably. A: You can use mysql_data_seek on the result object to seek to a particular row. E.g., to get the name value from row 2: mysql_data_seek($people, 2); $row_people = mysql_fetch_assoc($people); echo $row_people['name']; If you're doing this a lot it will be easier to gather all the rows together in a single array at the start: $data = array(); while ($row = mysql_fetch_assoc($people)) $data[] = $row; This way you can fetch any cells in the results trivially: echo $data[2]['name'];
{ "language": "en", "url": "https://stackoverflow.com/questions/7627844", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: shell scripting string replace using shell variables This is my very basic script: temp=hello while read line; do echo ${line} done However, ${line} will itself consist of "value of temp = ${temp}" I want my script to echo "value of temp is hello". I've tried doing many things, even echo `echo ${line}` but each time it always just prints "value of temp is ${temp}" I hope this question is clear. THanks! A: What about this? temp=hello while read line; do echo "Value of temp = `eval echo ${line}`" done Then in the console just type: ${temp} A: Well, I have solutions with eval, but using eval is mauvais ton, actually. $> cat 7627845.sh #!/bin/bash temp=hello cat file_with_values.log | while read line; do eval echo "${line}" done $> cat file_with_values.log value of temp = ${temp} $> ./7627845.sh value of temp = hello
{ "language": "en", "url": "https://stackoverflow.com/questions/7627845", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to update Ajax call (not content) Look at this code please - how could I kill / update or restart an ajax call (not content that Ajax calls) after the content has already been called? I mean the $('#posting_main') is called onclick and animated - how to stop ajax and make it another $('#posting_main') on another click? $(document).ready(function() { $("#img_x_ok").click(function(e){ e.preventDefault(); var post_text = $.trim($("#main_text_area").val()); var data_text = 'post_text='+ post_text; if (post_text === "") return; var xhr = $.ajax({ type: "POST", url: "comm_main_post.php", data: data_text, cache: false, success: function (data){ //content $("#posting_main").fadeIn(); $("#posting_main").load("pull_comm.php"); $("#main_text_area").attr("value", ""); $("#posting_main").animate({ marginTop: "+=130px", }, 1000 ); } }); //ajax close }); }); //both functions close A: You can abort the current request with: xhr.abort(); After having done that, you can run another $.ajax(...) to make a second request. You could implement it like the following. Note that indenting code makes it a lot more readable! $(document).ready(function() { var xhr; // by placing it outside the click handler, you don't create // a new xhr each time. Rather, you can access the previous xhr // and overwrite it this way $("#img_x_ok").click(function(e){ e.preventDefault(); var post_text = $.trim($("#main_text_area").val()); var data_text = 'post_text='+ post_text; if (post_text === "") return; if(xhr) xhr.abort(); // abort current xhr if there is one xhr = $.ajax({ type: "POST", url: "comm_main_post.php", data: data_text, cache: false, success: function (data){ //content $("#posting_main").fadeIn(); $("#posting_main").load("pull_comm.php"); $("#main_text_area").attr("value", ""); $("#posting_main").animate({ marginTop: "+=130px", }, 1000 ); } }); }); }); A: I am not sure I fully understand your question, however: * *xhr.abort() will kill the AJAX request. After calling abort(), you could modify and resend the request, if desired. *$("#posting_main").stop() will stop the fadeIn animation. (And I think you might need to follow that with $("#posting_main").hide() to be sure it isn't left partially visible.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7627846", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Data structure that supports the following in O(1) time: initialization, insertion, deletion, finding an element, deleting all elements Interview Question: Propose a data structure that holds elements from 0 to n − 1 and supports all of the following operations in O(1) time: initialization, insertion of an element, deletion of an element, finding an element, deleting all elements. A hash table (assume there are no collisions i.e the best case) would support insertion and search in O(1). I am not sure about deletion though...any ideas? A: Very interesting question! Assuming memory allocation and dealloaction is O(1), then an O(1) is possible for all. For this we use the trick by Hopcroft and Ullman which allows us to use arrays of size n, without having to spend Omega(n) time in actually initializing them. See here: http://eli.thegreenplace.net/2008/08/23/initializing-an-array-in-constant-time/ On insert, we just use the above array and set it to 1. On a search, if we find that the array element is not initialized, we return 0. On a delete, we set it to 0. On a delete all, we free the datastructure and use a new one. A: OK i think if the N is within rage you can just declare an array of N elements 0)Initialize memset(A,0,sizeof(A)) 1) Insert i A[i] = 1 2) Remove i A[i] = 0 3) Find i if( A[i] ) 4) Delete All memset(A,0,sizeof(A)) A: Hash Table can be O(1) for delete. List<Object> hashTableData = new ArrayList<Object>(); Edit: the code is a possible implementation of the data stored for the Hash Table. A: I was looking for solution to the same question! And I found a post where they achieved constant time complexity for insertion,deletion and search operations using hashing and maps. During insertion along with inserting element(key) store the index too as value of key. You can see here: https://www.geeksforgeeks.org/design-a-data-structure-that-supports-insert-delete-search-and-getrandom-in-constant-time/ https://www.geeksforgeeks.org/design-a-data-structure-that-supports-insert-delete-getrandom-in-o1-with-duplicates/ And also boolean array would do the same operations in O(1).
{ "language": "en", "url": "https://stackoverflow.com/questions/7627847", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Php associative array for offset from 1 to 26 I am trying to create an associative array with alphabets as keys and 1 to 26 as values which I need to use to find the offset of alphabet from 1. So array['a'] would give me 1 and array['c'] would give me 3. Is there a way to declare such an array without typing in all characters 1 by 1 as in array('a' => 1, 'b' =>2, 'c'=>3 .... and so on Or is there another way to get offset for alphabet from 1 to 26 A: You could do this using array_combine() and range(): array_combine(range('a', 'z'), range(1, 26)); A: No need to build the array, use like following - $index = ord($input_char) - ord('a') + 1; A: You can use chr and ord: chr(97); // a chr(122); // z ord('a'); // 97 ord('z'); // 122 arr = array(); for($i=1; $i<=26; ++$i) { arr(chr(96+$i)) = $i; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7627848", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Determine when caret reaches the end of input box I have found this question which provides a solution to compute the exact position of the caret in a text or input box. For my purposes, this is overkill. I only want to know when the caret is at the end of all the text of an input box. Is there an easy way to do that? A: In all modern browsers: //input refers to the text box if(input.value.length == input.selectionEnd){ //Caret at end. } The selectionEnd property of an input element equals the highest selection index. A: <script> input = document.getElementById('yourinputfieldsid'); if(input.selectionEnd == input.selectionStart && input.value.length == input.selectionEnd){ //your stuff } </script> This checks to see if the caret actually is at the end, and makes sure that it isn't only because of the selection that it shows an end value. A: You don't specify what you want to happen when some text is selected, so in that case my code just checks whether the end of the selection is at the end of the input. Here's a cross-browser function that wil work in IE < 9 (which other answers will not: IE only got selectionStart and selectionEnd in version 9). Live demo: http://jsfiddle.net/vkCpH/1/ Code: function isCaretAtTheEnd(el) { var valueLength = el.value.length; if (typeof el.selectionEnd == "number") { // Modern browsers return el.selectionEnd == valueLength; } else if (document.selection) { // IE < 9 var selRange = document.selection.createRange(); if (selRange && selRange.parentElement() == el) { // Create a working TextRange that lives only in the input var range = el.createTextRange(); range.moveToBookmark(selRange.getBookmark()); return range.moveEnd("character", valueLength) == 0; } } return false; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7627856", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Black Berry Hello World Program I am learning Black berry programming. I have written a program "Hello World" using the eclipse plug in for Black Berry. Then I want to run the program using the Black Simulator from Run As --> Black Berry Simulator. A blank window is appeared. I tried to Load .cob file, still it is not working. Can any body please help me. A: I think you didn't add the labelField (With helloworld text) in MainScreen. Otherwise, your labelfield foreground color is the same as screen color. Just try to override the pain() of the LabelField. eg:- labelField= new LabelField("HelloWorld") { protected void paint(Graphics graphics) { graphics.setColor(Color.RED); super.paint(graphics); }; }; Try this; I think this should help you. A: This is a very difficult question to answer correctly because there are many variables such as your OS, what exactly you mean by "blank window", the steps you may or may not have completed correctly in your tutorial. If you are using a Windows machine, instead of trying to install the eclipse plugin yourself it might be easier for you to download and run the pre-installed eclipse bundle provided by RIM. Next, I suggest you go back to the HelloWorld, tutorial, start from scratch. Double check each of your steps and take your time so you fully understand each of your steps. If you reach a part of the tutorial that you cannot complete then you should raise the exact part in this question. But also! (And this is one of the most important things you must learn to become a successful programmer like me) Do not assume people have knowledge of your setup, your coding, or any variable when you ask a question. Put yourself in the shoes of the person answering it and consider what they would need to know in order to do so. This is such a fundamental thing that it should perhaps even be part of every HelloWorld tutorial.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627867", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SnapsToDevicePixels option I am trying to style some tabs but I ran into this issue where the color of the border changes as I resize window. First of all, I used this http://blogs.intuidev.com/post/2010/01/25/TabControlStyling_PartOne.aspx to style the tabs if you're wondering about the code. Also, here is the pic of what's wrong. EDIT: <Color x:Key="BorderColor_Base">#888</Color> <Color x:Key="TabControl_BackgroundColor_Base">#CCC</Color> <SolidColorBrush x:Key="TabControl_BackgroundBrush_Base" Color="{StaticResource TabControl_BackgroundColor_Base}"/> <LinearGradientBrush x:Key="TabItemPanel_BackgroundBrush" StartPoint="0,0" EndPoint="0,1"> <LinearGradientBrush.GradientStops> <GradientStop Offset="0.98" Color="Transparent"/> <GradientStop Offset="0.99" Color="{StaticResource BorderColor_Base}"/> </LinearGradientBrush.GradientStops> </LinearGradientBrush> <SolidColorBrush x:Key="TabItem_BorderBrush_Selected" Color="{StaticResource BorderColor_Base}" /> <Style TargetType="{x:Type TabControl}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="TabControl"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="1*"/> <RowDefinition Height="10*"/> </Grid.RowDefinitions> <Border Background="{StaticResource TabItemPanel_BackgroundBrush}" Padding="{StaticResource TabItemPanel_Padding}"> <TabPanel Grid.Row="0" IsItemsHost="True"/> </Border> <ContentPresenter Grid.Row="1" ContentSource="SelectedContent"/> </Grid> </ControlTemplate> </Setter.Value> </Setter> </Style> <Style TargetType="{x:Type TabItem}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type TabItem}"> <Grid> <Border Name="Border" Background="{StaticResource TabControl_BackgroundBrush_Base}" BorderBrush="{StaticResource TabItem_BorderBrush_Selected}" Margin="{StaticResource TabItemMargin_Selected}" BorderThickness="2,1,1,1"> <!-- This is where the Content of the TabItem will be rendered. --> <Viewbox> <TextBlock x:Name="Header"> <ContentPresenter x:Name="ContentSite" ContentSource="Header" Margin="7,2,12,2" RecognizesAccessKey="True"/> </TextBlock> </Viewbox> </Border> </Grid> <ControlTemplate.Triggers> <Trigger Property="IsSelected" Value="False"> <Setter TargetName="Border" Property="Margin" Value="{StaticResource TabItemMargin_Base}" /> <Setter Property="Panel.ZIndex" Value="90" /> </Trigger> <Trigger Property="IsSelected" Value="True"> <Setter Property="Panel.ZIndex" Value="100" /> <Setter TargetName="Border" Property="BorderThickness" Value="2,1,1,0" /> <Setter TargetName="Border" Property="Background" Value="White" /> </Trigger> <Trigger Property="IsEnabled" Value="False"> <Setter TargetName="Header" Property="Background" Value="#CCC" /> <Setter TargetName="Header" Property="Foreground" Value="#888" /> <Setter Property="Panel.ZIndex" Value="80" /> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> A: Labas! Try to increase line's height, for instance set it to 5 or 10 pixels. If color is wrong again it means that you wrong styled TabControl. A: The issue is with this brush: <LinearGradientBrush x:Key="TabItemPanel_BackgroundBrush" StartPoint="0,0" EndPoint="0,1"> <LinearGradientBrush.GradientStops> <GradientStop Offset="0.98" Color="Transparent" /> <GradientStop Offset="0.99" Color="{StaticResource BorderColor_Base}" /> </LinearGradientBrush.GradientStops> </LinearGradientBrush> You are using a gradient from transparent to #888 as your background, so you are seeing one of the colors "in between" transparent and #888. Instead, you can use a Transparent background and border of #888, like so: <Style TargetType="{x:Type TabControl}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="TabControl"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="1*" /> <RowDefinition Height="10*" /> </Grid.RowDefinitions> <Border Grid.Row="0" Background="Transparent" BorderBrush="#888" BorderThickness="0,0,0,1" Padding="{StaticResource TabItemPanel_Padding}" SnapsToDevicePixels="True" /> <TabPanel Grid.Row="0" IsItemsHost="True" /> <ContentPresenter Grid.Row="1" ContentSource="SelectedContent" /> </Grid> </ControlTemplate> </Setter.Value> </Setter> </Style> You may need to tweak the Margin of the Border and/or the TabPanel to ensure they line up correctly though.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627868", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to draw a transparent circle? I'm trying to draw a transparent circle, but it just doesn't work. when I'm drawing a bitmap it works, but a circle doesn't become transparent. Here's my code in short: Paint paint = new Paint(); paint.setAlpha(125); canvas.drawBitmap(bitmap, sourceRect, destRect, paint); // this works fine canvas.drawCircle(x, y, radius, paint); // the circle is drawn but not transparent A: I found it. paint.setAlpha must come after paint.setColor
{ "language": "en", "url": "https://stackoverflow.com/questions/7627870", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: To view a result of mathematical action I'd like to show the text containing result of addition of two values: one from onespinner selected item, and another from twospinner selected item. But eclipse shows an error in line text.setText(onespinner.getSelectedItem + twospinner.getSelectedItem); What's the matter? Full code goes below. public class photographer extends Activity implements OnItemSelectedListener { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Spinner onespinner = (Spinner) findViewById(R.id.spinner1); ArrayAdapter<CharSequence> unitadapter = ArrayAdapter.createFromResource( this, R.array.onespinner, android.R.layout.simple_spinner_item); unitadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); onespinner.setAdapter(unitadapter); onespinner.setOnItemSelectedListener(this); Spinner twospinner = (Spinner) findViewById(R.id.spinner2); ArrayAdapter<CharSequence> courseadapter = ArrayAdapter.createFromResource( this, R.array.twospinner, android.R.layout.simple_spinner_item); courseadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); twospinner.setAdapter(courseadapter); twospinner.setOnItemSelectedListener(this); } @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { TextView text = (TextView)findViewById(R.id.result); text.setText(onespinner.getSelectedItem + twospinner.getSelectedItem); } @Override public void onNothingSelected(AdapterView<?> parent) { } } A: getSelectedItem is a method, but you are referencing it like an instance variable. You need to change your code to: text.setText(onespinner.getSelectedItem() + twospinner.getSelectedItem()); A: You haven't posted the exact error, but I'm guessing that your problem is that you are trying to make a reference to onespinner and twospinner in onItemSelected and those two objects are not in the scope of that function; they are declared in onCreate. Now, the View view argument of onItemSelected is the spinner that was clicked, but you need a reference to both spinners (not just the one that was selected). Easiest way to do this is to globally declare oneSpinner and twoSpinner and that should solve your problem. EDIT: Also what Ted Hopp said.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627874", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to abstract my business model using dbExpress and Delphi (maybe DataSnap as well)? If my question isn't clear, please help me improve it with comments. I'm new to Delphi and dbExpress and I'm just getting acquaintance with TSQLDataset, TDataSetProvider, TClientDataSet and TDataSource classes. The project that I'm working on uses this components in a way that feels strange to me. There is a huge data module unit that contains lots and lots of the quartet of classes previously described. I'm guessing that there are better (and more modularized) ways of doing this. DataSnap is used only to place this data module in a server application, so the clients access the data through it. So, let me try to explain some of my doubts: * *What is the role of each one of this classes? I read the documentation but I can't get a practical insight on this subject (specially about TDataSetProvider). *Which classes should be in the data module and which should be in my forms? *Is it possible to create an intermediate layer to abstract my business model from my database setup (maybe creating functions that return immutable datasets?)? *If so, is it wise to use DataSnap to do so? I'm sorry if I'm not clear enough. Thanks in advance. A: Components TDataSource is the bridge between data-aware controls and the dataset (TDataSet descendant) from which they are to get their values. TClientDataSet is one such dataset. TClientDataSet can be used in isolation, for example to access data contained in xml files, but can also be hooked up to a TDataSetProvider. TDataSetProvider is the bridge between the in-memory TClientDataSet and the actual dataset that takes its data from a database through some kind of driver. In Client Server development you will usually see a TRemoteDataSetProvider (name may be different, I don't work with these components that often), which bridges the gap between the client and server. TSQLDataSet is the actual dataset getting its data from some database. It would feel strange to me to see this quartet all in one executable. I would expect the TSQLDataSet on the server side hooked up to the TRemoteDataSetProvider's counter part. However, I guess that with an embedded database it could be a way to support the briefcase model, which is where TClientDataSet is really helpful (TClientDataset is very powerful, that is just one of its strong points.) Single datamodule Ouch. A single huge datamodule is lazy programming or the result of misconceptions about how to use datamodules. It is perfectly normal to have a single datamodule that "hosts" the database connection which is then used by various other datamodules that are more tightly focused on aspects of the application. Domain abstraction With regard to abstracting your business model, dbexpress and datasnap should really not be anywhere in your business model. They should be part of your data layer. TDataSource, TClientDataSet and custom TDataSetProvider descendant(s) can be used to leverage the power of the data-aware controls in the UI while still keeping the UI separate from the business model. In this case the custom TDataSetProvider would be the bridge between the client dataset and the collections and instances in the domain layer. Even so, I would still expect to see a separate data layer, using TRemoteDataSetProviders or straight TDataSet descendants (like TSQLDataSet) to provide the domain layer with its data. The single huge data module you mentioned could be part of that data layer, with the client datasets providing the business layer with its data. As you also mention TDataSource as part of a common quartet, the application was probably developed in a RAD-data-aware fashion where UI controls are basically hooked up straight to database columns/tables. If you want to transform this application to have a more layered architecture, tread carefully and slowly. Get to know the current architecture first and get to know it well enough to see the impact that this kind of transformation would have. The links provided by Serg will certainly help you there. Pawel Glowacki has written extensively about DataSnap. A: The project you are working on is a Delphi Multitier Database Application Your question is too wide for SO and hardly can be answered in its current form - you should learn to understand the underlying architecture. You can start from video tutorial by Pawel Glowacki: http://www.youtube.com/watch?v=B4uxLLIUddg http://cc.embarcadero.com/item/28188
{ "language": "en", "url": "https://stackoverflow.com/questions/7627876", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Disable the ':' character in Vim In my ~/.vimrc I have mapped ; to : so I don't have to press shift every time I want to enter a command and so I avoid typos like :W. I have mapped it using nnoremap ; :. My muscle memory is so strong however, is that I find myself frequently pressing : when I dont need to and I still get typos like :W. How can I disable the : character completely and just use ; in normal mode? A: nnoremap ; : nnoremap : <nop> would be considered fairly harmless. I don't need to point out that using this kind of setup will drive anyone trying to use your box nuts, and will render yourself crippled when at a random other UNIX console :)?...
{ "language": "en", "url": "https://stackoverflow.com/questions/7627877", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How do I get the text from a dynamically created textarea using Jquery? Ok so I have this: $('a[name=writecommentsmodal]').live('click',function(e) { e.preventDefault(); var date=new Date(); var currdate=date.getYear()+" "+date.getMonth+" "+date.getDate(); var comm=new addComment("",fullname,currdate,$ ***("#inputspace2").text()) ***; comm.appendComment($(".wallpostcontainer")); }); And I'm trying to get the text from inputspace2. inputspace2 is dynamically created when button is pushed (that button is 'a[name=writecommentsmodal]'). That button also happens to be dynamically created from a different button click (hence the use of live), but I digress. That inputspace2.text is empty when I click on the modal button. How do I access it? In firebug its "". I'm thinking maybe having to use live again but I'm no A: For text areas, use .val() instead of .text(). Using textContent, innerText, outerHTML or innerHTML on a textarea returns the contents of the text field as defined in the HTML. User's modifications of the content are only visible through the .value property.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627885", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why is this ajax post giving me an error? Does an ajax post require "true" or "false" to be returned? $.ajax({ url:"http://www.xxxxxxxxxxxxxx.com/cc/validate", type:"POST", dataType:"json", data: JSON.encode($parts), complete: function(){ }, success: function(n) { console.log(n); console.log(n.object); console.log("ajax complete"); }, error: function(){ console.log("error"); } }); * *This gets an array defined above the ajax post call and posts an encoded json array to a php file. The problem is determining why the post will only let me return "true" or "false". If i try to return any string, i get the error in the ajax. I want to be able to return a string created in the php and not only "true" or "false". A: are you on a local host? well if so you might have to change your mime headers (application/json) ... your javascript is expecting json but your php is echoing html. header('Content-type: application/json'); if you want to be able to return something else then json you have to delete or change the content type in your ajax call. the content type is for giving jquery a hint of what to expect from the server. if you tell it will receive json data you need to give it json or you'll have a parse error. A: your code is alright just make sure your php file return an echo json_encode($arrayOFdata) dataType:"json", means the data recived from php will be parsed as a json object it doesn't mean you will send a json object
{ "language": "en", "url": "https://stackoverflow.com/questions/7627894", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Right edge of divs not lining up when removing margin from middle columns When using the Blueprint CSS framework, I wanted to remove the margin between all columns. Unfortunately, when I remove these margins, any div that spans all columns now appears wider than the total combined width of the divs on those rows that have had margins removed. The effect is worse on those rows that have many columns. For those rows in which I'm using all 24 columns, I want the right edge of the divs to line up. Can this issue be resolved without resorting to a bunch of Blueprint hacks, or without manually resizing a container or something by just the right number of pixels to account for the missing margins? Code in Head: <style type="text/css"> .topnav{background-color:blue;} .logo{background-color:yellow;} .icons{background-color:orange;} .search{background-color:red;} </style> Code in Body: <div class="container"> <div class="span-24 first last top topnav">Top Nav</div> <div class="span-5 first logo">Logo</div> <div class="span-3 append-8 icons">Icons</div> <div class="span-8 last bottom search">Search</div> </div> A: If you really need to remove the margins between the columns (I doubt that's the case, but without more info I cannot provide more help) then the best thing would be to redo the entire grid. Here is a generator for blueprint, where you can specify all needed variables, including the gutter (margin between columns): http://ianli.com/blueprinter/
{ "language": "en", "url": "https://stackoverflow.com/questions/7627895", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Dumping a dynamic web page to file? I'm a C++ programmer and I'm new to web development. I need to figure out how I can log/dump the html of a dynamic 3rd party website to a static html file on my computer, every second? The dynamic webpage refreshes every second and updates a html table with latest price info. I would like a static snapshot of this table (or the whole html page) to be saved to disk every second. That way I can parse the file with my own program and add the updated price info to a database. How do I do this? If I cant do it this way, is there a way to eves drop (and log) on the the post/get messages and replies the dynamic webpage sends? A: Look into the cURL Library. I believe Scraping the content from a website, and doing your processing/business logic, then inserting or updating your database would be the most efficient way to do it, rather than saving the files contents to disk. Alternatively, file_get_contents() works pretty well assuming you have allow_url_fopen enabled. A: It would be easy to do with Selenium Webdriver. You can use Selenium to create a browser object with a method, getPageSource, that pulls the entire HTML from the page, but it doesn't seem there are any C++ bindings for Selenium. If it's convenient to use Ruby, Python, or Java as part of your application, just in order to open up a browser or headless browser and pull the data, then you should be able to set up a web service or a local file to transfer that data back into your C++ application. Web automation from C++ addresses the challenge of no Selenium C++ bindings Or, alternately you could write your own C++ bindings for Selenium (probably more difficult) However -- for simply pulling the HTML, you may not need Selenium if one of Dan's answers above will work. A: Hej someone else. insed of running there page every second to record there data so you can have a updated view of there prices, why not call there web service directly (the one there ajax call makes) Gl
{ "language": "en", "url": "https://stackoverflow.com/questions/7627901", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is Python ever supposed to crash? I am running a stand-alone Python v3.2.2/Tkinter program on Windows, not calling any external libraries. Idle has been very helpful in reporting exceptions, and the program has been debugged to the point where none are reported. However, the python interpreter does occasionally crash at non-deterministic times - operations will run fine for a while and then suddenly hang. The crash triggers the standard Windows non-responding process dialog asking if I want to send a crash dump to Microsoft: "pythonw.exe has encountered a problem and needs to close. We are sorry for the inconvenience." Crash reporting in Python says that the interpreter itself rarely crashes. My question is: no matter how many mistakes there are in a python script, is there any way it should in theory be able to crash the interpreter? Since there are no exceptions being reported and the crashes happen at random times, it's hard to narrow down. But if the interpreter is in theory supposed to be crash-proof, then something I'm doing is triggering a bug. The code (a scrolling strip-chart demonstration) is posted at What is the best real time plotting widget for wxPython?. It has 3 buttons - Run, Stop, Reset. To cause a crash just press the buttons in random order for a minute or so. With no interaction, the demo will run forever without crashing. A: Of course, the goal is for something like Python to never crash. Alas, we live in an imperfect world. A more useful question to ask, I think, is "What should I do if Python crashes?". If you want to help make a more perfect world, first make a quick search at the Python issue tracker to see if a similar problem has already been reported and possibly fixed in a newer or as yet unreleased version of Python. If not, see if you can find a way to reproduce the problem with clear directions about steps involved, what OS platform and version, what versions of Python and 3rd-party libraries, as applicable. Then open a new issue with all the details. Keep in mind that Python, like many open source projects, is an all-volunteer project so there can be no guarantee when or if the problem will be more deeply investigated or solved (most issues are resolved eventually) but you can be happy that you have done your part and likely saved someone (maybe many people) time and trouble. If you want other opinions before opening an issue, you could ask about it on the python-list mailing list/news group. A: Python isn't indeed 100% crash proof, especially when you using external libraries, which TkInter is. There is even page dedicated to it: http://wiki.python.org/moin/CrashingPython
{ "language": "en", "url": "https://stackoverflow.com/questions/7627903", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Graphviz .dot node ordering I'm building a epsilon NFA to recognize a regular expression using the canonical construction. I'm using subgraphs to group various parts of the regular expression. The * operator is giving me particular trouble since dot has decided to move the order of the nodes around. I've tried adding edge weights to force particular edges to be short to keep the order of the edges in line but that does not seem to be working. What I would like to do is force the nodes in a subgraph in to be placed in a particular order so that the output graph is recognizable as a particular type of (well known) construction. In the example below I would like edges 3, 4, 5 and 6 placed in that order, however the dot places them in the order 6, 3, 4, 5. Any pointers appreciated. Note that the current weight parameter produces no difference than no weight parameter at all. I have the following digraph G { rankdir = LR; node [shape = none]; 0 [label = "start"]; node [shape = circle]; 1 [label = "q1"]; 2 [label = "q2"]; 3 [label = "q3"]; 4 [label = "q4"]; 5 [label = "q5"]; node [shape = doublecircle]; 6 [label = "q6"]; subgraph re1 { rank = same; edge[label = "0"]; 1 -> 2; }; subgraph re2 { rank = same; edge[label = "&epsilon;"]; 3 -> 4 [weight = 10]; edge[label = "1"]; 4 -> 5 [weight = 10]; edge[label = "&epsilon;"]; 5 -> 6 [weight = 10]; 5 -> 4 [weight = 1]; 6 -> 3 [weight = 1]; }; edge[color=black]; 0 -> 1 edge[label = "&epsilon;"]; 2 -> 3; } A: Here's how I'd write that graph: * *First of all, to me this is a graph which goes from top to bottom, not left to right, therefore I removed the rankdir=LR and added rank=same only for nodes 0/1 and nodes 2/3. *I removed all the weights *Most importantly, I added constraint=false to the edges going against the direction of the graph - the one going from node 4 to node 5, and the one from node 6 to node 3. Here the source: digraph G { 0 [label = "start", shape = none]; node [shape = circle]; 1 [label = "q1"]; 2 [label = "q2"]; 3 [label = "q3"]; 4 [label = "q4"]; 5 [label = "q5"]; 6 [label = "q6", shape = doublecircle]; {rank = same; 0 -> 1; } 1 -> 2 [label = "0"]; {rank = same; 2 -> 3 [label = "&epsilon;"]; } 4 -> 5 [label = "1"]; edge [label = "&epsilon;"]; 3 -> 4; 5 -> 6; 5 -> 4 [constraint = false]; 6 -> 3 [constraint = false]; } And here's the result: Now if you want to, you could keep rankdir=LR, just take the markup you posted, remove the weights and add constraint=false to the same edges as I did, it works, too.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627904", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "32" }
Q: How to properly use jquery's tabs() function? In my Grails app, I've got a GSP that looks a bit like this: <div id="tabs"> <ul> <li><a href="#tabs-1">Nunc tincidunt</a></li> <li><a href="#tabs-2">Proin dolor</a></li> <li><a href="#tabs-3">Aenean lacinia</a></li> </ul> <div id="tabs-1"><p>foo</p></div> <div id="tabs-2"><p>bar</p></div> <div id="tabs-3"><p>zip</p></div> </div> <script type="text/javascript"> jQuery(document).ready(function() { jQuery("#tabs").tabs(); }); </script> If I've understood it right, the jQuery tabs() call should make my "tabs" div look like a tabbed panel. Is that correct? If so, it's not working. It just renders as a normal ul. Any ideas? A: if you have the scripts and not the CSS files, than you won't achieve anything. To get a bundle of jQueryUi framework along with the CSS files and scripts use themeroller: http://jqueryui.com/themeroller/ A: The tabs widget is part of jQuery UI, which is an extension of jQuery. You need to install jquery UI on your page. See http://learn.jquery.com/jquery-ui/getting-started to get you started with jQuery UI. A: I'd suggest just not bothering with the plugins for jQuery or jQueryUI. Instead just download the JS into your web-app/js folder. Then reference them using a traditional tag but also using the grails "resource" taglib, ala.... <script type="text/javascript" src="${resource(dir:'js',file:'jquery.js')}"></script> <script type="text/javascript" src="${resource(dir:'js',file:'jquery-ui.js')}"></script> <link rel="stylesheet" href="${resource(dir:'css',file:'jquery-ui.css')}" /> I like using plugins for many things, but for something as simple as a few JS libs, I just don't see enough value. There is a tiny bit of value in having the jQuery plugin as it provides a grails class that implements jQuery support for the 'remote*' taglibs (ala http://grails.org/doc/latest/ref/Tags/submitToRemote.html), but I never use this anyways since I favor using jQuery directly. A: Ok, thanks for the help everyone. Here's what finally worked: I obtained the jquery and jquery-ui distros and unzipped them directly into my web-app folders. I used the following tags: <g:javascript library="jquery-1.6.2.min"/> <g:javascript library="jquery-ui-1.8.16.custom.min"/> <link rel="stylesheet" href="${resource(dir:'css/smoothness',file:'jquery-ui-1.8.16.custom.css')}" /> Note that I had forgotten to link to the appropriate css. Turns out it's a bit quirky to get right. A: In ApplicationResources.groovy: modules = { application { resource url:'js/application.js' } jqueryui { resource url:'js/jquery-ui-1.10.2.custom.min.js' } } In your gsp file, simply add this in the head: <script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <r:require module="jqueryui" /> <script> $(document).ready(function() { $("#tabs").tabs(); }); </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/7627905", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: AppDelegate may not respond to 'delegate' I'm getting the error 'MillersAppAppDelegate' may not respond to 'delegate'. I'm still learning all of this but don't understand entirely because I've read that this generally happens when a method isn't declared in the header file. I'm using XCode 4. Here's the part of the code I'm looking at: #import <UIKit/UIKit.h> @interface MainViewController : UIViewController { } -(IBAction) contactButtonClick:(id)sender; @end And here's the .m file: #import "MainViewController.h" #import "MillersAppAppDelegate.h" #import "ContactViewController.h" @implementation MainViewController -(IBAction) contactButtonClick:(id)sender{ MillersAppAppDelegate *delegate = [(MillersAppAppDelegate *)[UIApplication sharedApplication] delegate]; <---this line gets the warning "'MillersAppAppDelegate' may not respond to 'delegate'" ContactViewController *contactView = [[ContactViewController alloc]initWithNibName:@"ContactViewController" bundle:nil]; [delegate switchViews:self.view toView:contactView.view]; } The program runs fine but I've got several other actions that come up with the same warnings (all dealing with view switches). Thanks for the help, I'm sure it's an easy answer but I'm still a beginner. This may also be an issue between XCode3 and XCode 4? A: Try (MillersAppAppDelegate *)[[UIApplication sharedApplication] delegate]; instead :) You want to cast the [[UIApplication sharedApplication] delegate] to MillersAppAppDelegate. You accidentally casted sharedApplication itself to MillersAppAppDelegate
{ "language": "en", "url": "https://stackoverflow.com/questions/7627906", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to combine 2 iOS navigation-based apps? I currently have two navigation-based apps, call them MainApp and SecondApp. I'd like to put the SecondApp within the MainApp. Both apps compiled and ran on my computer. However, when I copy the SecondApp's class files into the MainApp it won't compile. Is there a more elegant way of doing this, or at least a way that actually works? They error I'm getting is: "The run destination My Mac 64-bit is not valid for RUnning the scheme..." Which is weird because BOTH apps ran on my computer prior to their merging. EDIT: problem solved by created a new scheme (Product > New Scheme...). A: You're trying to Use Mac OS as the target. You should select an iOS version in the schemes drop down instead. This sometimes happens to me, and seems to be a bug in XCode 4. If the option isn't in the schemes dropdown, see this link for how to fix it: Xcode 4: My iPhone projects have become Mac OS projects.. and I can't change this
{ "language": "en", "url": "https://stackoverflow.com/questions/7627907", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Target all p elements that follow an h2 with CSS How can I target all p elements that follow a heading e.g.... <h2 class = 'history'>History</h2> <p>this is paragraph 1</p> <p>this is paragraph 2</p> <p>this is paragraph 3</p> <h2 class = 'present'>Present</h2> <p>I don't want to target this paragraph</p> <p>I don't want to target this paragraph</p> <p>I don't want to target this paragraph</p> by using .history + p I can target paragraph 1, but how to target the other paragraphs until I get to the 'Present' H2 tag? A: If there aren't any other p elements, you can use ~ instead of +: .history ~ p If there are any more p elements that come after your second h2, and you only want to select those between h2.history and h2.present, I don't think it's possible with current CSS selectors. The general sibling selector ~ matches every p sibling that comes after your h2, regardless of whether there are any other siblings among them. That said, you can easily accomplish it using jQuery: $('.history').nextUntil('.present')
{ "language": "en", "url": "https://stackoverflow.com/questions/7627910", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: using PopUpManager in a Flex 4.5 Mobile App This is more of a best practices question rater than something technical. I'm working on a mobile app using the Flex 4.5 SDK and I'm trying to figure out the best way to handle notification windows. In most cases these windows will be alerting the user to when something goes wrong. Ex: bad login, no data, cannot resolve server. I'm using a singleton design pattern, I have a Requests class that handles server calls. Most popups will be originating from this class (IOErrorEvents from my loader being used to access the API). Since this class is a singleton and is used from all Views inside the app it is not aware of applications current view. I'm also not sure having this class keep track of the current view and having it push popups on top of it would be best practice. I'm hoping that I can use PopUpManager to keep track of where to add popups and what popups are currently on the stage. Though all examples I've seen online about this show static Components being used in a views Declarations tag. I'm really just looking for any examples or input on how you would solve this problem. Any help would be greatly appreciated! A: I had the same problem, and sorted it by making an Alert popup component that you can call from anywhere in the code base, and it will pop up in the currently active window. It also has an always visible scrollbar text area which is handy http://bbishop.org/blog/?p=502 It works for a view navigator application, but if your using a tabbed navigator application, you can add a call for that, or simply change the code to mainTabbedNavigator = FlexGlobals.topLevelApplication.tabbedNavigator; currentTab = mainTabbedNavigator.selectedNavigator as ViewNavigator;
{ "language": "en", "url": "https://stackoverflow.com/questions/7627917", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Android Camera.takePicture() does not return some times? I am writing an application for android to take pictures. The code does some processing after getting a frame from preview in onPreviewFrame(byte[] data, Camera camera). The problem is with function takePicture() of android.hardware.Camera that sometimes do exactly what I want and sometimes does not return and no callbacks will be called. When I run the app some times taking the first picture does not return and some times I can take four pictures and the fifth will cause app to hang. There is a simillar thread: problem with taking pictures using the android camera. The suggested solution is to use the frame from last preview but surely it is not a good solution! This problem may raise because takePicture is Asancronous (Android Doc). I simply call the takePicture() function like this: public static void takePicture() { mCamera.takePicture(null, null, jpegCallback); } Here is the link to Logcat output. You can search in the output with phrase "takePicture" and you will see that this function sometimes return and sometimes does not return. This is the output for when takePicture return: 10-02 19:24:36.570: INFO/ShotSingle(3198): ShotSingle::takePicture start 10-02 19:24:36.570: DEBUG/CameraHal(3198): 2489: takePicture() ENTER 10-02 19:24:36.570: DEBUG/MessageQueue(3198): MQ.put(5,0xb6590,0x0,0x8,0x80b0af55) 10-02 19:24:36.570: DEBUG/MessageQueue(3198): MessageQueue::put EXIT 10-02 19:24:36.578: DEBUG/MessageQueue(3198): MQ.get(5,0xb6590,0x0,0x8,0x80b0af55) 10-02 19:24:36.578: DEBUG/CameraHal(3198): 1458: CameraStop() ENTER 10-02 19:24:36.617: DEBUG/CameraHal(3198): 1543: CameraStop() EXIT 10-02 19:24:36.617: DEBUG/MessageQueue(3198): MQ.put(14,0xb6590,0x0,0x8,0x80b0af55) 10-02 19:24:36.617: DEBUG/MessageQueue(3198): MQ.get(14,0xb6590,0x0,0x8,0x80b0af55) 10-02 19:24:36.617: DEBUG/CameraHal(3198): 2497: takePicture() EXIT 10-02 19:24:36.617: INFO/ShotSingle(3198): ShotSingle::takePicture end and this is the output for when takePicture does not return: 10-02 19:25:20.671: INFO/ShotSingle(3198): ShotSingle::takePicture start 10-02 19:25:20.671: DEBUG/CameraHal(3198): 2489: takePicture() ENTER 10-02 19:25:20.671: DEBUG/MessageQueue(3198): MQ.put(5,0xb8cb8,0x0,0x8,0x80b0af55) 10-02 19:25:20.671: DEBUG/MessageQueue(3198): MessageQueue::put EXIT 10-02 19:25:21.343: INFO/StatusBarPolicy(3393): onSignalStrengthsChanged 10-02 19:25:22.609: WARN/PowerManagerService(3330): Timer 0x7->0x3|0x7 10-02 19:25:23.062: INFO/AudioStreamOutALSA(3198): (virtual android::status_t android::AudioStreamOutALSA::standby()) enter 10-02 19:25:23.125: ERROR/AudioStreamOutALSA(3198): Output standby called!!. Turn off PCM device. 10-02 19:25:23.125: INFO/ALSAStreamOps(3198): [ALSAStreamOps]codecOff mode = 0 10-02 19:25:23.234: INFO/AudioStreamOutALSA(3198): [AudioOutLock]Relase_wake_Lock Does anyone have any explanation or solution for this problem? A: It seems that the problem is due to insufficient memory. I solved it by adding System.gc() just before calling takePicture(). System.gc(); CameraParameters.mCamera.takePicture(null, null, jpegCallback); A: Please see this. If you are using a preview callback you might solve the problem by removing it before taking the picture. mCamera.setPreviewCallback(null); mCamera.takePicture(null, null, mPictureCallback);
{ "language": "en", "url": "https://stackoverflow.com/questions/7627921", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: "unknown option: --output" after updating Android SDK from revision 12 to revision 13 I've just updated my android development tools to revision 13. This all went smoothly and I can continue to build in eclipse as usual. However once I try to de a release build with ant my build fails with the message "unknown option: --output". Further Info: I'm running 32bit Eclipse / Java on 64 bit windows. The issue occurs only when running a build from the command line and the build worked before I updated the sdk from revision 12 to 13. Here is the relevant output from "ant release" [proguard] Printing classes to [C:\Work\bugsy_workspace\bugsy\bin\proguard\dump.txt]... -dex: [echo] Converting compiled files and external libraries into C:\Work\bugsy_workspace\bugsy\bin\classes.dex... [apply] unknown option: --output [apply] usage: [apply] dx --dex [--debug] [--verbose] [--positions=<style>] [--no-locals] [apply] [--no-optimize] [--statistics] [--[no-]optimize-list=<file>] [--no-strict] [apply] [--keep-classes] [--output=<file>] [--dump-to=<file>] [--dump-width=<n>] [apply] [--dump-method=<name>[*]] [--verbose-dump] [--no-files] [--core-library] [apply] [--num-threads=<n>] [<file>.class | <file>.{zip,jar,apk} | <directory>] ... [apply] Convert a set of classfiles into a dex file, optionally embedded in a [apply] jar/zip. Output name must end with one of: .dex .jar .zip .apk. Positions [apply] options: none, important, lines. [apply] dx --annotool --annotation=<class> [--element=<element types>] [apply] [--print=<print types>] [apply] dx --dump [--debug] [--strict] [--bytes] [--optimize] [apply] [--basic-blocks | --rop-blocks | --ssa-blocks | --dot] [--ssa-step=<step>] [apply] [--width=<n>] [<file>.class | <file>.txt] ... [apply] Dump classfiles, or transformations thereof, in a human-oriented format. [apply] dx --junit [-wait] <TestClass> [apply] Run the indicated unit test. [apply] dx -J<option> ... <arguments, in one of the above forms> [apply] Pass VM-specific options to the virtual machine that runs dx. [apply] dx --version [apply] Print the version of this tool (1.6). [apply] dx --help [apply] Print this message. BUILD FAILED C:\PROGRA~2\Android\android-sdk\tools\ant\main_rules.xml:487: The following error occurred while executing this line: C:\PROGRA~2\Android\android-sdk\tools\ant\main_rules.xml:203: apply returned: 1 Total time: 12 seconds A: I've managed to get to the bottom of this myself. Android SDK Tools Revision 13 requires Android SDK Platform-tools revision 7. There are some instructions on how to get & install platform-tools 7 here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627922", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Removing redundant data from mysql I have a table in sql which looks like: 1 1w10 U UROK_HUMAN IIGGEFTTIENQPWFAAIYRRHRGGSVTYVCGGSLISPCWVISATHCFID... 2 1w11 U UROK_HUMAN IIGGEFTTIENQPWFAAIYRRHRGGSVTYVCGGSLISPCWVISATHCFID... 3 1w12 U UROK_HUMAN IIGGEFTTIENQPWFAAIYRRHRGGSVTYVCGGSLISPCWVISATHCFID... 4 1w13 U UROK_HUMAN IIGGEFTTIENQPWFAAIYRRHRGGSVTYVCGGSLISPCWVISATHCFID... 5 1w14 U UROK_HUMAN IIGGEFTTIENQPWFAAIYRRHRGGSVTYVCGGSLISPCWVISATHCFID... 6 1w15 A SYT4_RAT GSPGISGGGGGIPSGRGELLVSLCYQSTTNTLTVVVLKARHLPKSDVSGL... 7 1w16 A SYT4_RAT GSPGISGGGGGIPSGRGELLVSLCYQSTTNTLTVVVLKARHLPKSDVSGL... 8 1w17 B PDAA_BACSU MKWMCSICCAAVLLAGGAAQAEAVPNEPINWGFKRSVNHQPPDAGKQLNS... 10 1w18 B SACB_ACEDI AGVPGFPLPSIHTQQAYDPQSDFTARWTRADALQIKAHSDATVAAGQNSL... 12 1w18 E SACB_ACEDI MKGGAGVPDLPSLDASGVRLAIVASSWHGKICDALLDGARKVAAGCGLDD... I want to remove duplicate entries but leaving one of them. For instance, I want to keep the first row but remove 2,3,4,5. In short, I want to remove rows which have same column 4 value (here, UROK-HUMAN) but have different col2 and col3 values( here 1w10, 1w11 etc (col2) and U,A,B(col3)). However, I do not want to remove entry have same col2 and col3 (1w18 B-E) which have same col4 value(SACB-ACEDI). How can I write and sql statement to delete those rows? I tried to write like and did not work: SELECT pdb, chain, unp, sekans, COUNT(*) AS ct FROM protein JOIN (SELECT DISTINCT(unp) FROM protein GROUP by pdb) protein2 ON protein2.unp = protein.unp; Thank you very much for your help. A: Consider the alternative route instead: selecting those unique rows and inserting them into a temp table, then drop the old one and rename the new one. This circumvents the limitations on deleting from a table you select on, and it makes it far easier to test wether the results are correct. INSERT INTO newtable SELECT min(pdb), chain, unp, sekans FROM protein GROUP by chain, unp, sekans Note that if you have other columns that could have a different value in different rows (like the pdb), you should use an aggregate function (like min, max, sum, group_concat), or else the value that mysql will use for the new row will be undefined. A: I'm not writing it for you but I'll tell how to do that. First write a SELECT query that would return all the IDs (I guess it is the first column, right?) you want to delete. Then write a DELETE statement that would delete all of the rows with those IDs. Something like: DELETE from protein where pdb in (SELECT pdb from protein #here_goes_the_query_im_not_writing#) So, in short, you first get all the IDs you want to delete and then you tell the DBMs to delete those IDs. That's all. EDIT: Just adding a possible SQL to get all the duplicated rows but one. Not tested. SELECT pdb FROM protein WHERE pdb not in ( SELECT pdb FROM ( SELECT sekans, pdb FROM protein GROUP BY sekans) as T);
{ "language": "en", "url": "https://stackoverflow.com/questions/7627925", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Program to tell what scripts are running in a browser? Is there a program that tells me the script that a browser executes for a particular event? for example, what script clicking on a button initiates? A: Visual Event bookmarklet enables you to see DOM0 event bound to individual elements. (source: myopera.com) Webkit's WebInspector has EventListener inspector module.. but it often crashes Chrome, when you try to use it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627926", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How could C++ compile when there is an undefined function inside source? Ok this might be a weird question.. Here's the thing, in the overloaded operator=, I used a clear() helper; But for some reason what I actually implemented was clear(Node *curr) instead of clear(), so there is no function named clear() in the entire source code. However this just compiles fine. My question is why? It didn't even throw me a warning :| Thanks in advance A: It could be a compiler error, but what's more likely is that you simply forgot that you implemented such a function or the compiler has found one in a surprising place. If you have an IDE, you can attempt to use tools like Go To Definition and Go To Declaration to attempt to find the definition of the function you called. A: I see two possibilities: * *your compiler is not linking the operator= method in your app because it is never used, so any missing functions called by it do not matter *if operator= is used and it works, then you made a mistake, there is a clear() method defined. Just verify where the code goes with a source code debugger. A: Easy: It found a version of clear() that it can link too. Just because you don't see it means nothing. It compiled correctly because: * *There is a header file with a function declaration of clear() *You are linking against a library with the implementation of the function. Plain and simple. If it compiled it is there.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627930", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-4" }
Q: rating for the business from the Google Places API I am new to this but i need some examples or tutorial to start with. have to create a web page that takes information about a business (name, address, web address, etc.) and then gets the average review rating for the business from the Google Places API. This project must be built on the Asp.Net MVC version 3, using .Net 4.0. Any links or help is greatly appreciated. I am going through these links.. http://googlegeodevelopers.blogspot.com/2011/05/places-everybody-show-is-about-to-begin.html http://code.google.com/apis/maps/documentation/places/ A: Check out http://www.asp.net/mvc for some great tutorials. It looks like you are on the right track for Google Places API. EDIT: In response to your comment, it looks Google has a JavaScript API for accessing Google Maps / Places. Please see this link for more information. What you would have to do is include the proper .js files into the web pages that need them. Also here they have samples of using the places js API (scroll to the bottom). Since the data is exposed via Json through an http request, you could also use HttpWebRequest, and parse the data your self.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627931", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to tag a certain changeset in Git? I am trying to find out how to tag a changeset that occurred earlier in the history. I am doing this as a feature part of a program, so, I can't do checkout and then tag, because the working copy may not be clean, and I dare not to modify the stash either because it may already contain something. A: See the man: git tag <tagname> <commit> A: Just use: git tag tag_name commit_hash More on tags: Git tags in the Git Community Book.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627933", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: calculate a number without a variable in javascript Given this code: if(ipadmenuheight < contentheight).css('top', '' + contentheight + 44 + 'px'); Let's say contentheight=500 then this code snippet returns 50044px. How can it be a sum instead and return 544px? Do I need to use a variable or can I do this inline? A: Use a parenthesis to sum both numbers. If not, they will be appended as strings: ...css('top', (contentheight + 44) + 'px'); By the way, the first empty string '' is not needed, so you could also do: ...css('top', contentheight + 44 + 'px'); A: Use parentheses to force numerical addition: ('top', '' + (contentheight + 44) + 'px'); or just take off the leading string. ('top', contentheight + 44 + 'px'); A: Try if(ipadmenuheight < contentheight).css('top', '' + (contentheight + 44) + 'px'); or eventually if(ipadmenuheight < contentheight).css('top', '' + (parseInt(contentheight, 10) + 44) + 'px'); if contentheight is a string.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627937", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android: Creating a persistent event listener I am trying to figure out how to implement an event listener (unsure if this is the proper term.) I want the service, once my app is launched, to listen for the phones power status. I am uncertain to as how android handles this situation so don't really know what to search for. I've been working with this code that uses a broadcast receiver: BroadcastReceiver receiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { unregisterReceiver(this); int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1); if (plugged == BatteryManager.BATTERY_PLUGGED_AC) { // on AC power Toast.makeText(getApplicationContext(), "AC POWER", Toast.LENGTH_LONG).show(); } else if (plugged == BatteryManager.BATTERY_PLUGGED_USB) { // on USB power Toast.makeText(getApplicationContext(), "USB POWER", Toast.LENGTH_LONG).show(); startActivity(alarmClockIntent); } else if (plugged == 0) { Toast.makeText(getApplicationContext(), "On Battery", Toast.LENGTH_LONG).show(); } else { // intent didnt include extra info } } }; IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); registerReceiver(receiver, filter); The code works fine. When I open my app it will toast what the current status of the phone power is. Here is what I am trying to do: * *When the user launches the app, it is effectively turning on the service *The user can go about using the phone, but once it is plugged in, my service will catch that and use the code above How do I adapt this code to achieve the objectives above? A: You could keep the listener on for the battery status by removing the line unregisterReceiver(this); This way, the app will continue to listen to power status change in the background even though that the app is not running in the foreground. Note that at some point, you might still want to unregister your receiver. You probably want to allow the user to control that via settings. One other note, your code contains starting activity in the receiver in below code: else if (plugged == BatteryManager.BATTERY_PLUGGED_USB) { // on USB power Toast.makeText(getApplicationContext(), "USB POWER", Toast.LENGTH_LONG).show(); startActivity(alarmClockIntent); } If your activity is in the background then it can't start another activity. See this SO Question - how to start activity when the main activity is running in background?, the accepted answer has suggestion on how to handle situation that requires starting activity from the background
{ "language": "en", "url": "https://stackoverflow.com/questions/7627946", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP E-Mail Form w/Options I need to include the first code (which calls the e-mail from a WordPress options panel) in the second code where it says [email protected]. I tried to include " around the code, but it doesn't seem to work. I also tried to strip slashes, but to no avail. How I call the e-mail <?php echo get_option('to_email'); ?> The relevant part of my contact form: if(!isset($hasError)) { $emailTo = '[email protected]'; $subject = 'Contact Form Submission from '.$name; $sendCopy = trim($_POST['sendCopy']); $body = "Name: $name \n\nEmail: $email \n\nComments: $comments"; $headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email; mail($emailTo, $subject, $body, $headers); A: $emailTo = get_option('to_email'); You have to make sure the right files are included (wordpress config files).
{ "language": "en", "url": "https://stackoverflow.com/questions/7627953", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Wordpress jQuery fadeIn, fadeOut not working When I transfer my static HTML into a WP theme, my fadeIn effect stopped working on navigation buttons for a gallery. They no longer fadeIn/Out, but just pop up instantly. here the code: jQuery(document).ready(function($) { $("#showcase-nav").hide(); $("#showcase").hover(function() { $("#showcase-nav").fadeIn("slow"); }, function() { $("#showcase-nav").delay(800).fadeOut("slow"); } ); html: <div id="showcase-wrapper"> <div id="showcase"> <div id="showcase-items"> <a href="/portfolio/" title="Simona & Sebi - Wedding invitation design" class="active"><img src="/media/selected-simona-sebi.png" alt="Selected work - Simona & Sebi - Wedding invitation design" /></a> <a href="/portfolio/" title="TEMISZ anniversary kit - Visual identity"><img src="/media/selected-temisz-anniversary-kit.png" alt="Selected work - TEMISZ anniversary kit - Visual identity" /></a> <a href="/portfolio/" title="STMF - Visual identity"><img src="/media/selected-stmf-visual-identity.png" alt="Selected work - STMF - Visual identity" /></a> <a href="/portfolio/" title="TEMISZ - Website design and development"><img src="/media/selected-temisz-website.png" alt="Selected work - TEMISZ - Website design and development" /></a> </div> <div id="showcase-nav"> <a href="#" class="goleft">Previous</a> <a href="#" class="goright">Next</a> </div> </div> </div> <!-- END #showcase --> P.S.: I am using noConflict
{ "language": "en", "url": "https://stackoverflow.com/questions/7627957", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: python range weird behavior I need to check a variable, called status, of an object in python. What I am doing is the known: if p.status() in range(21,30): where p is my object. I need to check if this status is between -21 and -29, but it only works if I write the range in positive numbers instead of negative. When I wrote: if p.status() in range(-30,-21): it didn't return anything. (Of course I printed the status of this object and I am sure that this condition exist). Some ideas??? Thanks A: Forget range. Chained comparison operators are much more readable. if -29 <= p.status() <= -21: By the way, the stop argument of range is never included in the return value, so for -21 to -29 inlusive, you'd want range(-29,-20). A: You could subtract the value from 0 which would produce a positive value which would be in the range: if 0 - p.status() in range(21,30):
{ "language": "en", "url": "https://stackoverflow.com/questions/7627964", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Error, Retrieving a web page with data in Python 3 I have written a very basic Python 3 function to retrieve a web page with some data but I am getting an error message: import urllib.parse import urllib.request def fetch_web (url, par1,par2="",par3=""): values = {"s":"stor","l":"SVEENG"} data = urllib.parse.urlencode(values) req = urllib.request.Request(url,data) response = urllib.request.urlopen(req) page = response.read() url = "http://wwww.ord.se" fetch_web(url,"stor") When executing this program I am getting following error message: TypeError: POST data should be bytes or an iterable of bytes. It cannot be str. Any ideas about the misstake? A: You should learn about Bytes vs Characters in Python 3. And them use byte strings like: b'...' for data you post to a website.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627967", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Can we use step in GDB without breakpoints? First, thank you for all the helps so far. In Visual Studio, we can do Debug -> Step In without setting any breakpoints. In GDB, it seems like we HAVE to use breakpoints. int main () { int a = 10; int b = 111; return 0; } My goal is to find the addresses of each variable (say int a, int b). I want to know the values before and after the assignment of a and b. If we compile and run gdb on this source code, the program will terminate, and we don't have a way to trace the stack. So is there a way to step one single statement at a time in GDB like we do in VS? Thanks. (no breakpoint, cannot use cout....no watchers..) A: Yes, you can step in with step (s) command. First you start the program (as opposed to using run), so it would stop at the beginning. A: You can put a breakpoint in main and then step line by line using next. VS does that implicitly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627971", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Return Django Models for Template Rendering after an Ajax Request I would like to create an AJAX-based search for my webpage. So far I am able to send the form data and make the appropriate call to my Django model. What I am having a hard time with is just sending the Queryset back and having it rendered using the Django templating system. Your help/advice is greatly appreciated. Here is the code I am working with. views.py if request.is_ajax(): if request.method == 'POST': format = 'json' mimetype = 'application/json' try: q = request.POST['obj'] o = Object.objects.filter(name__icontains=q) return render_to_response( 'project_view_objects.html', {'username': request.user.username, 'results':o}) view.html <script> $(document).ready(function(){ $("#search_form").submit(function(event) { event.preventDefault(); $.ajax({ type: "POST", url: "/objects/search/", data: $(this).serialize(), processData: false, dataType: "json" }); });}); </script> <article> <blockquote> <form class="create_form" id="search_form"> <p> <input id="objectSearchNameInput" type="text" name="obj" value="Object name"> <input type="submit" value="search objects"> </p> </form> </blockquote> </article> <br /> {% if results %} <blockquote> <aside class="column"> {% for object in results %} <b><a href="#" class="extra-text-special">{{ object.name }}</a></b><br /> {% endfor %} </aside> <aside class="column"> {% for object in results %} <font class="extra-text-nospecial">{{ object.created_when }}</font><br /> {% endfor %} </aside> </blockquote> {% else %} <p>haha</p> {% endif %} At the moment, all I see displayed on the page is 'haha'. A: The thing you're missing is that the template has already been rendered by the time the AJAX is fired - as of course it must be, because templates are server-side and javascript is client-side. So the thing to do is to get your Ajax views not to return JSON, but rendered templates, which your Javascript callback then inserts into the template. A: this is the final answer python if request.is_ajax(): if request.method == 'POST': format = 'json' mimetype = 'application/json' try: q = request.POST['obj'] #message = {"object_name": "hey, you made it"} o = Object.objects.filter(name__icontains=q) except: message = {"object_name": "didn't make it"} #m = str(q['id']) #json = simplejson.dumps(message) #data = serializers.serialize(format, o) #return HttpResponse(data, mimetype) html = render_to_string( 'results.html', { 'username': request.user.username, 'objects': o } ) res = {'html': html} return HttpResponse( simplejson.dumps(res), mimetype ) html <script> $(document).ready(function(){ $("#search_form").submit(function(event) { event.preventDefault(); $.ajax({ type: "POST", url: "/objects/search/", data: $(this).serialize(), processData: false, dataType: "json", success: function( data ){ $( '#results' ).html( data.html ); } }); });}); </script> . . . <article> <blockquote> <form class="create_form" id="search_form"> <p> <input id="objectSearchNameInput" type="text" name="obj" value="Object name"> <input type="submit" value="search objects"> </p> </form> </blockquote> </article> <br /> <aside id="results"> </aside> A: My solution was using Dajax, creating small fragment templates for for instance rendering a list. Then render them in the Dajax functions, and write them in the document with the appropriate javascript calls. You can see an example on (and actually all the documentation of dajax is quite good): http://www.dajaxproject.com/pagination/ Another solution which I recently found (but have not tried myself) is: http://www.jperla.com/blog/post/write-bug-free-javascript-with-pebbles Lastly you might go totally the other way and use Backbone.js, but in that way you (more or less) end up with the same problem, how to share backbone templates with django templates (I think you should be able to write a template tag, which dependant on the 'mode' writes either a value, or a backbone template tag, thus allowing you to reuse your templates)
{ "language": "en", "url": "https://stackoverflow.com/questions/7627978", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Short program hangs in C Every time this code runs in UNIX, it hangs and displays a new line without a prompt. It compiles without error. Anyone know what's up here? /* This program uses a Monte Carlo simulation to maximize widget profits. */ #include <stdio.h> #include <stdlib.h> // constant values used in the simulation #define MIN_WIDGETS 1000 // minimum widgets per month #define MAX_WIDGETS 1500 // maximum widgets per month #define MIN_COST 0.25 // minimum cost per widget #define MAX_COST 0.82 // maximum cost per widget #define MIN_CONVERSION 0.01 // minimum converstion rate #define MAX_CONVERSION 0.05 // maximum converstion rate #define MIN_PROFIT 38 // minimum profit per sale #define MAX_PROFIT 43 // maximum profit per sale #define FIXED_OVERHEAD 400 // fixed overhead cost #define NUM_SIMULATIONS 100 // number of simulations performed void main() { // to keep track of inputs in highest-profit simulation int bestW = 0; // widgets per month float bestC = 0; // cost per widget float bestR = 0; // rate of converstion float bestP = 0; // profit per sale float bestProfit = 0; // highest profit srand(time(0)); // initialize the random number generator float h = FIXED_OVERHEAD; int i; // loop index for(i = 0; i < NUM_SIMULATIONS; i++) { // initialize inputs for this individual simulation int w = 0; // quantity of widgets bought float c = 0; // cost of a widget float r = 0; // conversion rate float p = 0; // profit per sale float profit = 0; // profit // simulate quantity of widgets bought per month, between MIN_WIDGETS and MAX_WIDGETS w = random() % (MAX_WIDGETS + 1); // to set the maximum value of w at MAX_WIDGETS while (w < MIN_WIDGETS) { w = random() % (MAX_WIDGETS + 1); // fetch new random number that may fit parameters } // simulate cost per widget, between MIN_COST and MAX_COST c = random() % 100; // to convert random number into an integer between 0 and 99 while (c < (MIN_COST*100) || c > (MAX_COST*100)) { c = random() % 100; // fetch new random number that may fit parameters } c = c / 100.0; // convert cost back from cents into dollars // simulate conversion rate, between MIN_CONVERSION and MAX_CONVERSION r = random() % 100; // to convert random number into an integer between 0 and 99 while (r < (MIN_CONVERSION*100) || r > (MAX_CONVERSION*100)) { r = random() % 100; // fetch new random number that may fit parameters } r = r / 10.0; // convert back into fraction // simulate profit per sale, between MIN_PROFIT and MAX_PROFIT p = random() % ((MAX_PROFIT + 1)*100); // to convert random number into an integer between 0 and 4300 while (p < MIN_PROFIT*100) { p = random() % (MAX_PROFIT + 1); // fetch new random number that may fit parameters } p = p / 100.0; // convert back into floating point with two decimal places after period profit = (w * r * p) - (h + c * w); printf("Current profit is $%.2f, with %d widgets at a %.2f cost per widget with a %.1f conversion rate and %.2f profit/sale.\n", profit, w, c, r, p); if (profit > bestProfit) { bestW = w; bestC = c; bestR = r; bestP = p; bestProfit = profit; } } printf("Maximum profit is $%.2f, with %d widgets at a %.2f cost per widget with a %.1f conversion rate and %.2f profit/sale.\n", bestProfit, bestW, bestC, bestR, bestP); } A: I think the error is here: while (p < MIN_PROFIT*100) { p = random() % (MAX_PROFIT + 1); // fetch new random number that may fit parameters } If the loop body is entered p will be set to a number between 0 and MAX_PROFIT (= 43). It will never be greater than or equal to MIN_PROFIT*100 (= 3800), so it will go into an infinite loop. As a side-note, you might want to consider using do { } while loops here instead of using a while loop and writing the loop body twice. Writing code twice is an excellent way to make errors, because when you change one of the implementations you always have to remember to change the other. If you forget to update both you will introduce a bug. And that seems to be what happened here. A: Hard to tell from that wall of code, but it is either taking longer than you think it should or one of your many while statements is incorrect. You could replace the while statements and speed the whole thing up by getting a random number between 0 and the difference between your various min and max parameters, then adding that to the min parameter, instead of what you are doing at the moment which is getting a random number up to the value of your max parameter, then trying again if is below your min. In the case of your widgets, for example, you are throwing away 2/3 of your results.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627979", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is the correct mysql (relational) database design structure for I have a table in my database called Resource. This has common information about a resource (a resource could be an article, a static web link, a YouTube video, or any number of other types). For my example: Table: resource primary key - id, column - type, column - title, column - description, column - created_on, column - updated_on Table: resource_video primary key - id, column - youtube_id (spose this could be the primary key, but not relevant in the question). column - ... Table: resource_weblink primary key - id, column - url column - ... So essentially the resource table contains the generic (pertains to all resources), columns, and then tables are set up to hold resource_type specific data. What is the best (normalized) way to create relationships between resource and resource_type. My first instinct is that it should be a one to one identifying relationship between the two tables with a foreign key of resource_id in the resource_video and resource_weblink tables, or would there be a better way to handle this situation? A: I'd make the primary key of each resource_* table have a foreign key constraint to the id column of resource. There's no need for a separate id for each resource subtype. See this thread for an example of how to do this (look at the SupportSystem hierarchy in the accepted answer).
{ "language": "en", "url": "https://stackoverflow.com/questions/7627980", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: joomla how to access menu alias from a document I have several menus that lead to the same page, but I need the page to do different things depending on the link that was clicked. (eg. site.com/monday, site.com/tuesday) How do I access a menu alias form a document with PHP in joomla 1.7? Any help is appreciated. Thanks. A: In the header code of your index.php file, use the following code to grab the active menu item <?php $menu = &JSite::getMenu(); $active = $menu->getActive(); ?> Later, use this to print the alias as need be <?php print $active->alias; ?> For example <body class="<?php print $active->alias; ?>"> A: Each menu item has a Itemid, it's the ID of the item, you can see it on its details on administrator panel). Tou can get and test it in PHP this way: $Itemid = JRequest::getInt("Itemid", 0); switch ($Itemid) { case 437: // some code for item 437... break; case 438: // some code for item 438... break; } A: it has been a while since I worked with Joomla, but I remember being able to control what was displayed on a page using the menu buttons So when you set up a module, you can specify which links must display it and which must not. So you can have multiple links to the same page but control what is displayed there via the links. Sorry I'm very rusty on Joomla so I can't remember the exact terminology. Hope this helps, Cheers
{ "language": "en", "url": "https://stackoverflow.com/questions/7627983", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Going back to code while debugging in eclipse From the createSecureConnection method in my code , i came to exception block catch (Exception ex) { ex.printStackTrace(); } Please tell me is it possible to go back to the createSecureConnection from the catch block ?? please see the scren shot here . http://imageupload.org/?d=8E567A951 A: you could add a finally block and call it again. but should happen if it fails again? EDIT: the finally block is always executed, also if the first call was successful. I'm not sure if this is a good approach, but if you want to do it like this, you have to simply use boolean flag like this: boolean success = false; try{ .... urlc = createSecureConnection(urlString); success = true; } catch() { ... } finally { if(!success) try{ createSecureConnection(urlString); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7627985", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Return a downloadable file link given a string with Django Given a URL string which points to a file on my local nginx instance, how do I make Django return a response that causes the file to be downloaded from nginx? I don't want Django to be opening up the file and streaming it. A: Use the X-Accel-Redirect header: http://wiki.nginx.org/XSendfile For example: resp = HttpResponse() resp['X-Accel-Redirect'] = "/static/my_file" return resp Note that, as per the documentation, you'll need to translate the local path into a URL which nginx can serve.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627987", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Partial match from string array I've got a string array that looks like this: string[] userFile = new string[] { "JohnDoe/23521/1", "JaneDoe/35232/4", ... }; I'm trying the following but this will only return exact matches. I want to be able to return a match if I am searching for "23521". var stringToCheck = "23521"; if (userFile.Any(s => stringToCheck.Contains(s))) { // ... A: Your Contains() call should be the other way round: if (userFile.Any(s => s.Contains(stringToCheck))) You want to check whether any string s in your userFile string array contains stringToCheck. A: if (userFile.Any(s => s.Contains(stringToCheck))) A: You want to check if the string in the array contains the check string, not the other way around: userFile.Any(s => s.Contains(stringToCheck)) A: The following seems like a better choice: if (userFile.Any(s => s.Contains(stringToCheck)))
{ "language": "en", "url": "https://stackoverflow.com/questions/7627988", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Trying to remove a specific character from a string I'm trying to write a quick function to remove underscore characters char yytext[25] = {"IDEN_T3FY_ER"}; char removeUnderscore[9]; int i, j = 0; printf("Before: %s\n", yytext); for (i = 0; i < strlen(yytext); i++){ if (j == 8) break; if (yytext[i] != '_') removeUnderscore[j++] = yytext[i]; } removeUnderscore[++j] = '\0'; printf("\nAfter: %s", removeUnderscore); However when printing, it will get the first 8 characters correct and append a garbage '8' value at the end, instead of the newline character. Can anyone explain why? Or perhaps offer an easier way of doing so? A: You are incrementing your index variable j before writing the null character to terminate the string. Try: removeUnderscore[j] = '\0'; instead. You also say there should be a newline character at the end but you've never written a newline character to the output string. A: its overstepping the size of removeUnderscore. that last line is actually setting 9 and not index 8. A: removeUnderscore[j++] = yytext[i]; ... removeUnderscore[++j] = '\0'; In ++j j is incremented before being used, and in j++ j is incremented after being used.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627989", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Wordpress wp_list_pages highlight current page I using this: <ul> <?php wp_list_pages("&post_type=projects&child_of=$parent_page&title_li="); ?> </ul> To get that: <ul> <li class="page_item page-item-588"><a href="#" title="One">One</a></li> <li class="page_item page-item-592"><a href="#" title="Two">Two</a></li> <li class="page_item page-item-599"><a href="#" title="Three">Three</a></li> </ul> First code should display list of child pages. Everything is fine, But i faced with some problem. If i used custom post type (like projects in example), Wordpress 3.2.1 can't add "current" class to <LI> and i can't highlight random opened current page. functions.php add_action( 'init', 'register_cpt_projects' ); function register_cpt_projects() { $labels = array( 'name' => _x( 'Проекты', 'projects' ), 'singular_name' => _x( 'Проект', 'projects' ), 'add_new' => _x( 'Добавить', 'projects' ), 'add_new_item' => _x( 'Добавить проект', 'projects' ), 'edit_item' => _x( 'Изменить', 'projects' ), 'new_item' => _x( 'Новый Проект', 'projects' ), 'view_item' => _x( 'Просмотреть', 'projects' ), 'search_items' => _x( 'Поиск проектов', 'projects' ), 'not_found' => _x( 'Ничего не найдено', 'projects' ), 'not_found_in_trash' => _x( 'Ничего не найдень в корзине', 'projects' ), 'parent_item_colon' => _x( 'Родительский Проект:', 'projects' ), 'menu_name' => _x( 'Проекты', 'projects' ), ); $args = array( 'labels' => $labels, 'hierarchical' => true, 'supports' => array( 'title', 'editor', 'thumbnail', 'custom-fields', 'post-formats', 'page-attributes' ), 'public' => true, 'show_ui' => true, 'show_in_menu' => true, 'menu_position' => 5, 'show_in_nav_menus' => true, 'publicly_queryable' => true, 'exclude_from_search' => false, 'has_archive' => false, 'query_var' => true, 'can_export' => true, 'rewrite' => true, 'capability_type' => 'page' ); register_post_type( 'projects', $args ); }; variable $parent_page: // get_top_parent_page_id function get_top_parent_page_id($id) { global $post; if ($post->ancestors) { return end($post->ancestors); } else { return $post->ID; } }; Please Help! A: wp_list_pages() will compare the current page to menu items and add class "current_page_item" to the li containing link to current page. All you need to do is add li.current_page_item{ /*your specific mark up here */ } to your style.css file in the theme folder. No need to modify functions.php Source: http://codex.wordpress.org/Template_Tags/wp_list_pages#Markup_and_styling_of_page_items A: I think the best way will be to consider using wp_nav_menu instead of wp_list_pages - it is much more flexible solution and can do what you want. You'll have to sync the menu with the list of your pages, but it can be done automatically using actions. A: in functions.php add this add_filter('nav_menu_css_class', 'current_type_nav_class', 10, 2 ); function current_type_nav_class($classes, $item) { $post_type = get_post_type(); if ($item->attr_title != '' && $item->attr_title == $post_type) { array_push($classes, 'current-menu-item'); }; return $classes; } Source: https://wordpress.stackexchange.com/a/12292/11610 A: Solve it with no pain and just body class :) In functions.php: function get_id_outside_loop() { global $wp_query; $thePostID = $wp_query->post->ID; return $thePostID; } In header.php: <body class="<?php echo get_id_outside_loop(); ?>"> In <head> sections or in footer.php: <STYLE> <!-- body.<?php echo get_id_outside_loop(); ?> .project_pages ul li.page-item-<?php echo get_id_outside_loop(); ?> { background: #0096f4; /* Highlight */ } --> </STYLE> Have a nice day! A: You need to add this to your functions.php: function kct_page_css_class( $css_class, $page, $depth, $args, $current_page ) { if ( !isset($args['post_type']) || !is_singular($args['post_type']) ) return $css_class; global $post; $current_page = $post->ID; $_current_page = $post; _get_post_ancestors($_current_page); if ( isset($_current_page->ancestors) && in_array($page->ID, (array) $_current_page->ancestors) ) $css_class[] = 'current_page_ancestor'; if ( $page->ID == $current_page ) $css_class[] = 'current_page_item'; elseif ( $_current_page && $page->ID == $_current_page->post_parent ) $css_class[] = 'current_page_parent'; return $css_class; } add_filter( 'page_css_class', 'kct_page_css_class', 10, 5 ); Via http://kucrut.org/wp_list_pages-for-custom-post-types/
{ "language": "en", "url": "https://stackoverflow.com/questions/7627990", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Custom collections and mutability in Coffeescript I'm reading about CoffeeScript and am still trying to position the language, what can be done, what are the best practices, etc; I'm more used to strongly typed languages (AS3, Java, Scala) so my two questions may make you smile a bit :) Question 1: Custom collections What do you think about custom collections ? JS/CS is one of the weakest languages in this aspect; For instance there is no Array.remove and you have to use the cumbersome splice() method instead. Some function libraries (Like underscore) augment the API by providing functions taking arrays/objects as the first arg but given the choice I would prefer to write: list fancyFunction 3, 4 rather than fancyFunction list 3, 4 Let's say I create a List class; Is it possible and if yes, what are the requisites for this class to be able to use CS's comprehension syntax ? Worst case scenario, I guess the List could have a toArray() method and the usual CS operations could be performed on that returned value instead, but I hope there is a better solution. Ideally, I would like to be able to define rich, custom collections, but not at the cost of losing comprehensions, etc. Question 2: Mutability What are people feelings about being very careful with mutability in CS/JS in general ? When I read various code online, I have the impression everything is mutable and people generally think it's better not to bother and have less lines of code instead. For instance, mutable versus immutable basic Point class: (Hopefully I'm not doing something wrong) Mutable class Point constructor: (@x, @y) -> Immutable class Point constructor: (x, y) -> @x = -> x @y = -> y Not that much more complicated but slightly weirder syntax. Another consideration is that JS is not the fastest thing known to man and having to create lots of objects in a loop just for the sake of being a purist might be counter productive, performance wise. I didn't benchmark the cost of creating new Point objects versus altering the members of one though. Imagine a big app with lots of modules communicating through thin APIs. Wouldn't you want to pass immutable objects around ? Or do you perform defensive copies instead ? Note: I am not trying to try and bend CS to the languages I know; Rather I want to know if it makes sense to reuse some of the concepts taken for granted in other languages. Thanks A: I think the short answer to this is that JavaScript is versatile, but it's unsafe. There are no static types, and nothing is immutable (except, as in your example, by being isolated in a different scope). Some people try to fight this looseness—Google, for example, heavily annotates their code, JavaDoc-style. But mainstream JavaScript programmers don't. They rarely hide instance variables behind getters, or throw an exceptions when you call their API with a string when they expected a boolean. That's partly for practical reasons—JS is the only language I know of where people commonly talk about their code's byte size—but it also reflects the language's surrounding culture, where documentation and tests are valued far above hand-holding. So, in short, I'd stick with constructor: (@x, @y) -> and write some good tests. You can't protect against every possible misuse of your API, after all. Better to make its proper usage clear through good docs and tests. By the way, Underscore does provide an alternate syntax that lets you write your code in the desired order: _(list).remove ... Or you can extend the [Array] prototype. See Sugar.js for some fine examples.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627992", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Android monthly reminder application i am creating an application where one needs to stored recurring reminders in the database. i have stored the reminder record in the database where user mentions on what day of every month he will have to perform his task in a table named alert. now i want some service which can remind user every month about this task on the day set by the user. i have looked into alarm manager and other options but can not figure out some concrete way. can some one help me out here? every thing is done. i am stuck on this last hurdle. my application launch is stuck because of this one pending task. can any one help? thanks a lot, Navraj singh A: A very good example for your application visit http://www.vogella.de/articles/AndroidServices/article.html public void startAlert(View view) { EditText text = (EditText) findViewById(R.id.time);// In this text box //you will give the time in seconds you can change it according to your //need.Like getting this text from database as you need. int i = Integer.parseInt(text.getText().toString()); Intent intent = new Intent(this, MyBroadcastReceiver.class); PendingIntent pendingIntent = PendingIntent.getBroadcast( this.getApplicationContext(), 234324243, intent, 0); AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (i * 1000), pendingIntent); Toast.makeText(this, "Alarm set in " + i + " seconds", Toast.LENGTH_LONG).show(); } Above function start the alarm after the given time. Here s the Broadcast receiver class public class MyBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Toast.makeText(context, "Don't panik but your time is up!!!!.", Toast.LENGTH_LONG).show(); // Vibrate the mobile phone Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE); vibrator.vibrate(2000); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7627997", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Node.js log4j-like logging system Could you recommend me a good log4j-like logging system for node.js? A: It's not a log4j port, but Winston offers some similar functionality. https://github.com/indexzero/winston A: LIGHEWEIGHT SOLUTION I have looked through many loggers, and I wasn't able to find a lightweight solution - so I decided to make a simple solution that is posted on github. * *Saves the file *Gives you a pretty output (we all love that) *Easy to use I hope this helps you out. SETUP https://github.com/bluejamesbond/Scribe.js PS: If there are any problems, I would appreciate it if you can fix it and then do a pull request. Otherwise, you are more than welcome to post as an issue. A: I think Winston is really good, however since you mentioned log4j you might be interested in the node port: node-log4js A: You can also try looking at https://www.npmjs.org/package/bunyan Its output is JSON format and can have different stream for output like stoud, log file along with option to number of files to maintain before rotate/recycle similar to Log4j. As per the documentation on npm, it is also used by Joyent in the production. A: I have had some success with log4js-node (or just log4js for short). I was even able to use watchr to stalk (watch) the log4js configuration file, and set logging levels without rebooting my .js code in my angular middleware. One tricky suggestion that isn't obvious in the docs, here is how you can handle the call back for the shutdown/reboot for hot conf changes within the 'update' switch from the watchr listener. console.log('shutting down log4js'); log4js.shutdown((err) => { if (err!=undefined) { console.log('shutting down log4js msg: ' + err); } }); console.log('rebooting log4js'); log4js.configure('./myconfigfile.json'); logger = log4js.getLogger(); A: To all do not use "log4j" library. Use the original one which is log4js. log4j is a duplicate of the original and it`s a hacked mode. For more information check those articles: https://www.theguardian.com/technology/2021/dec/10/software-flaw-most-critical-vulnerability-log-4-shell https://www.esecurityplanet.com/threats/apache-log4j-zero-day-puts-servers-at-risk/ https://www.huntress.com/blog/rapid-response-critical-rce-vulnerability-is-affecting-java
{ "language": "en", "url": "https://stackoverflow.com/questions/7627998", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: Print time stamp in kernel I'm newbie to Linux kernel. Is there a way to print from within kernel time stamp, which respects timezone and DST, as done in user space (e.g. by localtime(3))? I suspect TZ and DST live in user space land only and not relevant in context of kernel space, but I'm required to print user friendly message from kernel module. Thanks A: You are correct in that TZ and DST live only in userspace. The kernel never knows what time zone it is. If you really need to do this, you will need to have a userspace helper upload timezone offsets to kernelspace - remember to deal with daylight savings time properly here! Alternately have a userspace tool postprocess kernel messages (which would be in UTC) and convert them to local time.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628001", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How does UIEdgeInsetsMake work? I'm making an app where I use UIEdgeInsetsMake for resizableImageWithCapInsets, but I don't understand how does it works exactly, UIEdgeInsetsMake has 4 arguments: * *Top *Left *Bottom *Right But they're floats so I don't know how to set that to an image, thanks! :D A: According to the documentation: You use this method to add cap insets to an image or to change the existing cap insets of an image. In both cases, you get back a new image and the original image remains untouched. During scaling or resizing of the image, areas covered by a cap are not scaled or resized. Instead, the pixel area not covered by the cap in each direction is tiled, left-to-right and top-to-bottom, to resize the image. This technique is often used to create variable-width buttons, which retain the same rounded corners but whose center region grows or shrinks as needed. For best performance, use a tiled area that is a 1x1 pixel area in size. So you only need to use the amount of pixels you want to make unstretchable in the values of the UIEdgeInsetsMake function. Say you have an image of 21x50 points (21x50 pixels in standard definition, 42x100 pixels in Retina "@2x" definition) and want this image to be horizontally stretchable, keeping the 10 points on the left and on the right untouched when stretching the image, but only stretch the 1-point-wide band in the middle. Then you will use UIEdgeInsetsMake(0,10,0,10). Don't bother that they are floats (that's useful for subpixelling resizing for example, but in practice you will probably only use integers (or floats with no decimal parts) Be careful, this is an iOS5+ only method, not available prior iOS5. If you use pre-iOS5 SDK, use stretchableImageWithLeftCapWidth:topCapHeight: instead. [EDIT] Some tip I use since some time, as I never remember in which order the fields of the UIEdgeInsets structure are — and in which order we are supposed to pass the arguments to UIEdgeInsetsMake function — I prefer using the "designated inits" syntax like this: UIEdgeInsets insets = { .left = 50, .right = 50, .top = 10, .bottom = 10 }; Or when an explicit cast is needed: UIImage* rzImg = [image resizableImageWithCapInsets:(UIEdgeInsets){ .left = 50, .right = 50, .top = 10, .bottom = 10 }]; I find it more readable, especially to be sure we don't mix the different borders/directions! A: I just go through this article which cleared all my concept regarding UIEdgeInsetsMake iOS: How To Make A Stretchable Button With UIEdgeInsetsMake A: But they're floats so I don't know how to set that to an image This is a UIImage instance method. So, the way you use resizableImageWithCapInsets to create in an image is to start by sending that message to an image (a UIImage). Cool new feature: note that if the edge insets are all zero, the image will be tiled. This works as a background to anything that accepts a background image. It even works in a UIImageView.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628004", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "60" }
Q: spring context.refresh() and concurrent access I am planning to use spring as a configuration service for our enterprise application. This part has been well documented in spring reference guide and other blogs. Basically using a property file and a context:property-placeholder I plan to instantiate & populate values on a bean which is in turn used by the application. There are occasions when the property file is changed and in that event I want the bean to reflect the changed values. I understand that ApplicationContext.refresh() is the way to refresh the bean and its configuration values. ApplicationContext.refresh() worked like a charm. <context:property-override location="file:///d:/work/nano-coder/quickhacks/src/main/resources/myproperties.properties"/> <bean id="myconfig" class="org.nanocoder.quickhacks.config.MyPropertyBean"> <property name="cacheSize" value="${registry.ehcache.size}"/> <property name="httpHostName" value="${url.httpHostName}"/> <property name="httpsHostName" value="${url.httpsHostName}"/> <property name="imageServers"> <list> <value>${url.imageserver1}</value> <value>${url.imageserver2}</value> <value>${url.imageserver3}</value> </list> </property> </bean> However when the context is being refreshed, I found that concurrent calls to ApplicationContext.getBean() or any getter operation on bean potentially fails due to IllegalStateException or BeanCreationException. value = context.getBean("myconfig", MyPropertyBean.class).getHttpHostName(); Questions * *is it possible that the calls to context.refresh() don't impact other concurrent calls *if context.refresh() can disrupt concurrent access to the application context are there any strategies in place to avoid this from happening. Your pointers will be greatly appreciated. A: What you can do is create some wrapper around your config service and instead of refreshing existing context create a new one. When the new one is ready, start using this instead of the old one. I'm not sure whether this is the best choice for config management but the code could look like this (later on one could at least introduce an interface with no spring dependency): class MyConfig { private ApplicationContext context; public ApplicationContext getContext() { return context; } public void refresh() { context = new FileSystemXmlApplicationContext(..) } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7628008", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: JSLint with multiple files JSLint works fine for just one JavaScript file. Recently, I've started breaking my program into several pieces. I don't want to be stringing the pieces each time I use JSLint to check my code. What is the standard solution to deal with multiples files with JSLint? A: There is a version of JSLint (node-JSLint) (command line) that allows you to check multiple files at once. Follow link for download at GitHub: https://github.com/reid/node-jslint The following examples of calling via the command line: JSLint app.js JSLint lib / lib worker.js / server.js # Multiple files JSLint - white - onevar - regexp app.js JSLint # All options supported JSLint - bitwise false app.js # Defaults to true, but You Can Specify false JSLint - goodparts - # undef false app.js The Good Parts, except undef JSLint-gp app.js # Shorthand for - goodparts:-gp find . -name "*.js" -print0 | xargs -0 jslint # JSLint JSLint your Entire Project Note: This application was developed to NodeJS. A: You can run JSLint against HTML files, not just against JavaScript files (which makes sense, because of the <SCRIPT> tag). And JSLint is smart about external scripts - if it can locate them, it will load them as part of the processing. So try something like this: <html> <head> <script src="file1.js"></script> <script src="file2.js"></script> ... <script>mainRoutine();</script> </head> </html> Run JSLint on that, instead of on each of your files. A: The command line app JavaScript Lint (http://www.javascriptlint.com/) works with multiple files and can recurse directories. E.g. %JSLPATH%\jsl.exe +recurse -process src\scripts\*.js A: What's wrong with just running the command? jslint . will check all js files in the current directory and recurse down the tree. A: You can also have a look here: https://github.com/mikewest/jslint-utils It should work with either Rhino or NodeJS. You can also pass multiple files for checking. NB: if you have a command line script which doesn't take multiple files as arguments, you can always do something like: ls public/javascripts/**/*.js | jslint A: If you don't need a running count of errors, open terminal (in OS X) and paste this: for i in $(find . -iname "*.js"); do jshint $i; done A: (This Is taken from this link and formatted) Rhino is a Javascript engine that is written entirely in Java. It can be used to run JSLint from the command line on systems with Java interpreters. The file jslint.js can be run by Rhino. It will read a JavaScript program from a file. If there are no problems, it terminates quietly. If there is a problem, it outputs a message. The WSH edition of JSLint does not produce a Function Report. One way to run JSLint is with this command: C:\> java org.mozilla.javascript.tools.shell.Main jslint.js myprogram.js It runs java which loads and runs Rhino which loads and runs jslint.js, which will read the file myprogram.js and report an error if found. Download jslint.js.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628009", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "26" }
Q: validate Regular Expression using Java I need validate a String using a Regular Expression, the String must be like "createRobot(x,y)", where x and y are digits. I have Something like String ins; Pattern ptncreate= Pattern.compile("^createRobot(+\\d,\\d)"); Matcher m = ptncreate.matcher(ins); System.out.println(m.find()); but doesn't work Can you help me ?. Thanks. A: You forgot the word Robot in your pattern. Also, parenthesis are special characters in regex, and the + should be placed after the \d, not after a (: Pattern.compile("^createRobot\\(\\d+,\\d+\\)$") Note that if you want to validate input that should consist solely of this "createRobot"-string, you mind as well do: boolean success = s.matches("createRobot\\(\\d+,\\d+\\)"); where s is the String you want to validate. But if you want to retrieve the numbers that were matched, you do need to use a Pattern/Matcher: Pattern p = Pattern.compile("createRobot\\((\\d+),(\\d+)\\)"); Matcher m = p.matcher("createRobot(12,345)"); if(m.matches()) { System.out.printf("x=%s, y=%s", m.group(1), m.group(2)); } As you can see, after calling Matcher.matches() (or Matcher.find()), you can retrieve the nth match-group through group(n). A: You must add \ before ( because ( in regex is the special group character The regexp pattren is: ^create(\d+,\d+)
{ "language": "en", "url": "https://stackoverflow.com/questions/7628010", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Netbeans and Xampp I installed netbeans with php plugin.I also installed XAMP.My problem is how to configure /opt/lampp/htdocs/ to my netbeans application so that I can debug and run that from the application.Problem is when I try to make a project inside from netbeans it does not allow me to create files on that localhost.I guess netbeans doesn't have write access to the file system. What to do?any help?? A: * *Open your UNIX Terminal *Run the sudo chmod 777 /opt/lampp/htdocs command and give sudo your password when prompted Your htdocs directory should now be rewritable. A: You could set up a virtual host to point to your project directory which needs to reside in a directory that is writable. Here's a link to a tutorial for setting up a virtual host using XAMP: Setting Up Virtual Hosts for XAMPP
{ "language": "en", "url": "https://stackoverflow.com/questions/7628015", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Add search terms from form to search url I am trying to create a search input to a site that add the search terms to the end of the url. This is the url in question: http://apps.ticketbiscuit.com/ticketbiscuit.website/LyricTheatreOxford/Search/ You can manually search by adding the search term to the end of the url eg./Search/robert & if the string contains multiple words they need to be separated with "%20" eg./Search/Robert%20Earl. Here is my current search form: <form method="get" action="http://apps.ticketbiscuit.com/ticketbiscuit.website/LyricTheatreOxford/Events/Search/" id="searchform" role="search"> <input type="text" value="Search Events" name="s" id="s" onFocus="if (this.value == 'Search Events') {this.value=''; this.style.color='#000000';}"/> <input type="hidden" name="sitesearch" value=""/> </form> If I type Kevin into the input, the form returns this url: http://apps.ticketbiscuit.com/ticketbiscuit.website/LyricTheatreOxford/Search/?s=Kevin&sitesearch= I know that I need some Javascript in there to handle the search and build the correct url but I have no idea what is needed. Anyone have any ideas? Apologies if this has been answered elsewhere. I took a long look around but could not find anyything. A: Add onsubmit="return searchForm(this)" to the form tag. Then, define function searchForm: <script> function searchForm(form){ location.href = "http://apps.ticketbiscuit.com/ticketbiscuit.website/LyricTheatreOxford/Search/" + form.s.value; return false; } </script> See also: Open a URL based on search query without php "?q=(myTerm)" and instead with a simple "/(myTerm)"
{ "language": "en", "url": "https://stackoverflow.com/questions/7628018", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: DevExpress:How to programmatically remove a column from XtraReport? I have a Web application with XtraReport report. The report has several columns. Depending on a certain condition, in certain situations I do not need one of the columns to exist. What is a best way to programmatically remove it? I need not to ‘make the column invisible’, but remove it. The space that the column occupied before the removal should be distributed evenly between the other columns. A: A proper solution is to temporary remove the unnecessary XRTableCell from the XRTableRow.Cells collection... Review the http://www.devexpress.com/issue=Q216567 discussion in the DevExpress support center. Hope this helps. A: The easiest way to achieve this is to remove the cell from the row (for example on the report BeforePrint event). You should also wrap it in the suspend-resume layout code for the table itself: private void TableReport_BeforePrint(object sender, System.Drawing.Printing.PrintEventArgs e) { xrTable1.SuspendLayout(); xrTableRow1.Cells.Remove(xrTableCell1); xrTable1.PerformLayout(); } A: you can use dispose the cell If CEHide.Checked = True Then XrTableCell2.Dispose()
{ "language": "en", "url": "https://stackoverflow.com/questions/7628020", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Grails - Using JS variable in remoteFunction for controller and action args I want to call an Ajax function by using remoteFunction. But I'd like to set controller and action names with JS variables. Like this: ... var id = 1; for (var i = 0; i < updater.slaves.length; i++) { var slave = updater.slaves[i]; var ctrl = slave.data.controller; var action = slave.data.action; ${remoteFunction(controller: ctrl, action: action, params: "'id=' + id", onSuccess: "onSuccessLoadApplications(arguments)", onFailure: "error(arguments)")} } The problem is I can't retrieve the ctrl and action values (it's ok for id var). So, is it possible to make dynamic controller and action args for remoteFunction ? Thanks. A: I don't think it's possible to use remoteFunction like that. remoteFunction is a taglib, which will means it get processed at server side. At that stage, the javascript don't run, so you can't append string by '+'. In short, the code inside remoteFunction must follow valid Groovy syntax. which means you can't put javascript in like the example code. I think that to make things work, you must write your own javascript to do this ajax job. A: Really quickly, without testing it out. It seems if "'id=' + id" works for the params argument, shouldn't just "ctrl" work for the controller? Have you tried: ${remoteFunction(controller: "'' + ctrl", action: "'' + action", params: "'id=' + id", onSuccess: "onSuccessLoadApplications(arguments)", onFailure: "error(arguments)")} ??
{ "language": "en", "url": "https://stackoverflow.com/questions/7628021", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I pass an enum in this context I want to change the below function that I have written so that it will take the Enum (MyColors in this instance) as argument so that I can use the function on any suitable contiguous Enum. Everything I have tried so far has failed so I'm stuck. private enum MyColors { Red, Green, Blue } private String GetNext(String colorName) { MyColors colorValue; String colorNameOut = String.Empty; if (Enum.TryParse(colorName, out colorValue)) { MyColors initial = colorValue, next = colorValue; for (int i = ((Int32)initial) + 1; i < 10; i++) { if (Enum.IsDefined(typeof(MyColors), i)) { next = (MyColors)i; break; } else { next = (MyColors)0; } } colorNameOut = next.ToString(); } return colorNameOut; } A: The following ought to work: private static String GetNext<T>(String colorName) where T : struct { // Verify that T is actually an enum type if (!typeof(T).IsEnum) throw new ArgumentException("Type argument must be an enum type"); T colorValue; String colorNameOut = String.Empty; if (Enum.TryParse<T>(colorName, out colorValue)) { T initial = colorValue, next = colorValue; for (int i = (Convert.ToInt32(initial)) + 1; i < 10; i++) { if (Enum.IsDefined(typeof(T), i)) { next = (T)Enum.ToObject(typeof(T), i); break; } else { next = (T)Enum.ToObject(typeof(T), 0); } } colorNameOut = next.ToString(); } return colorNameOut; } Since the method is now generic it has to be called with a type argument of the enum type, like: GetNext<MyColors>("Red") A: This will give you the next value in an enum or null if the input is the last value public TEnum? GetNext<TEnum>(TEnum enm) where TEnum : struct { var values = Enum.GetValues(enm.GetType()); var index = Array.IndexOf(values, enm) + 1; return index < values.Length ? (TEnum?)values.GetValue(index) : null; } Usage var nextColor = GetNext(MyColors.Red); GetValues function for silverlight public static object[] GetValues(Type enumType) { if (!enumType.IsEnum) { throw new ArgumentException("Type '" + enumType.Name + "' is not an enum"); } List<object> values = new List<object>(); var fields = from field in enumType.GetFields() where field.IsLiteral select field; foreach (FieldInfo field in fields) { object value = field.GetValue(enumType); values.Add(value); } return values.ToArray(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7628022", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Getting a specific input from a specific form? I'm having difficulty grabbing a specific input from a specific form. Any tips? <form id ="frm_addtag-1"> <input type="text" name="tag" id="tag"> </form> <form id ="frm_addtag-2"> <input type="text" name="tag" id="tag"> </form> <form id ="frm_addtag-3"> <input type="text" name="tag" id="tag"> </form> If frm_addtag-1 is submitted, I only want to grab the tag input from that form and not the other forms. When I do something like the below, it will return the tag inputs from any other the forms regardless of which form is submitted. var tag = $("#tag"); var tag = tag.attr("value"); A: IDs should be unique. After changing the IDs, use .val() to get the value of an element. Besides, when you submit a form, only the elements WITHIN that form are added to the request. A: You cannot have multiple elements with the same ID on the same page. Why not do something like this: <form id ="frm_addtag-1"> <input type="text" name="tag1" id="tag1"> </form> <form id ="frm_addtag-2"> <input type="text" name="tag2" id="tag2"> </form> <form id ="frm_addtag-3"> <input type="text" name="tag3" id="tag3"> </form> And this to get the value: $('form').bind('submit', function(e){ // when any form on the page is submitted e.preventDefault(); // prevent the actual submit so the browser won't leave the current page var tag = $('input[name^="tag"]', this).val(); // the value of an input element whose name attribute starts with "tag" and that is a child of the current form });
{ "language": "en", "url": "https://stackoverflow.com/questions/7628026", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: maven gae plugin questions I'm having some issues making the maven google app engine plugin work properly. First of all, I'm not even sure if the archetype I'm using is the correct one, their examples show version 0.7.0 but it seems like never versions exist (i tried 0.9.1 and that works), where can I find a overview of what versions of the plugin is available? Secondly, the archetype seems.. messy, I don't like the package structure and it doesn't seem to actually include the GAE and GWT dependencies. I have to manually add them to my project in Eclipse, which kind of defeats the purpose of using maven. And how come they are breaking the gwt maven plugin? I know that one includes the actual gwt jars as maven dependencies? I'm fairly new to Maven, but I have been using the gwt maven plugin for a while, and I'm very happy with everything about it. Is there any way I could just their archetype to do the base project and add the gae plugin to it? UPDATE I suspect the problem I'm seeing with the GAE maven plug-in is in regards to undefined properties in the POM. I have no idea if its due to error these aren't set-up or if its due to me actually have to manually set them up. The documentation on this plugin is sparse. Thanks for the answer below, but I really don't want to add another archetype into play. I think the best solution for me is to try and adapt a GWT maven project manually, to include support for GAE. A: I've used the archetype like so : http://code.google.com/p/gae-mvn-archetype/ to generate a GAE project template.Then manually added my other dependencies. This got me a usable project which I can deploy to GAE and everything. Also, for Eclipse importing, once the template project was done, I've imported it into eclipse using the m2_eclipse plugin : http://m2eclipse.sonatype.org/installing-m2eclipse.html (note that i've imported it into Eclipse as a Maven project, NOT as an Eclipse whatever project) This imported the thing into eclipse with all the necessary dependencies and without errors.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628028", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How much days left from today to given date I have a date - 2015.05.20 What is the best way to calculate using python how much days left from today till this date? from datetime import * today = date.today() future = date(2015,05,20) ??? A: subtract them. >>> from datetime import * >>> today = date.today() >>> future = date(2015,05,20) >>> str(future - today) '1326 days, 0:00:00' >>> (future - today).days 1326 A: import datetime today = datetime.date.today() future = datetime.date(2019,9,20) diff = future - today print (diff.days) diff is a timedelta object.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628036", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: How to make sidebar's height equal to the content height (two columns table with divs)? I've created 2 columns layout - content div and sidebar div, with header and footer. See the live example here. How can I make sidebar's height equal to the content height (i.e. I should have something equal to the table with 2 columns). I use jquery and jquery ui. A: I've used this technique before to solve this exact problem and it works nicely: http://www.filamentgroup.com/lab/setting_equal_heights_with_jquery/ A: If you want a CSS solution, look into Faux Columns. You essentially fake the column with a repeating background image. The linked article is just an example, you can Google up 100 articles on it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628037", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Remove past dates and next months dates from the current month Is it possible to remove the past dates and next month's dates from the fullcalendar? So for the current month it should display only current dates and days. A: The grid cells for the next and previous month have the class "fc-other-month", so you can target them that way: e.g.: The hide the day numbers, add the CSS: .fc-other-month .fc-day-number { display:none;} or run this JavaScript: $(".fc-other-month .fc-day-number").hide() A: Try this! $('.fc-other-month').html(''); This works for me! A: None of the solutions provided on this answer properly solve the problem with the current version of FullCalendar. Using Bascht's answer as a starting point, I've updated his approach to use the current FullCalendar APIs. Below is working example code that will accomplish this task: eventRender: function (event, element) { var eventDate = event.start; var calendarDate = $('#activitiesCalendar').fullCalendar('getDate'); if (eventDate.get('month') !== calendarDate.get('month')) { return false; } } A: For Full calendar v5.0, add the below line in full calendar js: showNonCurrentDates: false Add below css to your page: .fc-day-disabled { visibility:hidden; } A: You could try skipping the events in the eventRender() method: eventRender: function(event, element, view) { if(event.start.getMonth() !== view.start.getMonth()) { return false; } } A: Add this setting showNonCurrentDates: false. With this setting, dates and events that do not belong to the current month will not be shown. $('#calendarId').fullCalendar({ // Other settings showNonCurrentDates: false }); A: eventRender: function (event, element, view) { var currentMon = new Date(event.start); var currentMonth = currentMon.getMonth(); var currentMonViewStart = new Date(view.start); var currentMonthViewStart = currentMon.getMonth(); var currentMonViewEnd = new Date(view.end); var currentMonthViewEnd = currentMonViewEnd.getMonth(); if((currentMonth == currentMonthViewStart) && (currentMonth == currentMonthViewEnd)){ return false; } } A: for version 2.0 or higher: eventRender: function (event, element, view) { if(event.start._d.getMonth() !== $('calendar').fullCalendar('getDate')._d.getMonth()) { return false; } } // if you want to remove other month's days from view add to css: .fcc-other-month { visibility:hidden; } A: Try using weekMode: http://fullcalendar.io/docs/display/weekMode/. weekMode: 'liquid', or `weekMode: 'variable',` Hope it helps A: For newer version of FullCalendar plugin, the following works utilizing Moment.js helper functions: eventRender: function(event, element, view){ var evStart = moment(view.intervalStart).subtract(1, 'days'); var evEnd = moment(view.intervalEnd).subtract(1, 'days'); if (!event.start.isAfter(evStart) || event.start.isAfter(evEnd)) { return false; } }, A: Using event render and a callback function solved my issue .Perfectly hiding previous and next month events from current view eventRender: function(event, element, view) { if (view.name == "month") { if (event.start._i.split("-")[1] != getMonthFromString(view.title.split(" ")[0])) { return false; } } } function getMonthFromString(mon) { var d = Date.parse(mon + "1, 2016"); if (!isNaN(d)) return new Date(d).getMonth() + 1; return -1; } Hope it helps A: you can try this clientOptions 'showNonCurrentDates' => false, and 'fixedWeekCount' => false, This code allow me to hide the days of previous months and next months but the cells of thouse days remains: Try using Fullcalendar Doc <?= $JSCode = <<<EOF function(event, element, view) { if(event.nonstandard.status =='0'){ element.find(".fc-title").css({"color": "red"}); $('.fc-day-top[data-date="'+event.nonstandard.date+'"]').find('.fc-day-number').css({"background-color": "red", "color": "white"}); } else if(event.nonstandard.status == '1'){ element.find(".fc-title").css({"color": "#1ab394"}); $('.fc-day-top[data-date="'+event.nonstandard.date+'"]').find('.fc-day-number').css({"background-color": "#1ab394", "color": "white"}); }else if(event.nonstandard.status == '4' || event.nonstandard.status == '5'){ $('.fc-day-top[data-date="'+event.nonstandard.date+'"]').find('.fc-day-number').css({"background-color": "#676a6c", "color": "white"}); }else if(event.nonstandard.status == '3'){ element.find(".fc-title").css({"color": "red"}); $('.fc-day-top[data-date="'+event.nonstandard.date+'"]').find('.fc-day-number').css({"background-color": "red", "color": "white"}); }else if(event.nonstandard.status == '2'){ element.find(".fc-title").css({"color": "orange"}); $('.fc-day-top[data-date="'+event.nonstandard.date+'"]').find('.fc-day-number').css({"background-color": "orange", "color": "white"}); } if(event.nonstandard.working_hours) { var new_description = '<strong>Total' + ' : </strong>' + event.nonstandard.working_hours + '<br/>'; element.append(new_description); } } EOF; yii2fullcalendar\yii2fullcalendar::widget([ 'id' => 'calendar', 'options' => [ 'lang' => 'en', 'header' => [ 'left' => 'prev,next today', 'center' => 'title', 'right' => 'month,agendaWeek,agendaDay' ], ], 'clientOptions' => [ 'height' => 750, 'showNonCurrentDates' => false, 'language' => 'en', 'eventLimit' => true, 'selectable' => true, 'selectHelper' => true, 'droppable' => false, 'editable' => false, 'fixedWeekCount' => false, 'defaultDate' => date('Y-m-d'), 'eventRender' => new JsExpression($JSCode), ], 'events' => Url::to(['/user/myattr/jsoncalendar']) ]); ?> A: $('.fc-other-month').html(''); and for disabling other month: $(".fc-other-month").addClass('fc-state-disabled'); A: Checked below solution in Full Calendar Version-4. It works, hides previous and next month's days and also does not pass previous/next month date in events URL. showNonCurrentDates: false Thanks to ask this question. A: For the latest version I used: eventRender: function(event,element,view) { var view_title = view.title; var event_title = event.start; var event_title2 = moment(event_title).format('MMMM YYYY'); if(event_title2 !== view_title) { return false; } else { var idname = 'event' + event.id; $(element).attr('id', idname).addClass('ttLT').attr('title', event.title); var mytitle = event.title; if (mytitle.toLowerCase().indexOf("open timeslot") >= 0) { $(element).addClass('alert').addClass('alert-success'); } else{ $(element).addClass('alert').addClass('alert-info'); $(element).find('.fc-event-title').addClass('capitalize'); $(element).find('.fc-event-inner').addClass('capitalize'); } element.qtip({ content: event.description, style:{classes:'qtip-bootstrap'}, position:{my:'bottom right',at:'top left'} }); } } A: This is working for me on version 3.6.1 eventRender: function(event, element, view) { if(!event.start.isBetween(view.intervalStart, view.intervalEnd)) { return false; } } A: Remove past dates and next months dates events from the current month in year view using this trick. eventAfterAllRender: function() { $(".fc-other-month").each(function() { var index=$(this).index(); var aa= $(this).closest("table").find("tbody").find("tr"). find("td:nth-child("+(index+1)+")"); aa.find(".fc-day-grid-event").hide(); }); }, A: You can change the color of the text as background color, i.e white so it will be invisible td.fc-other-month { color: white; } But it your version is >= 3, then you can check parameter- showNonCurrentDays : false, but this is for month view. A: As of Full Calendar v5.11.0, eventRender is no longer a valid option and the other answers didn't work for me. Using the VisibleRange function is what ended up doing the trick for me. var calendar = new Calendar(calendarEl, { initialView: 'timeGrid', visibleRange: function(currentDate) { // Generate a new date for manipulating in the next step var startDate = new Date(currentDate.valueOf()); var endDate = new Date(currentDate.valueOf()); // Adjust the start & end dates, respectively startDate.setDate(startDate.getDate() - 1); // One day in the past endDate.setDate(endDate.getDate() + 2); // Two days into the future return { start: startDate, end: endDate }; } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7628040", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "20" }
Q: Retrieving albums from age-restricted (alcohol) pages results in "An unknown error occurred" I've noticed when doing a Facebook Graph API call to retrieve a list of photo albums on an age-restricted page the following error occurs: {error_code: 1, error_msg: "An unknown error occurred"} I've tried both the JS API and the PHP API, same results. For testing purposes, I am using an age-restricted page I created myself (permission set to Alcohol-related). I also have double checked that I am using a valid auth_token that has full permission to read and write photos to the page. $albums = $facebook->api('/me/albums', 'GET', array( 'access_token' => 'XXX' )); Please note the same code works fine on non-age restricted pages. I should also mention, if I grab an album_id manually from Facebook, I have no problems posting photos to that album. The problem only seems to be with listing the albums. Is this a bug on Facebook's side, or is there an extra step one must take for age-restriced pages? A: Since the page is age restricted the user viewing this album should pass the age restriction check. Verify that the user viewing this passes that restriction.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628044", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Factory or constructor - where to set object properties? I am a little bit confused about, what is the right place to set object properties, in constructor or in factory method, or it does not matter? In constructor: class Foo { public $bar; function __constructor($b) { $this->bar = $b; } static function factory($b) { return new self($b); } } In factory: class Foo { public $bar; static function factory($b) { $obj = new self(); $obj->bar = $b; return $obj; } } A: The question is can you instantiate the class without setting the b property. If it will work, you do not need to set the property in the constructor. If the property is important for others method to work, you have to set it in the constructor. Factory has nothing to do with this. If the factory was the only way to instantiate the class (the constructor was private), then the code would be encapsulated, but still you need to pass the required parameters to the constructor, otherwise you can easly forget about them when you refactor your code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628045", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android: Random Sound FX on Button Click I'm trying to play a random sound FX on a button click using the soundpool. This works in the emulator but not on my device. Any clues? public class enc extends Activity { private static final String TAG = "MyActivity"; private SoundPool soundPool; private HashMap<Integer, Integer> soundsMap; int SOUND1=1; int SOUND2=2; int SOUND3=3; int SOUND4=4; int SOUND5=5; int SOUND6=6; int SOUND7=7; int SOUND8=8; int fSpeed = 1; Random random = new Random(); int hit = random.nextInt(6)+1; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //SoundPool soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 100); soundsMap = new HashMap<Integer, Integer>(); soundsMap.put(SOUND1, soundPool.load(this, R.raw.hit1, 1)); soundsMap.put(SOUND2, soundPool.load(this, R.raw.hit2, 1)); soundsMap.put(SOUND3, soundPool.load(this, R.raw.hit3, 1)); soundsMap.put(SOUND4, soundPool.load(this, R.raw.hit4, 1)); soundsMap.put(SOUND5, soundPool.load(this, R.raw.hit5, 1)); soundsMap.put(SOUND6, soundPool.load(this, R.raw.hit6, 1)); soundsMap.put(SOUND7, soundPool.load(this, R.raw.spell, 1)); soundsMap.put(SOUND8, soundPool.load(this, R.raw.kill, 1)); setContentView(R.layout.enc); } public void setButtonClickListener() { Button wepb = (Button)findViewById(R.id.uwep); wepb.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Log.i(TAG, "----------------------------SFX: " + hit); playSound(hit, fSpeed); hit = random.nextInt(6)+1; } }); } } A: I found the problem. I was using MP3 files and apparently, Android 2.0+ only works with OGG files. Converting all of them from MP3 to OGG fixed it. All is well!
{ "language": "en", "url": "https://stackoverflow.com/questions/7628047", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: iOS - UIImageWriteToSavedPhotosAlbum I wanted to use the following void API to write a captured image to the photo album but I am not very clear about 2 of the parameters UIImageWriteToSavedPhotosAlbum ( UIImage *image, id completionTarget, SEL completionSelector, void *contextInfo ); From the explanation from ADC: completionTarget: optional; the object whose selector should be called after the image has been written to the Camera Roll album. completionSelector: the method selector of the completionTarget object. This optional method should conform to the following signature: - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo: (void *) contextInfo; What is the significance of completionTarget here? Can someone explain with an example how this parameter should be used? Or any resource which can guide me through it. A: Calling UIImageWriteToSavedPhotosAlbum in modern iOS and Swift In modern iOS, there is an additional requirement for using UIImageWriteToSavedPhotosAlbum. You have to include in your Info.plist a key NSPhotoLibraryAddUsageDescription ("Privacy - Photo Library Additions Usage Description"). This is so that the system can present the user with a dialog requesting permission to write into the camera roll. You can then call UIImageWriteToSavedPhotosAlbum in your code: func myFunc() { let im = UIImage(named:"smiley.jpg")! UIImageWriteToSavedPhotosAlbum(im, self, #selector(savedImage), nil) } The last parameter, the context, will usually be nil. The idea of the second two parameters, self and #selector(savedImage), is that your savedImage method in self will be called back after the image is saved (or not saved). That method should look something like this: @objc func savedImage(_ im:UIImage, error:Error?, context:UnsafeMutableRawPointer?) { if let err = error { print(err) return } print("success") } A typical error would be if the user refused permission in the system dialog. If all goes well, the error will be nil and you'll know that the write succeeded. In general, UIImageWriteToSavedPhotosAlbum should probably be avoided, in favor of the Photos framework. However, it's a simple way to get the job done. A: * *The completionSelector is the selector (method) to call when the writing of the image has finished. *The completionTarget is the object on which to call this method. Generally: * *Either you don't need to be notified when the writing of the image is finished (in many cases that's not useful), so you use nil for both parameters *Or you really want to be notified when the image file has been written to the photo album (or ended up with a writing error), and in such case, you generally implement the callback (= the method to call on completion) in the same class that you called the UIImageWriteToSavedPhotosAlbum function from, so the completionTarget will generally be self As the documentation states, the completionSelector is a selector representing a method with the signature described in the documentation, so it has to have a signature like: - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo: (void *) contextInfo; It does not have to have this exact name, but it has to use the same signature, namely take 3 parameters (the first being an UIImage, the second an NSError and the third being of void* type) and return nothing (void). Example You may for example declare and implement a method that you could call anything like this : - (void)thisImage:(UIImage *)image hasBeenSavedInPhotoAlbumWithError:(NSError *)error usingContextInfo:(void*)ctxInfo { if (error) { // Do anything needed to handle the error or display it to the user } else { // .... do anything you want here to handle // .... when the image has been saved in the photo album } } And when you call UIImageWriteToSavedPhotosAlbum you will use it like this: UIImageWriteToSavedPhotosAlbum(theImage, self, // send the message to 'self' when calling the callback @selector(thisImage:hasBeenSavedInPhotoAlbumWithError:usingContextInfo:), // the selector to tell the method to call on completion NULL); // you generally won't need a contextInfo here Note the multiple ':' in the @selector(...) syntax. The colons are part of the method name so don't forget to add these ':' in the @selector (event the trainling one) when you write this line! A: SWIFT VERSION based on AliSoftware solution UIImageWriteToSavedPhotosAlbum( yourImage, self, // send the message to 'self' when calling the callback #selector(image(path:didFinishSavingWithError:contextInfo:)), // the selector to tell the method to call on completion nil // you generally won't need a contextInfo here ) @objc private func image(path: String, didFinishSavingWithError error: NSError?, contextInfo: UnsafeMutableRawPointer?) { if ((error) != nil) { // Do anything needed to handle the error or display it to the user } else { // .... do anything you want here to handle // .... when the image has been saved in the photo album } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7628048", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "40" }
Q: how to search one object and return another related object I am trying to create search form when user search for a course it returns list of user's names who are taking that course.So i have user table,course table and user-course join table.I want o use metasearch or ransack.But i wonder how i would use these in my case.Thank you in advance. create_table "users", :force => true do |t| t.string "firstname" t.string "email" t.string "encrypted_password", :limit => 128, :default => "", :null => false t.string "password_salt", :default => "", :null => false end create_table "courses", :force => true do |t| t.string "name" t.datetime "created_at" t.datetime "updated_at" t.integer "school_id", :null => false end create_table "user_courses", :force => true do |t| t.integer "user_id", :null => false t.integer "course_id", :null => false t.boolean "active", :null => false end class User < ActiveRecord::Base has_many :user_courses has_many :courses, :through => :user_courses has_many :active_courses, :through => :user_courses, :source => :course, :conditions => {'user_courses.active' => true} has_many :taken_courses, :through => :user_courses, :source => :course, :conditions => {'user_courses.active' => false} end class UserCourse < ActiveRecord::Base belongs_to :user belongs_to :course end class Course < ActiveRecord::Base validates_presence_of :name has_many :user_courses belongs_to :school end A: You can add this to your Course model: has_many :users, :through => :user_courses Then you can get the users from a course like so Course.find(1).users
{ "language": "en", "url": "https://stackoverflow.com/questions/7628054", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Redundant character in POST payload I'm building a Chrome extension in which I simulate form POST to send images over to a server. I managed to upload the file, yet its content is distorted. By comparing the byte array of the uploaded and the original, it can be observed that every byte > 127 is transformed into 2 other bytes. E.g: 137 -> 194 137 233 -> 195 169 The POST payload in Chrome developer tool suggests that the redundant byte is added before the request is sent. My original file Content: ‰PNG .... And content recorded in web payload ‰PNG .... A char not supposed to be there precedes the content. Do you have any idea how to avoid this issue? Below is the code I use to test: var fr = new FileReader(); fr.onloadend = function(evt){ if(evt.target.readyState == FileReader.DONE){ //str - image content var str = ""; var byteStr = ""; var dv = new DataView(evt.target.result); console.log("data length = " + evt.target.result.byteLength); for(var i = 0 ; i < evt.target.result.byteLength; i++){ var b1 = dv.getUint8(i); str += String.fromCharCode(b1); byteStr += b1 + " "; } console.log(str); console.log(byteStr); //use jQuery.ajax to post image to server attachImage(str, file.name,file.type); } } fr.readAsArrayBuffer(file); Thank you in advance.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628055", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Synchronized FIFO Buffer Usage I am trying to create a system where one thread A adds items to a buffer, then another thread B is responsible for reading the items in the exact order they were entered, and then doing some potentially lengthily operations on them. My best guess: Class B extends Thread { Buffer fifo = BufferUtils.synchronizedBuffer(new BoundedFifoBuffer()); add(Object o) { // Thread A calls me, and doesn't deal well with delays :) fifo.add(o); // will the sync below prevent this from happening? // or can .add be independent of the sync ? } run() { synchronized (fifo) { // why am i sync'd here? I am the only thread accessing... while ( item in buffer ) { // also how do i check this, and block otherwise? process(fifo.remove()); } } | } As you can see, I'm not even fully sure if synchronization is necessary. The thread safety issue I have has nothing to do with the get() access, as there will only be one thread accessing it, but what is most important is that thread A calls .add() without any Concurrent Access Exception during thread B's processing of the buffer's contents. Maybe I'm overthinking this? Is it safe to being with? Your evaluation of this problem is much appreciated. Sincerely, Jay A: If I am not wrong, you could also be interested in this ArrayBlockingQueue class. A: If you have a stream of characters for logging the fastest approach may be to use a pipe. PipedOutputStream pos = new PipedOutputStream(); final PipedInputStream pis = new PipedInputStream(pos, 256*1024); ExecutorService es = Executors.newSingleThreadExecutor(); es.execute(new Runnable() { @Override public void run() { byte[] bytes = new byte[256*1024]; int length; try { while ((length = pis.read(bytes)) > 0) { // something slow. Thread.sleep(1); } } catch (Exception e) { e.printStackTrace(); } } }); // time latency PrintWriter pw = new PrintWriter(pos); long start = System.nanoTime(); int runs = 10*1000*1000; for(int i=0;i<runs;i++) { pw.println("Hello "+i); } long time = System.nanoTime() - start; System.out.printf("Took an average of %,d nano-seconds per line%n", time/runs); es.shutdown(); prints Took an average of 269 nano-seconds per line Note: the pipe itself doesn't create any garbage. (Unlike a queue) You can use ExecutorService to wrap up a queue and thread(s) ExecutorService es = es.submit(new Runnable() { public void run() { process(o); } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7628056", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Re-Stream a MPEG2 TS PAL Stream with crtmpserver I want to build up some kind of stream wrapper: I own an old Dreambox PAL Sat Reciever with Networking. This stream I want to transcode to a lower resultion an restream it. My Goal is, to have a simple website, where this stream is embedded via rtmp. I thougt crtmpserver should be the right software. For now I have a site running and can play local files through jwplayer/crtmpserver. I am looking for a solution for this: httpUrl -> ffmpeg -> crtmpserver Is that possible? May I redirect the output of ffmpeg to a filed pipe, and crtmpserver could grab that? Or go with UDP? Any hints appreciated!!! Thanks!! A: That's easy: * *Start the server (in console mode for debugging) You should see something like this: |tcp| 0.0.0.0| 9999| inboundTcpTs| flvplayback| Basically, that is a tcp acceptor for mpegts streams * *Use ffmpeg to create the stream: ffmpeg -i < source > < source_related_parameters > < audio_codec_parameters > < video_codec_parameters > -f mpegts "tcp://127.0.0.1:9999" Example: ffmpeg -i /tmp/aaa.flv -acodec copy -vcodec copy -vbsf h264_mp4toannexb -f mpegts "tcp://127.0.0.1:9999" * *Go back to the server and watch the console. You should see something like this: Stream INTS(6) with name ts_13_257_256 registered to application flvplayback from protocol ITS(13) ts_13_257_256 is the stream name. Now you can use jwplayer or similar player and point it to that stream If you want to use UDP, you need to stop the server and change the config file so instead of having protocol="inboundTcpTs" you should have protocol="inboundUdpTs" Yo ucan even copy the entire section and change the port number to have both. Also, you have to change the ffmpeg so instead of having tcp://127.0.0.1:9999 you can have udp://127.0.0.1:9999 Now, if you also want a stream name and not that ts_13_257_256 (which is by the way ts_protocolId_AudioPID_VideoPID) you can use LiveFLV in a similar manner: ffmpeg -i /tmp/aaa.flv -acodec copy -vcodec copy -vbsf h264_mp4toannexb -f flv -metadata streamName=myStreamName "tcp://127.0.0.1:6666" And the server should show: Stream INLFLV(1) with name `myStreamName` registered to application `flvplayback` from protocol ILFL(3) There you go, now you have a "computed" stream name which is myStreamName One last observation. Please ask this kind of questions on the crtmpserver's mailing list. You will be better heard. You can find resources here: http://www.rtmpd.com/resources/ Look for the google group under Cheers, Andrei
{ "language": "en", "url": "https://stackoverflow.com/questions/7628060", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Undefined local variable or method `current_submission' for # I am trying to create an app for managing an academic conference. Users will sign in and submit abstracts for consideration of being presented at our annual conference. I have followed the "Ruby on Rails 3 Tutorial" for most of what I have done. My modifications include adding a Submission model, a Registration model, and an Order model. The Submission model belongs_to the User model and has_one order. I am trying to follow the Railscast 145/146 episodes about integrating PayPal Express checkout using ActiveMerchant. My goal is to put a PayPal checkout button on the submissions show.html.erb page so that after the author has submitted his abstract he can pay the submission fee right away. The error arises from the following code after I have submitted the order: class OrdersController < InheritedResources::Base def new @order = Order.new end def create @order = current_submission.orders.build_order(params[:order]) @order.ip_address = request.remote_ip if @order.save # flash[:notice] = "Successfully created order." #redirect_to orders_url else render :action => 'new' end end end From what I have read, I think the problem has to do with how orders are related to submissions. Each submission should have a related order entry, so in the Order table there should be a submission_id. I am really confused about how this works. Could someone please point me in the right direction? Is there a user guide that you would recommend that I read? There seems to be a lot of conflicting information out there between the different versions of Rails. I am using Rails 3.0.10. Thanks! A: You should setup your resources as resources :submissions do resource :order end This way your params will reflect the particular submission being accessed via an :id attribute. Your orders#create action would then change to @submission = Submission.find(params[:submission_id]) @order = @submission.orders.build_order(params[:order]) The relation you have reflected above seems to indicate Submission has_many :orders. Regarding your comment The Submission model belongs_to the User model and has_one order. In that case you need to change the above to - notice how orders becomes order: @order = @submission.order.build_order(params[:order]) So your relationships are Submission has_one :order; Order :belongs_to :submission and User :has_one :submission? Update Based on your comments describing your requirements, your relationships need to change as follows: class User < ActiveRecord::Base has_many :orders has_many :submissions, :through => :orders class Order < ActiveRecord::Base # this table needs attributes user_id and session_id belongs_to :user belongs_to :session validates :submission_id, :uniqueness => true class Submission < ActiveRecord::Base has_many :orders has_many :users, :through => :orders Since I've placed a uniqueness constraint on the join table, it will ensure that a particular submission_id can only occur once in any record. You can setup your controller using 'orders' like before and it'll most likely be @submission = Submission.find(params[:id]) rather than @submission = Submission.find(params[:submission_id]) since orders is a singular resource. If you need further assistance with this drop me an email at mike at bsodmike dot com.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628061", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Does OCaml have syntax like Haskell's ++? I know OCaml has List.append, but does it have an operator like Haskell's ++? A: For lists: # (@);; - : 'a list -> 'a list -> 'a list = <fun> # [1;2;3] @ [4;5;6];; - : int list = [1; 2; 3; 4; 5; 6] For strings: # (^);; - : string -> string -> string = <fun> # "abc" ^ "def";; - : string = "abcdef" A: Also, you could just say yourself let (@) = List.append or let (++) = List.append if noone had yet done it for you in the standard library.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628063", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Set up tunnel for SVN (using Cornerstone/Mac) I've been using Tortoise to checkout/commit to the svn repository. It is set up to use Tortoiseplink as SSH client (D:\TortoiseSVN\bin\TortoisePlink.exe -l foo -pw bar). I have now moved to a Mac (using Cornerstone) but I can't get the same sort of setup. Whatever I do, I can't get Cornerstone to connect to the repo. Do I need to set up an ssh tunnel? And how do I do that on a Mac? Update: screenshot of the settings needed A: What you have looks correct - the only thing I can think of is that your SSH connection is not working for some reason. Have you tried just doing an SSH to the server hosting the repository? To do this, open Terminal and type: $ ssh [email protected] If you are prompted for a password and you can log into the machine then that is a good start - if not that suggests that something is fishy with your network setup.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628066", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Two-way binding requires path or xpath I want to increase Progress-bar value based on two textbox's Text. I wrote this XAML but there is an error "Two-way binding requires path or xpath" when I do MultiBinding in ProgressBar.Value <Window.Resources> <local:Class1 x:Key="ConverterM"/> </Window.Resources> <TextBox Height="23" HorizontalAlignment="Left" Margin="157,59,0,0" Name="textBox1" VerticalAlignment="Top" Width="120" /> <TextBox Height="23" HorizontalAlignment="Left" Margin="157,108,0,0" Name="textBox2" VerticalAlignment="Top" Width="120" /> <ProgressBar Height="24" HorizontalAlignment="Left" Margin="120,160,0,0" Name="progressBar1" VerticalAlignment="Top" Width="243" > <ProgressBar.Value> <MultiBinding Converter="{StaticResource ConverterM}"> <Binding /> <Binding ElementName="textBox1" Path="Text" /> <Binding ElementName="textBox2" Path="Text" /> </MultiBinding> </ProgressBar.Value> </ProgressBar> Value Converter: public class Class1 : IMultiValueConverter { public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (values[1] != null && values[2]!=null) { if (((string)values[1]).Length==((string)values[2]).Length) { return 5.0; } } else { return 0.0; } } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } A: I think that <Binding /> is not necessary. try to delete it and change indexes in converter. A: Two-way binding requires path or xpath This happens when you haven’t set the Path= on binding. By default WPF binding will take the Path= part by default. To avoid this you need to give Path for each Binding you specify in MultiBinding. here in your case there was an empty binding which has no Path defined thats why you have experience with the above error. I have came across the same issue but the accepted answer does not say what the error is, So thought of sharing this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628069", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Pointer initialization in C In C why is it legal to do char * str = "Hello"; but illegal to do int * arr = {0,1,2,3}; A: As for C89: "A string", when used outside char array initialization, is a string literal; the standard says that when you use a string literal it's as if you created a global char array initialized to that value and wrote its name instead of the literal (there's also the additional restriction that any attempt to modify a string literal results in undefined behavior). In your code you are initializing a char * with a string literal, which decays to a char pointer and everything works fine. However, if you use a string literal to initialize a char array, several magic rules get in action, so it is no longer "as if an array ... etc" (which would not work in array initialization), but it's just a nice way to tell the compiler how the array should be initialized. The {1, 2, 3} way to initialize arrays keeps just this semantic: it's only for initialization of array, it's not an "array literal". A: In the case of: char * str = "Hello"; "Hello" is a string literal. It's loaded into memory (but often read-only) when the program is run, and has a memory address that can be assigned to a pointer like char *str. String literals like this are an exception, though. With: int * arr = {0,1,2,3}; ..you're effectively trying to point at an array that hasn't been put anywhere in particular in memory. arr is a pointer, not an array; it holds a memory address, but does not itself have storage for the array data. If you use int arr[] instead of int *arr, then it works, because an array like that is associated with storage for its contents. Though the array decays to a pointer to its data in many contexts, it's not the same thing. Even with string literals, char *str = "Hello"; and char str[] = "Hello"; do different things. The first sets the pointer str to point at the string literal, and the second initializes the array str with the values from "Hello". The array has storage for its data associated with it, but the pointer just points at data that happens to be loaded into memory somewhere already. A: Because there's no point in declaring and initializing a pointer to an int array, when the array name can be used as a pointer to the first element. After int arr[] = { 0, 1, 2, 3 }; you can use arr like an int * in almost all contexts (the exception being as operand to sizeof). A: ... or you can abuse the string literals and store the numbers as a string literal, which for a little endian machine will look as follows: int * arr = (int *)"\0\0\0\0\1\0\0\0\2\0\0\0\3\0\0\0"; A: I guess that's just how initializers work in C. However, you can do: int *v = (int[]){1, 2, 3}; /* C99. */
{ "language": "en", "url": "https://stackoverflow.com/questions/7628072", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "21" }
Q: Controlling placement of the edit link in Orchard Is there a way to control the placement of the edit link for a content item that get's rendered when you're logged in? I'm assuming this can be done using the placement.info but I'm not sure how do it. A: No, not with placement, just with CSS.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628073", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Creating a ruby IO object from request.body.read? I'm using sinatra and transloadit and sending files with xhr using valumns file uploader. I need to create a IO object and fill it with data in request.body.read How can I do that ? thank you. A: Use StringIO: require 'stringio' StringIO.new(request.body.read) Alternatively, can't you just pass request.body for your IO object? A: Just use request.body, call request.body.rewind first.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628074", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Cannot get Xcode SCM to work with Gitolite based server For whatever reason, I cannot get the built-in source control tools in Xcode 4.1 to work with the git repository I have setup on my server. The server is setup to use Gitolite. Everything works fine from the command line. I can add the remote, push, pull, and then clone out again. I can also access Github in Xcode just fine. Has anyone been successful getting these two tools to work together? Any idea how I can debug this (I have no idea what Xcode is doing behind the scenes)? The only thing that has stood out to me is that Xcode wants to include a top-level folder when accessing the repository, i.e.: [email protected]:folder/repository-name.git and Gitolite doesn't want you to do that. It wants: [email protected]:repository-name.git A: I have a Gitolite 2.0.3 server running on Ubuntu 11.10, and I am able to use with the built-in SCM integration in Xcode 4.2 running on Snow Leopard. To see log information about commits and other SCM operations, go to the Xcode log navigator (speech bubble icon in the left column, or select View > Navigators > Show Log Navigator, or press Cmd-9). The log navigator has filters to show only error messages. That should give you more information about what's going on. One thing that stands out for me in your question is that when using Gitolite, I never use the .git suffix on the client went entering the git URI. Try omitting that and see if that makes any difference when working in Xcode. For example, I have git repositories on the server in folders like ~gitolite/repositories/project1.git or ~gitolite/repositories/apps/ios/project2.git, but when I am on the client, the git URIs look like: ssh://[email protected]:12345/project1, or ssh://[email protected]:12345/apps/ios/project2.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628075", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Memory management of NSTimer -- does it need to be assigned to a variable? Whenever I want to make a timer, I just do: [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(someMethod) userInfo:nil repeats:NO]; rather than NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(someMethod) userInfo:nil repeats:NO]; Is the first one a memory leak? What's the correct way to use them? A: You have no memory problem in either snippet; you simply have to make a choice about your needs for interacting with the timer. When you schedule a timer, the run loop retains it, and a reference to the timer is passed along when it fires and its selector -- e.g., (void) doTimerThing: (NSTimer *)tim1 -- is used, so it isn't strictly necessary for you to put it into a variable and retain it yourself. Apple explains this pretty clearly in the "Memory Management" section of the Timer Programming Topics doc. If, however, you might want to invalidate the timer before it fires (or in between fires for a repeating timer), you do need to have a reference to it. In that case, it is also a good idea to call retain on it. The scheduledTimerWithTimeInterval:target:... method returns an object that you do not own, and you should not make assumptions about the memory status of objects you don't own (including whether they are in an autorelease pool or not, or how long the run loop is going to keep the timer around). If you need the timer (or any object) to stick around, you should make a claim of ownership on it by calling retain. 1 Note that a timer's method should always have one parameter; the selector in your snippet looks like it is for a method that does not. The timer seems to work that way, but you're operating contrary to the documented interface. A: In addition to previous answers, if you don't need repeating timer, you can use [self performSelector:@selector(someMethod) withObject:nil afterDelay:5.0]; instead of creating timer manually. A: In either way, there is no memory leak. The second solution is just affecting the result to a variable, whereas the first one don't store the result, but the effect are the same. As the naming convention suggests, given the name scheduledTimerWithTimeInterval:... of the method, you know that it will returns an autoreleased object (or to be more precise, it will return an object which you are not the owner, and for which you won't have to send a release to by yourself) You don't have to hold a reference to the created NSTimer if not needed: the timer will be scheduled on the RunLoop (and that's the RunLoop that will retain it until it is used, and release it when done, so you don't have to bother), so it will live by itself. But if you don't store the returned NSTimer in a variable like in your second code, you won't be able to cancel the timer if you ever wanted to. Especially, if you setup a repeating timer, you will need to store it in a variable so that you can access it later, especially to send it an invalidate message so it can be cancelled.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628076", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Which Box2D JavaScript library should I use? There are a few different ports of Box2D for JavaScript. Which one is the best? * *Box2DJS - "converted from Box2DFlashAS3_1.4.3.1 in an automatic manner" *Box2Dflash 2.0 ported to JavaScript - "one big nasty hack that just happens to work" *box2dweb - "a port of Box2DFlash 2.1a to JavaScript. I developed an ActionScript 3 -to- JavaScript converter to generate the code" *HBehrens/box2d.js - "a JavaScript Version of Box2D 2.1a" (Added Nov 21, 2011) *kripken/box2d.js - "a direct port of the Box2D 2D physics engine to JavaScript, using Emscripten" (Added Sep 24, 2013) Any ideas which version http://chrome.angrybirds.com/ uses, if any? A: Note to readers! This question was originally asked and answered in 2011, but I'll do my best to keep it up to date! Here's what I've found: * *kripken/box2d.js is a port of Box2D using Emscripten and works well and is fast. I have used this personally with great success. *planck.js is the newest port and is written from the ground-up in JavaScript *Box2DJS is a port of Box2DFlash 1.4.3.1. box2dweb is a port of version 2.1a. *Box2DJS works "as a CommonJS module without any modifications at all" [1] *Box2DJS "not up-to-date and you have to import a big amount of JavaScript files in every project" [2] *box2dweb is contained in a single file [2] *box2dweb is "a much newer port and has a lot fewer issues" than Box2DJS [3]. However, switching might introduce new issues [4]. *Box2DJS depends on Prototype but box2dweb does not [5] *Seth Ladd has promoted box2dweb with examples on his blog [6] *Nobody seems to be using the third alternative. *There are also physics simulators not based on Box2D. Check out Matter.js and p2.js There's also a similar discussion on gamedev.stackexchange.com. I'd say that the winner is kripken/box2d.js. A: LiquidFun (With JS Bindings) LiquidFun is, at the time I'm posting this, the most recent port to JS. It has all the features of Box2D and liquid physics features. It's ported using emscripten, so performance is decent. google/liquidfun google/liquidfun/tree/master/liquidfun/Box2D/lfjs A: Probably the best place to keep up to date with Box2D JavaScript ports is the official forum: http://box2d.org/forum/viewforum.php?f=22 JSBox2D looks like a good start. I would definitely have a look into Matter.js, which seems very well built and very quick. I'm going down this path. http://brm.io/matter-js A: Box2d-html5 is also another box2d port including Google's LiquidFun) and active update. * *https://code.google.com/p/box2d-html5/ *Now maintained at github: https://github.com/flyover/box2d.js A: This question and its best answer are from 2011. One recent new option is box2.js, an Emscripten translation of the C++ code to Javascript. As of August 2013 it's more up-to-date than the other ports I've found, and the demos seem to work. A: Box2DWeb supports most of the API from the original C++ Box2D except chain shapes. :/ It is the most widely used Javascript Box2D. If you need the API documentation for Box2DWeb, check out Box2DFlash. http://www.box2dflash.org/docs/2.1a/reference/ Box2DWeb is auto generated from Box2DFlash using a compiler. So the API is the same. I doubt Box2DWeb will get any update in the future anymore as Box2DFlash has shown no activities anymore. You can see the author's rational on why he decided not to write a direct Box2D --> Box2DWeb port. https://code.google.com/p/box2dweb/wiki/Roadmap
{ "language": "en", "url": "https://stackoverflow.com/questions/7628078", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "93" }
Q: How to get arguments list of a built-in Python class constructor? I'm trying to use the inspect module, however it seems I can't use it on a built-in (native?) class, or else I misunderstood. I'm using Python 2.7 and tried with Python 3.2. This is working: >>> import inspect >>> class C: ... def __init__(self,a,b=4): ... self.sum = a + b ... >>> inspect.getargspec(C.__init__) ArgSpec(args=['self','a', 'b'], varargs=None, keywords=None, defaults=(4,)) This is not working: >>> import inspect >>> import ast >>> inspect.getargspec(ast.If.__init__) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/inspect.py", line 813, in getargspec raise TypeError('{!r} is not a Python function'.format(func)) TypeError: <slot wrapper '__init__' of '_ast.AST' objects> is not a Python function I am wondering if there is another technique to get these parameters automatically? (In my case, I think about an alternative which would be to parse the Python grammar, the ASDL file which explain how to init AST nodes using some code I saw in PyPy Project's source, but I'm wondering if there is another way) A: There is no way to get them, as they are a property of the C code behind the function, and not of the function itself. A: Note that this code works just fine on PyPy (where there is no really distinction between those two function types). (pypy)fijal@helmut:~$ python class C(Python 2.7.1 (f1e873c5533d, Sep 19 2011, 02:01:57) [PyPy 1.6.0-dev1 with GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. Welcome to rlcompleter2 0.96 for nice experiences hit <tab> multiple times And now for something completely different: ``PyPy needs a Just-in-Time JIT'' >>>> class C: .... def __init__(self, a, b=4): .... pass .... >>>> import inspect >>>> inspect.getargspec(C.__init__) ArgSpec(args=['self', 'a', 'b'], varargs=None, keywords=None, defaults=(4,)) >>>>
{ "language": "en", "url": "https://stackoverflow.com/questions/7628081", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Changing UITableView to clear color I want my UITableView to be completely invisible but I have set a lot of things and nothing seems to be working. I use custom table cells. This is what I set in the cell.h self.textLabel.backgroundColor = [UIColor clearColor]; primaryLabel.backgroundColor = [UIColor clearColor]; secondaryLabel.backgroundColor = [UIColor clearColor]; self.backgroundColor = [UIColor clearColor]; self.contentView.backgroundColor = [UIColor clearColor]; self.backgroundView.backgroundColor = [UIColor clearColor]; self.accessoryView.backgroundColor = [UIColor clearColor]; self.selectedBackgroundView.backgroundColor = [UIColor clearColor]; And I also set _tableView.backgroundColor = [UIColor clearColor]; But still it is not working, what am I missing? A: Instead, you could use the hidden property of the tableView. tableView.hidden = YES; A: With regards to the "incorrect" answer given, I think you mean is that you want the tableView background to disapear (showing the views background). If so, in your viewDidLoad, add the following: (given you made your tableView programmatically) [self.tableView setBackgroundColor:[UIColor clearColor]]; If you also don't want to show the lines for each cell: [self.tableView setSeparatorColor:[UIColor clearColor]];
{ "language": "en", "url": "https://stackoverflow.com/questions/7628084", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I use to drag an image(image url only) into the droppable area to upload to the server using jquery or ajax? I want to upload an image to server through an image url. this image is dragged and dropped to a droppable area. (Or is there a way to post the Image URL to another page in the javascript function?) How do I use this image in the droppable area to upload to the server using jquery or ajax. Like once I dropped the image then it will automatically upload to the server by using the image url(e.g http://dfghg.com/sss.jpg). the image (e.g http://dfghg.com/sss.jpg) is within the the same page as the drop area. heres my code $("#query_image_container").droppable({ accept: ".thumb", activeClass: "ui-state-highlight", drop: function( event, ui ) { $(this).find(".thumb").remove(); $(this).append('<img class="thumb" src="'+ui.draggable.attr('src')+'">'); var imageurl = ui.draggable.attr('src'); $.ajax({ type: 'POST', url: 'uploadurl.php', data: imageurl, success:function() { } datatype: 'html' }); } }); can I use $.ajax({...}); within a droppable? Or is there any other way i can do a POST to uploadurl.php with the "data : imageurl" ? the idea is to drag an image(image on the same webpage) to the drop area and it will auto upload to the server. A: You might wont to dig deeper into fileuploadarea, this seems to be doing pretty much what you want.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628095", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Static Gmaps in winform Im trying to load a google static map in a winform. I found a control online that would helpme but i cant get it working. i got the control from Here. i was not able to drag on the control on to the form like others. i have also email the dev of the control but have not heard back yet. Any help would be Great. Thank here is my code Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim gmap As New CtpGglMap.Impl.StaticGMap gmap.Center.Address = "New york ,NY" gmap.Zoom = 14 gmap.Height = 400 gmap.Width = 600 gmap.Sensor = False PictureBox1.Image = gmap End Sub A: Got it working. Dim gmap As New CtpGglMap.Impl.StaticGMap Dim temp As New GMarker Dim temp2 As New GMarker gmap.Center = New GeoPointImpl(41.5442847, -73.8732391) gmap.Zoom = 14 gmap.Height = 334 gmap.Width = 362 gmap.Sensor = False TextBox1.Text = GetDrivingDirectionFromGoogle("fishkill ,ny", "41.5442847, -73.8732391") temp.Point = New GeoPointImpl(41.5442847, -73.8732391) temp.SetMap(gmap) 'CREATE A BITMAP FROM THE MEMORY STREAM PictureBox1.Image = New System.Drawing.Bitmap(gmap.Fetch)
{ "language": "en", "url": "https://stackoverflow.com/questions/7628098", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Convert Regexp in Js into PHP? I have the following regular expression in javascript and i would like to have the exact same functionality (or similar) in php: // -=> REGEXP - match "x bed" , "x or y bed": var subject = query; var myregexp1 = /(\d+) bed|(\d+) or (\d+) bed/img; var match = myregexp1.exec(subject); while (match != null){ if (match[1]) { "X => " + match[1]; } else{ "X => " + match[2] + " AND Y => " + match[3]} match = myregexp1.exec(subject); } This code searches a string for a pattern matching "x beds" or "x or y beds". When a match is located, variable x and variable y are required for further processing. QUESTION: How do you construct this code snippet in php? Any assistance appreciated guys... A: You can use the regex unchanged. The PCRE syntax supports everything that Javascript does. Except the /g flag which isn't used in PHP. Instead you have preg_match_all which returns an array of results: preg_match_all('/(\d+) bed|(\d+) or (\d+) bed/im', $subject, $matches, PREG_SET_ORDER); foreach ($matches as $match) { PREG_SET_ORDER is the other trick here, and will keep the $match array similar to how you'd get it in Javascript. A: I've found RosettaCode to be useful when answering these kinds of questions. It shows how to do the same thing in various languages. Regex is just one example; they also have file io, sorting, all kinds of basic stuff. A: You can use preg_match_all( $pattern, $subject, &$matches, $flags, $offset ), to run a regular expression over a string and then store all the matches to an array. After running the regexp, all the matches can be found in the array you passed as third argument. You can then iterate trough these matches using foreach. Without setting $flags, your array will have a structure like this: $array[0] => array ( // An array of all strings that matched (e.g. "5 beds" or "8 or 9 beds" ) 0 => "5 beds", 1 => "8 or 9 beds" ); $array[1] => array ( // An array containing all the values between brackets (e.g. "8", or "9" ) 0 => "5", 1 => "8", 2 => "9" ); This behaviour isn't exactly the same, and I personally don't like it that much. To change the behaviour to a more "JavaScript-like"-one, set $flags to PREG_SET_ORDER. Your array will now have the same structure as in JavaScript. $array[0] => array( 0 => "5 beds", // the full match 1 => "5", // the first value between brackets ); $array[1] => array( 0 => "8 or 9 beds", 1 => "8", 2 => "9" );
{ "language": "en", "url": "https://stackoverflow.com/questions/7628101", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Convert Java String to sql.Timestamp Got a String coming in with this format: YYYY-MM-DD-HH.MM.SS.NNNNNN The Timestamp is coming from a DB2 database. I need to parse it into a java.sql.Timestamp and NOT lose any precison. So far I've been unable to find existing code to parse that far out to microseconds. SimpleDateFormat returns a Date and only parses to milliseconds. Looked at JodaTime briefly and didn't see that would work either. A: You could use Timestamp.valueOf(String). The documentation states that it understands timestamps in the format yyyy-mm-dd hh:mm:ss[.f...], so you might need to change the field separators in your incoming string. Then again, if you're going to do that then you could just parse it yourself and use the setNanos method to store the microseconds. A: Have you tried using Timestamp.valueOf(String)? It looks like it should do almost exactly what you want - you just need to change the separator between your date and time to a space, and the ones between hours and minutes, and minutes and hours, to colons: import java.sql.*; public class Test { public static void main(String[] args) { String text = "2011-10-02 18:48:05.123456"; Timestamp ts = Timestamp.valueOf(text); System.out.println(ts.getNanos()); } } Assuming you've already validated the string length, this will convert to the right format: static String convertSeparators(String input) { char[] chars = input.toCharArray(); chars[10] = ' '; chars[13] = ':'; chars[16] = ':'; return new String(chars); } Alternatively, parse down to milliseconds by taking a substring and using Joda Time or SimpleDateFormat (I vastly prefer Joda Time, but your mileage may vary). Then take the remainder of the string as another string and parse it with Integer.parseInt. You can then combine the values pretty easily: Date date = parseDateFromFirstPart(); int micros = parseJustLastThreeDigits(); Timestamp ts = new Timestamp(date.getTime()); ts.setNanos(ts.getNanos() + micros * 1000); A: Here's the intended way to convert a String to a Date: String timestamp = "2011-10-02-18.48.05.123"; DateFormat df = new SimpleDateFormat("yyyy-MM-dd-kk.mm.ss.SSS"); Date parsedDate = df.parse(timestamp); Admittedly, it only has millisecond resolution, but in all services slower than Twitter, that's all you'll need, especially since most machines don't even track down to the actual nanoseconds. A: If you get time as string in format such as 1441963946053 you simply could do something as following: //String timestamp; Long miliseconds = Long.valueOf(timestamp); Timestamp ti = new Timestamp(miliseconds); A: I believe you need to do this: * *Convert everythingButNano using SimpleDateFormat or the like to everythingDate. *Convert nano using Long.valueof(nano) *Convert everythingDate to a Timestamp with new Timestamp(everythingDate.getTime()) *Set the Timestamp nanos with Timestamp.setNano() Option 2 Convert to the date format pointed out in Jon Skeet's answer and use that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628103", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "46" }
Q: C str functions and malloc I want to build a program which sum a big integers in C. So I'm ready with the code. The program compiling pass successfully with mingw and Visual C++ compiler. But I have a problem with the run part. The strange thing is that when I debug the program in Visual Studio there is no problems but when I run it my Windows show that the program stop working. This is the code : #include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> #include <ctype.h> #include "sum.h" int isNumber(char* number) { int lenght = strlen(number); int i,result = 0; for (i = 0 ; i < lenght ; i++) { if (isdigit(*number++)) { result = 1; } else { result = 0; break; } } return result; } int cti(char ch) { return ch - '0'; } char* addZeros(char* number,int lenght) { int num_lenght = strlen(number),size = abs(lenght - num_lenght),i; char* zeros = (char*)malloc(size); strcpy(zeros,""); zeros[size - 1] = '\0'; for (i = 0 ; i < abs(lenght - num_lenght) ; i++) { strcpy(&zeros[i],"0"); } strncat(zeros,number,size); number = (char*)malloc(sizeof(char)*size); strncpy(number,zeros,size); return number; } char* sum(char* numberOne,char* numberTwo) { if (numberOne == NULL || numberTwo == NULL) return NULL; if (!isNumber(numberOne) || !isNumber(numberTwo)) return NULL; int CF = 0; int lenghtOne = strlen(numberOne),lenghtTwo = strlen(numberTwo); if (lenghtOne == 0 || lenghtTwo == 0) return lenghtOne == 0 ? numberTwo : numberOne; int max = lenghtOne > lenghtTwo? lenghtOne : lenghtTwo,index; char* result = (char*)malloc(max); int res = 0; result[max] = '\0'; if (lenghtOne > lenghtTwo) numberTwo=addZeros(numberTwo,strlen(numberOne)); else if (lenghtOne < lenghtTwo) numberOne = addZeros(numberOne,strlen(numberTwo)); for ( index = max - 1 ; index >=0 ; index--) { res = cti(numberOne[index]) + cti(numberTwo[index]); if (((res%10) + CF) > 9) { int num = ((res%10) + CF); result[index] = (char)((int)'0'+num%10); CF = num / 10; } else { result[index] = (char)((int)'0'+((res%10) + CF)); CF = res / 10; } } return result; } int main(int argc, char *argv[]) { char* num = "12345678"; char* num2= "2341"; char* result = sum(num,num2); printf("%s\n",result); return 0; } I think that the problem is somewhere in the pointers but I'm not absolutely sure about this. Can anyone help me? A: The amount of memory you are allocating is not sufficient. It does not include space for the null character terminating the string and it does not take into account changes in the length of the result for sums such as "9" + "1". You are then writing the null terminating character after the end of the array. You should malloc with the length like this: char* result = (char*)malloc(max + 2); A: result[max] = '\0'; This is incorrect since you only allocated max characters for result. I've not studied the logic in detail but allocating max+1 characters would fix this particular problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628107", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Selecting all for the week xx, not working properly php Ok this is what i have: function getFirstDayOfWeek($iYear, $iWeekNumber) { if ( is_null($iYear) ) $iYear = date('Y'); if ( $iWeekNumber < 10 ) $iWeekNumber = '0'.$iWeekNumber; $iTime = strtotime($iYear.'W'.$iWeekNumber); return $iTime; } $firstdayofweek = getFirstDayOfWeek($data['year'], $data['week']); $mDate = date('m', $firstdayofweek); $dDate = date('d', $firstdayofweek); $min = mktime(0, 0, 0, $mDate, $dDate, $data['year']); $max = mktime(23, 59, 59, $dDate, $dDate+6, $data['year']); Where it later does: SELECT id FROM training_activities WHERE date time >= {$min} AND time <= {$max} As you may now until now, the times are saved in unix timestamp. This code is not working properly. Lets say $data year is 2011 and week 39. This shows me dates from 26/09-04/10, 8 days, while the week 39 is 29/09 - 02/10 How can i make it select and show weeks right? A: The $max month was using $dDate instead of $mDate; the following works: <?php function getFirstDayOfWeek($iYear, $iWeekNumber) { if ( is_null($iYear) ) $iYear = date('Y'); if ( $iWeekNumber < 10 ) $iWeekNumber = '0'.$iWeekNumber; $iTime = strtotime($iYear.'W'.$iWeekNumber); return $iTime; } for ($i = 1; $i <= 52; $i++) { $firstdayofweek = getFirstDayOfWeek(2011, $i); $mDate = date('m', $firstdayofweek); $dDate = date('d', $firstdayofweek); $min = mktime(0, 0, 0, $mDate, $dDate, 2011); $max = mktime(23, 59, 59, $mDate, ($dDate+6), 2011); echo date('m/d/Y',$min)." - ".date('m/d/Y',$max)." ($dDate - ".($dDate+6).")\n"; } ?> http://codepad.org/7hMJQFhq
{ "language": "en", "url": "https://stackoverflow.com/questions/7628109", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Subselect working on dev machine, but not live, with the same database, and both running mysql 5.1 This query is working perfectly on my dev machine, a PC with mysql 5.1.53 SELECT DISTINCT * FROM posts P1 WHERE user_id IN (2,1000001) AND NOT track_id = 34 AND (SELECT COUNT(*) FROM posts P2 WHERE P2.user_id = P1.user_id AND P2.id > P1.id AND P2.track_id <> 34) <= 1 GROUP BY track_id ORDER BY id desc LIMIT 5 when i run the very same piece of code in the same database on my live server (debian, mysql 5.1.39), i get this error: Unknown column 'P1.user_id' in 'where clause': How could this be? Any ideas? Result of show create table posts on the server CREATE TABLE `posts` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `track_id` int(11) unsigned DEFAULT '0', `tag_id` int(11) unsigned DEFAULT NULL, `user_id` int(11) DEFAULT '0', `comment` tinytext, `created_at` datetime DEFAULT NULL, `commentcount` tinyint(11) unsigned DEFAULT '0', PRIMARY KEY (`id`), KEY `track_id` (`track_id`), KEY `tag_id` (`tag_id`), KEY `user_id` (`user_id`) ) ENGINE=MyISAM AUTO_INCREMENT=484 DEFAULT CHARSET=utf8 | A: As a lot of comments suggested, it was an issue with case sensitivity. In the SQL query on the server, the alias of posts was set to "p1", but the subselect was looking for "P1". Mistake.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628118", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Post request via QNetworkAccessManager I have a problem while working with an object of QNetworkAccessManager class. I want to send a POST request to a web server. My code is QNetworkAccessManager *manager; manager = new QNetworkAccessManager (); QNetworkRequest req; req.setUrl(QUrl("http://example.com")); //Configure the parameters for the post request: QByteArray postData; postData.append("Login=log_name&"); postData.append("Password=some_pass"); //Now create a QCookieJar: manager->setCookieJar(new QNetworkCookieJar(manager)); //Define the Request-url: connect (manager, SIGNAL(finished(QNetworkReply *)), this, SLOT(replyFinish (QNetworkReply *))); //Send the request: manager->post(req, postData); The code of the used SLOT is: void MainWindow::replyFinish(QNetworkReply *reply) { QString answer = QString::fromUtf8(reply->readAll()); qDebug () << answer; } The problem is that the answer is an empty string,but i believe it should be some html-code that describes acceptance or rejection of the authorization. Thank you for your help. A: Most sites use a HTTP redirection after a login request (or after filling a form). And you need to test for error in the same slot. You can handle redirections (and errors) with something similar to that code. Since QNetworkAccessManager already create its own base QNetworkCookieJar object, you don't need to instantiate one if you didn't write a derived class or if you don't share a cookie jar with an other manager. But you'll need to use the same manager (or the same cookie jar) for subsequent request to be able to reuse the cookies set by the server during the login.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628120", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How can I refresh or reload the JFrame? I am doing project using Java and in that I need to reload whole JFrame after clicking particular button on that JFrame. How to do this? A: Try SwingUtilities.updateComponentTreeUI(frame); If it still doesn't work then after completing the above step try frame.invalidate(); frame.validate(); frame.repaint(); A: just use frame.setVisible(false); frame.setVisible(true); I've had this problem with JLabels with images, and this solved it A: Here's a short code that might help. <yourJFrameName> main = new <yourJFrameName>(); main.setVisible(true); this.dispose(); where... main.setVisible(true); will run the JFrame again. this.dispose(); will terminate the running window. A: You should use this code this.setVisible(false); //this will close frame i.e. NewJFrame new NewJFrame().setVisible(true); // Now this will open NewJFrame for you again and will also get refreshed A: Try this code. I also faced the same problem, but some how I solved it. public class KitchenUserInterface { private JFrame frame; private JPanel main_panel, northpanel , southpanel; private JLabel label; private JButton nextOrder; private JList list; private static KitchenUserInterface kitchenRunner ; public void setList(String[] order){ kitchenRunner.frame.dispose(); kitchenRunner.frame.setVisible(false); kitchenRunner= new KitchenUserInterface(order); } public KitchenUserInterface getInstance() { if(kitchenRunner == null) { synchronized(KitchenUserInterface.class) { if(kitchenRunner == null) { kitchenRunner = new KitchenUserInterface(); } } } return this.kitchenRunner; } private KitchenUserInterface() { frame = new JFrame("Lullaby's Kitchen"); main_panel = new JPanel(); main_panel.setLayout(new BorderLayout()); frame.setContentPane(main_panel); northpanel = new JPanel(); northpanel.setLayout(new FlowLayout()); label = new JLabel("Kitchen"); northpanel.add(label); main_panel.add(northpanel , BorderLayout.NORTH); frame.setSize(500 , 500 ); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } private KitchenUserInterface (String[] order){ this(); list = new JList<String>(order); main_panel.add(list , BorderLayout.CENTER); southpanel = new JPanel(); southpanel.setLayout(new FlowLayout()); nextOrder = new JButton("Next Order Set"); nextOrder.addActionListener(new OrderUpListener(list)); southpanel.add(nextOrder); main_panel.add(southpanel, BorderLayout.SOUTH); } public static void main(String[] args) { KitchenUserInterface dat = kitchenRunner.getInstance(); try{ Thread.sleep(1500); System.out.println("Ready"); dat.setList(OrderArray.getInstance().getOrders()); } catch(Exception event) { System.out.println("Error sleep"); System.out.println(event); } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7628121", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "28" }
Q: PHP Separate admin controllers CODEIGNITER I have some basic controllers and admin controllers, I'm trying to separate them in folder to avoid things like this one: controllers/user.php -> general users controllers/a_user.php -> for admin users I've read some things about route but couldn't find a way to do that. Thanks in advance for any help. A: Create a subfolder inside controllers folder and place your admin controllers in there.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628123", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: get all lines of a continuation line in traceback Is it possible to get all lines of a continuation line in a traceback? Example: #! /usr/bin/env python def function_with_long_name(foo, bar): raise Exception('problem?') function_with_long_name('very_important_value', 'meaningless_value') Output: $ ./test.py Traceback (most recent call last): File "./test.py", line 5, in <module> 'meaningless_value') File "./test.py", line 3, in function_with_long_name raise Exception('problem?') Exception: problem? Note that it prints only the last line of the continuation line. I would like to have all lines of the continuation line, something like this: $ ./test.py Traceback (most recent call last): File "./test.py", line 5, in <module> function_with_long_name('very_important_value', 'meaningless_value') File "./test.py", line 3, in function_with_long_name raise Exception('problem?') Exception: problem? Is this possible? I have looked at the traceback module, but the values it returns are already truncated. Example: #! /usr/bin/env python import traceback def function_with_long_name(foo, bar): print traceback.extract_stack() function_with_long_name('very_important_value', 'meaningless_value') Output: $ ./test.py [('./test.py', 6, '<module>', "'meaningless_value')"), ('./test.py', 4, 'function_with_long_name', 'print traceback.extract_stack()')] A: Someone appears to have just opened Python issue 12458 about this. Suggest you follow along there.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628124", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to change the content of ListBox when clicked on ListBoxItem? I have a ListBox and I whant to bind it to a generic list with items of my type (SubscribeUnit). List<SubscribeUnit> Subscribes = new List<SubscribeUnit>(); where class SubscribeUnit { public string Title { get; set; } public string Link { get; set; } public string Description { get; set; } public Dictionary<FeedUnit, bool> Feeds = new Dictionary<FeedUnit, bool>(); } class FeedUnit { public string Title { get; set; } public string Link { get; set; } public string PubDate { get; set; } public string Descr { get; set; } } When I click on ListBoxItem (that displays only the 'Title' property), the ListBox should change the content. To be exact it should now store (only the 'Title' property) FeedUnit's from Dictionary<FeedUnit, bool> Feeds = new Dictionary<FeedUnit, bool>(); How can I do that? Any help appriciated... A: Create a data template which changes itself when the ListBoxItem.IsSelected property becomes true using a trigger.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628126", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: googletest: construct fixtures with parameters? I have two implementations of an algorithm working on arrays and returning a single value, a slow and naive but correct method A and an optimized method B that may be buggy at corners of the input parameter space. Method B has branches depending on the size of the input array and I'd like to test B against A for different input array sizes. Both methods are templated to work with different types. I'm just starting to use googletest for the first time, but I don't really see a clear way of how to do this with a fixture (the following is simplified, there is more to set up to get the tests going and I'd also like to run other tests on the data): template<typename T, unsigned int length> // type to test on, test array size class BTest : public ::testing:Test { public: T* data; // test data public: BTest(); // allocate data, populate data with random elements ~BTest(); T run_method_a_on_data(); // reference: method A implementation }; // ... TYPED_TEST_CASE(...) // set up types, see text below TYPED_TEST(...) { // test that runs method B on data and compares to run_method_a_on_data() } In the googletest documentation the step to run the actual tests after the fixture definition would be to define the types typedef ::testing::Types<char, int, unsigned int> MyTypes; TYPED_TEST_CASE(BTest, MyTypes); but this shows the limitation, that only a single template parameter is allowed for classes derived from ::testing::Test. Am I reading this right? How would one go about this? A: You can always pack multiple parameter types into a tuple. To pack integer values, you can use type-value converters like this: template <size_t N> class TypeValue { public: static const size_t value = N; }; template <size_t N> const size_t TypeValue<N>::value; #include <tuple> /// Or <tr1/tuple> using testing::Test; using testing::Types; using std::tuple; // Or std::tr1::tuple using std::element; template<typename T> // tuple<type to test on, test array size> class BTest : public Test { public: typedef element<0, T>::type ElementType; static const size_t kElementCount = element<1, T>::type::value; ElementType* data; // test data public: BTest() { // allocate data, populate data with random elements } ~BTest(); ElementType run_method_a_on_data(); // reference: method A implementation }; template <typename T> const size_t BTest<T>::kElementCount; .... typedef Types<tuple<char, TypeValue<10> >, tuple<int, TypeValue<199> > MyTypes; TYPED_TEST_CASE(BTest, MyTypes);
{ "language": "en", "url": "https://stackoverflow.com/questions/7628131", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Polymorphism in Mongoid Is it possible to get real polymorphism in Mongoid? Example: class Company include Mongoid::Document has_many :workers, as: :workable end class Worker include Mongoid::Document field :hours belongs_to :workable, polymorphic: true end class Manager < Worker field :order has_many :contributors end class Contributor < Worker field :task end The problem with this is it goes through the worker superclass to try to figure out the referenced documents type. Which means that while HOURS can be manipulated, the fields that belong to the subclasses cannot like CONTRIBUTORS, ORDER, TASK cannot. Is there a way to make this truely polymorphic? And to elaborate when I say truely polymorphic, I mean is it possible to have the objects as workers and determine which type they are at a later time so their specific fields can be set. So I have the ability to loop over all workers but also the ability to set the worker's specific fields such as order and task when the Contributor or Manager is constructed. Also if polymorphism is doable, what would a controller and view look like that fills out a Manager and Contributor's fields in the company? Thanks A: I had a similar problem before.. You'll need to google for "Mongoid Inheritance" and "Mongoid Self referential relationship" -- see also: Mongoid 3 (current) * *http://mongoid.org/en/mongoid/docs/documents.html#inheritance *http://mongoid.org/en/mongoid/docs/relations.html#has_many Mongoid 2 * *http://two.mongoid.org/docs/documents/inheritance.html *http://two.mongoid.org/docs/relations/referenced/1-n.html Mongoid also has the concept of "Inheritance" .. with which you can model extending the behavior of classes , like Manager < Worker , and Contributer < Worker in your example -- all three Classes are stored in the "Worker" collection. You might also want to look at the "ancestry" Gem. try: class Company include Mongoid::Document has_many :workers end class Worker include Mongoid::Document field :hours belongs_to :company end class Manager < Worker field :order references_many :contributors, :class_name => "Worker" end class Contributor < Worker field :task belongs_to_related :manager, :class_name => "Worker" end
{ "language": "en", "url": "https://stackoverflow.com/questions/7628135", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }