text
stringlengths
8
267k
meta
dict
Q: Adding Links to HTML-output in Powershell I have wrote a PowerShell script that catches all of the running IIS worker processes on a remote server and returns back diagnostic information (appppolname, cpu, virtual memory etc). It is then converted to HTML and displayed to the user. $server = Read-Host Enter server name... if (!(test-connection -computername $server -quiet)) { Write-Host $server is not pingable, does not exist, or timed out. Please try a different server. } else { $command = {add-pssnapin WebAdministration function get-iiswp([string]$name="*") { $list = get-process w3wp -ea SilentlyContinue if ($error) { Write-Host There are no IIS worker processes currently running. Error Message: $error } else { foreach($p in $list) { $filter = "Handle='" + $p.Id + "'" $wmip = get-WmiObject Win32_Process -filter $filter if($wmip.CommandLine -match "-ap `"(.+)`"") { $appName = $matches[1] $p | add-member NoteProperty AppPoolName $appName } } $list | where { $_.AppPoolName -like $name } } } get-iiswp | select-object -property * } invoke-command -computername $server -scriptblock $command | ConvertTo-HTML ID, AppPoolName, @{Label="CPU(s)";Expression={if ($_.CPU -ne $()) {$_.CPU.ToString("N")}}}, @{Label="Virtual Memory";Expression={[int]($_.VM/1MB)}}, @{Label="Physical Memory";Expression={[int]($_.WS/1024)}} | Out-file D:/test.html } I am looking for a way to format the HTML-output to convert the AppPoolName output of the table into a link where it would use the AppPoolName and PID within the link itself (ex. http://powershell.com/requests.ps1x?PID=$PID&AppPoolName=$AppPoolName If any one has any thoughts or ideas that could solve and point me in the right direction, it would be much appreciated. Thanks! -----------Update------------------- Here is the example output: <tr><tr><tr> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>HTML TABLE</title> </head><body> <h2>IIS Worker Process Diagnostic</h2> <table> <colgroup> <col/> <col/> <col/> <col/> <col/> </colgroup> <tr><th>ID</th><th>AppPoolName</th><th>CPU(s)</th><th>Virtual Memory</th><th>Physical Memory</th></tr> <tr><td>3820</td><td>AppPool1</td><td>4.92</td><td>355</td><td>74200</td></tr> <tr><td>4108</td><td>AppPool2</td><td>0.23</td><td>106</td><td>21380</td></tr> <tr><td>4940</td><td>AppPool3</td><td>0.20</td><td>590</td><td>39444</td></tr> <tr><td>7244</td><td>AppPool4</td><td>0.33</td><td>596</td><td>42556</td></tr> </table> </body></html> A: I think you could replace the AppPoolName (in ConvertTo-HTML) with this... @{Label="AppPoolName";Expression={ '<a href="http://powershell.com/requests.ps1x?PID=$($_.PID)&AppPoolName=$($_.AppPoolName)">$($_.AppPoolName)</a>' }} That's just off the top of me head and not tested... :-)
{ "language": "en", "url": "https://stackoverflow.com/questions/7517726", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Html Helper CakePHP Fatal error: Call to a member function charset() on a non-object in D:\xampp\htdocs\demo\app\controllers\test_controller.php on line 10 PHP Controller Code: <?php class TestsController extends AppController { var $name="Tests"; var $helpers = array('Html'); var $uses=array(); # demo action to check wheather html helper is working or not function index() { echo "111111111"; echo $this->Html->charset(); echo "22222222222"; } } ?> I am getting the above error while hitting the url: http://localhost/demo/tests I am using CakePHP 2.0 ALPHA (latest version). Please let me know what is the root cause. A: Following CakePHP's MVC convention, you should by using behaviors in models, components in controllers and helpers in views. You are currently trying to use a helper in a controller, which won't work. I suggest you go back and have another look at the documentation, but for something like HtmlHelper::charset() you really want to be calling that once in the <head> tag of your layout (which is also part of the view layer): * *http://book.cakephp.org/2.0/en/views.html?highlight=layout#layouts
{ "language": "en", "url": "https://stackoverflow.com/questions/7517728", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: get a string line from bunch of text that contain specific word(s) with php I have some code generated by FCKEditor, eg. as follow : $content = "<p>some text with some tags and so on.. [here is html tag image source with image url] another some text with some tags and so on.. </p>"; I assigned all those code into a variable called $content. I want to "extract" and grep only the image source url from $content and put the result into variable $img_url, so I can echo the $img_url Any ideas how can I do that? A: If you have only one image tag you can directly use this function get_string_between($string, $start, $end){ $string = " ".$string; $ini = strpos($string,$start); if ($ini == 0) return ""; $ini += strlen($start); $len = strpos($string,$end,$ini) - $ini; return substr($string,$ini,$len); } echo $img_url = get_string_between($content,'<img src="','</img>'); If You have multiple then you should explode the $content and use the function as u wanted. A: $content = '<p style="text-align: center; "><img width="300" height="225" style="padding-top: 5px; padding-right: 5px; padding-bottom: 5px; padding-left: 5px; margin-right: 5px; " border="2" align="left" alt="" src="/datafitur/news_img/1/201109/Steve-Jobs.jpg" /><b><span style="font-size:14.0pt;mso-bidi-font-size:.....</p>' $explodeContent = explode('src=', $content); $explodeSrc = strstr($explodeContent[1], '/>', true); $explodeSrc = trim($explodeSrc,'"'); $explodeSrc = trim($explodeSrc,' '); Edit: I have changed to use strstr instead of explode in the second step.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517731", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get new image size after changing src in IE I have an image element with a spinner gif. I later dynamically change the src of that image with jQuery, and I want to get the actual width and height of the new image. Here is my code: function loadImage() { $('#uploaded-image').load(function() { var img = document.getElementById('uploaded-image'); // These statements return the correct values in FF and Chrome but not IE imgWidth = img.clientWidth; imgHeight = img.clientHeight; }); $('#uploaded-image').removeAttr('width').removeAttr('height').attr('src', imgUrl); } This works perfectly in Chrome and Firefox, but IE always returns the size of the original spinner gif instead of the new image. How can I get the width and height of the new image in IE? Notes: I've tried the jQuery .width() and .height() methods in addition to the pure Javascript approach, with the same results. The .load event is being fired as expected in all browsers. A: Use offsetHeight and offsetWidth in IE. Check this out in your IE: http://jsbin.com/abopih/5 var imgUrl = "http://www.google.com/intl/en_com/images/srpr/logo3w.png"; var img = document.getElementById('uploaded-image'); $('#uploaded-image').click(function() { imgWidth = img.clientWidth; imgHeight = img.clientHeight; $('#uploaded-image').removeAttr('width').removeAttr('height').attr('src', imgUrl); console.info('clientWidth: ', img.clientWidth); console.info('clientHeight: ', img.clientHeight); console.info('offsetWidth: ', img.offsetWidth); console.info('offsetWidth: ', img.offsetWidth); }); A: You could create a hidden div and place the image in there in order to get the size. Just make sure the hidden div isn't done with display:none, because then it will have no dimensions. Use visibility:hidden, grab the dimensions, and then remove it. A: Make sure you remove css height and width as well: $('#uploaded-image').css({ height: "auto", width: "auto" }); A: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <input type="file" id="file" /> <script type="text/javascript" charset="utf-8"> $("#file").change(function(e) { var file, img; file = document.getElementById("file"); if (file!=null) { img = new Image(); img.src = file.value; img.onload = function() { alert(img.width + " " + img.height); }; img.onerror = function() { alert( "not a valid file: " + file.type); }; } }); </script> A: It seems to be a cache problem. Add this to your image source url: imgUrl += new Date().getTime();
{ "language": "en", "url": "https://stackoverflow.com/questions/7517732", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Zend Filter Encryption / Decryption adds nullbytes when decrypting I am trying to do some symmetric encryption on some data with the Zend_Filter_Encrypt function. The problem is if i encrypt some data and then later decrypt it, there are nullbytes behind the decrypted data and I have no idea why. For instance: Plaintext: test Encrypted: ����pk� Decrypted: test���� It seems to be padding nullbytes at the end of the decrypted text to make it's length equal to some 2^n (a string with 11 characters is padded to fit 16 => 2^4). The most obvious thing would be to just strip these characters but I want to know why this is happening... This is the code I'm using, which is different than how the documentation wants you to do it because their code just doesn't work for me (see: http://framework.zend.com/manual/en/zend.filter.set.html) define('VECTOR','EXfPCW23'); //example, not the actual used VECTOR / KEY $key = 'lolwatlolwat'; public function encryptPassword($password, $key) { $filter = new Zend_Filter_Encrypt(); $filter->setEncryption(array('key' => $key)); $filter->setVector(VECTOR); return $filter->filter($password); } public function decryptPassword($password, $key) { $filter = new Zend_Filter_Decrypt(); $filter->setEncryption(array('key' => $key)); $filter->setVector(VECTOR); return $filter->filter($password); } A: You have to use rtrim function on Decrypt string. Example: public function decryptPassword($password, $key) { $filter = new Zend_Filter_Decrypt(); $filter->setEncryption(array('key' => $key)); $filter->setVector(VECTOR); return rtrim($filter->filter($password); } A: Does the Zend documentation tell you how to specify the padding? If so then specify a reversible padding; as you have found, zero padding is not reversible. Otherwise, find out what size padded plaintext Zend is expecting and add PKCS7 padding yourself. This is easily recognisable and removable afterwards.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517736", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SQL selecting records from one table and using this as input to another table to delete records I have table1 with columns: def_id, def_name, username etc I have another table table2 which has some association: assoc_id,parent_id,child_id The parent_id , child_id are actually def_id's from Table1 . They get inserted into Table2 based on parent_child relation user action in GUI. Now I want to select all def_id for a particular username from Table1 and then use that input to delete all the records if those def_ids are part of the parent_id or child_id from Table2. How do I do this in SQL? I am using Sybase database. Any help will be appreciated A: Delete Table2 Where parent_id In (Select def_id from table1 Where username = @username) Or child_id In (Select def_id from table1 Where username = @username) Or Delete t2 From table2 t2 Where Exists (Select * From Table1 Where def_id In (t2.parent_Id, t2.child_Id)) A: An easy way is adding a subquery to the where clause. DELETE ab FROM AuthorArticle AS ab WHERE ab.AuthID=(SELECT AuthID FROM Authors WHERE AuthorLastName='Yin') Never used Sybase, but this is basic SQL and should work. A: Try: DELETE table2 FROM table2 INNER JOIN table1 ON table1.def_id IN (table2.parent_id, table2.child_id)
{ "language": "en", "url": "https://stackoverflow.com/questions/7517738", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to implode array that uses array_push in foreach loop My tags are showing in the inner foreach loop in the right order. I would like to comma separate them but am not sure how. Is there a better way to display my tags without using the second foreach loop? $people = array(); while($row = mysqli_fetch_array($rs, MYSQLI_ASSOC)){ if(!isset($people[$row["id"]])){ $people[$row["id"]]["id"] = $row["id"]; $people[$row["id"]]["tag"] = $row["tag"]; $people[$row["id"]]["tags"] = array(); } array_push($people[$row["id"]]["tags"], array("id"=>$row["tags_id"],"tag_name"=>$row["tag"])); } foreach($people as $pid=>$p){ echo "(#{$p['id']}) "; foreach($p["tags"] as $tid=>$t){ echo "<a href='#'>{$t['tag_name']}</a> "; } echo "<br><br>"; } A: You don't need to use array_push, since you're only adding one element to the array. You can save the overhead of calling a function by using the syntax: $people[ $row["id"] ]["tags"][] = array(...); My answer depends on the necessity of the variables saved from the database. In your supplied code, you're only using the id and tag values from the database in the nested foreach loops. If this is this case, then you can simplify your arrays so you can use implode() on a new tags array. I have not tested this since I do not have your database schema, but I believe it will work. <?php $people = array(); $tags = array(); while( ($row = mysqli_fetch_array( $rs, MYSQLI_ASSOC))) { if( !isset( $people[$row['id']])) { $people[ $row['id'] ] = array( 'id' => $row['id'], 'tag' => $row['tag']); $tags[ $row['id'] ] = array(); } $tags[ $row['id'] ][] = $row['tag']; } foreach( $people as $pid => $p) { echo "(#{$p['id']}) "; echo '<a href="#">' . implode( '</a><a href="#">', $tags[ $p['id'] ]) . '</a>'; echo '<br /><br />'; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7517739", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Concatenate DateTimePicker in VS2010 How can I concatenate the values of two datetimepicker? DateTimePicker1 - this is for the the DATE mm/dd/yyyy DateTimePicker2 - this is for the the TIME hh:mm:ss I want a value of ... mm/dd/yyy hh:mm:ss in one variable, how can I do that? A: One easy way would be DateTime dt = new DateTime(dtp1.Year, dtp1.Month, dtp1.Day, dtp2.Hour, dtp2.Minute, dtp2.Second); Please check the order of the parameters, I am writing from memory. Here dtp1 is a DateTime object from the first datetime picker.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517744", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Master Page Loading Multiple Pages I'm developing a web site that has a master page that consists of 4 different pages that will load simultaneously (using ContentPlaceHolder). However, when I test the website on my local machine, only one page renders at a time (depending on the URL I type in). Is there any way that on Page Load, to tell the master (or maybe the browser?) to load all 4 pages instead of only the page that was directly requested from the browser? A: It sounds like you should be using iframes. Context place holders are designed so that a single page can display its content against a common theme or background - the master page. You can have multiple context place holders but they ALL must be populated by the page being loaded. For instance, 1 master page could have a place holder for a menu and another for the content and a third for a news feed sidebar, but the aspx page using the master page has to define the content of all 3 place holders. A: A master page doesn't work like a frameset that you display other pages in, you only display a single page using the frameset. You can have several content placeholders in the master page, but all content still comes from the same page. If you want to have the content in separate files, you should create user controls that you can include in a page. A: Maybe I'm not understanding, but add another page selecting "Web Form using Master Page" from the Add New Item dialog and then on the next window select your master page. Try navigating to the page you just added. A: I think you're misunderstanding master pages, the master page does not load anything. The master page defines some common layout (and possibly code), and then you create child pages which only need to supply the content that is not defined in the master pages via the ContentPlaceHolder. You then load the child pages, one at a time.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517747", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can i print a list contents in a stderr statement in python Here is the scenario: I want to be able to print the C Style statement: print >> sys.stderr, ("%s does not exist"%m_args) either inside the function, or in __main__ but I am getting Exception : print >> sys.stderr, ("%m_args[1] does not exist"%m_args[1]) IndexError: list index out of range Code: #!/usr/bin/env python import re, os, sys, jira, subprocess from optparse import OptionParser import warnings from collections import namedtuple global m_args def verify_commit_text(tags): for line in tags: if re.match(r'[^\NO-TIK]',line): return False elif re.match(r'[^\NO-REVIEW]', line): return False elif re.match(r'[a-zA-Z]+-\d+', line): # Validate the JIRA ID m = re.search("([a-zA-Z]+-\d+)",line) m_args = m.group(1) m_args = [m_args] print 'm_args' print m_args print type(m_args) if CheckForJiraIssueRecord(m_args): return False else: #warnings.warn("%s does not exist"%m_args) print >> sys.stderr, ("%s does not exist"%m_args) return True else: return True def CheckForJiraIssueRecord(my_args): # turn off stdout #sys.stdout = open(os.devnull) #sys.stderr = open(os.devnull) com = jira.Commands() logger = jira.setupLogging() jira_env = {'home':os.environ['HOME']} command_name = "cat" server = "http://jira.server.com:8080/rpc/soap/jirasoapservice-v2?wsdl" options = namedtuple('Options', 'user password')('user','password') jira.soap = jira.Client(server) jira.start_login(options, jira_env, command_name, com, logger) issue = com.run(command_name, logger, jira_env, my_args) if issue: return True if __name__ == '__main__': commit_text_verified = verify_commit_text(os.popen('hg tip --template "{desc}"')) if commit_text_verified: sys.exit(1) else: print >> sys.stderr, ('[obey the rules!]') print >> sys.stderr, ("%s does not exist"%m_args[0]) sys.exit(0) A: Look at this line: print >> sys.stderr, ("%s does not exist"%m_args) from the verify_commit_text() function. Now, look at the line causing the error in __main__: print >> sys.stderr, ("%m_args[0] does not exist"%m_args[0]) You need to replace the %m_args[0] inside the string with %s. Also, you're using two different m_args -- you're trying to print from the global one, while you made a local version in verify_commit_text(). Add global m_args to the top of verify_commit_text() to get rid of the index error (for the case that your last elif regex matched, you'll still get it for the case that you hit the else clause.) You also appear to have other problems. You have a for loop in verify_commit_text() but you're only ever entering the first iteration, because all of your if branches return. You're also sending sys.stderr to os.devnull, so you won't see anything even if your prints work. Also, you've got your exit condition wrong. You're returning True on failure, and then using exit(0) if the result was True -- change it to if not commit_text_verified: One more thing: CheckForJiraIssueRecord(m_args) doesn't have a return so it's always returning None, so the if condition it's in will never be True -- you'll always go to the else.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517756", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: MySql Update first entry that has X and Y else insert new record I have a chat user entry in a MySql table - id (primary key, autoincrement) - the chat user id user_id - the users id as it pertains to our product room_id - the id of the room your in If a chat operator enters the room, leaves, and then comes back - as it is now - will create two entries in the room (INSERT INTO chatuser ...) I know INSERT IF NOT EXISTS syntax, however I want to IF NOT EXISTS not on the primary key, but WHERE user_id = x AND room_id = y (which will be the same if they re-enter a room they have been in) something like INSERT INTO chatuser SET user_id=4, room_id=2 IF ENTRY DOESNT EXIST WITH THOSE VALUES ALREADY ;) thank you A: If you have a unique index on (user_id,room_id), you can do INSERT ... ON DUPLICATE KEY UPDATE (or INSERT IGNORE if you don't need to update anything when the record already exists): INSERT INTO table_1 (user_id, room_id, enter_date) VALUES (1,1, NOW()) ON DUPLICATE KEY UPDATE enter_date = NOW() // or INSERT IGNORE INTO table_1 (user_id, room_id) VALUES (1,1) A: I think what we have here is a design issue. You have 3 tables, a user table, a room table and a table that links that two. The last one is what we're working with here. Now, if you want to log every time a user enters a room, the table design you have is ideal. However it seems that is not what you are doing. It seems you want an entry for just the last visit. In this case your table should not have an auto incrementing primary key, and instead should have userID and roomID to both be parts of a multi-column primary key. Modify your table to that set-up then run your insert statement with ON DUPLICATE KEY UPDATE clause.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517770", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Mocking a method call generically Suppose I have a strongly typed caching interface that I want to mock. It takes objects of any kind and returns them, like this: interface IMyCache { void Add( int key, object obj ); T Get<T>(int key); } Can I write a RhinoMocks stub that will mock any parameter type that I send to it? Ideally it would just look something like this: var mock = MockRepository.GenerateStub<IMyCache>(); mock.Stub( m => m.Get<T>(1234)).Return( new T()); This doesn't work because it's expecting T to be a concrete class, but I'd like to genericize it. Is this possible? A: I don't think you can. When writing tests with rhino mocks, you need to follow the rules of the compiler, and avoiding to specify the generic type T, makes the compiler unhappy. If you need to reuse that stub-code between multiple tests, each using different types for T, you can make a helper method as proposed here: Rhino Mocks: How to stub a generic method to catch an anonymous type?
{ "language": "en", "url": "https://stackoverflow.com/questions/7517775", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: openDatabase() method throws an exception (SECURITY_ERR: DOM Exception 18) openDatabase() method throws an exception (SECURITY_ERR: DOM Exception 18) on iPad 4.3 and also on all iOS Simulators 4.x when the database size is specified greater than 5 MB. Compiling under XCode 4.2 (Mac OS X 10.6.8) using PhoneGap 1.0.0. Can we circumvent this restriction? Here is a sample code: <!DOCTYPE html> <html> <head> <script src="phonegap-1.0.0.js"></script> <script> try { var db = window.openDatabase("TMA", "1.0", "TMA Mobile Database", 1024 * 1024 * 10); } catch (err) { alert(err); } </script> <meta name="viewport" content="width=320; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;" /> </head> <body> </body> </html> A: According to this resource the maximum size imposed by the iOS itself is 5mb. Once it reaches a 5mb size it will ask the user if they want it to grow larger. I doubt there is any good way around it. Have you tried creating more than one DB? Perhaps two 5mb DBs would work for you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517778", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to give asp:Localize the localized text? My ASP.NET page has some html: Default.aspx: <h2><asp:Localize meta:resourcekey="lblTitle" Text="Welcome to so" runat="server"></h2> Now i want to localize that text. So i've created a resource file Default.aspx.resx. Following the examples of Microsoft, Microsoft, Microsoft, CodeProject, and Stackoverflow i create an lblTitle.Text entry: Except that little red error indicator's hint says, The resource name "lblTitle.Text" is not a valid identifier. How do i localize with asp:Localize? How do i localize with meta:? How do i create a resx? Update: Renamed App_GlobalResources to App_LocalResources: Web.config (partial): <system.web> <compilation debug="true" targetFramework="4.0"/> Update 2: What i don't understand is that i'm following the instructions on MSDN: To edit the resource file by using the Resource Editor * *In Solution Explorer, open Sample.aspx.resx. In the Resource Editor, under Value, are the Text properties for each of the controls that you placed onto your page. Changing the value here will change the value for the default culture. *Set ButtonResource1.Text to Edited English Text. *Save the file. i've also tried * *lblTitle.Text *lblTitle-Text *lblTitle_Text *lblTitle *lblTitleText A: You did everything right, but put your ressource file in the wrong folder. Use App_LocalResources instead of App_GlobalResources. See MSDN for more info on the difference between local and global ressource files: A local resources file is one that applies to only one ASP.NET page or user control (an ASP.NET file that has a file-name extension of .aspx, .ascx, or .master). You put local resource files in folders that have the reserved name App_LocalResources. Unlike the root App_GlobalResources folder, App_LocalResources folders can be in any folder in the application. You associate a set of resources files with a specific Web page by using the name of the resource file.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517781", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Inherit a class but it's usually created with a static method? I've got a class that I would like to inherit. i.e. ExpenseForm should inherit from Spreadsheet. Spreadsheet is provided by a third party: I can't change it. But parent class instances are usually generated with a static method: Spreadsheet myExpenses = Spreadsheet.Open(filename); (And Spreadsheet implements iDisposable, so the above statement is actually at the top of a using section, but I don't think that really affects this.) I'd like to have ExpenseForm myExpenses = ExpenseForm.Open(filename); This fails, of course, since ExpenseForm.Open (inherited from Spreadsheet) returns a Spreadsheet object. What's the best way to solve this? Maybe extension methods? (I have no experience with those.) I've gone a different direction; ExpenseForm now has an instance of Spreadsheet. (This feels a little messier, since I have to keep track of my disposable object to clean up when I'm done.) But it seems like I'm missing a way to solve the original inheritance problem. A: If Spreadsheet objects can only be created by means of a static function, then inheritance is not an option. Just provide your own Open static function within ExpenseForm that returns an object of that kind. A: Well you can create your own ExpenseForm.Open method easily enough: public static new ExpenseForm Open(string file) { // Do whatever you need } That's assuming you can create a subclass, i.e. that there are appropriate constructors you can chain to. You say that you would normally use Spreadsheet.Open, but are there protected or public constructors available? Personally I'd favour the composition route anyway - do you actually want other code to treat an ExpenseForm as if it were any other kind of Spreadsheet? I'm generally more of a fan of composition than inheritance - it makes code easier to reason about, in my experience.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517788", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Iterating through prefixes with Python I have a hierarchical descriptor string that looks like foo:bar:baz where elements in the hierarchy are delimited by :, and I would like to iterate through the hierarchy levels. Is there an easy way to do this, something easier than this: def hierarchy(s): segments = s.split(':') for i in range(len(segments)): prefix = ':'.join(segments[0:i+1]) print prefix # or do something else instead of prefix A: How about: In [9]: [s[:m.start()] for m in re.finditer(':|$', s)] Out[9]: ['foo', 'foo:bar', 'foo:bar:baz'] A: A more readable solution: def heirarchy(s): segments = s.split(':') result = [] for segment in segments: result.append(segment) yield ':'.join(result)
{ "language": "en", "url": "https://stackoverflow.com/questions/7517789", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Facebook Connect Debugger and site won't use Meta Tags Possible Duplicate: How does Facebook Sharer select Images? I'm trying to use Facebook Comments on a Drupal website correctly. The comment box shows up and works exactly as I want it to, but when I go to facebook debugger http://developers.facebook.com/tools/debug it tells me that none of the required open graph meta tags (og:title, etc.) are set. It's not recognizing any of the meta tags, which also means I can't use the fb:admins tag to moderate comments. My problem sounds very similar to this one: Missing og meta tags when running debug but I manually set the Content-Length parameter using PHP and the meta Tags still are not being recognized by facebook. I'm running PHP 5.2.9, and I have NO access to upgrading or editing it at all. (University environment, they're a trifle slow and obfuscating when asking for server changes.) I've found multiple questions on Stack Overflow along similar lines, and have tried implementing all the suggested fixes to no avail, any help would be appreciated! Please let me know if I left out any needed info! I'm getting quite frustrated here, it took about 3 minutes flat to get the facebook comments to work, and now hours and hours of work still haven't resolved this issue. . . <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN" "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:og="http://opengraphprotocol.org/schema/" xmlns:fb="http://www.facebook.com/2008/fbml"> <head> <title><?php print $head_title ?></title> <script type="text/javascript" src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script> <meta property="fb:app_id" content="{my app id}" /> <meta property="fb:admins" content="{my facebook id}"/> <meta property="og:title" content="<?php echo $title; ?>" /> <meta property="og:type" content="sports_team" /> <meta property="og:url" content="<?php echo $url; ?>" /> <meta property="og:image" content="http://example.com/logo-200.jpg" /> <meta property="og:site_name" content="Site Name" /> A: Putting those meta tags on my page worked so I think you have the tags correct. http://developers.facebook.com/tools/debug/og/object?q=http%3A%2F%2Fpaulisageek.com%2Ftmp%2Fso_7517794.php Maybe you are issuing content before the <head>? Or your webserver isn't responding well to an HTTP query with a Range: header? Check your access logs for the exact query Facebook is making to see what to test.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517794", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Keeping subrepos in sync on central server I keep thinking I understand subrepos and how I can make them work for my teams workflow, but clearly I don't, because every time I try to implement some basic workflow, something doesn't end up working right. I've read pretty much everything there is to read about subrepos online, and I follow all of the trivial examples people post, but when I try to do something more complicated. Or maybe I do understand it perfectly well, and what I'm trying to do is just not something that works well. Lets get the basics out of the way. Lets say I have a remote "blessed" collection of repos. http://acme.com/BlessedRepos/ProjA /LibA /LibB So I do a clone of /ProjA to C:\ProjA and clone /LibA to C:\ProjA\LibA and /LibB to C:\ProjA\LibB. I create my .hgsub file with LibA = http://acme.com/BlessedRepos/LibA LibB = http://acme.com/BlessedRepos/LibB I commit everything. I can then push ProjA and all is well. So now someone on my team can go clone /PrjoA to C:\dev\ProjA and it will bring down LibA and LibB too as subrepos. This person can easily push/pull from the "blessed repo" just like I can. So good so far. Now, I say: Ok, ProjA Team, stop pushing to the blessed repo, that's for me to do after reviewing your work. Starting now, I want you all to push your changes to the ProjA dev and ProjA QA remote repos located at: http://acme.com/Dev/ProjA http://acme.com/QA/ProjA This is where we stop. Trying to push to http://acme.com/Dev/ProjA will only push /ProjA, while /ProjA/LibA and /ProjA/LibB get pushed back to their original location in the blessed repo and not the desired location of http://acme.com/Dev/ProjA. Now, I could have setup my .hgsub file as LibA = ../LibA. This would work initially, but if I were to do a clone of ProjA from the blessed repo, it fails to get LibA or LibB, I believe because it's expecting to find local repos LibA and LibB as siblings to the ProjA repo I'm cloning. What I mean is if I'm cloning to http://acme.com/BlessedRepos/ProjA to C:\Test\ProjA it will fail because it expect to find an existing repo at C:\Test\LibA. I could also have setup my hgsub as LibA = LibA. But doing this fails when you try to push to the blessed repo as LibA is not a nested of ProjA in the blessed space. I could create them, but then I'm never pushing back to http://acme.com/BlessedRepos/LibA, only to http://acme.com/BlessedRepos/ProjA/LibA, and then it seems that has defeated the purpose of the subrepo to begin with. I'm pretty sure my first method could work if I also had some script that I would run that would go through and change out all the values in the .hgsub file from "blessed" remote locations to the "dev" and "QA" locations, but this seems less than ideal. So. If there is anyone out there that really groks this stuff, could you either explain to me where I've gone wrong, or how I could achieve my original workflow using subrepos, or maybe just confirm that I am going after something that isn't really suited for subrepos. If it helps to understand the situation, we have probably something like 15-20 "products/solutions" and 50 "shared" projects. Any of the 15-20 products can make use of N number of the 50 shared projects in it's solution. A: The key part you are missing is that you can expose the LibA and LibB repositories multiple times on the server without having multiple copies on the server. Please see my answer to another question about subrepos for the details. Also, just come talk to us at #mercurial if you have problems like that -- that's much better than writing long posts on StackOverflow since that's not where the Mercurial community is anyway. You can also use the mailinglists we have.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517795", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Spring form, create elements client side usig javascript I have a spring form, with backing object that includes a LazyList - works hunky dory. The form initally shows: <tr><td> <form:textarea path="myList[0]" cssClass="myClass" rows="2" cols="35"/> </td><tr> <tr><td> <form:textarea path="myList[1]" cssClass="myClass" rows="2" cols="35"/> </td><tr> When a user focusses on the final textarea I want another one to be appended. The html and javascript I have OK, its the binding to the spring backing object that is a problem, my javascript so far: var myStr = '<tr><td>'+ '<form:textarea path="myList[2]" cssClass="myClass" rows="2" cols="35"/>'+ '</td><tr>' function myAppend(){ jq('#myTable tr:last').find("textarea").unbind('focus'); jq('#myTable tr:last').after(myStr); jq('#instructionTable tr:last').find("textarea").bind('focus', function() { myAppend(); }); } However the rendering is screwed up ... any tips ? I've found this, which performs and ajax call for each new line. Is their any other option ? A: The spring <form:textarea ... /> tag is evaluated on server side. It renders the according HTML Element based on the given tag parameters. So a: <form:textarea path="name"/> is rendered to <textarea id="name" name="name"></textarea> So you have to append a <textarea /> Element with your javascript. The reason for using the tag is to bind the submited value to the 'commandBean' provided by your spring controller.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517801", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: maven tomcat7 deploy POM.xml: <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>tomcat-maven-plugin</artifactId> <configuration> <url>http://localhost:8080/manager/html</url> <server>myserver</server> <path>/test</path> <warFile>${project.build.directory}/${project.build.finalName}.war</warFile> </configuration> </plugin> Eclipse used: Eclipse indigo 3.7 with m2e plugin modified Tomcat7/conf/tomcat-users.xml <role rolename="admin"/> <role rolename="manager"/> <user username="admin" password="admin" roles="admin,manager"/> </tomcat-users> Context.xml Tomcat7/conf/context.xml, change <context> to <Context antiJARLocking="true" antiResourceLocking="true"> under apache-maven\conf\settings.xml add following entry under server tag: <servers> <server> <id>myserver</id> <username>admin</username> <password>admin</password> </server> Start tomcat server. target run: tomcat:deploy and tomcat:undeploy getting following error: [ERROR] Failed to execute goal org.codehaus.mojo:tomcat-maven-plugin:1.1:redeploy (default-cli) on project test: Cannot invoke Tomcat manager: Server returned HTTP response code: 403 for URL: http://localhost:8080/manager/html/deploy?path=%2Ftest&war=&update=true -> [Help 1] [ERROR] [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch. [ERROR] Re-run Maven using the -X switch to enable full debug logging. [ERROR] [ERROR] For more information about the errors and possible solutions, please read the following articles: [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException project name: test war file name: test-1.0-SNAPSHOT.war similar issue found but didnot get much use: Tomcat-maven-plugin 401 error tomcat-maven-plugin 403 error A: Though a late answer , someone might find this useful. If you are using maven3 and tomcat7.The below method worked for me.I was not aware of the change in application manager endpoint in tomcat7. Environment - Apache Maven 3.0.4,apache-tomcat-7.0.34,Windows 7 Tomcat7 has changed its deployment end point from http://tomcatserver:8080/manager/html to http://tomcatserver:8080/manager/text . So my pom.xml will be <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>tomcat-maven-plugin</artifactId> <configuration> <url>http://tomcatserver:8080/manager/text</url> <server>tomcat</server> <path>/myWebApp</path> </configuration> </plugin> In tomcat-users.xml <role rolename="manager-gui"/> <role rolename="manager-script"/> <role rolename="manager-jmx"/> <role rolename="manager-status"/> <role rolename="admin-gui"/> <role rolename="admin-script"/> <user username="root" password="root" roles="manager-gui,manager-script,manager-jmx,manager-status,admin-gui,admin-script"/> In maven settings.xml <server> <id>tomcat</id> <username>root</username> <password>root</password> </server> In context.xml , though this is optional and is not related to maven3 deployment to tomcat7 ,sometimes jar locking might happen,so to be on the safer side. <Context antiJARLocking="true" antiResourceLocking="true"> Now issue mvn tomcat:deploy Remember to start tomcat before maven deployment. If deployment is success , your application will be available at http://tomcatserver:8080/myWebApp A: Add manager-gui to the roles: <user username="admin" password="admin" roles="admin,manager,manager-gui" /> And restart Tomcat. Make sure that your XML configuration files are in use. A simple way to do this is writing an unclosed tag inside them and checking the error messages. If you don't get any error message you've written in an unused XML. A: in tomcat 7 you should set <user username="admin" password="admin" roles="manager-script,manager-gui" /> to deploy using maven plugin A: For tomcat 7 you're using the wrong goals. Try tomcat7:deploy and tomcat7:undeploy instead. A: Found Quick Solution on Mentioned Website... http://www.avajava.com/tutorials/lessons/how-do-i-deploy-a-maven-web-application-to-tomcat.html Working as expected in Eclipse and Sprint Test Suite Note :- I have used clean tomcat:deploy, worked perfectly for me.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517808", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Cross Join in SQL 2005 with like Below are two queries. I get correct returns in Access but NO returns in SQL. Is my syntax in the SQL version wrong? Curiously, even if I leave out the second part of the WHERE statement, the returned values don't make sense (i.e. last names = tblx.Last Name = Hull / tbly.Last Name = Morris)...Any ideas? --SQL 2005 SELECT tblx.[Last Name], tblx.[First Name] FROM tblx cross join tbly WHERE (tblx.[Last Name] Like '%[tbly].[Last Name]%') AND (tblx.[First Name] Like '%Right([tbly].[First Name],3) %') --Access 2007 SELECT tblx.[Last Name], tblx.[First Name] FROM tblx cross join tbly WHERE (((tblx.[Last Name]) Like "" & [tbly].[Last Name] & "") AND ((tblx.[First Name]) Like "" & Right([tbly].[First Name],3) & "")) A: It should be: SELECT tblx.[Last Name], tblx.[First Name] FROM tblx cross join tbly WHERE (((tblx.[Last Name]) Like '%' + [tbly].[Last Name]+'%') AND ((tblx.[First Name]) Like '%' + Right([tbly].[First Name],3) +'%')) Same for Acess sql.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517815", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Sending a command to screen via PHP? I was wondering how I could execute a command through PHP into a screen running on my virtual private server. i.e. if(submit){ do "say This is a minecraft server." in screen. } Thanks in advance, A: Still unclear on exactly what you mean, but if this is what you're looking for, you can execute linux commands by using the backtick operator, such as echo `ls`; to print the contents of the directory where the script is located. So if you wanted to print commands to your server, you could do it that way. A: If you are running the script under screen, then just echo or print the data you want to display. Otherwise you can: * *make a system call to write or wall *write to a file that you are tail -fing in the screen (or some other system by which the screen polls something for new messages) *run a service in the screen that you can connect to over the network
{ "language": "en", "url": "https://stackoverflow.com/questions/7517818", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Correct way of php concatenation Hey is this the correct way to do concatenation? it does not seem to want to work for me!. $driver1points = 0; $driver2points = 0; $driver3points = 0; $driver4points = 0; for($i = 1; $i <= 4; $++){ if(${"driver".$i} == $driverrace["fastestlap"]) { ${"driver". $i ."points"} += $driver_points_system["fastestlap"]; $racepoints += $team_points_system["fastestlap"]; break; } } A: I agree with what is said in the comments. An array is a much better way to handle this. <?php $driver1points = 0; $driver2points = 0; $driver3points = 0; $driver4points = 0; for($i = 1; $i <= 4; $++) { $driver = "driver$i"; if($$driver == $driverrace["fastestlap"]) { ${$driver."points"} += $driver_points_system["fastestlap"]; $racepoints += $team_points_system["fastestlap"]; break; } } Can be translated into: <?php $drivers['bill'] = 0; $drivers['ted'] = 0; $drivers['cheech'] = 0; $drivers['chong'] = 0; foreach ( $drivers as $driver => &$points ) { if ( $driver == $race['fastestlap'] ) { echo "$driver had the fastest lap!"; $points += $driver_points_system['fastestlap']; $racepoints += $team_points_system['fastestlap']; break; } } You can obviously do this as a numerative array and replace all of the $drivers[$driverName] assignments to just $drivers[]. I used an associative array to demonstrate that arrays are not only more efficient for this application, they can also be much easier to work with. I passed the value argument of the foreach by reference, the "&" prefix (similar to a pointer, variable stores the memory address as opposed to the value); this allows you to directly manipulate the value in your logic as opposed to being given a copy of the value and needing to reassign with something similar to a $drivers[$driver] = $points;
{ "language": "en", "url": "https://stackoverflow.com/questions/7517820", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Uploading Image to a website using HttpWebRequest in WP7 how i can upload any image to a website using HttpWebrequest in WP7 Mango?? and another doubt regarding with HttpWebequest is that how i can achieve the secured version of HttpWebRequest in WP7 Mango?? Does new add-on sockets in wp7 has any role in secured data transfer over HttpWebequest? please help me on this issues.. ThanX in advance.. A: See this question for uploading to a server using HttpWebRequest. Using sockets would be an alternative approach, but I would ignore this unless you have a specific requierment to do it this way. Sending the image over HTTPS should be no problem as long as you have a certificate with a root cert recognised by the phone.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517821", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: I'm a .Net, C# and WPF programmer. Is Expression Blend worth it? I mean, as a normal developer, is there something that I will achieve with Expression Blend that I won't using VS? I have no idea of Expression Blend and at first sight didn't look very friendly / easy to learn. What do you thing out there? It's worth the time learning to use it or I will do the same as I do with VS? Thanks! EDIT: I know what Microsoft says about the tools. What I want to know is if you, as a developer like me, tried Expression Blend and found that it was a waste of time or you thought it was a good tool and you stopped developing the WPF GUIs from VS and switched to EB. A: I have it and rarely use it. I greatly dislike all the extra markup that gets added to the XAML files, and prefer to know what I'm doing to just dragging/dropping items. The few times I have used it have been to pull out the default styles or templates of a control, or to build something like a gradient, animation, or path, and then copy/paste the XAML into my project. It's nice if you're into drag/drop coding, or if you're working on a large enough team to be have a separate UI and Coding team, but other than that I don't use it for solo development since I have to maintain the XAML mess it generates. A: I stopped developing GUIs in VS and switched to Blend. It was very confusing at first, but I'm now glad I took the time to learn Blend. Most things that you can do in Blend can be done in Visual Studio, but Blend makes them much easier (once you learn how to do it). I constantly astound my fellow developers when I show them how to do something in Blend because a simple drag and drop can replace quite a bit of typing. The thing I really like about Blend is that the design surface is accurate while the Cider WPF designer in Visual Studio often lies to you or misleads you (and is just a piece of crap in general). Blend can do the following things that Visual Studio cannot: * *Create and manage visual states. (I guess you could do this all by hand in VS, but that's just insane for anything even moderately complex.) *Extract and modify control templates. *Easily work with behaviors (I can't imagine doing a FluidMoveBehavior by hand in VS). *Generate sample data for use at design time (reduces coupling of your software components). *WYSIWYG animation editor. (In VS you have to run the application to see the animations; Blend gives you live previews.) *Built in transition effects and easing functions. *SketchFlow (great for making a high fidelity mockup that you can show a client/stakeholder). *WYSIWYG path editor (great for doing simple vector artwork). *WYSIWYG gradient editor. *Import artwork from Photoshop and Illustrator. These are the sorts of things that can really set your user experience apart from every other freelancer out there. And for the record I'm a developer with no design experience. A: I think there's an easy way to answer your question... all you have to do is ask yourself what is the end result of anything you do in Blend? The answer is XAML. So if this tool generates XAML for you, why wouldn't you work directly with XAML in the first place? XAML is human readable, it's easy to understand and master and between VS Intellisense and Resharper code completion there's really not a whole lot of typing required. The time you invest in mastering Blend is much better invested in mastering XAML because Blend is just a tool used to generate XAML in a visual way so working directly with XAML means better understading of the underlying technology and taking full control of your code instead of relying on some black box tool to generate something you don't really understand. And what if you invest all that time in mastering Blend and you end up in some other company 6 months down the road and they decided not to use Blend? If you don't know XAML, you'll now have to invest more time to learn it and if you do know XAML you'll be good to go in any environment as I really doubt it any company would force coders who need to work with UI as well to use Blend and not allow them to work with XAML directly. There are a few scenarios Blend would save you quite a bit of time (people mentioned visual states and animations) so it's certainly good to have Blend on such occasions but if you're developing typicall LOB apps there's pretty much nothing there that will make you feel like you really, really need Blend... A: When the Visual Studio is more oriented on the developers, Expression Blend is oriented to the designers. It have a lot of predefiend tools whitch can generate a lot of code and simple to use (espessially animations, design issues, etc.). So everything what can be done in Expression Blend you can do in Visual Studio. I'm not sure about viсe-versa. Here is what said on official site: Expression Blend, Visual Studio, Silverlight and .NET provide the most compelling and seamless design and development workflow on the market today. Rapidly iterate on both the user experience and core architecture, evolving your ideas quickly from initial prototype through to completed project. Key components of Expression Blend, including Behaviors, Visual State Manager, transition effects, and SketchFlow (Expression Blend 4 includes SketchFlow in Expression Studio 4 Ultimate product only), coupled with the speed and flexibility of this modern workflow challenge you to push boundaries and work beyond the limits of what you thought possible. So, it depends on where you are: if you mostly working with the UI layer of the application you may found a lot of useful things in Expression Blend, otherwise if you mostly work with backgound - Visual Studio is your choiсe. Update Also check out following tread on SO: WPF Applications: Visual Studio vs. Expression Blend A: As a professional developer Expression Blend is invaluable and does many things which VS does not, Just off top of my head, Sample data, Storyboarding, Far superior datatemplate support Way better resource dictionary support Much better Custom Control tooling Much better XAML control If you are simply editing very basic UI then Blend wont be of any use stick with VS. Blend is for design and animation it is for front-end. A: * *It's much easier to edit default styles as you have option Edit a copy which is extracting default style into the new one and you can change it *I find also very useful to edit additional styles like generated content as you can easly see what additional styles control has. *If you are doing animations it can make a difference as you can actually see during desgin time how is it behaving *If you have a dedicated designer in your team it is much more friendly for them as it's similar to photoshop/flash editing software *From my point of view if you are working in a team its enough to have only few expression blends A: I always have Expression Blend open next to Visual Studio and switch back and forth between the two when working on Silverlight, WPF or Windows Phone Projects. These are my main resons: I use a lot of animations and visual states in my applications. To create these you would like to see what is going on. In the visual studio you can't (yet). It's almost impossible to write a real animation or visual state by hand. Managing resources is something I use Expression Blend for too. Creating new dictionaries and moving resources around is very easy in Blend. It even notifies you when you try to delete a resouce you are using in some place. Finding and editing a resouce is very easy. With a click of a button a property is converted to a resource and ready for use in other places. One other thing I use a lot is Sample Data. I would like to see my forms and lists filled with data when creating them. Depending on the state of the application I create sample data by hand, use an xml export from the database or generate sample data from code. Databinding becomes a lot easier when you are using sample data. Just drag'n'drop the property on a textbox and you'll have a binding. Through the databinding editor you can finetune the binding the way you want. A: Blend tool having multi purpose. I assume it's mainly on 1.build animation(Story Board) in silverlight 2.create WPF/SL/WP XAML layout If you want to create some animation silverlight/ some data-bound sliverlight application, my answer is yes after i try to use Adobe Edge in 7 days and used flash from flash 4 ,MX2004, flash 5 in long time ago. To create a fancy animation, Expression Blend still beat Adobe Edge and comparable to Adobe Flash. And you can write your familiar programming language to control everything just like flash action script. In my optional, Action Script is quite messy on mid-large project and very hard to debug/maintenance.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517822", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "49" }
Q: msbuild “Unable to remove directory” One of our CruiseControl.NET projects keeps intermittently failing because a msbuild task fails with error MSB3231: Unable to remove directory "d:\Somewhere\Dir\Admin". The parameter is incorrect. The corresponding msbuild script line is just <RemoveDir Directories="$(DistributionDir)\Admin" Condition="Exists('$(DistributionDir)\Admin')" /> When I look at the state after the failed build, the directory contents was removed successfully, but the empty directory itself is left there. And the next build usually succeeds (having to remove just the empty directory). Note that the problem does not seem to be the usual “some other process (like antivirus) keeps locking the directory”, the error is not “access denied”, but a very strange “the parameter is incorrect”. I monitored the build with SysInternals Process Monitor, and the result is strange – everything goes as expected, the contents of the directory is enumerated, deleted, and when the top-level directory enumeration finishes with “NO MORE FILES”, the directory is closed, and… nothing. No other operation gets to the process monitor: 10:04:09,9190557 MSBuild.exe 3516 QueryDirectory D:\Somewhere\Dir\Admin NO MORE FILES 10:04:09,9190928 MSBuild.exe 3516 CloseFile D:\Somewhere\Dir\Admin SUCCESS The next (successful) build attempt is just a boring successful directory removal: 10:31:21,8616463 MSBuild.exe 1760 CreateFile D:\Somewhere\Dir\Admin SUCCESS Desired Access: Read Data/List Directory, Synchronize, Disposition: Open, Options: Directory, Synchronous IO Non-Alert, Attributes: n/a, ShareMode: Read, Write, Delete, AllocationSize: n/a, OpenResult: Opened 10:31:21,8616861 MSBuild.exe 1760 QueryDirectory D:\Somewhere\Dir\Admin\* SUCCESS Filter: *, 1: . 10:31:21,8617305 MSBuild.exe 1760 QueryDirectory D:\Somewhere\Dir\Admin SUCCESS 0: .. 10:31:21,8617589 MSBuild.exe 1760 QueryDirectory D:\Somewhere\Dir\Admin NO MORE FILES 10:31:21,8618209 MSBuild.exe 1760 CloseFile D:\Somewhere\Dir\Admin SUCCESS 10:31:21,8621579 MSBuild.exe 1760 CreateFile D:\Somewhere\Dir\Admin SUCCESS Desired Access: Read Attributes, Delete, Synchronize, Disposition: Open, Options: Directory, Synchronous IO Non-Alert, Open Reparse Point, Attributes: n/a, ShareMode: Read, Write, Delete, AllocationSize: n/a, OpenResult: Opened 10:31:21,8622118 MSBuild.exe 1760 QueryAttributeTagFile D:\Somewhere\Dir\Admin SUCCESS Attributes: D, ReparseTag: 0x0 10:31:21,8622408 MSBuild.exe 1760 SetDispositionInformationFile D:\Somewhere\Dir\Admin SUCCESS Delete: True 10:31:21,8622676 MSBuild.exe 1760 CloseFile D:\Somewhere\Dir\Admin SUCCESS It seems for some reason, MSBuild/Windows detects some kind of invalid parameter error before the directory removal is executed, but I have no idea where to look. (I have also tried to run chkdsk, nothing was found. I have also removed and recreated the parent D:\Somewhere\Dir directory, nothing changed.) So – any idea where the problem could be or how should I investigate further? (I am not sure where this question should have gone, it is kind of somewhere between SO, Progs SE, Server Fault, Superuser…) A: I can't say why it is failing, but if the folder is the only thing left over can the build complete correctly? If so, a workaround would be to specify ContinueOnError="True". A: Tried a lot of things, but I couldn't figure out why this sometimes fails when the directory isn't empty; in our case the directory contains symbolic links if that matters. Anyway I don't like using ContinueOnError since that means when there is an actual error you don't know it, or have to do an extra check like <Error Condition="Exists... after every RemoveDir. The solution we use now is to explicitely empty the directory, after which msbuild doesn't seem to have any problems removing it: <MSBuild.ExtensionPack.FileSystem.Folder Condition="Exists( $(PathtoEmpty) )" TaskAction="RemoveContent" Path="$(PathtoEmpty)" /> <RemoveDir Directories="$(PathtoEmpty)" /> A: I've just encountered this error myself, it turned out that I had the offending folder opened in a Windows Explorer and that prevented it from being properly deleted. A: May be this comes a little late, but I found the same error and the problem appears to be in the Exists condition. It seems that the evaluation of the condition somehow doesn't release the directory properly conflicting with the execution of the task. By removing the condition the directory will be removed if it exists but the statement won't fail if it doesn't exist: <RemoveDir Directories="$(DistributionDir)\Admin" /> A: The selected answer seems to be a hack,as it stops you from getting the actual error which might be a critical error. I could use remove content instead of removing the directory as below. <MSBuild.ExtensionPack.FileSystem.Folder Condition="Exists( $(OutputPath) )" TaskAction="RemoveContent" Path="$(OutputPath)" />
{ "language": "en", "url": "https://stackoverflow.com/questions/7517823", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: c # regular expressions unsigned short,int,long i am having a problem with dealing with regular expressions. What i need is to make a regular expression that checks a bunch of numbers written through the console separated with spaces and to check how many of them is: 1) unsigned short 2) unsigned int 3) unsigned long for someone like me without any regular expression experience it is like impossible. A: Michael is right; technically the problem you face is one solvable by regular expressions. (Obviously; the language "strings which are legal unsigned long literals" is a finite language and therefore trivially a regular language. But it's a finite language with 16 billion billion members, which is rather a lot.) In practice, you should write a regular expression that splits up the input string into tokens where a token is either whitespace or a string of numbers, and then write a non-regular-expression-based analyzer that figures out whether the number is a legal long, short, and so on. Perhaps you could show the work you've done so far on the problem and ask a more specific question about what is stumping you. A: You are asking too much from RegEx... it can certainly handle splitting the numbers up, but you should implement the logic to check what kind of number they are by iterating over each one outside of the Regex. See Jon Skeet's excellent blog about this: http://msmvps.com/blogs/jon_skeet/archive/2005/09/21/67247.aspx A: Why do you want to use regex? You could instead use String.Split(), UInt32.TryParse(), UInt64.TryParse() (unsigned long), and UInt16.TryParse() (unsigned short).
{ "language": "en", "url": "https://stackoverflow.com/questions/7517825", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: How can I write a web service that returns a dynamic set of variables in .NET? My current set up is an ASMX web service that has an Item object, and returns a List<> of Items. Item has 114 fields of various types. It is consumed by .NET web apps, as well as Java web apps (using Axis2 to generate a client proxy). My problem is that every time we want to add a field to the result set, we have to modify the service to add the field to the object, as well as generate a new client proxy for the java side. Also, the mapping of the sql fields to the object fields is one large method loading each field from the datareader into the object, making sure to convert to the proper datatype. Is there a more dynamic way to do this? I looked into a list of Dictionary, but that cannot be serialized. An alternative is to send a List<> of Struct with Key and Value fields. This now puts the effort of parsing the types onto the client, which isn't necessarily optimal. Is there a pattern that handles something like this, or barring that, does anyone have a good solution to help make this a little more maintainable? I'm open to converting it to WCF (though I am not too familiar with WCF) if there is a decent way for our Java apps to consume the service. If you need more details, just ask. Thanks! A: Outside of using something like a List<KeyValuePair<string, object>> I don't think you're going to find any other solution; WCF isn't going to help much in that respect. I think that's actually a good solution, it will make the reading of your data much simpler and scalable, and you wouldn't need to change your server side code much when you add new fields. You could write code on the clients that do the work of mapping the value pairs back to a real structure, and then most of the code changes (when a field is added) is isolated to your clients. Also, if your clients don't need the new fields, you can just ignore the changes without breaking anything.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517829", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Having trouble getting if statements to work in VBA My first question is whether excel VBA will recognize an if statement with two constraints, i.e. IF Range(somecell).value > 0 AND Range(anothercell).value < 100 Then: execute code here Because I am having a problem with getting the code enclosed in an if statement to trigger when I know that both constraints are satisfied in a script I'm running. Maybe its a problem with my logic. I've included the code, please see if you can point out any errors in my logic or VBA. Background Information (I also included some in the code): There are two levers that change cell F71(D40 and D41). The requirements are that F71 be greater than 0 and it must be less than the current value for F71 (Saved in variable currentValueAdd). So I loop through both layers iterating through all the possible combinations trying to find the optimal combination that satisfies the above conditions. Sometimes I open excel and it works fine, other times it doesn't work at all. The results are very erratic. Private Sub OptimizeFI_Click() Dim waiveLoop As Integer Dim comissionLoop As Integer Dim finalWaive As Integer Dim finalCommission As Integer Dim currentValueAdd As Double Dim F71 As Range, D41 As Range currentValueAdd = Range("$F$71").Value ' <-- This is the cell I am trying to optimize. For waiveLoop = 0 To 7 Range("$D$40").Value = waiveLoop ' <-- one of the levers in changing cell F71 For comissionLoop = 0 To 7 Range("$D$41").Value = comissionLoop ' <-- a second lever in changing cell F71 If Range("$F$71").Value > 0 And Range("$F$71").Value < currentValueAdd Then finalWaive = Range("$D$40").Value finalComission = Range("$D$41").Value Range("$E$27").Value = finalWaive * 0.05 Range("$E$28").Value = finalComission * 0.05 currentValueAdd = Range("$F$71").Value End If Next comissionLoop Next waiveLoop Range("$D$40").Value = Range("$E$27") / 0.05 Range("$D$41").Value = Range("$E$28") / 0.05 Range("$F$8").Value = currentValueAdd End Sub A: My first question is whether excel VBA will recognize an if statement with two constraints Of. Course. BTW, there is no "Excel VBA", there is just VBA. And it is virtually equivalent to VB. Maybe its a problem with my logic. Very probably. There is no immediate problem to see in your code, though. A: If im not mistaken then the second half of your if condition is never true right? By this i mean that "Range("$F$71").Value" is never less than "currentValueAdd". If this is the case then i you need to relook into your logic of currentValueAdd = Range("$F$71").Value as this will always send the value of Range("$F$71") to currentValueAdd and when you are checking the condition Range("$F$71").Value < currentValueAdd the value in cell F71 has not changed since you transferred it to the variable and so your value in the variable is the same as the value in F71 thus your second condition will never be true. Hope it has been of some help.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517833", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Accessing a folder to list/play clips one by one I just want to know if there is an object to access a folder path which includes list of clips in javascript. Which object I should use to list clips in a folder? Actually I can't use all objects, only provided for Ecmascript. A: JavaScript/Ecmascript cannot see the local filesystem. If it could then we'd have web pages sniffing all of our files without our consent. A: JavaScript doesn't get to see the user's file system. That'd be a huge security problem for everyone everywhere. If you're referring to the server's file system then you probably already have a better language like php that can list the directory contents and dynamically generate the JS before it is sent to the browser.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517837", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What does split function look like? I came across this statement : userName = document.cookie.split("=")[1]; after reading about split statement here at w3schools. which says that syntax of split is string.split(separator, limit). Then what does the square bracket after first parens. mean ? If this is true what does split function look like ? A: String.split(separator, limit) returns an array. In Javascript, you can access array values by index using the square brackets. Arrays are zero-based, 0 is the first element, 1 the second and so on. The equivalent of your code would be: var arr = document.cookie.split("="); userName = arr[1]; This separates the document.cookie by the equal-sign (=) and takes the second element (index 1) from it. document.cookie is a special property (datatype: String) of the document object which contains all cookies of a webpage, separated by the ; character. E.g. if document.cookie contains name=Adam, the array arr will contain the values name and Adam. The second one is stored in userName. Note that if the cookie contains multiple values, or if the value contains multiple equal-signs, it won't work. Consider the next cases: * *document.cookie contains name=Adam; home=Nowhere. Using the above code, this would make userName contain Adam; home because the string is separated by the equal-sign, and then the second value is taken. *document.cookie contains home=Nowhere; name=Adam. This would result in userName containing Nowhere; name *document.cookie contains name=Adam=cool. In this case, userName would be Adam and not Adam=cool. Also, w3schools is not that reliable. Use more authorative sources like the Mozilla Developer Network: * *document.cookie *String.split *Array A: The split function returns an array of strings split by the given separator. With the square bracket you are accessing the nth element of that (returned) array. If you are familiar with Java, its the same behavior as the String.split() method there. A: It gets the second index of the resulting array Same as: var split = document.cookie.split("="); var userName = split[1]; A: split returns an array of strings. So square brackets mean get second string from the returned array. A: The square bracket in the code you supplied is accessing the second element of the array returned by split(). The function itself returns an array. That code would be the same as: var temp = document.cookie.split("="); userName = temp[1]; A: Split would return an array e.g. [1, 2, 3]. If you supply the square bracket after it, it will return the specified key in the brackets, in this case userName would be 2 A: You shouldn't be using w3schools, but... In JavaScript, function parameters are optional and it is possible to supply fewer parameters than the function expects. The extra parameters in the function are then undefined. Some functions are programmed to deal with that possibility and string.split is one of them. The other part has to do with the fact that split returns an array. Arrays can then be indexed using the square bracket notation, hence the [1] after the function call.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517841", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: SVN: Synchronize branch with trunk in Eclipse? I have an SVN branch and a trunk. The trunk changes regularly and the branch doesn't. Every now and then (let's say once per week) I want to update the local working copy of the branch with the latest changes of the trunk. Ideally I would want to do this the same way as I do it with the latest version of the branch: with Eclipse : Team->Synchronize, so I can review all changes before updating. Is this also possible with a different repository (for example : trunk) ? If not, how do people review the changes before updating then?? I looked at Team->Merge, but this seems to update the changes directly to my working copy, without the possibility to review the changes first (the Preview-function is confusing, I think, and doesn't provide the nice side-by-side view of changes/conflicts that Synchronize has). A: The right way to do this is with Merge. Subclipse includes a merge client that makes this easy to do. You are right that it does not give you a true preview, but the way it works is better from a Subversion perspective. The Merge Results view UI is basically the same as the Synchronize view. It lets you easily examine every change that the merge made in your working copy and the Eclipse compare editor that it opens makes it very easy to take out any parts of the change that you do not want in your code before you commit. The problem with trying to do this from the Synchronize view is that you are then doing the merge yourself using code editors and Subversion has no awareness of what is merged. If you let Subversion first do the merge, then it can update all of its metadata properly and it is perfectly fine for you to then fixup the code to be the way you want it before you commit the results of the merge. A: I'd checkout both branch and trunk as a separate eclipse projects into workspace. Then use some merging tool, for example meld to merge changes between them. After merge you can refresh branch in Eclipse and synchronize it with svn repository - now you can review all changes. (it's how I do it, since I do not believe svn eclipse plugin ;)) A: I agree that it is not really intuitive by design, but Mark is right, you "synchronize" your changes when committing them back to the trunk: * *first make sure your local branch is completely synchronized with your repository branch (no changes) *Team -> Merge... your local copy of the branch with the repository trunk *you now have a local version of that merge *you can locally edit this version, make sure tests are working and there are no compiler errors *finally you synchronize your local merged branch version with the repository branch and commit all changes that have been made besides, the same way you'll merge your branch back into the repository trunk * *make sure all changes of your branch are committed to the repository branch *switch to the trunk Team -> Switch... *merge your trunk with your branch Team -> Merge... (Tab 'Reintegrate') *you now have a local version of the merge, you may edit the changes and review them, make sure that you have a working version now *synchronize your local trunk (merged version) with the repository trunk *commit all changes that you want to appear in the trunk i recommend to commit all changes that you've made locally to your merge, since you've tested them locally. if you commit just a few changes, make sure the repository version is still working then with missing changes
{ "language": "en", "url": "https://stackoverflow.com/questions/7517842", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: I am expecting myApp.exe runs faster than myApp.vshost.exe, but from vshost (run in VS release) array pure 00:00:02.9634819 1200000000 Basic: 00:00:04.1682663 from standalone program (compiled release) array pure 00:00:09.1783278 // slower, why? 1200000000 Basic: 00:00:00.5985118 // faster, as expected So it seems that running from VS sometimes speed up the programs? My test code is: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; namespace vsHostTest { class Program { static long Five(int s0, int s1, int s2, int s3, int s4) { return s4 + 100 * s3 + 10000 * s2 + 1000000 * s1 + 100000000 * s0; } static void Main(string[] args) { Stopwatch watch = new Stopwatch(); long testSize = 10000000; int[] myarray = new int[] { 1, 2, 3 }; watch.Start(); for (int j = 0; j < testSize; j++) { bool i = myarray.Contains(2); } watch.Stop(); Console.WriteLine("array pure {0}", watch.Elapsed); testSize = 200000000; long checksum = 0; watch.Restart(); for (long i = 0; i < testSize; i++) { long ret = Five(1, 2, 3, 4, 5); checksum += ret % 9; } watch.Stop(); Console.WriteLine(checksum); Console.WriteLine("Basic: {0}", watch.Elapsed); Console.ReadKey(); } } } A: I ran each one four times, but not including the first result for each average. vshost: array pure: 6.83 Basic: 3.62 console: array pure: 6.64 Basic: 1.57 I should add that all times were slower in vshost than they were in console. I'm not sure why you're getting the results you are, but vshost attaches a debugger to the process whereas running it via console does not. The console version will always be faster because of that. Furthermore, while benchmarking .net applications, running the test once is not enough to get accurate measurements. You should always run the test multiple numbers of times, throwing out either the first (if you want don't want to compare cold runs, as .net caches a lot) or the most outlying measurement. Also, and I feel stupid for asking this, are you sure you ran the release version when you were running via console? I'm sure you did, but I always ask, since I sometimes make silly mistakes like that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517844", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Console Application drag and drop "C#" I was loading an MS Word file programmatically using Interop.Microsoft.Office.Interop.Word.dll. When the Word file is opened, I want to disable drag and drop facility for it. How do I do that? Is it possible to achieve this in user32.dll? A: You're probably looking for Application.Options.AllowDragAndDrop = false; Application.Options Options class members I'm not sure if any options you change persist or not when the application is closed, but I would make sure you revert any options changes you do when you application closes or in case of an unexpected termination.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517847", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Compressing multiple JavaScript files with YUIcompressor? I'm trying to compress multiple JS files using the YUI Compressor. I think that I'm getting the syntax wrong. I want to compress all files in a directory that start with at_. However, when YUI Compressor runs, I find that YUI Compressor has placed only the compressed version of one file in the output. To be specific, suppose I have three files: at_1.js, at_2.js, and at_3.js. I would like the compressed output of all three js files in at_min.js I'm using the following syntax: java -jar c:\Tools\yuicompressor-2.4.2.jar --type js --charset utf-8 -o c:\temp\at_min.js c:\temp\scripts\at_* When I open up at_min.js, I find only the compressed contents of at_1.js. What am I doing wrong? A: If you are using Windows you can use YUI Compressor for .Net to do that. Or combining files before compressing with a simple command: copy /b at_1.js+at_2.js+at_3.js at_combined.js java -jar c:\Tools\yuicompressor-2.4.2.jar --type js --charset utf-8 -o at_min.js at_combined.js A: I have written a small program to compress multiple javascript files using yuicompressor and node js. var compressor = require('yuicompressor'); //Compressor Options: var compressorOptions = { charset: 'utf8', type: 'js', nomunge: false } /* List of files and file path. Just replace the file names and path with yours */ var file = [{ "path": "assets/www/modules/eApp/controllers/", "type": "js", "name": ["BuyOnlineController", "CustomerDetailsController", "DashboardController", "DashboardListingController", "DocumentUploadController", "HomeController", "KYCDetailsController", "PaymentAcknowledgementController", "PaymentController", "ProductListingController", "ReviewAndAcceptanceController"] }, { "path": "assets/www/modules/login/controllers/", "type": "js", "name": ["EappLoginController", "InboxController", "LandingController", "LoginController", "MenuController", "MyAccountController", "SyncForEappController"] }, { "path": "assets/www/lib/vendor/general/", "type": "js", "name": ["overlays"] }]; function minify(i, j){ i = (i == undefined) ? 0 : i; j = (j == undefined) ? 0 : j; filePath = file[i].path; fileType = file[i].type; name = file[i].name[j]; fileName = filePath+name+"."+fileType; minifiedFileName = filePath+name+".min."+fileType; if(j == file[i].name.length - 1){ i += 1; j = 0; } else j += 1; compressor.compress(fileName, compressorOptions, function(err, data, extra) { var fs = require('fs'); fs.writeFile(minifiedFileName, data, function(err) { if(err) { console.log(err); } else { console.log("The file "+minifiedFileName+" was saved successfully!"); if(i != file.length) minify(i, j); } }); }); } minify(0,0);
{ "language": "en", "url": "https://stackoverflow.com/questions/7517849", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Automating a directory diff while ignoring some particular lines in files I need to compare two directories, and produce some sort of structured output (text file is fine) of the differences. That is, the output might looks something like this: file1 exists only in directory2 file2 exists only in directory1 file3 is different between directory1 and directory2 I don't care about the format, so long as the information is there. The second requirement is that I need to be able to ignore certain character sequences when diffing two files. Araxis Merge has this ability: you can type in a Regex and any files whose only difference is in character sequences matching that Regex will be reported as identical. That would make Araxis Merge a good candidate, BUT, as of yet I have found no way to produce a structured output of the diff. Even when launching consolecompare.exe with command-line argumetns, it just opens an Araxis GUI window showing the differences. So, does either of the following exist? * *A way to get Araxis Merge to print a diff result to a text file? *Another utility that do a diff while ignoring certain character sequences, and produce structured output? Extra credit if such a utility exists as a module or plugin for Python. Please keep in mind this must be done entirely from a command line / python script - no GUIs. A: To some extent, the plain old diff command can do just that, i.e. compare directory contents and ignoring changes that match a certain regex pattern (Using the -I option). From man bash: -I regexp Ignore changes that just insert or delete lines that match regexp. Quick demo: [me@home]$ diff images/ images2 Only in images2: x Only in images/: y diff images/z images2/z 1c1 < zzz --- > zzzyy2 [me@home]$ # a less verbose version [me@home]$ diff -q images/ images2 Only in images2: x Only in images/: y Files images/z and images2/z differ [me@home]$ # ignore diffs on lines that contain "zzz" [me@home]$ diff -q -I ".*zzz.*" images/ images2/ Only in images2/: x Only in images/: y
{ "language": "en", "url": "https://stackoverflow.com/questions/7517850", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is there a way to show the TFS changeset number after a check-in? Is there a way, with power tools or other extensions, to make it so that the changeset number is be displayed on an alert? Currently it displays on the status bar, but disappears after a while, or at least make this more prominent? A: Output from TFS commands shows up in Visual Studio's Output window, but you need to change the "Show output from" dropdown to "Source Control - Team Foundation". Check-ins will produce output like: Changeset 1234567 successfully checked in. A: You can setup alerts in TFS which sends you an email with the checkin information, including the changeset number. There is an limited alert editor shipped with visual studio (see in the menu Team -> Project Alerts). You can choose the option "Anything checked in" There are also the power tools which give an editor with more options. You can then filter also on user name. But be aware that everybody should set up their own alert.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517851", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: SQL Partition Elimination I am currently testing a partitioning configuration, using actual execution plan to identify RunTimePartitionSummary/PartitionsAccessed info. When a query is run with a literal against the partitioning column the partition elimination works fine (using = and <=). However if the query is joined to a lookup table, with the partitioning column <= to a column in the lookup table and restricting the lookup table with another criteria (so that only one row is returned, the same as if it was a literal) elimination does not occur. This only seems to happen if the join criteria is <= rather than =, even though the result is the same. Reversing the logic and using between does not work either, nor does using a cross applied function. Edit: (Repro Steps) OK here you go! --Create sample function CREATE PARTITION FUNCTION pf_Test(date) AS RANGE RIGHT FOR VALUES ('20110101','20110102','20110103','20110104','20110105') --Create sample scheme CREATE PARTITION SCHEME ps_Test AS PARTITION pf_Test ALL TO ([PRIMARY]) --Create sample table CREATE TABLE t_Test ( RowID int identity(1,1) ,StartDate date NOT NULL ,EndDate date NULL ,Data varchar(50) NULL ) ON ps_Test(StartDate) --Insert some sample data INSERT INTO t_Test(StartDate,EndDate,Data) VALUES ('20110101','20110102','A') ,('20110103','20110104','A') ,('20110105',NULL,'A') ,('20110101',NULL,'B') ,('20110102','20110104','C') ,('20110105',NULL,'C') ,('20110104',NULL,'D') --Check partition allocation SELECT *,$PARTITION.pf_Test(StartDate) AS PartitionNumber FROM t_Test --Run simple test (inlcude actual execution plan) SELECT * ,$PARTITION.pf_Test(StartDate) FROM t_Test WHERE StartDate <= '20110103' AND ISNULL(EndDate,getdate()) >= '20110103' --<PartitionRange Start="1" End="4" /> --Run test with join to a lookup (with CTE for simplicity, but doesnt work with table either) WITH testCTE AS ( SELECT convert(date,'20110101') AS CalendarDate,'A' AS SomethingInteresting UNION ALL SELECT convert(date,'20110102') AS CalendarDate,'B' AS SomethingInteresting UNION ALL SELECT convert(date,'20110103') AS CalendarDate,'C' AS SomethingInteresting UNION ALL SELECT convert(date,'20110104') AS CalendarDate,'D' AS SomethingInteresting UNION ALL SELECT convert(date,'20110105') AS CalendarDate,'E' AS SomethingInteresting UNION ALL SELECT convert(date,'20110106') AS CalendarDate,'F' AS SomethingInteresting UNION ALL SELECT convert(date,'20110107') AS CalendarDate,'G' AS SomethingInteresting UNION ALL SELECT convert(date,'20110108') AS CalendarDate,'H' AS SomethingInteresting UNION ALL SELECT convert(date,'20110109') AS CalendarDate,'I' AS SomethingInteresting ) SELECT C.CalendarDate ,T.* ,$PARTITION.pf_Test(StartDate) FROM t_Test T INNER JOIN testCTE C ON T.StartDate <= C.CalendarDate AND ISNULL(T.EndDate,getdate()) >= C.CalendarDate WHERE C.SomethingInteresting = 'C' --<PartitionRange Start="1" End="6" /> --So all 6 partitions are scanned despite only 2,3,4 being required, as per the simple select. --edited to make resultant ranges identical to ensure fair test A: It makes sense for the query to scan all the partitions. All partitions are involved in the predicate T.StartDate <= C.CalendarDate, because the query planner can't possibly know which values C.CalendarDate might take.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517855", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: sample SSL code server I need a little server (OBJ-C, iPad, XCode) using ssl negociations and exchanges when a client tries to connect. Is someone knows how to do this or have a little example? Thanks to all A: cocoahttpserver
{ "language": "en", "url": "https://stackoverflow.com/questions/7517856", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Strange behaviour of bash script for running parallel subprocess in bash This following script is used for running parallel subprocess in bash,which is slightly changed from Running a limited number of child processes in parallel in bash? #!/bin/bash set -o monitor # means: run background processes in a separate processes... N=1000 todo_array=($(seq 0 $((N-1)))) max_jobs=5 trap add_next_job CHLD index=0 function add_next_job { if [[ $index -lt ${#todo_array[@]} ]] then do_job $index & index=$(($index+1)) fi } function do_job { echo $1 start time=$(echo "scale=0;x=$RANDOM % 10;scale=5;x/20+0.05" |bc);sleep $time;echo $time echo $1 done } while [[ $index -lt $max_jobs ]] && [[ $index -lt ${#todo_array[@]} ]] do add_next_job done wait The job is choosing a random number in 0.05:0.05:5.00 and sleep that much second. For example, with N=10, a sample out put is 1 start 4 start 3 start 2 start 0 start .25000 2 done 5 start .30000 3 done 6 start .35000 0 done 7 start .40000 1 done 8 start .40000 4 done 9 start .05000 7 done .20000 5 done .25000 9 done .45000 6 done .50000 8 done which has 30 lines in total. But for big N such as 1000,the result can be strange.One run gives 2996 lines of ouput,with 998 lines with start ,999 with done ,and 999 with float number.644 and 652 is missing in start,644 is missing in done. These test are runned on an Arch Linux with bash 4.2.10(2).Similar results can be produced on debian stable with bash 4.1.5(1). EDIT:I tried parallel in moreutils and GNU parallel for this test.Parallel in moreutils has the same problem.But GNU parallel works perfect. A: I think this is just due to all of the subprocesses inheriting the same file descriptor and trying to append to it in parallel. Very rarely two of the processes race and both start appending at the same location and one overwrites the other. This is essentially the reverse of what one of the comments suggests. You could easily check this by redirecting through a pipe, such as with your_script | tee file because pipes have rules about atomicity of data delivered by single write() calls that are smaller than a particular size. There's another question on SO that's similar to this (I think it just involved two threads both quickly writing numbers) where this is also explained but I can't find it. A: The only thing I can imagine is that you're running out of resources; check "ulimit -a" and look for "max user processes". If that's less then the number of processes you want to spawn, you will end up with errors. Try to set the limits for your user (if you're not running as root) to a higher limit. On Redhatish systems you can do this by: Adding that line to /etc/pam.d/login: session required pam_limits.so Adding the following content to /etc/security/limits.conf: myuser soft nproc 1000 myuser hard nproc 1024 where "myuser" is the username who is granted the right, 1000 the default value of "max user processes" and 1024 the maximum number of userprocesses. Soft- and hard-limit shouldn't be too much apart. It only says what the user is allowed to set himself using the "ulimit" command in his shell. So the myuser will start with a total of a 1000 processes (including the shell, all other spawned processes), but may raise it to 1024 using ulimit: $ ulimit -u 1000 $ ulimit -u 1024 $ ulimit -u 1024 $ ulimit -u 2000 -bash: ulimit: max user processes: cannot modify limit: Operation not permitted A reboot is not required, it works instantly. Good luck! Alex.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517862", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: RemoteViews - void method setRemoteAdapter I'm trying to implement a widget, with a layout that has a GridView. My onUpdate method inside the widget class is: @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { final int N = appWidgetIds.length; for (int i=0; i<N; i++) { int widgetId = appWidgetIds[i]; RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget); /**views.setRemoteAdapter(..)**/ Intent intent = new Intent(context, MainAppDelegate.class); appWidgetManager.updateAppWidget(widgetId, views); } } The thing is that when I call views.setRemoteAdapter(..) java doesn't know what method it is. Why is that happening? Do I need to upgrade the sdk? Also, it doesn't recognise setBundle() method A: setRemoteAdapter() is only available on API Level 11. You need to have your build target set to API Level 11 or higher to compile using this method, and you need to take care to ensure that this code then only runs on API Level 11 or higher devices.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517868", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Expandable ListView with custom objects I'm fairly new to android and am slowly adjusting to how android works. I am in the process of creating an android application which uses a .net web service to pull back data from a sql database. I have two methods which return a json response with a list of custom objects. I am parsing these into arrays of matching objects on the android client. I am looking to implement a multiple tier grid displaying information from these two arrays. The items in the first array will have child items contained within the second array.(one to many relationship) I am guessing I will need to create two custom array adapters? (which will allow me to have custom layouts for each tier). I have had a look around and struggled to find a comprehensive example of using the expandable list view. What data source will this expect? (some kind of hash table I would imagine?) Does my approach above sound reasonable? Any advice would be appreciated. Thanks, A: ExpandableListView expects a class which implements the interface ExpandableListAdapter as the data source. There are several implementations included in the Android SDK. The SimpleExpandableListAdapter would probably get you up and running the fastest, it uses Lists and Maps for it's data. It won't give you the ability to use different layouts for each group within the list but it will let you have a different layout for groups and children. If SimpleExpandableListAdapter isn't enough then you are going to want to write your own adapter. I'd suggest extending BaseExpandableAdapter (this Adapter implements ExpandableListAdapter and takes care of some of the housekeeping aspects for you, it leaves the rest of the implementation to you). There is a simple example that shows how to do this in the API Demos ExpandableList1.java example. Your implementation will likely be more complex than the example, but it should give you some idea how to do it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517878", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What is the most suitable classification algorithm to classify legal document pictures? I have a set of documents such as (identifiers, driving license and passports etc) in more than one country, so i need to classify them each in its class and then i can classify any new documents -not in my set- in its class. Documents maybe rotated or shifted or both . Documents color of two documents from the same class maybe not exactly the same . What is the best algorithm to do that? A: The Problem is not which classification algorithm to choose, but to understand all the relevant hidden dimensions in your classification problem. Once you understand all the dimensions involved, you could use any one of the classification algorithms to achieve what you want. A: As others have mentioned, it's not a true classification problem. Additionally, because you have items that might be rotated, skewed, etc, you should really perform some sort of object detection/feature analysis on the images. I'd recommend looking into perceptual hashing or Speeded Up Robust Features (SURF) (more the latter, if you are dealing with a tremendous amount of rotation/skew). Namely, I'd break the images down into regions that are non-identifying (you would eliminate areas that have the user's information, or their photo, for example) concentrating on areas that have a high number of matching feature points. Use areas that are consistent across all instances of a particular class of ID so that your match scores will be higher, then take aggregates of all the sections you compare to perform your classification. A: There are dozens if not hundreds of classification algorithms -- basically what you are looking for is clustering. http://en.wikipedia.org/wiki/Cluster_analysis To make this work, you are going to have to analyze the document and boil it down to a few key numbers. This doesn't have to be perfect for clustering to work. So, it might be good to do some kind of normalization (rotate all documents so that text is horizontal), but perhaps not. For example, if a key classification number was based on overall color -- that would be the same for any rotation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517880", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: "Stay on top" main form and modal dialogs in Delphi XE In Delphi XE Update 1, I’m getting seemingly random behavior of modal forms if the parent (main) form’s FormStyle is set to fsStayOnTop. 1) With MainFormOnTaskbar := False (the old way), everything “just works”. With the new MainFormOnTaskbar := True, modal forms get hidden behind the main form when the main form is set to “stay on top”. In most cases saying modalForm.PopupParent := self; just before the call to modalForm.ShowModal seems to help. But not always. 2) All my modal forms are simple, no frills, positioned at MainFormCenter, not using form inheritance, etc. And yet the PopupParent fix only works for about half of them, while the other half still get hidden behind the main form. Strangest of all, in one case the ordering of unrelated lines of code breaks or makes it. See lines marked (1) and (2) in this code: procedure TEchoMainForm.DBMaintenancePrompt( actions : TMaintenanceActions ); var frm : TDBMaintenanceForm; begin frm := TDBMaintenanceForm.Create( self ); try frm.Actions := actions; // (1) frm.PopupParent := self; // (2) frm.ShowModal; finally frm.Free; end; end; When executed in this order, the modal form shows correctly on top of the main form. But when I reverse the lines, the modal form hides behind main. The line marked (1) sets a property of the modal form, which results in several checkboxes being checked on unchecked in a TRzCheckGroup, sitting on a TRzPageControl (from Raize components). This is the setter method that runs when line (1) above executes: procedure TDBMaintenanceForm.SetActions(const Value: TMaintenanceActions); var ma : TMaintenanceAction; begin for ma := low( ma ) to high( ma ) do cgMaintActions.ItemChecked[ ord( ma )] := ( ma in Value ); end; end; This is enough for the modal form to show behind the main form if the order of the lines (1) and (2) is reversed. This might point to TRzCheckGroup (which gets manipulated when the setter code runs), but I have two other forms that show the same problem and do not use TRzCheckGroup (or TRzPageControl). And I could not reproduce the problem with a separate sample app using Raize components. Disabling the form, the pagecontrol or the TRzCheckGroup for the duration of the setter has no effect. It does not appear to be a timing issue, because when the modal form shows hidden once, it always does. The change in behavior only comes from rearranging the lines of code. 3) One last observation: my modal forms are fairly simple, so they get displayed pretty much instantly, with no visible delay. But when the main form is fsStayOnTop, then very often I can see the modal form show on top of it, then see it get “pushed” behind. Then, on hitting Esc, the (invisible) modal form shows on top of the main form for a fraction of a second, then gets closed. Either I‘m missing something that’ll seem obvious in hindsight, or this is a call for psychic debugging, I don’t know. Any ideas, please? UPDATE. I’ve tried to track down the problem on another form where it occurs. It has a few buttons (Raize) and a TSyntaxMemo (an enhanced memo component from eControl.ru). This form has almost nothing in common with the other forms that experience the problem. After removing parts of the code and testing, I can now reproduce the problem by making a tiny change in a method that assigns a string to the memo component: This is my original code, which causes the form containing the editor to hide behind the main form: procedure TEditorForm.SetAsText(const Value: string); begin Editor.Text := Value; end; When I change the assignment to an empty string, the form displays correctly: procedure TEditorForm.SetAsText(const Value: string); begin Editor.Text := ''; // CRAZY! Problem goes away end; When I assign a single character to the editor, the form starts hiding again: procedure TEditorForm.SetAsText(const Value: string); begin Editor.Text := 'a'; // Problem is back end; Of course the other two problematic forms do not use this editor component or any of its units. I've tried deleting the memo control and adding it again (think creation order etc.), but it had no effect. Same if I create the memo in code. The form hides as soon as a non-empty string is assigned to the memo's Text property. A: I had the same issue some time ago. My solution was to add a Self.BringToFront; to the OnShow event of the modal form. A: Windows does not support many top most forms for app. And modal form is topmost by default. But you have this style for your own form. One decision in mind: remove top most of your main form (no visible effect), call modal form, set back topmost style when modal finished.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517882", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Forcing child divs to use parent's style I wanted to give all of the child's div elements a background-color of parent div. But, as I see, child divs' style overwrite parent's style even though child's did not have that property. For example, <!-- Parent's div --> <div style="background-color:#ADADAD;"> some codes here... <!-- child's div --> <div style="position:absolute;font-size:12px; left:600px;top:100px;"> again some codes... </div> </div> In here, If i delete the style of child div, it works fine. I think my problem may be solved if i did the same thing with external css file also. But, I have already done hundreds of divs exactly like this. So, is there anyway to force parent's style to child style, just for background-color?(new in css) A: But, as i see, chid divs' style overwrite parent's style even though child's did not have that property. No, they just don't inherit the value by default, so they get whatever value they would otherwise have (which is usually transparent). You can (in theory) get what you want with background-color: inherit. That has problems in older versions of IE though. A: Use css selectors like this to make the background of child div's inherit from their parent: Parent's div <div id="thisparticulardiv"> some codes here... child's div <div class="childrendiv"> again some codes... </div></div> CSS: #thisparticulardiv { background-color:#ADADAD; ... } #thisparticulardiv div { background: inherit; position:absolute; font-size:12px; left:600px; top:100px; } A: Use the inherit property on the child div : background:inherit <div style="position:absolute;font-size:12px; left:600px;top:100px; background:inherit">
{ "language": "en", "url": "https://stackoverflow.com/questions/7517885", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: RavenDB - When I do want a reference to another Root Aggregate I have been using DDD for a while know so I am comfortable with the idea of aggregates. At first I did have troubles wrapping my head around not using/persisting references to other root aggregates but I think I'm on board... so: * *Storing a root aggregate as a one document.... check *Using denormalized references containing properties that do not change or rarely change.... check For the times that I DO want to have a full reference to another root aggregate, I understand it is recommended that I persist a reference to its ID and can use the RavenDB client API's Includes to retrieve all the entities efficiently. That handles the data part, what I haven't seen is the best way to handle this in my entity class: * *Have both Product and ProductId properties in my class using [JsonIgnore] on the Product to ensure it doesn't get persisted with the document. * *The full object graph could then be glued back together in the repository (using API's Includes for efficiency) or I could inject a service into the entity that would fetch Product lazily (possible N+1 hit) *Glue it back together in a ViewModel. I don't like this idea as I could end up with an unexpected NULL reference in the domain if not used correctly. *Some other obvious way that I'm not seeing? Thoughts? A: In DDD there are at least two valid points of view. Some ppl link root aggregates only by ID or another valid key and second is using platform specific references to other objects. Both has it's own pros and cons. With NoSql solutions like RavenDb, it's probably better to use first approach, because second is just technically wrong. A: You are going explicitly against the recommended design here, why do you want a Product property refering to another aggregate? What does it gives you?
{ "language": "en", "url": "https://stackoverflow.com/questions/7517887", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Remote (free) SVN Host I'm sure this has been asked a thousand times but in my initial search I couldn't come across anything that seemed to answer my question, hence why I'm typing this :) We have a few developers starting a new side project. Each of us are in different locations. We (I) want to use SVN to manage the code. Using something like Dropbox would work, but it would just be a huge pain since SVN can take care of the merging and all that as well. Are there any free sites that will allow me to set something like this up, or any ways to do it myself? We are NOT open source, as I know some sites will let you do this only if your open source. Ideal situation would be to each have a local Tortoise SVN client on our machines, with a local repo of files that are synced to a remote location containing the official repo of files. Thanks. A: You should check out the Subversion Hosting Webpage. Free hosting, unlimited developers, unlimited modules, unlimited size brings up the following: * *Google *BerliOS Deviloper *SourceForge *Gna *Assembla Of course, another possibility is to use Git. The advantage of Git is that you can work without necessarily having your source repository always up, running, and available. Git will allow you to share your changes via email. I find Git a bit harder to use than Subversion, and I am not thrilled with the way it keeps everything as patches. However, in situations like yours where you have a half dozen or so people sharing source and no real centralized server, it can be much more convenient than Subversion. EDIT I forgot you mentioned that this is not an open source project. However, you can still go to the Subversion Hosting Webpage. One of the options is to check non-oss. Assembla offers free non-oss hosting. Git is still a good option if you don't want a public server. You can submit patches to each other via email, and you wouldn't even need a server. You can put the Git repository on Dropbox, but let your team members know not to push changes to it: Only fetch the latest changes and submit your changes to the gatekeeper via email. Another possibility: You might be able to share your Subversion repository via Dropbox. Each user can run svnserve on their own system. I'll have to check with the Subversion developers about the safety of this, though. Accessing the repository via file:// might be safer. Nope: I just checked with the Subversion developers. This is a definite no-no. A: Install Collabnet Subversion Edge. It is a all in one, apache/svn/web svn interface that is very hassle free. http://www.collab.net/downloads/subversion/ A: I have found VisualSVN to be very easy to set up if you have a spare box lying around to host it. If you want it to be remote, I would consider Assembla. I think that's who I'm using on that "side project I really should be working on more". They're free AND private. (A lot of free hosting sites require it to be open.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7517890", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Static content in UITableView - Problems with Apples guide I have been following the guide from Apple: http://developer.apple.com/library/ios/#documentation/UserExperience/Conceptual/TableView_iPhone/TableViewCells/TableViewCells.html#//apple_ref/doc/uid/TP40007451-CH7 concerning: Technique for Static Row Content. My problem is the following: All my cells are nil. According to Apple, the loading of the view should instantiate all object populating that nib file, bit only the tableview is instantiated. Thus the cell are nil and crashes the program in method cellForRowAtIndexPath: when it is returning a NULL cell. I have followed the guide to the letter, search all over and have found no solution, except creating a nib for each cell and loading those ones when needed, but that solution is much less elegant than the Apple solution. Any help would be appreciated. A: You have probably not bound your IBOutlets for the cells to the cells themselves. If your cell ivars are nil, then you didn't wire something. EDIT If the IBOutlets are connected, but the ivars are nil, then the IBOutlets aren't connected. There other possibilities, but that's the most common. Other possibilities: you're trying to access prior to viewDidLoad. In particular, you can't access your ivars during initWithFrame:. Other possibility is that you're overwriting them at some point. Check their values in viewDidLoad. Other possibility is that you're loading the wrong nib file, or not loading a nib file at all. All possibilities, but I'd first check everything in viewDidLoad and double-check you're connections. A: When instantiating your table view controller, in your init method you should call the overridden designated initializer of the superclass ([UIViewController initWithNibName:bundle:]), passing in the nib name: - (id)init { return [self initWithNibName:NSStringFromClass([self class]) bundle:[NSBundle mainBundle]]; } - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization here } return self; } For more details, see this answer: Automatically Loading XIB for UITableViewController
{ "language": "en", "url": "https://stackoverflow.com/questions/7517893", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Function str_replace do not work I have a problem with the function str_replace(). I have this code: $headImageName = "C:\Program Files\EasyPHP-5.3.3.1\www\realitka/headImages/hImageMini4e7b5a6ea8c95Pyro.png"; die(var_dump(str_replace("C:\Program Files\EasyPHP-5.3.3.1\www\realitka/", "", $headImageName))); And the result of var_dump is again: string(88) "C:\Program Files\EasyPHP-5.3.3.1\www\realitka/headImages/hImageMini4e7b5bae39148Pyro.png" Do you have any idea where is the problem? A: The \r in a double quoted string has special meaning. PHP interpret it as carriage return character. Either use single quotes: str_replace('C:\Program Files\EasyPHP-5.3.3.1\www\realitka/', "", $headImageMiniName) Or escape all your slashes: str_replace("C:\\Program Files\\EasyPHP-5.3.3.1\\www\\realitka/", "", $headImageMiniName) See the list of escape sequences in double-quoted strings. A: You need to escape \ symbols: str_replace("C:\\Program Files\\EasyPHP-5.3.3.1\\www\\realitka/", "", $headImageName)
{ "language": "en", "url": "https://stackoverflow.com/questions/7517894", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Enable/Disable a specific dynamically-added form-input I'm creating an HTML form, which takes some of its options from a database (php + mysql) In the php, I'm creating a checkbox input, with a select box next to it. I named the checkbox houseAppsSelected[] and the select customCategories[], so I'll get the values as an array. I append all the HTML into a var called $options, and I echo it later on. while ($row=mysql_fetch_array($result)) { $cat_id=$row["category_id"]; $cat_name=$row["category_name"]; $options.="<INPUT type=\"checkbox\" name=\"houseAppsSelected[]\" VALUE=\"$cat_id\">".$cat_name." ---> "; $custom_sql="SELECT custom_cat_id, cat_name FROM custom_categories WHERE house_app='$cat_id'"; $custom_result=mysql_query($custom_sql); $options.="<SELECT name=\"customCategories[]\">"; $options.="<OPTION value=\"0\"> Choose Category </option>"; while ($custom_row=mysql_fetch_array($custom_result)) { $custom_id = $custom_row['custom_cat_id']; $custom_name = $custom_row['cat_name']; $options.="<OPTION value=\"$custom_id\">".$custom_name."</option>"; } $options.="</SELECT> <br /> <br />"; } I want to have the checkbox control whether the select box is enabled or disabled. I found this article, which makes it look easy, but if all the select boxes have the same name, it will disable all of them. Is there a way to have a specific checkbox disable/enable only a specific select box, if I build them dynamically with php? (they all have the same name). A: You can give each tag a unique "id" value, which is independent of the "name". Then you can use var elem = document.getElementById(something); to access them by that unique value. Exactly how your php code makes up the unique values sort-of depends on what you need, exactly. It can really be anything. A: You can use the nextSibling property to find the select. function chkboxClick(chkbox) { chkbox.nextSibling.nextSibling.disabled = !chkbox.checked; } Add the click handler like this: <INPUT type="checkbox" onclick="chkboxClick(this)" ... /> Demo here: http://jsfiddle.net/gilly3/vAK7N/
{ "language": "en", "url": "https://stackoverflow.com/questions/7517899", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Select those that HAVE NEVER had certain entry I have a table of services that have been provided to clients. I'm trying to make a query that selects all the clients who received a service that WEREN'T provided by a certain user. So consider this table... id_client | id_service | id_user -------------------------------- 5 | 3 | 2 7 | 4 | 2 7 | 4 | 1 9 | 4 | 2 8 | 4 | 1 If I write the query like this: SELECT id_client FROM table WHERE id_service=4 AND id_user<>1 I still end up getting id_client 7. But I don't want to get client 7 because that client HAS received that service from user 1. (They're showing up because they've also received that service from user 2) In the example above I would only want to be returned with client 9 How can I write the query to make sure that clients that have EVER received service 4 from user 1 don't show up? A: Try this: SELECT DISTINCT id_client FROM yourtable t WHERE id_service = 4 AND id_client NOT IN (SELECT DISTINCT id_client FROM yourtable t WHERE id_user = 1 ) A: I'd write it like this: SELECT DISTINCT id_client FROM mytable t1 LEFT OUTER JOIN mytable t2 ON t1.id_client = t2.id_client AND t2.id_user = 1 WHERE t2.id_client IS NULL When the conditions of a left outer join are not met, the row on the left side is still returned, and all the columns for the row on the right side are null. So if you search for cases of null in a column that would be certain to be non-null if there were a match, you know the outer join found no match. A: SELECT id_client FROM table WHERE id_service = 4 GROUP BY id_client HAVING MAX(CASE WHEN id_user = 1 THEN 2 ELSE 1 END) = 1
{ "language": "en", "url": "https://stackoverflow.com/questions/7517901", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Hosted bug tracking software I'm looking for a free bug tracking software (hosted preferably, as my host doesn't allow me to use ssh, so i can't really install anything). What i want to do with it, is put a form on my website, and allow my beta testers to send in bugs (for now, only beta testers know of the site, so no login required). I do have PHP and MySql, but all the software i came across needed SSH someplace during the installation. I tried Mantis, bugzilla and fogbugz. I tried fogbugz, but i can't find any way to let users send in new bugs without logging in. Also, their XML api does not seem to allow you to add new bugs through it. So what i basically need is: -Bugtracking software -Free -Hosted -Ability to send in bugs through either 1. Interface on their host, without having to log in 2. Ability to embed, without having to log in 3. Something like an XML Api, which allows me to send in new bugs Does anyone know of one that can do these things, or have other tips? A: If you have normal hosting with just PHP/MySQL and FTP access, you could try to install the bug tracking software on our own linux box and then just FTP transfer the php files, maybe after you manually edit some setup files. You will also need to specify the connection to the database, but then use exactly the same setup as you normally use when you connect the database from PHP. A: Have a look at OnTime11 from axosoft. It's hosted, free for 2 users and looks extremely polished with a great feature set. There's a slick 2 min demo link on the homepage.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517906", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: as3 swf file can't execute a php file I have an actionscript3 swf file which execute a php file using this code : var load_php:URLLoader = new URLLoader(new URLRequest("php+txt/TIME.php")); This php file will get the server time and write it to a text file for the swf file to read The problem is this : The php file didn't execute at all I tested the same files in a different hosting and they all worked correctly Whats is the reason for this problem and how to solve it ? Please tell me if you need more details Solved: There was some naming problems because of today's date it was containing zeros but my as3 code was reading it with out zeros so it didn't find the file as an example : file name was: 07-02-2012 my as3 code read it as : 7-2-2012 A: You need to execute the script and get the return value when the script is complete, follow the code: var phpLoader:URLLoader = new URLLoader(); var request:URLRequest = new URLRequest("phpUrl"); //getting any problem with file not found phpLoader.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler, false, 0, true); //Getting any security error phpLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler, false,0, true); //When the script is complete phpLoader.addEventListener(Event.COMPLETE, onCompleteHandler, false, 0, true); //Execute the script phpLoader.load(request); private function onCompleteHandler():void{ var loader:URLLoader = URLLoader(e.target); trace ("loader.data", loader.data); } private function securityErrorHandler():void{/*TODO:*/} private function ioErrorHandler():void{/*TODO:*/} Remember, your PHP needs to pass some information to AS3 through method POST or GET
{ "language": "en", "url": "https://stackoverflow.com/questions/7517911", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: BlackBerry: browse specific folder, with a picture view I don't find how to start Filepicker in a specific folder, with a picture view : When I sayfp.setView(VIEW_PICTURES); and fp.setPath("file:///SDCard/Blackberry/travail/"); the view is correct, but not the path. I always go in the picture path, but with the good view (pictures only). If I only say fp.setPath("file:///SDCard/Blackberry/travail/");, the path is correct, but the view is default one, with icons and labels. Is ther any simply other way ? Thanks A: I believe you should try this: fp.setView(VIEW_ALL); // instead of VIEW_PICTURES fp.setFilter(".jpg"); // show files with ".jpg" extention only A: Go to this below link: http://208.74.204.192/t5/Java-Development/Display-photos-in-a-specific-folder-with-the-m%C3%A9dia-player/m-p/1319435#M174957 and see the alishaik786 message you can get the information. If you have reputation more than 20 then you can meet us in stackOverFlow's chat Room name is: "Life for Blackberry " and ask directly questions.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517913", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What is the use of Website preference in windows phone? in Website preference, if I select Mobile version instead of Desktop version. what is the use of it. is it redirect automatically to mobile version of current site or is it some thing relate to browser performance? A: Many websites today offer a slimmed-down version of their full desktop site that's customized for the smaller screens and slower Internet connections commonly found on mobile phones. Some people prefer these mobile sites, others don't. Internet Explorer Mobile can help show you the version you prefer. Grabbed from here. You might also find this handy.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517914", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What should I configure SVN to ignore in my Delphi projects? What files should I tell Tortoise SVN to ignore when committing to a repository? In particular I am interested in practical information such as whether to include such files as *.dproj.2007 etc that seem to appear but may not be needed. A: Using Delphi2005, our team has long ago adopted this: *.bdsproj *.scc *.suo *.user .~ *.local *.identcache *.dsk obj bin testing __history *.o *.lo *.la *.al .libs *.so .so.[0-9] *.a *.pyc *.pyo *.rej ~ ## .#* .*.swp .DS_Store Not sure if they're all needed or not, or what some of them are. I didn't come up with it, just following our internal wiki.... Along those lines, you should look at server-side pre-commit hooks. We've got a pre-commit trigger that dis-allows check of .bdsproj, .dpr, and .res files unless a specific tag is included in the comment: [Add Project File] [Add Res File]. If you try to commit a .bdsproj, .res, or .dpr without those tags, the commit will fail the audit and be rejected, and an embarrassing e-mail will be sent to the whole dev team. This is because these files rarely have any legitimate changes. If you need to add a unit to a project, fine, do it and include the tag with the checkin, and it'll be fine. The tag says "I know what I'm doing, and I have a good reason to change this file". Otherwise, you've got all sorts of crap being checked in - rev numbers, path changes, packages coming and going, etc.. We've also got some grep filters in the pre-commit, looking for certain things being added. Like unwanted "skins" units from DevExpress, because some developer has all of the skins installed and the IDE decided to add them. Or MadExcept, because someone left it turned on after debugging something (we don't allow MadExcept in production on this particular project, for a variety of reasons). Stuff like that. Update: because our environment is non-typical, I removed *.res from the list above. A: I use these in D2007, which seem to still work fine in XE and XE2: *.dcu *.~* *.ddp *.exe *.map *.bak *.obj *.dsk *.err *.log *.tmp *.identcache *.tvsconfig __history *.todo ModelSupport* *.local I don't include ModelSupport because I don't use the IDE's modeling stuff, so there's no point in versioning it if it's created by mistake. I also don't version anything in the __history folder, as that's just temporary versioning between checkins; once the checkin to SVN is made, it's not necessary any longer. (I disagree with Chris about *.res, BTW, especially when it comes to XE2. Resource files can be created now using Project|Resources and Images, and those go directly into a resource file. Since the resource\image may be actually coming from somewhere else not in the current folder, and the image file might accidentally not be checked in, I keep the .res file now. I also keep the project file; it has all the paths and compiler options set. If something happens where that needs to change, it's easy to just remove the project file and let the IDE recreate it as needed.) A: The official Emba answer is here: https://docwiki.embarcadero.com/RADStudio/Sydney/en/File_Extensions_of_Files_Generated_by_RAD_Studio At time of this writing, I believe this list of types to be incomplete (example: there is no mention of Android .obb files), but the wiki format allows suggestions, and the page does appear to be updated. You could also look at this: https://delphi.fandom.com/wiki/Delphi_File_Extensions although it seems to be less than complete, and not updated very often (Example: no mention of android-related files at all.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7517918", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "22" }
Q: C# Structure for objects in a 2D game First, let me apologize for asking a question that may seem a bit vague (or badly formalized), but I lack experience to ask anything more specific. I'm building an engine for playing 2D adventure games (the you-click-on-an-object-and-something-happens sort) in C# and I'm considering the best structure for it. As you can imagine, different things can happen when you interact with an object: if it's a door, you expect to enter another room, if it's a person, you expect to start talking to them, etc. My idea is to achieve this behaviour with delegates, like this: public abstract class GameObject { public delegate void onAction(); public onAction Click; } public class Door : GameObject { public Door() { Click = new onAction(ChangeRoom); } private void ChangeRoom() { //code to change room here } } public class Person : GameObject { public Person() { Click = new onAction(StartTalking); } private void StartTalking() { //code to display dialogue here } } I find this solution quite elegant, because if I want to create a special object with some behaviour not covered by its class, I can simply do this: specialObject.Click += new onAction(SpecialMethod); But this is also where things get complicated. I want my engine to be capable of playing different games simply by loading different data, without changes to the engine itself, so hard-coding the SpecialMethod somewhere inside the engine is not an option, it must be part of the data. For normal object, it can all be done with (de)serialization, but from what I've read, this is problematic with delegates. Can you suggest a way to do it? P.S.: Since I'm still on the concept level and the code above is not yet implemented, you are free to suggest whatever solution you find best, even one that avoids delegates completely. A: What you need is scripting. Essentially a script is an external resource (i.e. An external file) which contain a source code, which describe actions. C# has different option for this. You can emit assemblies from .NET languages. Or you can integrate another language (python, for example) and executin the script at runtime. Essentially the script is loaded, interpreted or compiled, and executed at the right time. If the script is able to modify the application state (the data structures), you can define objects behavior with external data (data-driven development). There is a lot literature about this issue, but I feel to suggest GPU Programming Gems 6 (section 4). However, the effort required to integrate a great scripting engine is very much. That way I tried to figure out a simple logic based on XML files (here is my question about, joining another question for defining the XML contents); sadly, I found that almost depends on the flexibility you need. A: You don't need to hard-code the SpecialMethod function into your engine, you can use it from different games that use your engine: var medievalDoor = new Door(); medievalDoor.Click += OpenDoorNormally; But in a different game: var starTrekDoor = new Door(); starTrekDoor.Click += SlideDoorUpward; So long as you expose the Click event, you don't need to hard-code anything into your engine. It can be put into your game which might have your engine as a DLL reference. A: First of all writing engine when you lack experience may be harder then you think. I'll suggest that you write you first game without engine and hardcode as much as you want and then learn from the experience and write your engine... I know that's not what you want :D If you haven't checked yet look at http://www.adventuregamestudio.co.uk/ play with the editor and think of the object model underneath. It will help. Since you want your games to be data driven you have to be able dynamically load and execute code. "It doesn't have to be a scripting language." It's against my nature to suggest adding scripting language and learning it at the same time when you learn how to build an engine. .NET Framework has a great reflection system that allows you to load C# code and compile it at runtime. I have to point out that this is kind of scripting in C# but there is a lack of proper definition of scripting language. Since you don't have a lot of experience in this my suggestion would be to use XML files that define your rooms and have a basic sequence of nodes (commands) that define what should happened when you click something. You should implement all the commands in your "engine" but you would be able to easily create new rooms therefore similar games. XML will be also very expandable approach since because of it's hierarchical structure it will allow you to add conditions, loops, etc. that will expand your engine's "scripting" capabilities. A: I do not see the problem if the 'decision' to execute some special behavior or not is left to the game object itself. If you want the engine to decide then you have, I think, incompatible design specifications as you would be effectively making the engine take a game-defined decision which is exactly what you do not want. Create an ISpecialBehaviorProvider field in your game objects and set it to an appropiate value when necessary (via constructor, public property, what have you). Your engine will always execute GameObject.Click whenever the user clicks. However, if specialBehaviorProvider is null, make the GameObject.Click execute the 'in class' code, otherwise call ISpecialBehaviorProvider.SpecialMethod. This way the engine has no part in deciding which method to call. A: The first thing I'll note here is that since these are classes, polymorphism would be pretty ideal here - with a virtual Click method, for example. Delegates can indeed be tricky for serializers, depending on the serialization approach. BinaryFormatter will do that, but I tend to avoid that serializer at all costs as a general rule. If it is possible, I would suggest just have your customisations subclass the standard implemetations, and use polymorphism. If it must be defined purely through data, you would essentially be implementing a scripting engine. Many such are available in .NET - IronPython might be useful, although for games lua is pretty common (you should be able to use Lua.NET quite easily). Then you can just have an optional script associated with the action, and invoke the script (defined in the data).
{ "language": "en", "url": "https://stackoverflow.com/questions/7517919", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Term Bubbles in Search Engine So I'll do my best to describe what I'm trying to do, but I think a picture will do more justice. Basically I'm working on a search engine of sorts and the engine accepts comma-delimited keywords. The way I'd like it to work is after the user enters a term and puts a comma, the term appears below the search bar in a "bubble" that is sized appropriately, with an "x" that allows them to remove the term from their search. Programmatically, I know how to do it. I'm a little stuck on how to do the graphics though. I know this is a programming forum, but I'm not sure if I should create the "base" graphic for the bubble and then have it dynamically size based on the length of the search term, or if there's some other way to do it. Thoughts? EDIT: Wow, just remembered that StackExchange accomplishes exactly what I'm wanting, sans the 'x' option. That's what I want, except with more rounded styling. A: Something along the lines of: span { display: inline-block; background: blue; padding: 5px 10px; -webkit-border-radius: 25px; -moz-border-radius: 25px; border-radius: 25px; } … should do the trick. No need to play with graphics except for the delete icons. A: Use the sliding doors technique... http://kailoon.com/css-sliding-door-using-only-1-image/ and then have an auto width with padding either side. A: You can go either the HTML 5 way be adding rounded corners to li's / div's. Look at the border-radius property for this. Although is isn't support by all (older / IE :) ) browsers. Or You can make something like the follwing (semi pseudocode): <div class="button"> <div class="left"></div> <div class="content">Term</div> <div class="right"></div> </div> .button .left { background: url('image with the left part of the button'); width: the width of the image; } .button .right { background: url('image with the rightpart of the button'); width: the width of the image; } .button .content { background: gray; } Which will have two sides (left / right) with the rounded corners as image and fixed width. And the middle content part which doesn't have a fixed width. EDIT Demo of the second way to go: http://jsfiddle.net/kc5ZC/4/ I just set the left / right with the same red background color. You would have to create left / right images with round corners for it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517930", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Difficulty in opening database in BroadcastReceiver I am having difficulty opening my database in my class. I am trying to get my application to start on the phone bootup, that is only if the boolean value in the database is true, if false it will not boot the application on startup. I have the errors to the bottom public class My_BroadcastReceiver extends BroadcastReceiver { SQLiteDatabase sqlDB; private static String DBNAME2 = "database2.db"; private static String Table2 = "options"; Boolean isOk = true; Context context; @Override public void onReceive(Context context, Intent intent) { try { sqlDB = SQLiteDatabase.openOrCreateDatabase(DBNAME2, null); Cursor r = sqlDB.rawQuery("SELECT Apponstart FROM " + Table2, null); System.out.println("COUNT of Location: " + r.getCount()); int loc = r.getColumnIndex("Apponstart"); int j = 0; if (r.moveToFirst()) { do { System.out.println("Apponstart is " + r.getString(loc)); isOk = Boolean.parseBoolean(r.getString(loc)); j++; } while (r.moveToNext()); if (j == 0) { System.out.println("No data found"); } } r.close(); // sqlDB.close(); } catch (Exception e) { e.printStackTrace(); } finally { sqlDB.close(); } if(isOk){ Intent i = new Intent(context, JoshTwoActivity.class); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(i); } } 09-23 08:10:05.615: WARN/System.err(208): android.database.sqlite.SQLiteException: unable to open database file 09-23 08:10:05.625: WARN/System.err(208): at android.database.sqlite.SQLiteDatabase.dbopen(Native Method) 09-23 08:10:05.625: WARN/System.err(208): at android.database.sqlite.SQLiteDatabase.<init>(SQLiteDatabase.java:1812) 09-23 08:10:05.625: WARN/System.err(208): at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:817) 09-23 08:10:05.625: WARN/System.err(208): at android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:851) 09-23 08:10:05.625: WARN/System.err(208): at three.three.My_BroadcastReceiver.onReceive(My_BroadcastReceiver.java:31) 09-23 08:10:05.625: WARN/System.err(208): at android.app.ActivityThread.handleReceiver(ActivityThread.java:2810) 09-23 08:10:05.625: WARN/System.err(208): at android.app.ActivityThread.access$3200(ActivityThread.java:125) 09-23 08:10:05.625: WARN/System.err(208): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2083) 09-23 08:10:05.625: WARN/System.err(208): at android.os.Handler.dispatchMessage(Handler.java:99) 09-23 08:10:05.625: WARN/System.err(208): at android.os.Looper.loop(Looper.java:123) 09-23 08:10:05.625: WARN/System.err(208): at android.app.ActivityThread.main(ActivityThread.java:4627) 09-23 08:10:05.625: WARN/System.err(208): at java.lang.reflect.Method.invokeNative(Native Method) 09-23 08:10:05.625: WARN/System.err(208): at java.lang.reflect.Method.invoke(Method.java:521) 09-23 08:10:05.625: WARN/System.err(208): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868) 09-23 08:10:05.625: WARN/System.err(208): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626) 09-23 08:10:05.625: WARN/System.err(208): at dalvik.system.NativeStart.main(Native Method) And again at 09-23 08:10:06.046: ERROR/AndroidRuntime(208): FATAL EXCEPTION: main 09-23 08:10:06.046: ERROR/AndroidRuntime(208): java.lang.RuntimeException: Unable to start receiver three.three.My_BroadcastReceiver: java.lang.NullPointerException 09-23 08:10:06.046: ERROR/AndroidRuntime(208): at android.app.ActivityThread.handleReceiver(ActivityThread.java:2821) 09-23 08:10:06.046: ERROR/AndroidRuntime(208): at android.app.ActivityThread.access$3200(ActivityThread.java:125) 09-23 08:10:06.046: ERROR/AndroidRuntime(208): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2083) 09-23 08:10:06.046: ERROR/AndroidRuntime(208): at android.os.Handler.dispatchMessage(Handler.java:99) 09-23 08:10:06.046: ERROR/AndroidRuntime(208): at android.os.Looper.loop(Looper.java:123) 09-23 08:10:06.046: ERROR/AndroidRuntime(208): at android.app.ActivityThread.main(ActivityThread.java:4627) 09-23 08:10:06.046: ERROR/AndroidRuntime(208): at java.lang.reflect.Method.invokeNative(Native Method) 09-23 08:10:06.046: ERROR/AndroidRuntime(208): at java.lang.reflect.Method.invoke(Method.java:521) 09-23 08:10:06.046: ERROR/AndroidRuntime(208): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868) 09-23 08:10:06.046: ERROR/AndroidRuntime(208): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626) 09-23 08:10:06.046: ERROR/AndroidRuntime(208): at dalvik.system.NativeStart.main(Native Method) 09-23 08:10:06.046: ERROR/AndroidRuntime(208): Caused by: java.lang.NullPointerException 09-23 08:10:06.046: ERROR/AndroidRuntime(208): at three.three.My_BroadcastReceiver.onReceive(My_BroadcastReceiver.java:57) 09-23 08:10:06.046: ERROR/AndroidRuntime(208): at android.app.ActivityThread.handleReceiver(ActivityThread.java:2810) 09-23 08:10:06.046: ERROR/AndroidRuntime(208): ... 10 more A: Will probably need more code to solve the problem, but I imagine the problem has something to do with teh way that the receiver is registered. Do you declare in XML or via registerReceiver? Is this onReceive ever being reached? Read about the BroadcastReceiver lifecycle on this reference page: http://developer.android.com/reference/android/content/BroadcastReceiver.html A: The database was the problem. I created a method and added context to the opening of the database. Here is my solution. public void guru(Context ctx){ System.out.println("Flax"); try { Log.e("troll", "alol"); sqlDB = ctx.openOrCreateDatabase(DBNAME2, 0,null); //sqlDB = SQLiteDatabase.openOrCreateDatabase(DBNAME2, null); Cursor r = sqlDB.rawQuery("SELECT Apponstart FROM " + Table2, null); System.out.println("COUNT of Location: " + r.getCount()); int loc = r.getColumnIndex("Apponstart"); int j = 0; if (r.moveToFirst()) { do { System.out.println("Apponstart is " + r.getString(loc)); Log.d("happening", "here"); isOk = Boolean.parseBoolean(r.getString(loc)); j++; } while (r.moveToNext()); if (j == 0) { System.out.println("No data found"); } } r.close(); // sqlDB.close(); } catch (Exception e) { e.printStackTrace(); Log.e("exception", e.toString()); } finally { sqlDB.close(); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7517932", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: installing TFS, JIRA, Subversion Any guy can guide me how long it will take to install (if you never did it before): - TFS - JIRA - Subversion on a VPS server... (windows 2008 R2)? Greetings A: I can answer for Subversion. I would recommend you download and install a project I manage - Subversion Edge. It is free and open-source and provides an easy to install packaging of everything you need to setup a Subversion server. It also includes a simple web user interface for ongoing management and configuration of the server. You should have at least 1GB of RAM on your VPS, but other than that it is as simple as running a Windows installer and then going to your web browser to configure the server. Finally, have you considered a different approach? There are cloud providers like Codesion that can host these tools in the cloud for you at a fairly inexpensive price. This takes away all of the administration details like installation, security and backup. A: JIRA is probably an hour to download, install and configure to talk to JIRA. However I'd recommend using FishEye to connect to Subversion, and then JIRA connects easily to FishEye.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517934", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SQL to increment on change of item in a sequenced list I have a SQL server 2008 table with the folling data in it: seq | item 1 | A 2 | B 3 | C 4 | C 5 | C 6 | B 7 | D 8 | D 9 | C I what return a new column which is a number which increments on change of item, as follows: seq | item | Seq2 1 | A | 1 2 | B | 2 3 | C | 3 4 | C | 3 5 | C | 3 6 | B | 4 7 | D | 5 8 | D | 5 9 | C | 6 The initial sequence must be maintained. Hope you can help, Tim Edit: I don't what to update the table, just return the result set via a view or query. Thanks for all your efforts. A: I think you want this: SELECT seq, Item, COUNT(*) OVER(PARTITION BY Item) [Count] FROM YourTable For your second query it would be: SELECT seq, Item, DENSE_RANK() OVER(PARTITION BY Item ORDER BY Seq) Seq2 FROM yourTable But in your example there is some inconsistency with the value of Item "B". A: declare @T table(seq int, item char(1)) insert into @T values ( 1, 'A'), ( 2, 'B'), ( 3, 'C'), ( 4, 'C'), ( 5, 'C'), ( 6, 'B'), ( 7, 'D'), ( 8, 'D'), ( 9, 'C') ;with C as ( select seq, item, 1 as seq2 from @T where seq = 1 union all select T.seq, T.item, C.seq2 + case when C.item <> T.item then 1 else 0 end from @T as T inner join C on T.seq - 1 = C.seq ) select seq, item, seq2 from c order by seq Update A version where seq is a datetime. I have added an extra CTE that enumerates the rows ordered by seq. declare @T table(seq datetime, item char(1)) insert into @T values ( getdate()+1, 'A'), ( getdate()+2, 'B'), ( getdate()+3, 'C'), ( getdate()+4, 'C'), ( getdate()+5, 'C'), ( getdate()+6, 'B'), ( getdate()+7, 'D'), ( getdate()+8, 'D'), ( getdate()+9, 'C') ;with C1 as ( select seq, item, row_number() over(order by seq) as rn from @T ), C2 as ( select seq, item, rn, 1 as seq2 from C1 where rn = 1 union all select C1.seq, C1.item, C1.rn, C2.seq2 + case when C2.item <> C1.item then 1 else 0 end from C1 inner join C2 on C1.rn - 1 = C2.rn ) select seq, item, seq2 from C2 order by seq A: for first one select A.seq,A.item, B.count from table_name A,(select item,count(item) count from table_name group by item) derived_tab B where A.item =B.item
{ "language": "en", "url": "https://stackoverflow.com/questions/7517935", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Confusion with javascript array.splice() I'm really confused about this. My understanding was that array.splice(startIndex, deleteLength, insertThing) would insert insertThing into the result of splice() at startIndex and delete deleteLength's worth of entries? ... so: var a = [1,2,3,4,5]; var b = a.splice(1, 0, 'foo'); console.log(b); Should give me: [1,'foo',2,3,4,5] And console.log([1,2,3,4,5].splice(2, 0, 'foo')); should give me [1,2,'foo',3,4,5] etc. But for some reason it's giving me just an empty array? Take a look: http://jsfiddle.net/trolleymusic/STmbp/3/ Thanks :) A: splice() modifies the source array and returns an array of the removed items. Since you didn't ask to remove any items, you get an empty array back. It modifies the original array to insert your new items. Did you look in a to see what it was? Look for your result in a. var a = [1,2,3,4,5]; var b = a.splice(1, 0, 'foo'); console.log(a); // [1,'foo',2,3,4,5] console.log(b); // [] In a derivation of your jsFiddle, see the result in a here: http://jsfiddle.net/jfriend00/9cHre/. A: The array.splice function splices an array returns the elements that were removed. Since you are not removing anything and just using it to insert an element, it will return the empty array. I think this is what you are wanting. var a = [1,2,3,4,5]; a.splice(1, 0, 'foo'); var b = a; console.log(b); A: The "splice()" function returns not the affected array, but the array of removed elements. If you remove nothing, the result array is empty. A: I had this issue. "The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place." https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice This will work: var a = [1,2,3,4,5]; a.splice(1,0,'Foo'); console.log(a); If you want it inside a function you could do this: function placeInMiddle(arr){ arr.splice(2,0, "foo"); return arr; } placeInMiddle([1,2,6,7]) Array.prototype.splice() page on Mozilla developer is more clear than other resources about how the splice method works and how it can be implemented, described briefly below! const months = ['Jan', 'March', 'April', 'June']; months.splice(1, 0, 'Feb'); // inserts at index 1 console.log(months); // expected output: Array ["Jan", "Feb", "March", "April", "June"] months.splice(4, 1, 'May'); // replaces 1 element at index 4 console.log(months); // expected output: Array ["Jan", "Feb", "March", "April", "May"]
{ "language": "en", "url": "https://stackoverflow.com/questions/7517937", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "21" }
Q: iPhone - SQLite using TEXT primary key Does anyone know if I can use a TEXT (UUID) primary key for an SQLite iPhone database? I am not using CoreData. A: Yes. You can use text field as primary key: CREATE TABLE myTable (uniqueText VARCHAR NOT NULL PRIMARY KEY, text VARCHAR) Some insert: INSERT INTO myTable (uniqueText, text) VALUES ('hello', 'world') Result: OK. Another insert: INSERT INTO myTable (uniqueText, text) VALUES ('hello', 'world') Result: Error - Column uniqueText is not unique. A: SQLite it is allowing you to use TEXT as primary key and if you are using SQLite api you should have no problems.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517938", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: pass a list to a mixin as a single argument with SASS I like to make mixins with SASS that help me make good cross-browser compatibility. I want to make a mixin that looks like this: @mixin box-shadow($value) { box-shadow: $value; -webkit-box-shadow: $value; -moz-box-shadow: $value; } to which I can pass something like this: @include box-shadow(inset -2px -2px 2px rgba(0,0,0,0.5), inset 1px 1px 2px rgba(255,255,255,0.5), inset 0px 0px 0px 1px #ff800f); with the result being something like this: box-shadow: inset -2px -2px 2px rgba(0,0,0,0.5), inset 1px 1px 2px rgba(255,255,255,0.5),inset 0px 0px 0px 1px #ff800f; -moz-box-shadow: inset -2px -2px 2px rgba(0,0,0,0.5), inset 1px 1px 2px rgba(255,255,255,0.5),inset 0px 0px 0px 1px #ff800f; -webkit-box-shadow: inset -2px -2px 2px rgba(0,0,0,0.5), inset 1px 1px 2px rgba(255,255,255,0.5),inset 0px 0px 0px 1px #ff800f; However, This doesn't work because the complier thinks I am trying to pass the mixin 3 arguments. box-shadow takes a variable number of comma separated bits, so I can't just define a mixin like box-shadow($1,$2,$3). I tried passing @include box-shadow("inset -2px -2px 2px rgba(0,0,0,0.5), inset 1px 1px 2px rgba(255,255,255,0.5), inset 0px 0px 0px 1px #ff800f"); and it compiled, but didn't actually render the styles. Any tips on how to resolve this? A: Variable Arguments Sometimes it makes sense for a mixin to take an unknown number of arguments. For example, a mixin for creating box shadows might take any number of shadows as arguments. For these situations, Sass supports “variable arguments,” which are arguments at the end of a mixin declaration that take all leftover arguments and package them up as a list. These arguments look just like normal arguments, but are followed by .... For example: @mixin box-shadow($shadows...) { -moz-box-shadow: $shadows; -webkit-box-shadow: $shadows; box-shadow: $shadows; } .shadows { @include box-shadow(0px 4px 5px #666, 2px 6px 10px #999); } via: http://sass-lang.com/docs/yardoc/file.SASS_REFERENCE.html#variable_arguments A: There's many ways to do this, the best way is using a mixin like so: @mixin box-shadow($value...) { -webkit-box-shadow: $value; -moz-box-shadow: $value; box-shadow: $value; } And include it like this: @include box-shadow(inset 0 1px 0 #FFD265, 0 0 0 1px #912E01, 0 0 0 7px rgba(0, 0, 0, .1), 0 1px 4px rgba(0, 0, 0, .6)); or @mixin box-shadow($value) { -webkit-box-shadow: #{$value}; -moz-box-shadow: #{$value}; box-shadow: #{$value}; } And include it like this: @include box-shadow("inset 0 1px 0 #FFD265, 0 0 0 1px #912E01, 0 0 0 7px rgba(0, 0, 0, .1), 0 1px 4px rgba(0, 0, 0, .6)"); or: @mixin box-shadow($value) { $value: unquote($value); -webkit-box-shadow: $value; -moz-box-shadow: $value; box-shadow: $value; } or: @mixin box-shadow($value) { -webkit-box-shadow: $value; -moz-box-shadow: $value; box-shadow: $value; } And include it like this: @include box-shadow((inset 0 1px 0 #FFD265, 0 0 0 1px #912E01, 0 0 0 7px rgba(0, 0, 0, .1), 0 1px 4px rgba(0, 0, 0, .6))); Sass is very powerful :) A: SASS 3.1 or less Note: If you're using SASS 3.2+ then use the Variable Arguments feature as rzar suggests. Just use string interpolation in the mixin itself, like so: @mixin box-shadow($value) { -webkit-box-shadow: #{$value}; // #{} removes the quotation marks that -moz-box-shadow: #{$value}; // cause the CSS to render incorrectly. box-shadow: #{$value}; } // ... calling it with quotations works great ... @include box-shadow("inset -2px -2px 2px rgba(0,0,0,0.5), inset 1px 1px 2px rgba(255,255,255,0.5), inset 0px 0px 0px 1px #ff800f"); Thanks for the tip Ryan. A: i want to point out that you can also pass a value using the argument name as you call the mixin: @mixin shadow($shadow: 0 0 2px #000) { box-shadow: $shadow; -webkit-box-shadow: $shadow; -moz-box-shadow: $shadow; } .my-shadow { @include shadow($shadow: 0 0 5px #900, 0 2px 2px #000); } note that scss is scoped so $shadow will still retain its mixin value if used again later. less i believe, suffers from reassignment in this scenario A: Use string interpolation @include box-shadow(#{"inset -2px -2px 2px rgba(0,0,0,0.5), inset 1px 1px 2px rgba(255,255,255,0.5), inset 0px 0px 0px 1px #ff800f"}); A: This doesn't compile: +box-shadow(inset 0 1px 0 #FFD265, 0 0 0 1px #912E01, 0 0 0 7px rgba(0, 0, 0, .1), 0 1px 4px rgba(0, 0, 0, .6)) this compiles: +box-shadow((inset 0 1px 0 #FFD265, 0 0 0 1px #912E01, 0 0 0 7px rgba(0, 0, 0, .1), 0 1px 4px rgba(0, 0, 0, .6))) That is, add a parenthesis around the comma-separated list of shadows and it should work: +box-shadow( (myshadow1, myshadow2, ...) )
{ "language": "en", "url": "https://stackoverflow.com/questions/7517941", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "47" }
Q: Problem with java app and hosted DBs Some time ago, I started a new Java app wich function was to provide access to a remote DB, to browse, sort, filter and operate with some registers. To test it out, I was using a PostgreSQL DB located in my PC and then I finished the Java app. Everything was fine so I was about to rent a hosting service only for my DB, to provide real service. The thing is that I haven't found any hosting company who provides direct DB access through JDBC f.e. For security reasons they don't permit that. Does anyone know a hosting service wich allows PostgreSQL + direct DB access? If not, the other way to do it is to create a WS in php f.e., to connect to the DB and then make my Java app to use that WS. But thats A LOT of extra work (I have many procedures) and I have little time. Thx in advance. A: You can always get a VPS solution where you are open to install whatever you want and however you want to use the services. Usually you will not find PostgreSQL service providers (or any other database for that matter) which exposes its ports on the internet, usually databases are meant to be access by App servers. For my company's PostgreSQL hosting, we use AWS instances with Resin Caucho as Java app server. A: you can always stand up an AWS instance with the servlet container and database of your choice. i wouldn't be surprised if they had pre-defined instances with the appropriate configuration (maybe something like tomcat and mysql). A: Have you tried to find hosting which provides dedicated server? It's more expensive than usually but you can do on computer (or VM) everything that you want. It shoud solve your problem. UPD. I also can suggest this pretty nice startup http://jelastic.com/
{ "language": "en", "url": "https://stackoverflow.com/questions/7517943", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Call to undefined method useIncludePath() i'm trying to learn symfony2. I was trying to install FOSUserBundle with those terminal commands (without any errors in a terminal): $ git submodule add git://github.com/FriendsOfSymfony/FOSUserBundle.git vendor/bundles/FOS/UserBundle $ git submodule update --init But after running them, my website is not working anymore and all i'm getting is this error: Fatal error: Call to undefined method Symfony\Component\ClassLoader\DebugUniversalClassLoader::useIncludePath() in /var/www/Symfony/wmap/vendor/symfony/src/Symfony/Component/ClassLoader/DebugUniversalClassLoader.php on line 41 it can be something really simple but i'm symfony2 newbie so any help will be appreciated :) thanks in advance A: Try with the version tagged 1.0.0: cd vendor/bundles/FOS/UserBundle && git checkout origin/1.0.0 The master version may work only with the master version of Symfony.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517945", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Drupal Anonymous Users Hidden Fields on Webform not showing up on e-mail I'm trying to capture the url of the webform. For validated users, the code below works: %server[SERVER_NAME]%server[REQUEST_URI] For anonymous users, it does not. From Post#7, I checked out this thread and tried the patch, but it did not work http://drupal.org/node/781786 When I tried that fix, the hidden form text title even disappeared. When a user is verified, the field shows up just fine. I need it to show when a user is anonymous. A: This functionality seems to be the way that the webform creators want it. There are some workarounds, including dynamically setting the values with javascript. Check out this issue. Javascript fix from thread: Drupal.Ajax.plugins.anypluginname = function(hook, args){ switch (hook) { case 'submit': // after submit was pressed $('#edit-submitted--product-link').val(window.location); // I know ID of my field :) /* Anything you want here */ break; } return true; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7517947", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Match all from the Regexp till it reachs a certain string PHP $str = 'href="http://grego.com" href="httpxoobar" href="xxx" href="ZZZZZ"'; preg_match_all('/http:\/\/(?<!href=")([\s\S]+)"/', $str,$m); print_r($m); I'm trying this code. I want to create 4 matches, I want to match all the href=" that doesn't have "http://" after it, and then get what is inside the href="(this)" (I'm using \s\S because it may contain new lines) and when it finds a quote ( " ) it stops and keep fetching the next (that in this case is in the same line), in this example it should bring all 4 results. how do I do that? Thanks. A: You've got things a bit mixed up. * *You've made http:// part of the match although you're writing that you don't want to match it, *you're using a negative lookbehind where a positive one would make sense, *you're not using the /s option to allow the dot to match newlines, *you're using a greedy quantifier that will match too much, and *you're using regexes to match HTML. That said, you might get away with this: (?<=href=")(?!http://)[^"]+ i. e. in PHP: preg_match_all( '%(?<=href=") # Assert position right after href=" (?!http://) # Assert that http:// is not right ahead [^"]+ # Match one or more characters until the next " %x', $subject, $result, PREG_PATTERN_ORDER); $result = $result[0];
{ "language": "en", "url": "https://stackoverflow.com/questions/7517948", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Oauth2 in Symfony2 I'd like to use some APIs, foursquare for example, in my Symfony2 project. The problem is that instead of the 2 great FOS bundles concerning Twitter/Facebook, I'm not finding anything on OAuth (I tried the EtcPasswdOAuthBundle but did not manage to make it work because of a missing file I guess). Moreover, I'd like to make it work with FOSUserBundle. So, if you could give me some help, I do not understand how to manage OAuth with Symfony ... Thanks ! A: Two years later, but for all who might step over this link while searching for a solution: The new OAuth2 package for client integration in Symfony2 is the HWIOAuthBundle, the KNPLabs is no longer maintained. - the server pendant is the FOSOAuthServerBundle. A: Facebook is using OAuth2, I guess you can easily make a Foursquare bundle based on the FacebookBundle. A: Guzzle is a really good client to do http request with objects. You can add guzzle-oauth2-plugin to handle OAuth easily. There is a tutorial if you need help.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517951", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: accessing/handling wireless keboard input(key press) in my ipad application i have already done much googling on this neither i found a tutorial/way to accomplish this nor find that it could not be acheived(so that i can assist my client ,it's not possible) we have requirement to integrate a wireless keyboard in our existing ipad application. some of the scenarios are.... suppose you are having a uibutton on the view. then according to the requirement if user tap the key "entr/return" on the wireless keyboard the result is same as tapping the button on view.if user tap the key "i" on the wireless keyboard the result is same as tapping the information button (UIButtonTypeInfoDark) on view. Means we have to handl wireless keyboard key press events. any idea/link/tutorial would very helpful for this situation. thanks! A: // Use the keyboard (<UIKeyInput>) class and provide for the delegates // required by this class // Put the <UIKeyInput> at the end of the @interface line in the header file. // Then make sure these methods are in your class as they are delegates // for the UIKeyInput class: - (BOOL) canBecomeFirstResponder { return YES; } - (void) deleteBackward { } - (void) insertText:(NSString *)theText { theText = [theText capitalizedString]; // Ignore case const char *keyPressed = [theText UTF8String]; switch(keyPressed[0]) { case 'A': // Do something associated with the 'A' key break; case '4': // Do something associated with the '4' key break; // etc. } } - (BOOL) hasText { return YES; } -(void) endUserInput { }
{ "language": "en", "url": "https://stackoverflow.com/questions/7517952", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Ajax-MySql-Php issue (submit text from form, send via AJAX to php script, back to div) I would like to send data to a MySql DB from a form via AJAX and a PHP script. I can get it perfect using option selection in the form, but I simply cannot get it using a text submit form. First what works: HTML Form: <form> <select name="users" onchange="showUser(this.value)"> <option value="">Select a person:</option> <option value="1">Peter Griffin</option> <option value="2">Lois Griffin</option> </select> </form> .js Scipt: function showUser(str) { if (str=="") { document.getElementById("txtHint").innerHTML=""; return; } if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("txtHint").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","getuser.php?q="+str,true); xmlhttp.send(); } PHP Script: <?php $q=$_GET['q']; $con = mysql_connect('localhost', 'root'); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("ajax_demo", $con); $sql="SELECT * FROM emp WHERE id = '$q'"; $result = mysql_query($sql); $i = 0; echo "<table class=\"table-master\"> <tr> <th>Firstname</th> <th>Lastname</th> <th>Age</th> <th>Hometown</th> <th>Job</th> </tr>"; while($row = mysql_fetch_array($result)) { $i++; echo "<tr class=\"d".($i & 1)."\">"; echo "<td>" . $row['FirstName'] . "</td>"; echo "<td>" . $row['LastName'] . "</td>"; echo "<td>" . $row['Age'] . "</td>"; echo "<td>" . $row['Hometown'] . "</td>"; echo "<td>" . $row['Job'] . "</td>"; echo "</tr>"; } echo "</table>"; mysql_close($con); ?> What I want to do is to have a text field in my HTML which will be filled out by the user when the user hits 'submit', that information gets passed into the js script containing the AJAX segment, gets queried by the DB and the results are outputed into my DIV. Where I think I am going wrong - cannot use onchange obviously in the form when using a text form for submition. Has to be onsubmit !? The js script works so therefore I think my AJAX part is fine. The PHP script also works but again, everything breaks down as soon as I try to get text input from the form. Perhaps my js script is not set up to capture the incoming text form variables!? Any help / guidance would be appreciated. A: First of all, I'm lazy and use jquery. But If you have multiple inputs in your form, the best way is to use an onsubmit handler, or an onclick handler on your submit button. You have to get each elements value, and build your query string appropriately: <form> <select id="users" name="users"> <option value="">Select a person:</option> <option value="1">Peter Griffin</option> <option value="2">Lois Griffin</option> </select> <input id="textfield" name="textfield" type ="text" /> <input type="submit" value="process" onclick="showUser()" /> </form> function showUser() { var sel = document.getElementById('users'); var selvalue = sel.options[sel.selectedIndex].value; var textfield = document.getElementById('textfield').value; if (selvalue=="" || textfield = "") { document.getElementById("txtHint").innerHTML=""; return false; } if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("txtHint").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","getuser.php?q=" + selvalue + "&t=" + textfield,true); xmlhttp.send(); return false; } You have to check for the T variable in your php script and do whatever you want with it. Please Please Please sanitize your inputs before interacting with the database. you should cast to int, and use mysql_real_escape_string() or parameterized queries. I'm assuming this works. I am used to Jquery where I would just serialize the form and forget about it. I'm sure somebody has a much better way to do this - I don't know javascript that well. A: If you want XmlHttp here it is how I do it for one text field, add more you self. Make a test table named emp with 5 fields f1,f2,..,f5 and this will work: index.htm <html> <head> <script type="text/javascript"> var request = false; try { request = new XMLHttpRequest(); } catch (trymicrosoft) { try { request = new ActiveXObject("Msxml2.XMLHTTP"); } catch (othermicrosoft) { try { request = new ActiveXObject("Microsoft.XMLHTTP"); } catch (failed) { request = false; } } } if (!request) alert("Error initializing XMLHttpRequest!"); </script> <script type="text/javascript"> function getEmp(emp) { document.getElementById('results').innerHTML="Please wait..."; //we will call asychronously getData.php var url = "getEmp.php"; var params = emp;//no url parameters var params = "empField=" +emp+""; request.open("POST", url, true);//use post for connect harder to attack, lots of data transfer //Some http headers must be set along with any POST request. request.setRequestHeader("Content-type", "application/x-www-form-urlencoded;charset=utf-8"); request.setRequestHeader("Content-length", params.length); request.setRequestHeader("Connection", "close"); request.onreadystatechange = updatePage; request.send(params); }//////////////////// //You're looking for a status code of 200 which simply means okay. function updatePage() { if (request.readyState == 4) { if (request.status == 200) { document.getElementById('results').innerHTML=request.responseText; } else{ //alert("status is " + request.status); } } } </script> </head> <body > Write employ name: <input type="text" name="emp" id='empField' value='John'/> <span style="background-color:blue;color:yellow;" onClick="getEmp(document.getElementById('empField').value )"/> Click to find </span> <div id="results"> </div> </body> </html> getEmp.php <?PHP mysql_connect('localhost', 'root',''); mysql_select_db("ajax_demo" ); $sq='\''; $sql="SELECT * FROM emp WHERE f1 = ".$sq.$_POST['empField'].$sq." "; $result = mysql_query($sql); $row = mysql_fetch_row($result); ?> <table border=4> <tr><td>Field 1</td><td>Field 2</td><td>Field 3</td><td>Field 4</td><td>Field 5</td></tr> <tr> <td><?PHP echo $row[0]; ?></td> <td><?PHP echo $row[1]; ?></td> <td><?PHP echo $row[2]; ?></td> <td><?PHP echo $row[3]; ?></td> <td><?PHP echo $row[4]; ?></td> <tr> </table>
{ "language": "en", "url": "https://stackoverflow.com/questions/7517957", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Syntaxhighlighter can't find any brushes after ajax request I'm using Syntaxhighlighter on a web page, I have made a javascript function to load all brushes using SyntaxHighlighter.autoloader(...) and apply SyntaxHighlighter.all() I run this function once when the page gets loaded, result: the syntax highlighting gets applied correctly. Afterwards, I load some new content using ajax and run this same function to highlight the new content as well. However this time Syntaxhighlighter seems to have forgotten about all the loaded brushes, I get an alert saying the brush is not loaded. I have no idea what is causing this although I have looked around and found 2 possible causes: An issue on the bitbucket repository This looks like the solution but when I use the unpacked shCore.js from the repository my IDE indicates a syntax error and I get javascript errors when I try to run it anyway. Another solution I've found on a few answers on other similar Stack Overflow posts is to use SyntaxHighlighter.highlight() instead of .all() after the page has been loaded. This doesn't work however. The function I'm using: function loadSyntaxHighLighter() { SyntaxHighlighter.autoloader( 'ahk ' + app.assets + 'js/syntaxhighlighter/brushes/shBrushAhk.js', 'aps ' + app.assets + 'js/syntaxhighlighter/brushes/shBrushAppleScript.js' //... ); SyntaxHighlighter.defaults['toolbar'] = false; if (SyntaxHighlighter != 'undefined') { SyntaxHighlighter.highlight(); } else { SyntaxHighlighter.all(); } } Does anyone have any idea on how to fix this? (Or can someone point me out how I can make the change suggested on bitbucket) Thanks A: I had the same issue. I've just solved it similar to bitbucket's suggestions. Add following code just before: loadSyntaxHighLighter() call: SyntaxHighlighter.vars.discoveredBrushes=null; SyntaxHighlighter will be forced to rediscover brushes on your page and load appopriate ones. Regards Tom A: Just an initial guess, have you printed out the result of this: 'ahk ' + app.assets + 'js/syntaxhighlighter/brushes/shBrushAhk.js' ? If this construction is not pointing to correct path of the brushes they won´t be loaded. Make sure also that the path is right in relation of the relative base path you are.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517962", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Program hangs if thread is created in static initializer block I have come across a situation where my program hangs, looks like deadlock. But I tried figuring it out with jconsole and visualvm, but they didn't detect any deadlock. Sample code: public class StaticInitializer { private static int state = 10; static { Thread t1 = new Thread(new Runnable() { @Override public void run() { state = 11; System.out.println("Exit Thread"); } }); t1.start(); try { t1.join(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("exiting static block"); } public static void main(String...strings) { System.out.println(state); } } When I execute this in debug mode then I could see control reaching @Override public void run() { state = 11; but as soon as state=11 is executed it just hangs/deadlocks. I looked in different postings in stackoverflow and I thought that static initializers are thread-safe but in that case jconsole should report this. About main thread, jconsole saying that it is in waiting state, and that's fine. But for the thread created in static initializer block, jconsole says that it is in RUNNABLE state and not blocked. I am confused and here lacking some concept. Please help me out. A: I was able to get your program to run by commenting out the line state = 11; You can not set state=11 until you have completed initialization. You can not complete initialization until t1 finishes running. T1 can not finish running until you set state=11. Deadlock. A: Here is what I think happens: * *The main thread tries to initialize StaticInitializer. This involves locking the corresponding Class object. *While still holding the lock, the main thread spawns another thread, and waits for it to terminate. *The other thread's run() method attempts to access state, which requires StaticInitializer to be fully initialized; this involves waiting on the same lock as in step 1. End result: a deadlock. See the JLS for a detailed description of the intialization procedure. If you move t1.join() into main(), everything works. A: You're not just starting another thread - you're joining on it. That new thread has to wait for StaticInitializer to be fully initialized before it can proceed, because it's trying to set the state field... and initialization is already in progress, so it waits. However, it's going to be waiting forever, because that initialization is waiting for that new thread to terminate. Classic deadlock. See the Java Language Specification section 12.4.2 for details about what's involved in class initialization. Importantly, the initializing thread will "own" the monitor for StaticInitializer.class, but the new thread will be waiting to acquire that monitor. In other words, your code is a bit like this non-initializer code (exception handling elided). final Object foo = new Object(); synchronized (foo) { Thread t1 = new Thread(new Runnable() { @Override public void run() { synchronized (foo) { System.out.println("In the new thread!"); } }); t1.start(); t1.join(); }); If you can understand why that code would deadlock, it's basically the same for your code. The moral is not to do much work in static initializers. A: classloading is kind of a sensitive time in the jvm. when classes are being initialized, they hold an internal jvm lock which will pause any other thread trying to work with the same class. so, your spawned thread is most likely waiting for the StaticInitializer class to be fully initialized before proceeding. however, your StaticInitializer class is waiting for the thread to complete before being fully initialized. thus, deadlock. of course, if you are truly trying to do something like this, the secondary thread is superfluous since you are joining it right after you start it (so you might as well just execute that code directly). UPDATE: my guess as to why the deadlock is not detected is because it is occurring at a much lower level than the level at which the standard deadlock detection code works. that code works with normal object locking, whereas this is deep jvm internal stuff.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517964", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "21" }
Q: Accessing BcdStore from Delphi I'm trying to convert this code fragment into Delphi and I got stuck on the for each objWBL in colObjects. if not objBcdStore.EnumerateObjects( &h10200003, colObjects ) then WScript.Echo "ERROR objBcdStore.EnumerateObjects( &h10200003 ) failed." WScript.Quit(1) end if for each objWBL in colObjects WScript.Echo "" WScript.Echo "Windows Boot Loader" WScript.Echo "-------------------" WScript.Echo "identifier " & GetBcdId( objWBL.Id ) If objWBL.Id = current then if not objWBL.GetElement(BcdOSLoaderInteger_NumberOfProcessors, objElement ) then WScript.Echo "ERROR WBL GetElement for " & Hex(BcdOSLoaderInteger_NumberOfProcessors) & " failed." WScript.Quit(1) end if WScript.Echo "numproc " & objElement.Integer if not objWBL.GetElement(BcdOSLoaderBoolean_UseBootProcessorOnly, objElement ) then WScript.Echo "ERROR WBL GetElement for " & Hex(BcdOSLoaderBoolean_UseBootProcessorOnly) & " failed." WScript.Quit(1) end if WScript.Echo "onecpu " & objElement.Boolean end if next My partial q&d translation (caution, must be Admin to run it): uses OleAuto, ActiveX; function GetObject(const objectName: String): IDispatch; var bindCtx: IBindCtx; moniker: IMoniker; chEaten: Integer; begin OleCheck(CreateBindCtx(0, bindCtx)); OleCheck(MkParseDisplayName(bindCtx, StringToOleStr(objectName), chEaten, moniker)); OleCheck(moniker.BindToObject(bindCtx, nil, IDispatch, Result)); end; procedure TForm44.btnClick(Sender: TObject); var colObjects : OleVariant; objBcdStore : OleVariant; objWMIService: OleVariant; begin objWMIService := GetObject('winmgmts:{impersonationlevel=Impersonate,(Backup,Restore)}!root/wmi:BcdStore'); if not objWMIService.OpenStore('', objBcdStore) then Caption := 'error' else begin objBcdStore.EnumerateObjects($10200003, colObjects); //??? end; end; EnumerateObjects is defined as boolean EnumerateObjects( [in] uint32 Type, [out] BcdObject Objects[] ); I have no idea how to walk over the BcdObject array in Delphi. A: you must use the VarArrayLowBound and VarArrayHighBound functions to get the bounds of the variant array returned by the EnumerateObjects function and then you can use a for loop to iterate over the elements of the array. check this sample Uses ComObj, ActiveX; function GetObject(const objectName: String): IDispatch; var bindCtx: IBindCtx; moniker: IMoniker; chEaten: Integer; begin OleCheck(CreateBindCtx(0, bindCtx)); OleCheck(MkParseDisplayName(bindCtx, StringToOleStr(objectName), chEaten, moniker)); OleCheck(moniker.BindToObject(bindCtx, nil, IDispatch, Result)); end; procedure TForm44.Button1Click(Sender: TObject); var colObjects : OleVariant; objBcdStore : OleVariant; objWMIService: OleVariant; i : Integer; objWBL : OleVariant; begin objWMIService := GetObject('winmgmts:{impersonationlevel=Impersonate,(Backup,Restore)}!root/wmi:BcdStore'); if not objWMIService.OpenStore('', objBcdStore) then Caption := 'error' else begin objBcdStore.EnumerateObjects($10200003, colObjects); if not VarIsNull(colObjects) and VarIsArray(colObjects) then for i := VarArrayLowBound(colObjects, 1) to VarArrayHighBound(colObjects, 1) do begin objWBL:=colObjects[i]; //do your stuff here end; end; end; A: Thanks to RRUZ for answer - I learned something new - but sadly the correct answer was "Don't do that" (how typical!). It turned out that by enumerating the Windows Boot Loader objects, one can't find out which of the objects is the "current" one. As I finally found out (thanks to the Hey, Scripting Guy! article from the July 2008 issue of the TechNet Magazine), the correct way is to open the loader object directly by it's well-known ID. (Which is, again, well-hidden and not well-known. The only official documentation I managed to find on the well-known BCD GUIDs is Boot Configuration Data in Windows Vista document.) The sample code below first opens BCD WMI object. Then it opens the default store and shows the information for the {current} boot entry object (accessed by the well-known ID). Next it opens the Windows Boot Manager object (by using its well-known ID), reads its DefaultObject element to determine the GUID of the default boot entry, opens this object by its GUID and shows the information. ShowLoaderInfo displays only ID (GUID), Description and NumberOfProcessors (which was an information I wanted to get from the BCD). A funny trick here is that the latter is of the BcdIntegerElement type, which returns its value through the Integer property, with a "feature" that the returned value is not an integer but a string. A note from the MSDN explains: The integer value of the element. The value is passed as a string because Automation does not natively support 64-bit integers. (Yeah, great! Why does it have to be 64-bit anyway? Are 2 billion processors not enough?) For a full list of supported Windows Boot Loader elements see BcdOSLoaderElementTypes. program ShowBCDInfo; {$APPTYPE CONSOLE} uses SysUtils, ComObj, ActiveX; const Description = $12000004; //http://msdn.microsoft.com/en-us/aa362652(v=VS.85) UseBootProcessorOnly = $26000060; //http://msdn.microsoft.com/en-us/aa362641(v=VS.85) NumberOfProcessors = $25000061; ForceMaximumProcessors = $26000062; ProcessorConfigurationFlags = $25000063; DefaultObject = $23000003; //http://msdn.microsoft.com/en-us/aa362641(v=VS.85) CurrentGUID = '{fa926493-6f1c-4193-a414-58f0b2456d1e}'; //http://msdn.microsoft.com/en-us/windows/hardware/gg463059.aspx WBMGUID = '{9dea862c-5cdd-4e70-acc1-f32b344d4795}'; function GetObject(const objectName: String): IDispatch; var bindCtx: IBindCtx; moniker: IMoniker; chEaten: Integer; begin OleCheck(CreateBindCtx(0, bindCtx)); OleCheck(MkParseDisplayName(bindCtx, StringToOleStr(objectName), chEaten, moniker)); OleCheck(moniker.BindToObject(bindCtx, nil, IDispatch, Result)); end; procedure ShowLoaderInfo(const name: string; const obj: OleVariant); var objElement: OleVariant; begin Writeln(Format('%s ID: %s', [name, string(obj.id)])); if obj.GetElement(Description, objElement) then Writeln(Format('Description: %s', [objElement.String])); if obj.GetElement(NumberOfProcessors, objElement) then Writeln(Format('NumProc: %s', [objElement.Integer])); end; procedure ShowBcdInfo; var objBcdStore : OleVariant; objWBL : OleVariant; objWBM : OleVariant; objWMIService: OleVariant; begin objWMIService := GetObject('winmgmts:{(Backup,Restore)}\\.\root\wmi:BcdStore'); if not objWMIService.OpenStore('', objBcdStore) then Writeln('*** error opening store') else begin if objBcdStore.OpenObject(CurrentGUID, objWBL) then ShowLoaderInfo('{current}', objWBL); if objBcdStore.OpenObject(WBMGuid, objWBM) and objWBM.GetElement(DefaultObject, objWBL) and objBcdStore.OpenObject(string(objWBL.ID), objWBL) then ShowLoaderInfo('{default}', objWBL); end; end; begin try OleInitialize(nil); try ShowBCDInfo; finally OleUninitialize; end; Readln; except on E:Exception do Writeln(E.Classname, ': ', E.Message); end; end.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517965", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to compare 2 dataTables I have 2 datatables and I just want to know if they are the same or not. By "the same", I mean do they have exactly the same number of rows with exactly the same data in each column, or not. I'd love to write (find) a method which accepts both tables and returns a boolean. How can I compare 2 datatables in this way? Both have identical schemas. A: You would need to loop through the rows of each table, and then through each column within that loop to compare individual values. There's a code sample here: http://canlu.blogspot.com/2009/05/how-to-compare-two-datatables-in-adonet.html A: The OP, MAW74656, originally posted this answer in the question body in response to the accepted answer, as explained in this comment: I used this and wrote a public method to call the code and return the boolean. The OP's answer: Code Used: public bool tablesAreTheSame(DataTable table1, DataTable table2) { DataTable dt; dt = getDifferentRecords(table1, table2); if (dt.Rows.Count == 0) return true; else return false; } //Found at http://canlu.blogspot.com/2009/05/how-to-compare-two-datatables-in-adonet.html private DataTable getDifferentRecords(DataTable FirstDataTable, DataTable SecondDataTable) { //Create Empty Table DataTable ResultDataTable = new DataTable("ResultDataTable"); //use a Dataset to make use of a DataRelation object using (DataSet ds = new DataSet()) { //Add tables ds.Tables.AddRange(new DataTable[] { FirstDataTable.Copy(), SecondDataTable.Copy() }); //Get Columns for DataRelation DataColumn[] firstColumns = new DataColumn[ds.Tables[0].Columns.Count]; for (int i = 0; i < firstColumns.Length; i++) { firstColumns[i] = ds.Tables[0].Columns[i]; } DataColumn[] secondColumns = new DataColumn[ds.Tables[1].Columns.Count]; for (int i = 0; i < secondColumns.Length; i++) { secondColumns[i] = ds.Tables[1].Columns[i]; } //Create DataRelation DataRelation r1 = new DataRelation(string.Empty, firstColumns, secondColumns, false); ds.Relations.Add(r1); DataRelation r2 = new DataRelation(string.Empty, secondColumns, firstColumns, false); ds.Relations.Add(r2); //Create columns for return table for (int i = 0; i < FirstDataTable.Columns.Count; i++) { ResultDataTable.Columns.Add(FirstDataTable.Columns[i].ColumnName, FirstDataTable.Columns[i].DataType); } //If FirstDataTable Row not in SecondDataTable, Add to ResultDataTable. ResultDataTable.BeginLoadData(); foreach (DataRow parentrow in ds.Tables[0].Rows) { DataRow[] childrows = parentrow.GetChildRows(r1); if (childrows == null || childrows.Length == 0) ResultDataTable.LoadDataRow(parentrow.ItemArray, true); } //If SecondDataTable Row not in FirstDataTable, Add to ResultDataTable. foreach (DataRow parentrow in ds.Tables[1].Rows) { DataRow[] childrows = parentrow.GetChildRows(r2); if (childrows == null || childrows.Length == 0) ResultDataTable.LoadDataRow(parentrow.ItemArray, true); } ResultDataTable.EndLoadData(); } return ResultDataTable; } A: Try to make use of linq to Dataset (from b in table1.AsEnumerable() select new { id = b.Field<int>("id")}).Except( from a in table2.AsEnumerable() select new {id = a.Field<int>("id")}) Check this article : Comparing DataSets using LINQ A: /// <summary> /// https://stackoverflow.com/a/45620698/2390270 /// Compare a source and target datatables and return the row that are the same, different, added, and removed /// </summary> /// <param name="dtOld">DataTable to compare</param> /// <param name="dtNew">DataTable to compare to dtOld</param> /// <param name="dtSame">DataTable that would give you the common rows in both</param> /// <param name="dtDifferences">DataTable that would give you the difference</param> /// <param name="dtAdded">DataTable that would give you the rows added going from dtOld to dtNew</param> /// <param name="dtRemoved">DataTable that would give you the rows removed going from dtOld to dtNew</param> public static void GetTableDiff(DataTable dtOld, DataTable dtNew, ref DataTable dtSame, ref DataTable dtDifferences, ref DataTable dtAdded, ref DataTable dtRemoved) { try { dtAdded = dtOld.Clone(); dtAdded.Clear(); dtRemoved = dtOld.Clone(); dtRemoved.Clear(); dtSame = dtOld.Clone(); dtSame.Clear(); if (dtNew.Rows.Count > 0) dtDifferences.Merge(dtNew.AsEnumerable().Except(dtOld.AsEnumerable(), DataRowComparer.Default).CopyToDataTable<DataRow>()); if (dtOld.Rows.Count > 0) dtDifferences.Merge(dtOld.AsEnumerable().Except(dtNew.AsEnumerable(), DataRowComparer.Default).CopyToDataTable<DataRow>()); if (dtOld.Rows.Count > 0 && dtNew.Rows.Count > 0) dtSame = dtOld.AsEnumerable().Intersect(dtNew.AsEnumerable(), DataRowComparer.Default).CopyToDataTable<DataRow>(); foreach (DataRow row in dtDifferences.Rows) { if (dtOld.AsEnumerable().Any(r => Enumerable.SequenceEqual(r.ItemArray, row.ItemArray)) && !dtNew.AsEnumerable().Any(r => Enumerable.SequenceEqual(r.ItemArray, row.ItemArray))) { dtRemoved.Rows.Add(row.ItemArray); } else if (dtNew.AsEnumerable().Any(r => Enumerable.SequenceEqual(r.ItemArray, row.ItemArray)) && !dtOld.AsEnumerable().Any(r => Enumerable.SequenceEqual(r.ItemArray, row.ItemArray))) { dtAdded.Rows.Add(row.ItemArray); } } } catch (Exception ex) { Debug.WriteLine(ex.ToString()); } } A: public static bool AreTablesTheSame( DataTable tbl1, DataTable tbl2) { if (tbl1.Rows.Count != tbl2.Rows.Count || tbl1.Columns.Count != tbl2.Columns.Count) return false; for ( int i = 0; i < tbl1.Rows.Count; i++) { for ( int c = 0; c < tbl1.Columns.Count; c++) { if (!Equals(tbl1.Rows[i][c] ,tbl2.Rows[i][c])) return false; } } return true; } A: If you were returning a DataTable as a function you could: DataTable dataTable1; // Load with data DataTable dataTable2; // Load with data (same schema) // Fast check for row count equality. if ( dataTable1.Rows.Count != dataTable2.Rows.Count) { return true; } var differences = dataTable1.AsEnumerable().Except(dataTable2.AsEnumerable(), DataRowComparer.Default); return differences.Any() ? differences.CopyToDataTable() : new DataTable(); A: There is nothing out there that is going to do this for you; the only way you're going to accomplish this is to iterate all the rows/columns and compare them to each other. A: or this, I did not implement the array comparison so you will also have some fun :) public bool CompareTables(DataTable a, DataTable b) { if(a.Rows.Count != b.Rows.Count) { // different size means different tables return false; } for(int rowIndex=0; rowIndex<a.Rows.Count; ++rowIndex) { if(!arraysHaveSameContent(a.Rows[rowIndex].ItemArray, b.Rows[rowIndex].ItemArray,)) { return false; } } // Tables have same data return true; } private bool arraysHaveSameContent(object[] a, object[] b) { // Here your super cool method to compare the two arrays with LINQ, // or if you are a loser do it with a for loop :D } A: Well if you are using a DataTable at all then rather than comparing two 'DataTables' could you just compare the DataTable that is going to have changes with the original data when it was loaded AKA DataTable.GetChanges Method (DataRowState) A: Inspired by samneric's answer using DataRowComparer.Default but needing something that would only compare a subset of columns within a DataTable, I made a DataTableComparer object where you can specify which columns to use in the comparison. Especially great if they have different columns/schemas. DataRowComparer.Default works because it implements IEqualityComparer. Then I created an object where you can define which columns of the DataRow will be compared. public class DataTableComparer : IEqualityComparer<DataRow> { private IEnumerable<String> g_TestColumns; public void SetCompareColumns(IEnumerable<String> p_Columns) { g_TestColumns = p_Columns; } public bool Equals(DataRow x, DataRow y) { foreach (String sCol in g_TestColumns) if (!x[sCol].Equals(y[sCol])) return false; return true; } public int GetHashCode(DataRow obj) { StringBuilder hashBuff = new StringBuilder(); foreach (String sCol in g_TestColumns) hashBuff.AppendLine(obj[sCol].ToString()); return hashBuff.ToString().GetHashCode(); } } You can use this by: DataTableComparer comp = new DataTableComparer(); comp.SetCompareColumns(new String[] { "Name", "DoB" }); DataTable celebrities = SomeDataTableSource(); DataTable politicians = SomeDataTableSource2(); List<DataRow> celebrityPoliticians = celebrities.AsEnumerable().Intersect(politicians.AsEnumerable(), comp).ToList(); A: How about merging 2 data tables and then comparing the changes? Not sure if that will fill 100% of your needs but for the quick compare it will do a job. public DataTable GetTwoDataTablesChanges(DataTable firstDataTable, DataTable secondDataTable) { firstDataTable.Merge(secondDataTable); return secondDataTable.GetChanges(); } You can read more about DataTable.Merge() here A: If you have the tables in a database, you can make a full outer join to get the differences. Example: select t1.Field1, t1.Field2, t2.Field1, t2.Field2 from Table1 t1 full outer join Table2 t2 on t1.Field1 = t2.Field1 and t1.Field2 = t2.Field2 where t1.Field1 is null or t2.Field2 is null All records that are identical are filtered out. There is data either in the first two or the last two fields, depending on what table the record comes from.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517968", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "31" }
Q: How to exchange text in PostScript I do have the following content of PostScript code that is originally generated by the Ghostscript Printer on Windows XP. /Euro /Times-BoldItalic /Times-BoldItalic-Copy BuildNewFont } if F /F1 0 /256 T /Times-BoldItalic mF /F1S52 F1 [82.664 0 0 -82.664 0 0 ] mFS F1S52 Ji 581 547 M (This is just a little test content)[55 42 42 23 46 37 42 37 28 21 51 42 21 51 46 42 32 66 42 21 60 42 55 21 21 21 55 37 32 46 55 42 23 0]xS ; I just want to edit the text but if I try to change the text between the brackets the text gets distorted no matter if the new text is longer or shorter. I tried to understand what the code above does, but I didn't find an appropriative documentation for that. Could you please help me to understand what the code - especially the line starting with '581' means and how I can edit the text without destroying the layout? Thank you in advance! PS: I need this for a python script that automatically exchanges some paragraphs and therefore am not looking for a third party tool for editing, a PDF editing tool or something like that ;) A: The line starting with '581' apparently moves to the point 581 547 then pushes a string and and array which is used by xS somehow. I suspect that xS is an extended version of show that uses that array, but I don't know how. You'd have to look at the beginning of the PS file to find the definition of xS. Also mFS seems like a transformation because it gets a matrix. Anyway, if the PS file contains typeset text, it's unlikely that you'll be able to change the text inside it without breaking the typesetting. A: The xS is almost certainly just xshow which is taking the string and the array and using the array to kern the text. You can replace the text by using simple show. Where you see: (This is just a little test content)[...]xS replace that with: (This is my replacement content) show The preamble of your file will have some shorthand name for show but you don't have to use it. That text may still fail to fit, but if you're just changing an entry in a form or something equally isolated (a title, a footnote, etc) it will probably be fine. If you want to get fancy you can take advantage of the fact that PostScript is a full-fledged programming language. You could write a function which determines the width of the old string (for this xshow you would find the right edge from last element of the array plus the stringwidth of the last character of the string) and then computes the length of your new string (stringwidth) and then uses ashow to squeeze/stretch your string into its place. A: I agree with @lhf. You really should do this sort of editing "upstream" fom the postscript level. Whatever the source application is, that's were the scripting needs to take effect. If the application has no native scripting then you can still interface to it with something like WinBatch. I've used WinBatch to make macro wizards to feed keystrokes to a telnet3270 client: enabling "batch" operations through the interactive system. For unix, there's expect.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517976", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: .NET Entity Framework 4 - How to run custom SQL when a certain table is updated When Table1.Foo changes, I want to update a column on Table2. What would be easiest is if I could just "run" some custom SQL after the update to Table1 is committed, however there doesn't seem to be a place to do this. It seems the "recommended" solution is to override the SaveChanges() method of EntitiesContext. However, I have several dozen models and hundreds of columns - it seems rather hacky and inefficient to execute code every time any model anywhere is changed, and then say "If it happens to be this property of this model, then do this.." My first approach was to use a database trigger, which would be great. Unfortunately, Oracle doesn't appear to support this type of updating I need to do in a trigger. Any other ideas for this sort of thing? A: Are you sure you can't just add a trigger that calls a stored procedure like this: http://searchoracle.techtarget.com/answer/Calling-a-stored-procedure-from-a-trigger It'll let you put in the functionality you want without disturbing your dozens of models/programs. A: you can create a stored procedure and call it in a very easy way... I think A: use the POCO feature in EF 4.0. check this link: http://www.devart.com/blogs/dotconnect/index.php/entity-framework-tips-and-tricks-part-2.html specially this section 'ObjectContext.ExecuteStoreQuery' A: You can create a partial class for the given entity in your project, if you did not create one. In your partial class, you override PropertyChangedEvent handler to update other table. I don't think you have to create a stored procedure for that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517977", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: although I am using a background worker GUI still hanging... I have a GUI Where i have to import some document , but when i do using background worker, the GUI is hanging , which must not happen since I am using a background worker, why this happens? kindly find code below.. void ImportNotes_ContextMenuStripItem_Click(object sender, EventArgs e) { if (!backgroundWorker_notesImport.IsBusy) { mainFrm.ProgressBar.Visible = true; backgroundWorker_notesImport.RunWorkerAsync(); } } private void backgroundWorker_notesImport_DoWork(object sender, DoWorkEventArgs e) { ImportNotes(); } private void backgroundWorker_notesImport_ProgressChanged(object sender, ProgressChangedEventArgs e) { mainFrm.ProgressBar.Value = e.ProgressPercentage; } void ImportNotes() { } A: Does the ImportNotes() method just do the whole import in one big step? If so then you still aren't giving the UI chance to do anything. The example from the MSDN shows how it should be used: // This event handler is where the time-consuming work is done. private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { BackgroundWorker worker = sender as BackgroundWorker; for (int i = 1; i <= 10; i++) { if (worker.CancellationPending == true) { e.Cancel = true; break; } else { // Perform a time consuming operation and report progress. System.Threading.Thread.Sleep(500); worker.ReportProgress(i * 10); } } } You need to have a loop that allows some processing (the Sleep in this case) and a call to ReportProgress.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517979", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Do onMeasure in Android returns Size including padding and margin? I am working on a Custom Component and would like to know if onMeasure called on children would return width and height of the child including padding and margin of it? A: The sizes passed in onMeasure includes the padding, but not the margin. So, while implementing your onMeasure you should keep in mind: * *The padding. *The minimum width and minimum height of our view (use getSuggestedMinimumWidth() and getSuggestedMinimumHeight() to get those values). *The widthMeasureSpec and heightMeasureSpec which are the requirements passed to us by the parent. Ref: Custom View: mastering onMeasure | Lorenzo Quiroli
{ "language": "en", "url": "https://stackoverflow.com/questions/7517980", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: From SID get user@domain not domain\user This is a bit of an obscure one: I need to get the user@domain form of a user/group, but I do NOT want the domain\user form. I encountered a problem once with long windows 2003+ names where the two are NOT the same because of the domain\user length limit, because the new form does not have the limit. I'm under C#, and while I can do the following: string GetUserName(SecurityIdentifier SID) { NTAccount account = SID.Translate(typeof(NTAccount)); string [] splits = string.Split("\\", account.Value); return splits[1] + @"@" + splits[0]; } This isn't always right, as I stated in my intro, the username@domain is NOT NECESSARILY the same as the old windows NT form of the username. If you don't believe me, go into AD Users and computers on a 2k3+ box and see how there's different fields for the old NT username versus the new one. So how do I guarantee I get the right username@domain from a SID? Add to that, I also need this type of thing to work for local users/groups. A: The Windows API to get this is called DsCrackNames - http://msdn.microsoft.com/en-us/library/ms675970. It will give you the output in any number of formats depending on the flags you provide. A: Can't you use System.DirectoryServices.AccountManagement.Principal and the UPN (your name@domain.com) to look up the Sid (also a property on the principal)? http://msdn.microsoft.com/en-us/library/bb340707.aspx Here is a TechNet snippet that uses a DirectorySearcher to search for a user by UPN http://gallery.technet.microsoft.com/ScriptCenter/de2cb677-f930-40a5-867d-ea0326ccbcdb/ After fetching the principal you should be able to get the Sid property. A: I have post some C# code for retreiving user data from SID, here is the same aapted to your question : /* Retreiving object from SID */ string SidLDAPURLForm = "LDAP://WM2008R2ENT:389/<SID={0}>"; System.Security.Principal.SecurityIdentifier sidToFind = new System.Security.Principal.SecurityIdentifier("S-1-5-21-3115856885-816991240-3296679909-1106"); DirectoryEntry userEntry = new DirectoryEntry(string.Format(SidLDAPURLForm, sidToFind.Value)); string name = userEntry.Properties["userPrincipalName"].Value.ToString();
{ "language": "en", "url": "https://stackoverflow.com/questions/7517981", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Toggle between divs inside another div using jQuery? So I have a div that can have several divs inside of it. Something like: <div id="news"> <span>Latest News!</span> <div> //News 1 </div> <div> //News 2 </div> </div> What I'm trying to do is on page load, the first div is visible, then after so many seconds, it fades out and the second div fades in. Pretty simple with fadeIn and fadeOut but I have to specifiy each div's actions. Is there a way to say 'Toggle between every div inside my #news div'? This way I can add new divs without having to add code to hide/show them? Thanks! A: // count the number of news items var len = $("#news div").length; // hide all but the first $("#news div:gt(0)").hide(); // set up a counter var counter = 0; // function to hide all except the current iteration function changeDiv() { $("#news div").eq(counter).show().siblings("div").hide(); counter++; // when we reach the last one, start again if(counter === len) { counter = 0; } } // go! var i = setInterval(changeDiv, 2000); Demo. A: Try the following $(document).ready(function() { $('#news div:gt(0)').hide(); var swap = function(item) { setTimeout(function() { $(item).fadeOut(1000, function() { var next = $(item).next()[0]; if (!next) { next = $('#news div')[0]; } $(next).fadeIn(1000, function() { swap($(this)[0]); }) }); }, 1000); }; swap($('#news div')[0]); }); Fiddle: http://jsfiddle.net/9gwzt/2/ A: You could try using jQueryUI, which has a tab control: http://jqueryui.com/demos/tabs/ Otherwise you could give all the divs a common class, say "tab". Then for your tab buttons you can just have: $(".tab").fadeOut(); $("#tab-that-I-want").fadeIn(); A: You may also want to look into using the jQuery Cycle plugin: http://jquery.malsup.com/cycle/ A: Probably you need some plugin with content rotation. Here is one of them: http://demo.smartnetzone.com/auto-rotating-tabs-using-jquery/ A: This will loop through the news items. When it reaches the end, it'll start back at the top. Change the 2000 to whatever interval you want (in ms). function switchNewsItem(){ $('#news div:visible').fadeOut(function(){ $(this).next().length ? $(this).next().fadeIn() : $('#news div').eq(0).fadeIn(); }); }; $('#news div').eq(0).show(); // show the first news item setInterval(switchNewsItem, 2000); See working example.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517987", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: on Internet Explorer's ,when textarea bind keyup or keypress the keyboard shortcuts Ctrl+Z Ctrl+Y does't work? on Internet Explorer's ,when textarea bind keyup or keypress that the keyboard shortcuts Ctrl+Z Ctrl+Y does't work! Like this: http://jsbin.com/ivaca the second textarea,How to fix this bug in IE? A: I noticed this code in your page. I seems to do nothing, but I that is the problem. (I tried it on my computer - running the page without this block - works fine) Event.on('el-b', 'keypress', function(e) { var el = document.createElement('p'); document.body.appendChild(el); document.body.removeChild(el); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7518004", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: The process could not execute 'sp_replcmds' on 'database_name' I got an error message in my Log Reader Agent: The process could not execute 'sp_replcmds' on 'Database Name'. I created another agent profile with a large query timeout and a min value to batch, but it still doesn't work. Can someone help me? I'm using SQL Server 2008 and I'm trying to do a replication between databases on different servers. A: It could be possible that owner of the database could be someone other than what you have permissions for. Below there's a simple command to change ownership...if you have the rights to do so. --TSQL Code-- USE PublishedDatabase GO EXEC sp_changedbowner 'sa' GO A: There are a lot of things that can cause this error (which include, but is not limited to): * *The database has been publication disabled *The account trying to run the log reader agent doesn't have the ability connect to the publisher server *The account trying to run the log reader agent doesn't have permission to run sp_replcmds In my experience, there's a little more to the error in the replication monitor. Is this the case for you? A: This could be due to Owner is not set for the database. You can check by right clicking on database then choose Property and go to File Table and the Owner selection should be there.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518010", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Subscribing Users to MailChimp using ASP.NET I've been tasked with developing a simple package to post from a newsletter signup form to MailChimp. Easy enough for me to do in PHP, but this has to be in ASP.NET, which I don't know at all. I've found my way to PerceptiveMCAPI, gotten my API keys, my list id, and my form fields set up, but I just have no idea how I'm supposed to create the actual listSubscribe command. The only examples I can find are for listBatchSubscribe, which I haven't been able to water down to only work for a single iteration. Please help! I need to be pointed in the right direction, or given an example of how to actually build this command. Thanks in advance. A: Hope you understand c# code. listSubscribe cmd = new listSubscribe(); listSubscribeParms newlistSubscribeParms = new listSubscribeParms { apikey = apikey, id = listid, email_address = "test@gmail.com", merge_vars = new Dictionary<string, object>(), double_optin = false, email_type = EnumValues.emailType.html, replace_interests = true, send_welcome = false, update_existing = true }; listSubscribeInput newlistSubscribeInput = new listSubscribeInput(newlistSubscribeParms); var subscribeSuccess = cmd.Execute(newlistSubscribeInput); The listSubscribe, listSubscribeParms, listSubscribeInput come from the PerceptiveMCAPI library. hope this helps. if it does, then don't forget to mark as answer. A: Here is the VB code that works great for me. The above code didnt convert well for me... You need to get this http://perceptivemcapi.codeplex.com/ If using VS pro you can just copy the two dlls into the bin, in express i think you need to import them/reference them or something! Your need to do these imports Imports PerceptiveMCAPI Imports PerceptiveMCAPI.Types Imports PerceptiveMCAPI.Methods then this code... Dim cmd As New listSubscribe() Dim newlistSubscribeParms As New listSubscribeParms() newlistSubscribeParms.apikey = "YourApiKeyFromMailChimp" newlistSubscribeParms.id = "YourListIdFromMailChimp" newlistSubscribeParms.email_address = "NewEmailToAddToList@domain.com" newlistSubscribeParms.double_optin = False newlistSubscribeParms.email_type = EnumValues.emailType.html newlistSubscribeParms.replace_interests = True newlistSubscribeParms.send_welcome = False newlistSubscribeParms.update_existing = True Dim newlistSubscribeInput As New listSubscribeInput(newlistSubscribeParms) Dim subscribeSuccess = cmd.Execute(newlistSubscribeInput) Simples!
{ "language": "en", "url": "https://stackoverflow.com/questions/7518014", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Manipulating a string in javascript If I have a long string, lets say var str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean eu accumsan urna. Phasellus imperdiet elementum massa sit amet condimentum. Vivamus porttitor lobortis dignissim. Nam non tellus sapien, at pulvinar augue. Nulla metus mauris, cursus a sodales varius, imperdiet nec nisi. Quisque ut est quis massa sagittis pharetra quis aliquam dui. Phasellus id nisi quis mauris ultricies tristique et ut orci."; and I want to manipulate it to display it something like this "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean eu..." How can I do that? A: Try using the substring() method https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/substring Returns a subset of a string between one index and another, or through the end of the string. var max = 20; str = str.length > max ? str.substring(0, max - 3) + "..." : str; A: You can do this with simple javascript string manipulation. var limit = 30 //or wherever you want to cut it off str = str.substring(0, Math.Min(limit, str.length)) + '...' EDIT: You do not need the Math.Min as javascript's substring method will take care of the issue if the limit is longer than the string. Note: This will append "..." even if your string is too short and is displayed in its entirety. See hunter's answer for how to avoid this. A: jQuery, while providing many useful bits of prewritten code, isn't aimed at people doing string manipulation. Just use substring var truncated = str.substring(0, 40); if (truncated !== str) { str = truncated + "…"; } A: You can use substr var limit = 100; str = str.substring(0,limit) + '...'; A: var shortStr = str.substr(0, 66) + '...'; A: You need to learn JavaScript then use jQuery! All the string manipulation can be done with JavaScript. You should use functions like .substring() .substr() .slice() and so... In this case you can use substr: str.substr(0, str.indexOf('eu') + 2) + '...'; A: You could use a regular expression replace: str = str.replace(/^(.{0,29}[\w\d])(\b.+)?$/, function($0, $1) { if($1.length < str.length) { return $1+'...'; } return $0; }); This will: * *If str is shorter than 30 characters, the result is the entire string. *It str is longer than 30 characters, it will be cut off at a word boundary and a ... will be appended to it. This ensures you don't end up with results like Lorem ipsum dolor sit amet,... (with the comma before the ...) To change it to truncate at 66 characters... str = str.replace(/^(.{0,65}[\w\d])(\b.+)?$/, function($0, $1) { if($1.length < str.length) { return $1+'...'; } return $0; });
{ "language": "en", "url": "https://stackoverflow.com/questions/7518015", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Issue with std::BinaryPredicate using Solaris CC I have a problem on Solaris using the Sun Studio compiler. It seems related to libCstd. Consider the following code : #include <list> static bool f(double fFreq1, double fFreq2) { return false; } int main() { std::list< double > l; l.unique(f); } The error message I get is : "uniq.cpp", line 6: Error: Could not find a match for std::list<double>::unique(bool(double,double)) needed in main(). But when I use references instead of values, it compiles just fine : #include <list> static bool f(const double& fFreq1, const double& fFreq2) { return false; } int main() { std::list< double > l; l.unique(f); } Compilation is ok for both using g++. Does anyone know what is going on ? Thanks ! A: Try building with -library=stlport4 as the standard C++ library is not standards compliant. See http://www.oracle.com/technetwork/server-storage/solarisstudio/documentation/cplusplus-faq-355066.html#LibComp5 for more info.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518022", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Php email sent with issues on subject chars in Outlook only Im sending a mail using php, and the subject of the mail has accents. Im receiving weird characters in Outlook instead the accented chars. If i see the email in a web email client i see the subject perfect. This is the code that im using to send the email: $to = 'whateveremail@whatever.com'; $subject = '[WEBSITE] áccent – tésts'; $message = '<p>Test message</p> $headers = 'MIME-Version: 1.0' . "\r\n"; $headers.= 'From:equipothermomix@thermomix.com' . "\r\n"; $headers.= 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; mail($to, $subject, $message , $headers); How i could solve the issue, do i have to use another charset? A: The only reliable way to send e-mail is using plain 7 bit ASCII so you need to encode strings properly when you want to use anything else. In your case, [WEBSITE] áccent – tésts should be encoded as (e.g.) =?windows-1252?B?W1dFQlNJVEVdIOFjY2VudCCWIHTpc3Rz?=, where the string splits as: =?windows-1252?B?W1dFQlNJVEVdIOFjY2VudCCWIHTpc3Rz?= ^ ^ ^ | | | Charset | Data | Base64 Check: echo base64_decode('W1dFQlNJVEVdIOFjY2VudCCWIHTpc3Rz'); // [WEBSITE] áccent – tésts This is just an example of one of the possible ways to encode non-ASCII strings. When sending e-mail, there are many little details like this that need attention. That's why sooner or later you end up using a proper e-mail package like Swift Mailer or PHPMailer. A: If there is a mix of encoding types, special characters are destroyed. PHP messing with HTML Charset Encoding PHP also has an option for encoding messages. mb_language('uni'); // mail() encoding PHP - Multibyte String * *http://php.net/manual/en/mbstring.overload.php *http://php.net/manual/en/ref.mbstring.php
{ "language": "en", "url": "https://stackoverflow.com/questions/7518024", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: SqlServerCe 4.0 "Database already opened by a different user" Error I am working with a SqlServerCe 4.0 database located in an Asp.Net app's /App_Data/ folder - in this case hosted by IISExpress via WebMatrix. The database is also accessed from a Microsoft WebMatrix Extension - which runs in the WebMatrix.exe process. Either the WebMatrix Extension or the Asp.Net app can access the database just fine as long as each is the first to access - in the case the accessing app is the second to open a connection, the following error is returned: Database already opened by a different user. [ Db name = ... ] : at System.Data.SqlServerCe.SqlCeConnection.ProcessResults(Int32 hr) at System.Data.SqlServerCe.SqlCeConnection.Open(Boolean silent) at System.Data.SqlServerCe.SqlCeConnection.Open() The code opening the connection from the WebMatrix Extension is: SqlCeConnection conn = new SqlCeConnection("DataSource=" + dbPath + "\\App_Data\\db.sdf"); conn.Open(); SqlCeCommand cmd = new SqlCeCommand("select ...", conn); SqlCeDataReader r = cmd.ExecuteReader(); Which throws the exception on the conn.Open() line. I am running the latest SqlServerCe 4.0 bits and have tried running WebMatrix as Administrator, but the result is consistent with the above. There is precious little in terms of search results for this. -Paul
{ "language": "en", "url": "https://stackoverflow.com/questions/7518032", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to get file paths of MS SQL database that is stuck Restoring I distribute updates to our database in the form of backups "With Replace", but the users can install it to any location on any hard drive, which means I need to "Exec SP_HelpFile" on it before running "Restore With Move". But SP_HelpFile requires me to "Use TheDatabase" first, which I can't do if it's already stuck in a failed restore. I can't even run "With Recovery" if I can't tell it where to restore. Is there any way to use the Master database to get the filenames? Right now my only solution is to delete and reinstall, but I'd like the automated updater to be able to handle it on its own. UPDATE: Server version is 2005 & 2008 A: In SQL 2005+, you can use the system view sys.master_files. select name, physical_name from sys.master_files where db_id = db_id('your_database') A: You should be able to get the path+filename without having to use the database. sp_helpfile uses the local sys.sysfiles but for now at least you can use the catalog view sysaltfiles, still in master for backward compatibility reasons... this is assuming SQL Server 2005+ (please always specify the version of SQL Server you're using): SELECT filename FROM master.sys.sysaltfiles WHERE db_id = DB_ID('database name'); A: In the SQL Server 2008, you should use as follows: SELECT filename FROM master.sys.sysaltfiles WHERE dbid = DB_ID('db_name');
{ "language": "en", "url": "https://stackoverflow.com/questions/7518035", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: IIS7 - Client side caching a .ashx file that already has no-cache data set In IIS7, I have a .ashx file from a third party which sets caching headers to be no-cache,private I want this to be cached on the client so I have added the following code to the global.asax void Application_EndRequest(object sender, EventArgs e) { if (Request.Path.IndexOf("Script.ashx") > -1) { Response.Cache.SetCacheability(HttpCacheability.Public); Response.Cache.SetExpires(DateTime.Now.AddDays(7)); Response.Cache.SetValidUntilExpires(true); Response.Cache.VaryByHeaders["Accept-Language"] = true; } } I would expect the resulting cache information to be public, Expires: Thu, 29 Sep 2011 16:06:27 GMT Instead however I get the Franken-response of no-cache,public Expires: Thu, 29 Sep 2011 16:06:27 GMT So the code is taking replacing the private with public as I want but it fails to replace the no-cache directive. Is it possible to replace the no-cache directive with this approach: if so what am I missing; if not what other approaches are there? A: The above code fails in IIS7 Classic mode but the Integrated mode the code works as expected and produces sensible response headers. I assume this is due to the way that classic works similar to an ISAPI filter. I have switched to Integrated mode and this has solved the issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518036", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP value doesn't equal to what it echoes I got a value in $array[1] and I want to know what it is, so I can compare it in other parts of my code. So I echo out $array[1] and I get "vrij &nbsp &nbsp " or "vrij " $value = $array[1]; echo $value ; // outputs "vrij " if($value = $array[1]){ echo "TRUE 1"; } if($value = "vrij "){ echo "TRUE 2"; } The problem is, it only echo's TRUE 1. I copy pasted the echo exactly but it doesn't return TRUE 2 A: You're assigning the value of $array[1] to $value, not comparing them. Change the = into == inside the if clauses.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518055", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: @Register directive in ASP.NET 2.0 I use the following directive in my aspx page: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="myWebParts._Default" %> <%@ Register Namespace="myWebParts" TagPrefix="myWebParts_tag" %> And my page has code snippet like this: <ZoneTemplate> <myWebParts_tag:HelloWorldWebPart runat="server" ID="_wp1" /> </ZoneTemplate> But I got the following error: Parser Error Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately. Parser Error Message: Unknown server tag 'myWebParts_tag:HelloWorldWebPart'. What's wrong? Thanks. A: Your register directive is missing either an assembly or a src information. * *If you want to reference a whole namespace of controls in another assembly, add the assembly name with assembly="AssemblyName". *If you want to add a single user control in the current assembly, add the location via src="LocationOfUserControl.ascx. See MSDN for more info on the @Register directive. A: It is solved by adding this: <pages> <controls> <add tagPrefix="myWebParts_tag" namespace="myWebParts" assembly="myWebParts"/> </controls> </pages>
{ "language": "en", "url": "https://stackoverflow.com/questions/7518058", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to perform an upsert in Mongoose looking for an embedded document? SocialProfileSchema = new mongoose.Schema source: type: String enum: ['twitter','facebook'] lowercase: true user_id: String profile_url: String primary: type: Boolean default: true added_on: type: String default: Math.round(new Date().getTime()/1000.0) UserProfileSchema = new mongoose.Schema socialProfiles: [SocialProfileSchema] added_on: type: String default: Math.round(new Date().getTime()/1000.0) That's my Schema. To check for a specific user_id within a SocialProfileSchema and then perform an upsert seems like a gargantuan task. Is it even possible? A: Here's an example of how you can do an update if exists, otherwise insert: Arguments for update are: findQuery, data, queryOptions, onComplete var update = { data: "1", expires: 300 }; that.update({ session_id: sid }, { $set: update }, { upsert: true }, function(err, data) { callback.apply(this, arguments); }); A: How about a dbref? It will let you access the SocialProfiles directly instead of having to loop through a bunch of embedded objects http://mongoosejs.com/docs/populate.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7518059", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Objective-C: autoreleased object as parameter for method could the following code lead to problems? - (void) method1 { NSMutableArray *myArray = [[[NSMutableArray alloc] init] autorelease]; ... fill the array [someObject someMethod:myArray]; // someObject does work on that array (without retain!) } A sometimes-appearing crash in my app looks like it IS a problem; but I would not understand that... shouldn't myArray stay alive at least until the end of method1? Thanks a lot for your help! So my questions besides "can that be a problem" are: - would it be enough to remove autorelease and make a release at the end of the method? - if not: do I have to make a retain/release in "someMethod"? EDIT: but this can be a problem, am I right? - (void) method1 { NSMutableArray *myArray = [self getArray]; ... fill the array [someObject someMethod:myArray]; // someObject does work on that array (without retain!) } - (NSMutableArray) method2 { return [[[NSMutableArray alloc] init] autorelease]; } A: I'm going to assume for a moment that you meant this to be NSMutableArray rather than NSArray. If you really mean NSArray here, then it is all impossible. You can't "fill the array" on an immutable array. Yes, this should work. Your problem is likely elsewhere. A common mistake here would be over-releasing something you put into myArray. A: Looks like you're missing a couple of open brackets on the line where you allocate your array. Should be [[[NSMutableArray alloc] init] autorelease]; A: Your code is completely correct. Do not listen to people telling you to remove the autorelease and manually release the array after the call to someMethod:. In 99% of cases using an autorelease'd object has absolutely no negative performance impact on your application. The only time you want to worry about it is in loops. The [[[Foo alloc] init] autorelease] pattern is just the same as using a built-in helper method like [NSString stringWithFormat:...]. They both return an autoreleased object, but you probably don't worry about performance with the latter. Again, only worry about autorelease in large loops, or when Instruments tells you you have a problem. Using the [[[Foo alloc] init] autorelease] style also keeps all the memory management on a single line. If you get used to typing [[[ you won't forget the release. If you are copying and pasting code, or moving code around, you won't accidentally lose the corresponding release because it's all on the same line. It's also easier to review code that uses the [[[Foo alloc] init] autorelease] style because you don't have to go around hunting for the release further down the method to make sure the memory management is correct. So in terms of readability and safety and correctness, your code is absolutely fine and good. This applies to both your original snippet and the follow up you added below. Performance of autorelease only becomes an issue when you have large loops. Your crashing issue must be caused by some other factor that is not evident in the code you posted. I also suggest you read the Memory Management Programming Guideline if you have not already. Basically, and autorelease'd object is guaranteed to remain valid until the enclosing pool is released. In your case, the autorelease pool exists higher up in the call stack (probably the main runloop) so you can be safe in the knowledge that your autorelease'd array will remain valid for the duration of any calls you make. One last point. Your array allocation code could also make use of the array helper constructor: NSMutableArray *myArray = [NSMutableArray array]; This is even simpler, cleaner and shorter than your original. A: Best thing to do will be something like that: - (void) method1 { NSMutableArray *myArray = [[NSMutableArray alloc] init]; ... fill the array [someObject someMethod:myArray]; // someObject does work on that array (without retain!) [myArray release]; } and it's best from two different angles. One way you are holding your array till you have no need for it, so it will no wipe from memory until you say so. Second is the same sentence, only the reason is that you will clean up memory from no more needed objects as soon as it could be done.The last may need some more explanation... Autoreleased objects should be autoreleased as soon as you have no need for it, but they are released on two basic rules: at the end of block(not always) or at the memory pressure after end of the block(yes always). In other words NSAutoreleasePool doesn't always release stuff at the end of some block of the code, and it's not even close to be rare that it delays those releases to later point.Anyway you should always check for over-releasing your object as it will lead to crash when you'll try to reach such object at your code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518064", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Storing data in matrix in for and if loops I have a problem in storing the data in matrix in for and if loops, The results give me only the last value of the last iteration. I want all the results of all iterations to be stored in a matrix be sequence. Here is a sample of my code: clear all clc %%%%%%%%%%%%%% for M=1:3; for D=1:5; %%%%%%%%%%%%%% if ((M == 1) && (D <= 3)) || ((M == 3) && (2 <= D && D <= 5)) U1=[5 6]; else U1=[0 0]; end % desired output: % U1=[5 6 5 6 5 6 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 5 6 5 6 5 6 5 6] %%%%%%%%%%%%%% if (M == 1) && (D==4) || ((M == 3) && (D == 1)) U2=[8 9]; else U2=[0 0]; end % desired output: % U2=[0 0 0 0 0 0 8 9 0 0 0 0 0 0 0 0 0 0 0 0 8 9 0 0 0 0 0 0 0 0] %%%%%%%%%%%%%% if ((M == 1) && (D == 5)) || ((M == 2) && (1 <= D && D <= 5)) U3=[2 6]; else U3=[0 0]; end % desired output: % U3=[0 0 0 0 0 0 0 0 2 6 2 6 2 6 2 6 2 6 2 6 0 0 0 0 0 0 0 0 0 0] %%%%%%%%%%%%%% end end A: You are overwriting your matrices each time you write UX=[X Y];. If you want to append data, either preallocate your matrices and specify the matrix index each time you assign a new value, or write UX=[UX X Y]; to directly append data at the end of your matrices. clear all clc U1=[]; U2=[]; U3=[]; for M=1:3 for D=1:5 if ((M == 1) && (D <= 3)) || ((M == 3) && (2 <= D && D <= 5)) U1=[U1 5 6]; else U1=[U1 0 0]; end % desired output: % U1=[5 6 5 6 5 6 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 5 6 5 6 5 6 5 6] if (M == 1) && (D==4) || ((M == 3) && (D == 1)) U2=[U2 8 9]; else U2=[U2 0 0]; end % desired output: % U2=[0 0 0 0 0 0 8 9 0 0 0 0 0 0 0 0 0 0 0 0 8 9 0 0 0 0 0 0 0 0] if ((M == 1) && (D == 5)) || ((M == 2) && (1 <= D && D <= 5)) U3=[U3 2 6]; else U3=[U3 0 0]; end % desired output: % U3=[0 0 0 0 0 0 0 0 2 6 2 6 2 6 2 6 2 6 2 6 0 0 0 0 0 0 0 0 0 0] end end A: You can avoid the loops altogether: [M,D] = meshgrid(1:3,1:5); M = M(:)'; D = D(:)'; idx1 = ( M==1 & D<=3 ) | ( M== 3 & 2<=D & D<=5 ); idx2 = ( M==1 & D==4) | ( M==3 & D==1 ); idx3 = ( M==1 & D==5 ) | ( M==2 & 1<=D & D<=5 ); U1 = bsxfun(@times, idx1, [5;6]); U1 = U1(:)'; U2 = bsxfun(@times, idx2, [8;9]); U2 = U2(:)'; U3 = bsxfun(@times, idx3, [2;6]); U3 = U3(:)';
{ "language": "en", "url": "https://stackoverflow.com/questions/7518065", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Python. IOError: [Errno 13] Permission denied: when i'm copying file I have two folders: In, Out - it is not system folder on disk D: - Windows 7. Out contain "myfile.txt" I run the following command in python: >>> shutil.copyfile( r"d:\Out\myfile.txt", r"D:\In" ) Traceback (most recent call last): File "<pyshell#39>", line 1, in <module> shutil.copyfile( r"d:\Out\myfile.txt", r"D:\In" ) File "C:\Python27\lib\shutil.py", line 82, in copyfile with open(dst, 'wb') as fdst: IOError: [Errno 13] Permission denied: 'D:\\In' What's the problem? A: Read the docs: shutil.copyfile(src, dst) Copy the contents (no metadata) of the file named src to a file named dst. dst must be the complete target file name; look at copy() for a copy that accepts a target directory path. A: Use shutil.copy2 instead of shutil.copyfile import shutil shutil.copy2('/src/dir/file.ext','/dst/dir/newname.ext') # file copy to another file shutil.copy2('/src/file.ext', '/dst/dir') # file copy to diff directory A: I solved this problem, you should be the complete target file name for destination destination = pathdirectory + filename.* I use this code fir copy wav file with shutil : # open file with QFileDialog browse_file = QFileDialog.getOpenFileName(None, 'Open file', 'c:', "wav files (*.wav)") # get file name base = os.path.basename(browse_file[0]) os.path.splitext(base) print(os.path.splitext(base)[1]) # make destination path with file name destination= "test/" + os.path.splitext(base)[0] + os.path.splitext(base)[1] shutil.copyfile(browse_file[0], destination) A: use shutil.copy instead of shutil.copyfile example: shutil.copy(PathOf_SourceFileName.extension,TargetFolderPath) A: First of all, make sure that your files aren't locked by Windows, some applications, like MS Office, locks the oppened files. I got erro 13 when i was is trying to rename a long file list in a directory, but Python was trying to rename some folders that was at the same path of my files. So, if you are not using shutil library, check if it is a directory or file! import os path="abc.txt" if os.path.isfile(path): #do yor copy here print("\nIt is a normal file") Or if os.path.isdir(path): print("It is a directory!") else: #do yor copy here print("It is a file!") A: Visual Studio 2019 Solution : Administrator provided full Access to this folder "C:\ProgramData\Docker" it is working. ERROR: File IO error seen copying files to volume: edgehubdev. Errno: 13, Error Permission denied : [Errno 13] Permission denied: 'C:\ProgramData\Docker\volumes\edgehubdev\_data\edge-chain-ca.cert.pem' [ERROR]: Failed to run 'iotedgehubdev start -d "C:\Users\radhe.sah\source\repos\testing\AzureIotEdgeApp1\config\deployment.windows-amd64.json" -v' with error: WARNING! Using --password via the CLI is insecure. Use --password-stdin. ERROR: File IO error seen copying files to volume: edgehubdev. Errno: 13, Error Permission denied : [Errno 13] Permission denied: 'C:\ProgramData\Docker\volumes\edgehubdev\_data\edge-chain-ca.cert.pem' A: use > from shutil import copyfile > > copyfile(src, dst) for src and dst use: srcname = os.path.join(src, name) dstname = os.path.join(dst, name) A: This works for me: import os import shutil import random dir = r'E:/up/2000_img' output_dir = r'E:/train_test_split/out_dir' files = [file for file in os.listdir(dir) if os.path.isfile(os.path.join(dir, file))] if len(files) < 200: # for file in files: # shutil.copyfile(os.path.join(dir, file), dst) pass else: # Amount of random files you'd like to select random_amount = 10 for x in range(random_amount): if len(files) == 0: break else: file = random.choice(files) shutil.copyfile(os.path.join(dir, file), os.path.join(output_dir, file)) A: Make sure you aren't in (locked) any of the the files you're trying to use shutil.copy in. This should assist in solving your problem A: well the questionis old, for new viewer of Python 3.6 use shutil.copyfile( "D:\Out\myfile.txt", "D:\In" ) instead of shutil.copyfile( r"d:\Out\myfile.txt", r"D:\In" ) r argument is passed for reading file not for copying A: I avoid this error by doing this: * *Import lib 'pdb' and insert 'pdb.set_trace()' before 'shutil.copyfile', it would just like this: import pdb ... print(dst) pdb.set_trace() shutil.copyfile(src,dst) *run the python file in a terminal, it will execute to the line 'pdb.set_trace()', and now the 'dst' file will print out. *copy the 'src' file by myself, and substitute and remove the 'dst' file which has been created by the above code. *Then input 'c' and click the 'Enter' key in the terminal to execute the following code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518067", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "48" }
Q: How to make the Windows OSK open when a TextBox gets focus, instead of requiring users to tap a keyboard icon? We are working on a WPF application in .NET 4 that will be used with a touch screen. We are trying to use the built-in Windows OSK for our input, and the last remaining issue is to get the keyboard to open up as soon as a text box gets focus. Currently, if a text box gets focus, a small keyboard icon appears (this is the InputPanel icon) and the user has to tap that icon to make the keyboard open up. Is there a way to skip the icon step, and just have the keyboard open up all the way on focus? Preferably something that can be set or coded in one place and apply to all text boxes globally? It also needs to use the current culture settings of the application thread (which it already appears to be doing). I haven't been able to find anything in the control panel settings that lets you skip the icon step. I also found some examples online of using the TextInputPanel.CurrentInPlaceState, but when I implemented code to open up a TextInputPanel on preview focus of the main window, I kept getting COM INTEROP exceptions and basically hit a dead end (the Microsoft.Ink.dll is an interop DLL). Is it possible that there is a registry key that can change the default CurrentInPlaceState to Expanded instead of HoverTarget? I haven't been able to find one in my net searching. Thanks, Valerie EDIT: Here is some code that I put in the main window's code behind, as well as the exception message I keep getting - and I have no idea what it means or how to fix it (my net searches failed me!) protected override void OnPreviewGotKeyboardFocus(KeyboardFocusChangedEventArgs e) { base.OnPreviewGotKeyboardFocus(e); TextBox textbox = e.NewFocus as TextBox; TextBox oldTextbox = e.OldFocus as TextBox; if (oldTextbox != null && boxesToInputs.ContainsKey(oldTextbox)) { TextInputPanel oldPanel = boxesToInputs[oldTextbox]; oldPanel.Dispose(); boxesToInputs.Remove(oldTextbox); } if (textbox != null) { // Make sure we've cleaned up old panels, just in case if (boxesToInputs.ContainsKey(textbox)) { boxesToInputs[textbox].Dispose(); boxesToInputs.Remove(textbox); } TextInputPanel newPanel = new TextInputPanel(((HwndSource)PresentationSource.FromDependencyObject(textbox)).Handle); newPanel.DefaultInPlaceState = InPlaceState.Expanded; newPanel.DefaultInputArea = PanelInputArea.Keyboard; boxesToInputs[textbox] = newPanel; } } And here is the exception message, which occurs when my code calls the TextInputPanel constructor: Retrieving the COM class factory for component with CLSID {F9B189D7-228B-4F2B-8650-B97F59E02C8C} failed due to the following error: 80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)) I verified that the platform target of the WPF app is x86. I ran Dependency Walker and it said that the Microsoft.Ink.dll I was using was 64 bit, and that two delay-loaded dependencies were missing (GPSVC.dll and IESHIMS.dll). I found a 32 bit version of Microsoft.Ink.dll, but I am still getting the same error, and Dependency Walker is saying the same thing - GPSVC.dll and IESHIMS.dll are missing. I can't target x64, and I'd prefer not to have to put the missing DLLs into my application folder (if that would work?). I hope there is something simple I am missing, because this is a lot of trouble to just get rid of a keyboard hint... Any help is greatly appreciated - I am a bit of a newb when it comes to working with unmanaged/interop assemblies... A: I researched for a similar propose. In my case it was to create a custom OSK. It seems that (by now) it's not possible to create a custom input device. The explanation is in this link: http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/a813a08a-7960-45fe-bc91-e81cdb75bd10 Moreover, I found a "workaround" which uses Win32 API calls to access SendKey method, and report input independently of the target. The project that I found is: http://wosk.codeplex.com/ SendKey is also available on WinForms (see http://msdn.microsoft.com/en-us/library/system.windows.forms.sendkeys.aspx ) but I'm not sure if it will produce the same behavior. I'll checking these options in the following days, but perhaps some of this information might help. Regards Herber
{ "language": "en", "url": "https://stackoverflow.com/questions/7518074", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to force visual studio debugger to skip specific exceptions? I have client-server (Silverlight) app. Some server code throws exceptions that I handle on client. When I debug - Visual Studion breaks on those exceptions and I have to hit "Continue". It really slows down development. Is there any way to skip specific exceptions or deal with this somehow? A: See How to: Correct Run-Time Errors with the Exception Assistant Basically you can disable checkbox "Enable the exception assistant" under the Visual Studio menu: -> Debug -> Options and Settings -> Debugging -> General Also it could be that you've checked specific exception types to be handled so check it under the Visual Studio menu: -> Debug -> Exceptions A: In visual studio, the Debug menu -> Exceptions. You can check and uncheck exceptions. You can have it break on handled thrown ones, or unhandled ones. Also, if your exceptions are custom, they won't appear in there by default (only CLR exceptions are there). You can add them using the same window, be sure to use the fully qualified name for the exception (namespace and all) A: Debug Menu -> Exceptions (Ctrl + Alt + E) -> Find.. type the exception name, then untick the check boxes. If it's your own exception, you can add it by clicking Add, select Common Language Runtime Exceptions and then putting in the fully qualified name of the exception. Then untick the boxes. A: It happened to me once when i was debugging a code and it will show a Continue button and will never go inside the exception. The error that i was having is like i was creating and instances before the InitializeComponent() was called. I think this can help you to find what you are doing before that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518080", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: jQuery .html() of all matched elements .html() function on class selector ($('.class').html()) applies only to the first element that matches it. I'd like to get a value of all elements with class .class. A: You could map the html() of each element in a filtered jQuery selection to an array and then join the result: //Make selection var html = $('.class') //Filter the selection, returning only those whose HTML contains string .filter(function(){ return this.innerHTML.indexOf("String to search for") > -1 }) //Map innerHTML to jQuery object .map(function(){ return this.innerHTML; }) //Convert jQuery object to array .get() //Join strings together on an empty string .join(""); Documentation: * *.filter() *.map() *.get() *.join() A: $('.class').toArray().map((v) => $(v).html()) A: You are selection all elements with class .class but to gather all html content you need to walk trough all of them: var fullHtml; $('.class').each(function() { fullHtml += $(this).html(); }); search items by containig text inside of it: $('.class:contains("My Something to search")').each(function() { // do somethign with that }); Code: http://jsfiddle.net/CC2rL/1/ A: I prefer a one liner: var fullHtml = $( '<div/>' ).append( $('.class').clone() ).html(); A: Samich Answer is correct. Maybe having an array of htmls is better! var fullHtml = []; $('.class').each(function() { fullHtml.push( $(this).html() ); }); A: In case you require the whole elements (with the outer HTML as well), there is another question with relevant answers here : Get selected element's outer HTML A simple solution was provided by @Volomike : var myItems = $('.wrapper .items'); var itemsHtml = ''; // We need to clone first, so that we don’t modify the original item // Thin we wrap the clone, so we can get the element’s outer HTML myItems.each(function() { itemsHtml += $(this).clone().wrap('<p>').parent().html(); }); console.log( 'All items HTML', itemsHtml ); An even simpler solution by @Eric Hu. Note that not all browsers support outerHTML : var myItems = $('.wrapper .items'); var itemsHtml = ''; // vanilla JavaScript to the rescue myItems.each(function() { itemsHtml += this.outerHTML; }); console.log( 'All items HTML', itemsHtml ); I am posting the link to the other answer and what worked for me because when searching I arrived here first. A: If you turn your jQuery object into an Array you can reduce over it. const fullHtml = $('.class') .toArray() .reduce((result, el) => result.concat($(el).html()), '')
{ "language": "en", "url": "https://stackoverflow.com/questions/7518086", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "27" }
Q: Recursive CTE in MySql for tree structure (adjacency list) I'm just starting out with MySQL (I come from using SQL Server previously). I haven't yet started implementing anything in MySQL, just researching how to do things and what problems I might encounter. In SQL Server I've used CTEs to successfully recurse through an adjacency list table structure to produce the desired result set. From what I can tell so far with MySQL, it does not support CTEs. I've got a fairly simple table structure to hold my hierarchy (written in SQL Server syntax b/c of my familiarity with it): CREATE TABLE TreeNodes ( NodeId int IDENTITY(1,1) NOT NULL PRIMARY KEY, ParentNodeId int NULL, Name varchar(50) NOT NULL, FullPathName varchar(MAX) NOT NULL, -- '/' delimited names from root to current node IsLeaf bit NOT NULL -- is this node a leaf? ) Side Note: I realize that FullPathName and IsLeaf are not required and could be determined at query time, but the insert of a tree node will be a very uncommon occurrence as opposed to the queries against this table - which is why I plan to compute those two values as part of the insert SP (will make the queries that need those two values less costly). With CTE (in SQL Server), I would have a function like the following to find leaf nodes of current node: CREATE FUNCTION fn_GetLeafNodesBelowNode ( @TreeNodeId int ) RETURNS TABLE AS RETURN WITH Tree (NodeId, Name, FullPathName, IsLeaf) AS ( SELECT NodeId, Name, FullPathName, IsLeaf FROM TreeNodes WHERE NodeId = @TreeNodeId UNION ALL SELECT c.NodeId, c.Name, c.FullPathName, c.IsLeaf FROM Tree t INNER JOIN TreeNodes c ON t.NodeId = c.ParentNodeId ) SELECT * FROM Tree WHERE IsLeaf = 1 How would I do the same with MySQL? Thanks in advance. A: You can get it done by some sort of stored functions and bit logic. Here is one example. Have a try.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518088", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }