text
stringlengths
8
267k
meta
dict
Q: ID of newly created entity not getting written into view I have an action that basically does this: public ViewResult Save(Foo postedFoo) { Foo foo; if (postedFoo.Id == 0) //New foo; need to save for first time { foo = new Foo(); } else //Already exists, need to load and update { foo = FooRepository.LoadFoo(postedFoo.Id); } UpdateModel(foo); FooRepository.Save(foo); return View(foo); } As you can see, the action handles both creating new Foo instances and updating existing ones. The Foo's Id property is written into a hidden field in the view like this: @Html.HiddenFor(m => m.Id) The problem is that in the scenario where the user saves a new Foo, the Foo's Id property (which is being set in the line FooRepository.Save(foo)) is NOT being written to the hidden field before the page is redisplayed to the user. This means that if the user saves a new Foo, then immediately changes something and saves again, the controller thinks it's another new Foo and creates a new Foo in the database rather than just updating it. Can anyone suggest why the hidden field is not being populated? A: Write ModelState.Remove("Id") Before returning View(); This behavior is caused by the fact that ModelState is the primary supplier for values when rendering (yes, not the Model itself). So removing Id from ModelState, makes editors use Model's value (In your case, updated Id) A: shouldn't the else line read foo = FooRepository.LoadFoo(postedFoo.Id); Also, the new Foo(); isn't setting the value of ID anywhere unless you've hardcoded it into your model. But if FooRepository.Save(foo) is meant to do this, it's not. You need to return the ID field back to your controller. foo = FooRepository.Save(foo);
{ "language": "en", "url": "https://stackoverflow.com/questions/7516322", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What Makes a Binary Stream Special? std::fstream has the option to consider streams as binary, rather than textual. What's the difference? As far as I know, it all depends on how the file is opened in other programs. If I write A to a binary stream, it'll just get converted to 01000001 (65, A's ASCII code) - the exact same representation. That can be read as the letter "A" in text editors, or the binary sequence 01000001 for other programs. Am I missing something, or does it not make any difference whether a stream is considered binary or not? A: In text streams, newline characters may be translated to and from the \n character; with binary streams, this doesn't happen. The reason is that different OS's have different conventions for storing newlines; Unix uses \n, Windows \r\n, and old-school Macs used \r. To a C++ program using text streams, these all appear as \n. A: You got it the other way around, it's text streams that are special, specifically because of the \n translation to either \n or \r\n (or even \r..) depending on your system. A: The practical difference is the treatment of line-ending sequences on Microsoft operating systems. Binary streams return the data in the file precisely as it is stored. Text streams normalize line-ending sequences, replacing them with '\n'. A: If you open it as text then the C or C++ runtime will perform newline conversions depending on the host (Windows or linux). A: On Linux/Unix/Android there is no difference. On a Mac OS/X or later there is no difference, but I think older Macs might change an '\n' to an '\r' on reading, and the reverse on writing (only for a Text stream). On Windows, for a text stream some characters get treated specially. A '\n' character is written as "\r\n", and a "\r\n" pair is read as '\n'. An '\0x1A' character is treated as "end of file" and terminates reading. I think Symbian PalmOS/WebOS behave the same as Windows. A binary stream just writes bytes and won't do any transformation on any platform.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516323", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: IE doesn't receive data via jQuery.post i`ve faced some strange problem. jQuery.post fails silently only in IE, other browsers get information. jQuery.post( 'index.php', { 'option' : 'com_expautos', 'controller': 'admanager', //'dataType' : 'text', 'task' : 'get_'+name, 'id' : parent.val(), }, function(data) { //alert(data); item.html(data); item.attr('disabled', ''); } ); PHP function get_markid() { $id = JRequest::getInt('id', 0); $db = &JFactory::getDBO(); $items = array(); $null_item = JHTML::_('select.option', '', JText::_( 'EXPA_SELECT_MARK' ), 'id', 'name' ); if ( $id ) { $sql = "SELECT id, name FROM #__expautos_mark WHERE catid = '".$id."' AND published = '1' ORDER BY name"; $db->setQuery($sql); $items = $db->loadObjectList(); } array_unshift( $items, $null_item ); echo JHTML::_('select.options', $items, 'id', 'name' ); $mainframe = &JFactory::getApplication(); $mainframe->close(); } jQuery.get fails too. I am in despair :( A: { 'option' : 'com_expautos', 'controller': 'admanager', //'dataType' : 'text', 'task' : 'get_'+name, 'id' : parent.val(), // <-- } IE doesn't like commas at the end of a json. Maybe that's the problem
{ "language": "en", "url": "https://stackoverflow.com/questions/7516325", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is the outcome of: var myvar1 = myvar2 = myvar3? I have seen in some nodejs scripts variables/objects being used like this: var myvar1 = myvar2 = myvar3; Why is this used and what does it mean? A: It will evaluate to: var myvar1 = myvar2 = myvar3; var myvar1 = myvar3; // 'myvar2' has been set to 'myvar3' by now myvar3; // 'myvar1' has been set to 'myvar3' by now It will first assign myvar3 to myvar2 (without var, so possibly implicit global, watch out for that). Then it will assign myvar3's value to myvar1, because the set value is returned. The result is again returned, which won't do anything further - in the final line nothing happens with myvar3's value. So in the end they have all the same value. A: This sets myvar2 to myvar3, and sets myvar1 to myvar2. I assume myvar3 and myvar2 have been declared before this line. If not, myvar2 would be a global (as there's no var), and if myvar3 wasn't defined, this would give an error. This expands to: myvar2 = myvar3; // Notice there's no "var" here var myvar1 = myvar2; A: If: var myvar3 = 5; var myvar1 = myvar2 = myvar3; Then they are all = 5 A: myvar1 and myvar2 both get the name of myvar3. the first expression to evaluate is myvar2 = myvar3. This assigns myvar3 to myvar2. The result of this operation is the assigned value , and this is then assigned to myvar1. A: This will assign the variables myvar1 and myvar2 to the value of myvar3. Why they do this is unknown to me, but my best guess is they want the two vars to be the same value of myvar3. A: as already explained, the statement results in all variables having the value myvar3. I like to add: using statements like that you have to beware of scope, demonstrated by: function foo(){ var c = 1; var a = b = c; console.log(a,b,c); //=> 1 1 1 c = 2; console.log(a,b,c); //=> 1 1 2 } console.log(b); //=> 1! [b] is now a variable in the global scope And of assigning non primitive values (so, references to objects) function foo(){ var c = {}; var a = b = c; c.bar = 2; console.log(a.bar,b.bar,c.bar); //=> 1 1 1 (a, b and c point to the same object) }
{ "language": "en", "url": "https://stackoverflow.com/questions/7516326", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ajax CalendarExtender, How to get the date after i click on a button? I want to add add an Ajax CalendarExtender to my page. And then after selecting a date and clicking on a button I get the selected Day in a label. I have a text box which is the target of the CalendarExtender <asp:TextBox ID="DateText" runat="server" ReadOnly="true" ></asp:TextBox> <ajaxToolkit:CalendarExtender ID="Calendar1" runat="server" TargetControlID="DateText" Format="MMMM d, yyyy" PopupPosition="Right" /> <asp:Button runat="server" ID="Button1" onclick="Button1_Click" /> In the Code Behind: On the first page load I set the date to Today. protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { Calendar1.SelectedDate = DateTime.Today; } } In the Button1_Click Event protected void Button1_Click(object sender, EventArgs e) { Label1.Text = Calendar1.SelectedDate.Value.Day.ToString(); } The problem is when I click the button (or after any post backs) the value selected get reset to Today's date. And if I don't set it to DateTime.Today in the Page_Load It get reset to null and throw a null exception. How can I solve this? Thank you very much for any help. I hope i was clear A: Maybe this will work: protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { if(!Calendar1.SelectedDate) Calendar1.SelectedDate = DateTime.Today; } } A: The solution to the issue is making use of Request.Form collections. As this collection has values of all fields that are posted back to the server and also it has the values that are set using client side scripts like JavaScript. Thus we need to do a small change in the way we are fetching the value server side. C# protected void Submit(object sender, EventArgs e) { string date = Request.Form[txtDate.UniqueID]; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7516328", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: JSF: NUMBER_OF_VIEWS_IN_SESSION and the back button I've got a memory problem in my application because of AJAX4JSF high memory consumption. So we have decided to set the NUMBER_OF_VIEWS_IN_SESSION to 1 and compromise the back button functionality. However, after adding the following to the web.xml file, the back button still works. <context-param> <param-name>org.apache.myfaces.NUMBER_OF_VIEWS_IN_SESSION</param-name> <param-value>1</param-value> </context-param> I would like to understand: How the back button still works?!! I've read that setting the NUMBER_OF_VIEWS_IN_SESSION to 1 looses the browser back button functionality. Thanks in advance for your help. A: I've read that setting the NUMBER_OF_VIEWS_IN_SESSION to 1 loses the browser back button functionality. Either that article you're reading is babbling nonsense or you've misinterpreted the article. The back button's functionality can in no way be controlled from the server side on. Perhaps the article meant the fact that you cannot submit the page which is been served from the browser cache by back button anymore because this would result in a ViewExpiredException. You'd need to create a Filter which adds response header to instruct the browser to not cache the page so that pressing the back button would fire a brand new GET request on the page so that you won't get a ViewExpiredException anymore when submitting a form on that page. As to the high memory consumption, I suspect that your problem is caused by something else. Perhaps you're just cobbling too many data in a view or session scoped bean. Read this thoroughly: Why JSF saves the state of UI components on server? Last, but not least, run a profiler before making assumptions.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516329", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Strings with formatting in SQL to Silverlight App need help I am moving all strings in my Silverlight app to the db, but am having some trouble keeping the formatting. Really the only issue is for paragraph sized strings, which in the app used to keep the paragraph sized right and spacing between paragraphs. Unfortunately now that I need to bind the textblock I have to use it's text property instead of just sandwiching the text between the opening and closing tags to let the formatting do its thing. The result is that the formatting is displayed as part of the text now and isn't applied. Does anyone know how to get around this? I've tried adding Char(13), \n, different configurations of ' ', it all displays exactly how I enter it. Any ideas? A: You need to use a rich text box control. Here are some options for Silverlight: What is the best substitute for FlowDocument in Silverlight? A: Silverlight uses \r for line breaks and in SQL Server line breaks are \r\n. There is a nice value converter in this post that converts between the two.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516336", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PowerShell - List all SQL instances on my system? Is there a Powershell command to list all SQL instances on my system? (MS SQL 2008) A: Import powershell sql server extensions: Import-Module SqlServer Then do these commands Set-Location SQLSERVER:\SQL\localhost Get-ChildItem A: I found that (for me at least) none of the above returned my SQL Express instance. I have 5 named instances, 4 full-fat SQL Server, 1 SQL Express. The 4 full-fat are included in the answers above, the SQL Express isn't. SO, I did a little digging around the internet and came across this article by James Kehr, which lists information about all SQL Server instances on a machine. I used this code as a basis for writing the function below. # get all sql instances, defaults to local machine, '.' Function Get-SqlInstances { Param($ServerName = '.') $localInstances = @() [array]$captions = gwmi win32_service -computerName $ServerName | ?{$_.Name -match "mssql*" -and $_.PathName -match "sqlservr.exe"} | %{$_.Caption} foreach ($caption in $captions) { if ($caption -eq "MSSQLSERVER") { $localInstances += "MSSQLSERVER" } else { $temp = $caption | %{$_.split(" ")[-1]} | %{$_.trimStart("(")} | %{$_.trimEnd(")")} $localInstances += "$ServerName\$temp" } } $localInstances } A: [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SqlWmiManagement") | out-null $mach = '.' $m = New-Object ('Microsoft.SqlServer.Management.Smo.Wmi.ManagedComputer') $mach $m.ServerInstances A: Just another way of doing it...can be a little quicker than SQLPS to get a quick answer. (get-itemproperty 'HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server').InstalledInstances A: $a = "MyComputerName" [System.Data.Sql.SqlDataSourceEnumerator]::Instance.GetDataSources() | ? { $_.servername -eq $a} Aaron method return a more sure response. Read Here about Instance.GetDataSources() A: The System.Data.Sql namespace contains classes that support SQL Server-specific functionality. By using the System.Data.Sql namespace you can get all MSSQL instances on a machine using this command in windows power shell: [System.Data.Sql.SqlDataSourceEnumerator]::Instance.GetDataSources() A: This function it gonna return all the installed instances with the version details in a object list: function ListSQLInstances { $listinstances = New-Object System.Collections.ArrayList $installedInstances = (get-itemproperty 'HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server').InstalledInstances foreach ($i in $installedInstances) { $instancefullname = (Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL').$i $productversion = (Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server\$instancefullname\Setup").Version $majorversion = switch -Regex ($productversion) { '8' { 'SQL2000' } '9' { 'SQL2005' } '10.0' { 'SQL2008' } '10.5' { 'SQL2008 R2' } '11' { 'SQL2012' } '12' { 'SQL2014' } '13' { 'SQL2016' } '14' { 'SQL2017' } '15' { 'SQL2019' } default { "Unknown" } } $instance = [PSCustomObject]@{ Instance = $i InstanceNameFullName = $instancefullname; Edition = (Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server\$instancefullname\Setup").Edition; ProductVersion = $productversion; MajorVersion = $majorversion; } $listinstances.Add($instance) } Return $listinstances } $instances = ListSQLInstances foreach ($instance in $instances) { Write-Host $instance.Instance }
{ "language": "en", "url": "https://stackoverflow.com/questions/7516337", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: Using nHibernate in a windows service I want to use nHibernate in a windows service. If the systems boots, it might start my service before the database. In that case, configuration of nHibernate fails and the service crashes. So now I'm wondering how I can check if the database service has already been started. In case it has not yet started, my service should wait a bit and try again later. A: If your service always runs on the same machine as SQL Server, You should be using ServiceInstaller.ServicesDependedOn to tell Windows(SCM) that you depend on 'MSSQLSERVER' (the name of service that runs SQL Server). From MSDN: A service can require other services to be running before it can start. The information from this property is written to a key in the registry. When the user (or the system, in the case of automatic startup) tries to run the service, the Service Control Manager (SCM) verifies that each of the services in the array has already been started. ServiceInstaller is the class that is used by InstallUtil when it installs your service. Other installation packages including InstallShield also support this windows functionality. Equivalent SC command. So your service will only start after SQL Server is already running. But even in this case, it might still be a good idea to offload all potentially long running startup procedures to the background thread. Do as little as possible in OnStart method. Ideally you would just spawn a new initialization thread that would take care of NHibernate session factory initialization. If for some reasons you still want to do this in OnStart, then you should consider retrying NHibernate initialization and calling ServiceBase.RequestAdditionalTime to avoid: Error 1053: The service did not respond to the start or control request in a timely fashion. Ideally your service should not depend on the database availability because it might be running on a remote machine. The service is an 'always on' process that should tolerate intermittent database connectivity issues. A: No clue if there are better ways, but in your service startup, check for the system uptime. If this is less then let's say 5 minutes, wait for (5 minutes - Uptime) and after that start the rest of the service as you normally would. See the following for Calculating server uptime gives "The network path was not found" This is not a solution however for when your service tries to connect to a SQL which is down, however if this happens you want to handle the exception and actually be notified that the SQL is down. Very unlikely you want the service to keep trying without you yourself beeing aware the SQL is down. A: You could use ServiceController class and call its static method GetServices() to get the list of services. It will give an array of services, find the right one and check its status. See ServiceController on MSDN A: Currently I am making sure I can establish a connection to the database needed and running a default query (configurable). If this is successful I proceed to start the service. What I've found in some cases is that even if the MSSQL service is started it doesn't guarantee that you can connect to it and execute queries against it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516344", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Incrementing a foreach loop and only showing one child I'm creating a custom Google map that plots multiple markers. View the link as it will make it easier to explain what is happening and what I want If you click on each marker it shows company names that are grabbed from the child pages. At the moment it's showing ALL the company names on each marker. How can I show just one company name per marker? i.e So one say "MediWales" and the other says "Teamworks Design & Marketing", and so on when I add more companies. Here's the code controlling the little popup: <?php $pages = get_pages(array('child_of' => 1873, 'sort_column' => 'menu_order')); $counter = 1; foreach($pages as $post) { setup_postdata($post); $fields = get_fields(); ?> <p><?php $counter++; echo $fields->company_name;?></p> <?php } wp_reset_query(); ?> Once it's looped through once, the next time it loops through I need it to start on the next child and not show the first one. UPDATE: It seems like it's very close, it's showing one company but the same one on both markers. <?php $counter = 1; $pages = get_pages(array('child_of' => 1873, 'sort_column' => 'menu_order', 'offset' => $counter, 'number' => 1)); foreach($pages as $post) { setup_postdata($post); $fields = get_fields(); ?> <p><?php echo $fields->company_name; echo $counter; ?></p> <?php $counter++; } wp_reset_query(); ?> A: Your issue is the fact that PHP is by nature preprocessed. JavaScript doesn't run that PHP everytime you click that marker. Your best bet is to output a JSON object from PHP containing all the markers and their attributes, then parse it dynamically with JavaScript.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516350", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do we clear grid parameters in jqgrid? If I set the jqgrid parameters and then I again want to reset the parameters with new ones, without the old parameters being appended, how do I achieve that? Lets say,for example: Step 1: jQuery("#list").setGridParam({url:"testJsp.jsp", mtype: "POST", postData:{xyz: '23fd', asd: 'were' } }); Step2: jQuery("#list").setGridParam({url:"testJsp.jsp", mtype: "POST", postData:{ert: 'trer', ghj: 'rew' } }); Now when I do this, by the end of "Step 2" I have a total of 4 parameters, including the parameters from "Step 1". But I don't want this. After "Step 2" I just want to have the parameters of "Step 2". Is there a way to clear the grid parameters between "Step 1" and "Step 2"? A: Set postData to null before setting the new value. You don't have to redefine values for url and mtype if they're not changing. jQuery("#list").setGridParam({postData: null}); jQuery("#list").setGridParam({postData: {ert: 'trer', ghj: 'rew' } }); A: The expression jQuery("#list").jqGrid('getGridParam', 'postData') get you the reference to object which represent the postData. So you can work with it like with an object and add or delete properties whenever you need or not more need these: var myGrid = jQuery("#list"), myPostData = myGrid.jqGrid('getGridParam', 'postData'); // next two lines are equivalent to // myGrid.jqGrid('setGridParam', 'postData', {xyz: '23fd', asd: 'were' }); myPostData.xyz = '23fd'; myPostData.asd = 'were'; ... delete myPostData.xyz; delete myPostData.asd; ... // next two lines are equivalent to // myGrid.jqGrid('setGridParam', 'postData', {ert: 'trer', ghj: 'rew' }); myPostData.ert = 'trer'; myPostData.ghj = 'rew'; ... A: You can use the GridUnload Method to clear the grid
{ "language": "en", "url": "https://stackoverflow.com/questions/7516354", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is there any webservice or Jquery plugin to get longitude and latitude Am trying to integrate goople map api with a jquery plugin- gMap. It looks good and simple. It needs latitude and longitude to produce dynamic maps. So am looking for any plugin or webservice which can give me the lat and long if i pass the address , city , country. Any info is invited! Is there any jquery map plugin which can generate map by just giving address? $("#locmap").live("click", function(){ $('#map5').gMap( { markers: [{ address: 'address', html: "location name", popup: true }], zoom:6 }); }); A: gMap can use an address instead of lat/long. Just use $('#map').gMap({address: 'address, city, country'}, zoom:10}) A: You can find some info here: http://www.jquery4u.com/api-calls/geo-location-2-lines-javascript/ A: this gives a map by passing only the address in: http://maps.google.co.uk/maps?q=yemen+road,+yemen&hl=en
{ "language": "en", "url": "https://stackoverflow.com/questions/7516361", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Regular expression which accepts multiple email addresses seperated by comma in java In my project I give email address to send the mail in a text box. I can give either a single email address or a multiple email address separated by commas. Is there any regular expression for this situation. I used the following code and its check for single email address only. public static boolean isEmailValid(String email){ boolean isValid = false; String expression = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$"; CharSequence inputStr = email; Pattern pattern = Pattern.compile(expression,Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(inputStr); if(matcher.matches()){ isValid = true; } return isValid; } A: * *Split the input by a delimiter in your case ','. *Check each email if its a valid format. *Show appropriate message (email 1 is valid , email 2 is not valid , email 3 is not valid etc etc) A: You can split your email-var on a ",", and check for each emailaddress you got :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7516362", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android crashes because of SharedPreferences I'm a beginner in Android, but I've done all the research I could on this problem and I just can't seem to find a way to solve it... The app worked fine until I decided to add the SharedPreferences in order to update some high scores. Now I can't seem to make it work, it always crashes at the very start (after the splash screen) In the on Create method, below the setContentView I have the following lines: highScores = getSharedPreferences("HighScores", 0); hs1 = highScores.getInt("HighScore1", 0); shs1 = highScores.getString("sHighScore1", "User1"); and a couple more, but mostle they are alternate takes on lines 2 and 3 in the prior code. I have declared the highScores as SharedPreferences in the body of the class. The only place in this class where I use the info gathered from the SharedPreferences is in editing a TextView, which uses the following code: High1.setText(String.format("1. %04d - %s", hs1, shs1)); My guess is that I made an error somewhere in the code, but am unable to find it... Just for additional info, I only use the SharedPreferences in one other class (which should update the high scores at the end of games) and uses a simillar code: highScores = getSharedPreferences("HighScores", 0); hs1 = highScores.getInt("HighScore1", 0); shs1 = highScores.getString("sHighScore1", "User1"); The code above was for getting previous high scores, while the code below is used for updating: prefEditor.putInt("HighScore1", hs1); prefEditor.putString("sHighScore1", shs1); prefEditor.commit(); I have declared the SharedPrefs editor as: SharedPreferences.Editor prefEditor = highScores.edit(); I would really appreciate any help, as I can't seem to find what I've done wrong, probably it's a small error somewhere, but it's really driving me nuts :P I would give you more of the code, but I can't see any purpose in that, because it doesn't use the SharedPreferences and I'm pretty sure they're the cause of the issue... Thank you in advance for your help :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7516365", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can show some item in my list when bind my list to a grid? I have a list that bound to a grid. My list items have properties like RunTimeState. The user can select each item in the grid and delete it. When an item is deleted its RunTimeState is set to Deleted. How can I get my grid to not show these deleted items? A: Whenever your item is deleted, you should raise INotifyPropertyChanged.PropertyChanged event with property name set to grid data source. And that property should filter the items or the item should be removed from your collection before. A code can look like this: var myDataSource = ...; public void DeleteItem(Item item) { item.RunTimeState = RunTimeState.Deleted; // you can remove the item from the myDataSource here or filter it later PropertyChanged(this, new PropertyChangedEventArgs("DataSource")); } public IList<Item> DataSource { get { return myDataSource; } // or get { return myDataSource.Where(i => i.RunTimeState != RunTimeState.Deleted).ToList(); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7516370", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Traversing key/values of an NSDictionary, is enumerateKeysAndObjectsUsingBlock more efficient than looping keys and calling objectForkey:? I need to traverse all key/values pairs of a dictionary and do something with both fields. I am wondering what is more efficient, the traditional 'foreach key' approach or the blocks approach using enumerateKeysAndObjectsUsingBlock:. Here you have an example: Traditional approach (before blocks) for (NSString* key in [self.dictionary allKeys] ) { [self processKey:key value: [self.dictionary objectForKey:value ]]; } Blocks approach. [self.dictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop){ [self processKey:key value:obj]; }]; My gut feeling is that traversing the key/value pairs using the block is faster, but I am not sure since I don't know how dictionaries and the particular block method is implemented. Any thoughts? Thanks in advance! A: They would be basically the same -- they are both synchronous traversals. However, the following would allow for concurrent traversal, which would be faster: [self.dictionary enumerateKeysAndObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(id key, id object, BOOL *stop) { }]; A: You should use the block based method. This is faster, as shown here. In particular, it does not require an extra lookup in the dictionary to grab the value, which saves performance. However, performance gains will be negligible unless operating on reasonably-large dictionaries.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516371", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: Using jQuery to send data from a multipart/form-data through ajax I've been working on this all day now, and I just can't get it working. I have basically got a simple ajax request using the jQuery library and I want to send the data which I post through a mutlipart/form-data file input, however, I have tried everything I can think of. My File upload script is in place awaiting the file name as a parameter (tried without also), but it just doesn't want to get the data from the file input box itself. Could someone please enlighten me on how to do this without another plugin (multiple upload, etc). Here is my jQuery Code for this bit: function uploadTimesheets(){ $('#waiting').show(); var error = ''; var msg = ''; //Performs the Ajax Request var data = $.ajax({ type : 'POST', url : '/ajax/timesheet/uploadNewTimesheets.php', dataType : 'json', contentType : 'multipart/form-data', data : data, error : error, msg : msg, success : function(data){ if(!data){ $('#notification').removeClass(this).addClass('notification-success').html(data).show().delay(1200).fadeOut(800); getActiveTimesheets(getSelectedPage()); }else{ $('#notification').removeClass().addClass('notification-error').html(data.msg + data.errorList).show(); alert('PHHAIL'); } $('#waiting').hide(); function(xhr, status, errorThrown){ $('#waiting').hide(); } } }); } And here is my PHP upload script: /** * Creates a directory in the active directory with the given folder name * * @author RichardC * @param string $dirName * @return boolean */ public function createDir( $dirName ) { $docRoot = getenv('DOCUMENT_ROOT'); if (!is_dir(sprintf('%s/%s', $docRoot, $dirName))) { $makeDir = mkdir(sprintf('%s/%s', $docRoot, $dirName)); echo sprintf('Creating a folder called \'/%s/\' ...', $dirName); if ($makeDir) { echo '<br />Successfully created the folder.<br />'; return true; } else { echo sprintf('<br /> Sorry, please create the folder manually at: %s/%s', $docRoot, $dirName); return false; } } } /** * Uploads either a CSV or an EXCEL file to a temporary directory * * @author RichardC * @param Resource $file * @return Boolean true/false */ public function upload( $filename ) { $filename = (!isset($filename)) ? $this->file : $filename; //Get the document root $docRoot = getenv('DOCUMENT_ROOT'); $this->createDir('uploads'); if (($_FILES['file']['type'] == 'application/vnd.ms-excel') || ($_FILES['file']['type'] == 'application/csv') || ($_FILES['file']['type'] == 'text/csv') || ($_FILES['file']['type'] == 'text/comma-separated-values') || ($_FILES['file']['type'] == 'application/excel') && ($_FILES["file"]["size"] < 1000000)) { if ($_FILES["file"]["error"] > 0) { echo "Return Code: " . $_FILES["file"]["error"] . "<br />"; } else { if (file_exists($docRoot . "upload/" . $_FILES["file"]["name"])) { echo $_FILES["file"]["name"] . " already exists. "; $this->file = $docRoot . '/upload/' . $_FILES["file"]["name"]; } else { move_uploaded_file($_FILES["file"]["tmp_name"], $docRoot . "/upload/" . $_FILES["file"]["name"]); $this->file = $docRoot . '/upload/' . $_FILES["file"]["name"]; } } } else { echo "Invalid file"; return false; } //Remove the unwanted file now $this->fileContents = file_get_contents($this->file); @unlink($this->file); unset($this->file); return true; } If anyone can help on this, it'd be much appreciated! A: In order to make your multipart/formdata work, you must add some extra stuff in your ajax-request: cache: false, contentType: false, processData: false, You can easily create your data-field by doing this: var uploadData = $("#uploadFile").prop("files")[0]; var newData = new FormData(); $.each($('#uploadFile').prop("files"), function(i, file) { newData.append('file-'+i, file); }); in your ajax-request you'll have to set this: data: newData
{ "language": "en", "url": "https://stackoverflow.com/questions/7516381", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: iOS remove all Activity Indicators i have a Problem with my Activity Indicators. I have an Button which reload a Website and Display between a Activity Indicator. The Problem is if the User hits more than 1 Times on the Button it will rebuild a new Indicator and this Indicator freezes on the Screen all the Time. Button disabling is not working. Has anyone a Solution for this Problem. Please help. Here is my Code: -(IBAction) buttonReload { Reachability *r = [Reachability reachabilityWithHostName:@"www.google.com"]; NetworkStatus internetStatus = [r currentReachabilityStatus]; if ((internetStatus != ReachableViaWiFi) && (internetStatus != ReachableViaWWAN)){ UIAlertView *myAlert = [[UIAlertView alloc] initWithTitle:@"No Inet!" message:@"You need a Inet Connection..." delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil]; [myAlert show]; [myAlert release]; } else { //Website loading [self performSelector: @selector(doLoadWebsite) withObject: nil afterDelay: 0]; return; } } - (void) doLoadWebsite { //add activity indicator NewsActivity = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(140.0f, 180.0f, 40.0f, 40.0f)]; [NewsActivity setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleGray]; [self.view addSubview: NewsActivity]; [NewsActivity startAnimating]; [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(finishActivity) userInfo:nil repeats:YES]; //NewsActivity.backgroundColor = [UIColor grayColor]; NewsActivity.hidesWhenStopped = YES; // Show Status Bar network indicator [UIApplication sharedApplication].networkActivityIndicatorVisible = YES; //perform time-consuming tasks //load News Website [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.google.com"]]]; } -(void) finishActivity { if (!webView.loading) { [self.NewsActivity removeFromSuperview]; [NewsActivity stopAnimating]; //Hide network activity indicator [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; } else { [NewsActivity startAnimating]; [UIApplication sharedApplication].networkActivityIndicatorVisible = YES; } } A: You should perform stopAnimating , removeFromSuperView once the page is loaded. If the user refreshes the page again, you can again add it to the subView and startAnimating.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516382", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to manipulate user selected text using webdriver? Lets say i have the following snippet in my web page: <p> This is some text </p> I want WebDriver to select "some" in this text, as if the user selected it. How should i do this? I know how to get the <p>-element: WebElement editable = getDriver().findElement(By.id("someId")); editable = editable.findElement(By.tagName("p")); System.out.println(p.getText()); The println prints "This is some text". I tried sending keys to the element, and that used to work(in selenium 2.0b), but i'm using selenium 2.6.0 now, and it stopped working: editable.sendKeys(Keys.chord(Keys.SHIFT, Keys.LEFT)); Does anyone have ideas? I'm using the FirefoxDriver. A: I did this once for Firefox using Javascript. Basically I used the range object in Firefox to select the text. Change the start and end range index based on what you want to select. This would not work in IE, because selecting range is conceptually different in IE. I don't have the IE code handy but since you are concerned about FF, you could give this a shot. Let me know if you interested in IE text range. String script = "var range = document.createRange();" + "var start = document.getElementById('idofthedivthatcontainstext');" + "var textNode = start.getElementsByTagName('p')[0].firstChild;" + "range.setStart(textNode, 8);" + "range.setEnd(textNode, 13);" + "window.getSelection().addRange(range);"; ((JavascriptExecutor)driver).executeScript(script); A: You are trying to select the contents of the p tag by drag select right I am not sure if that is objectively possible to be done by the user as your are suggesting.. Selenium now tries to mock the exact action that a user can perform on a browser. thus you just cant send a shift and left select key on the p tag and expect it to select unlike a textbox where it is very much possible but you might probably have to click on the text box first to get it into focus. Here is what I would suggest to achieve this, not sure if it will work. a) send the left click on the p tag b) hold the shift key c) drag the mouse to the end of the p tag. Hope that helps. A: Use the .Text property of the IWebElement WebElement editable = getDriver().findElement(By.id("someId")); editable = editable.findElement(By.tagName("p").Text).ToString(); editable.Replace("This is ", "").Replace(" text."); System.out.println(p.getText());
{ "language": "en", "url": "https://stackoverflow.com/questions/7516383", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Confusion about data alignment suppose a struct defined like this: struct S{ char a[3]; char b[3]; char c[3]; }; then what will be the output of printf("%d", sizeof(S)) ? On My compiler of Vc++ 2008 expression, the output is 9. And I got confused... I suppose the result be 12, but it is not. Shouldn't the compiler align the structure to 4 or 8 ? A: The value of the sizeof-expression is implementation-dependent; the only thing guaranteed by the C++ standard is that it must be at least nine since you're storing nine char's in the struct. The new C++11 standard has an alignas keyword, but this may not be implemented in VC++08. Check your compiler's manual (see e.g. __declspec(align(#))). A: There's nothing in S that would force any of its members to be aligned other than per-byte so the compiler doesn't need to add any padding at all. A: The typical requirement that each member be aligned only requires that the structure itself be aligned to the largest member type. Since all member types are char, the alignment is 1, so there's no need for padding. (For arrays, the base type (all extents removed) is what counts.) Think about making an array of your structure: You'll want all the members of all the elements of that array to be aligned. But in your case that's just one large array of chars, so there's no need for padding. As an example, suppose that on your platform sizeof(short) == 2 and that alignment equals size, and consider struct X { char a; short b; char c; };. Then there's one byte internal padding between a and b to align b correctly, but also one byte terminal padding after c so that the entire struct has a size that's a multiple of 2, the largest member size. That way, when you have an array X arr[10], all the elements of arr will be properly aligned individually. A: First, the alignment is implementation dependent, so it will depend on the compiler. Now, remember that for a statically allocated array, the size need not be stored (the standard does not require it is), therefore it is usual for the alignment of an array to be the alignment of its elements. Here, char[3] thus has an alignment of 1, and they are perfectly packed. A: There is a compiler switch, /Zp, that allows you to set the default struct member alignment. There are also some other methods for specifying alignment in the c language. Check out this MSDN post for details: http://msdn.microsoft.com/en-us/library/xh3e3fd0(v=vs.80).aspx Maybe your compiler is using one of these settings? A: The compiler is given fairly wide latitude about how its aligns data. As a practical matter, however, the alignment of a datum will not exceed its size. That is, chars must be byte-aligned, while ints and longs are often four-byte aligned. Additionally, structs are aligned to the strictest alignment requirement of their members. So, in your example, the strictest internal alignment requirement is 1-byte aligned, so the struct is 1-byte aligned. This means that it requires no padding.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516390", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Matlab: add vector to matrix I have a 3XN matrix representing a list of 3D coordinates,something like 33 33 33 33 34 34 34 34 34 35 35 17 18 19 20 16 17 18 19 20 16 17 10 10 10 10 10 10 10 10 10 10 10 I want to shift all coordinates by some vector v=[1 2 3], that is add the 3D vector to each column of the matrix. I know how to do that with a for loop, but how can I do it without a loop? Surely there's a way... A: you mean like this? D=[33 33 33 33 34 34 34 34 34 35 35; 17 18 19 20 16 17 18 19 20 16 17; 10 10 10 10 10 10 10 10 10 10 10 ]; A=[1 2 3]'; C= bsxfun(@plus, D, A) C = 34 34 34 34 35 35 35 35 35 36 36 19 20 21 22 18 19 20 21 22 18 19 13 13 13 13 13 13 13 13 13 13 13 A: Use repmat: M = randn(3, N); % your 3 x N matrix v = randn(3, 1); % your vector r = M + repmat(v, [1 N]); % add v to every column of M
{ "language": "en", "url": "https://stackoverflow.com/questions/7516402", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: jQuery: animate text color i wanna dynamically change the link color within a hover event. I got the following code so far but it doesn´t work. Any suggestions why? In my oppinion it seems to be right... $('.fadelink').hover(function(){ $(this).animate({ color: '#333' }, 600); }, function(){ $(this).animate({ color: '#999' }, 600); }); A: You have to add colors plugin to make it work. That is stripped from core. A: jQuery doesn't support animation of colors, but it can with the color plugin: http://plugins.jquery.com/project/color However, there's another route you could take, with CSS3, if you don't mind it not working in some older browsers: .baseClass { color:#999; -webkit-transition-property:color; -webkit-transition-duration: 1s, 1s; -webkit-transition-timing-function: linear, ease-in; } .baseClass:hover { color: #333; } A: See the answer to this question: jQuery: animate text color for input field? You cannot animate css text color with jQuery. A: You have to use jQuery color plugin to make color animation work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516407", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: How to get XElement value with spaces? I have following XElement: <title> <bold>Foo</bold> <italic>Bar</italic> </title> When I get Value property it returns FooBar without space. How to fix it? A: By definition, the Value of the <title> element is the concatenation of all text in this element. By default whitespace between elements and their contents is ignored, so it gives "FooBar". You can specify that you want to preserve whitespace: var element = XElement.Parse(xml, LoadOptions.PreserveWhitespace); However it will preserve all whitespace, including the line feeds and indentation. In your XML, there is a line feed and two spaces between "Foo" and "Bar"; how is it supposed to guess that you only want to keep one space? A: From the documentation for the Value property of the XElement class: Gets or sets the concatenated text contents of this element. Given your example, this behavior is expected. If you want spaces, you will have to provide the logic to do it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516410", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: javascript time ticker I want to build a simple time ticker. Basically I will have a global javascript variable injected from the server side that will represent in my business model a active task start time for an agent. I want to show in a tag the digital time format between that global that date and now, but the issue I have is with the milliseconds from the difference between those 2 dates. I have created a JSFiddle but the difference between new Date() and that specific date is not showing properly. enter code herehttp://jsfiddle.net/alexpeta/ZmzDh/3/ Can you guys spot the bug or the issue? A: Example Replace: var t = setInterval('tick()',1000); with: var t = setInterval(tick,1000); It's always a good idea to use function reference and not a string in setInterval A: d.toLocaleString() might have a word with you ;) tip: no, you are not measuring time since September 22, you are measuring time to October 22. http://jsfiddle.net/LDKh7/ A: <script language="JavaScript"> TargetDate = "12/31/2020 5:00 AM"; BackColor = "palegreen"; ForeColor = "navy"; CountActive = true; CountStepper = -1; LeadingZero = true; DisplayFormat = "%%D%% Days, %%H%% Hours, %%M%% Minutes, %%S%% Seconds."; FinishMessage = "It is finally here!"; </script> <script language="JavaScript" src="http://scripts.hashemian.com/js/countdown.js"></script>
{ "language": "en", "url": "https://stackoverflow.com/questions/7516414", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Window on top of other window I have two NSWindows ( independent windows,No Parent and Child relationship), One Window should always be on top of the other Window.When I minimize and again maximize the mainWindow,second window should be on top of it. I used the makeKeyAndOrderFront to keep the window on top of the mainWindow [[self window] makeKeyAndOrderFront:self]; How can I achieve the above functionality. A: Found a similar question posted earlier: NSWindow - show new window that will always stay on top of current window Hope this helps :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7516440", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Visual Studio MVC Oddity? I've been stuck on the same DropDownList problem for days now while working on a MVC project in VS2010. The problem has become even more frustrating right now because when I copy all relevant code into a completely new, blank project, the second instance actually runs perfectly and produces exactly the result I expect... Controller: <HandleError()> _ Public Class HomeController Inherits System.Web.Mvc.Controller Function Index() As ActionResult ViewData("Message") = "Welcome to ASP.NET MVC!" Return View() End Function Function About() As ActionResult Dim configList As List(Of String) = New List(Of String) configList.Add("10GBaseLX4") configList.Add("10GFC") configList.Add("10GigE") configList.Add("100BaseFX") configList.Add("Test") ViewData("cprotocols") = New SelectList(configList) Return View() End Function End Class View: <%@ Page Language="VB" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %> <asp:Content ID="aboutTitle" ContentPlaceHolderID="TitleContent" runat="server"> About Us </asp:Content> <asp:Content ID="aboutContent" ContentPlaceHolderID="MainContent" runat="server"> <h2>About</h2> <p> <% Using Html.BeginForm()%> <%= Html.DropDownList("cprotocols") %> <% End Using %> </p> </asp:Content> The page doesn't do anything right now other than simply display a dropdownlist with the options shown hard-coded in the controller, but I'm not even going to bother with writing logic when my current site refuses to even show the list to the user. The error message is There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'cprotocols'. but once again, there are no runtime errors when i copy this bit of code over to a blanked solution. Any ideas how to solve this or even any clues on what is causing such an inconsistency? I don't want to copy over all the other files from my current project into the new one just to have the problem manifest itself again somewhere down the line (which is bound to happen when the code is only half broken...) A: I would try changing the ViewData key name and see if that helps anywhere. If not, if you can you could create a new project and copy all your existing model/controller/view classes over the other project, this seems like something in your project configuration that could have gone off. Hope this helps a little :) A: Turns out it was a problem with the module; the code itself is fine. I had to delete Temporary ASP.NET files, clean up my GAC, as well as nuke all current assembly references in my project, clean solution, re-add required references, and finally clean and rebuild. I'm still not clear on why exactly VS2010 was referring to assemblies from an old build (simply cleaning and rebuilding is not enough). I also don't know at what point the environment stops "refreshing" and decides to simply refer to obsolete builds. I'll try to do a bit more research on this point and then add on to this post.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516451", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: sed Extract version number from string (only version, without other numbers) I want to achieve the same as explained in sed: Extract version number from string, but taking into consideration only the first sequence of numbers or even safer, tell sed to keep only the sequence of numbers following the name of the command, leaving out the rest. I have: Chromium 12.0.742.112 Ubuntu 11.04 I want: 12.0.742.112 Instead of: 12.0.742.11211.04 I now know that using head or tail with sort it is possible to display the largest/smallest number, but how can I tell sed to consider the first sequence only? EDIT: I forgot to mention that I'm using bash. A: Here's a solution that doesn't rely on the position of the command in your string, but that will pick up whatever comes after it: command="Chromium" string1="Chromium 12.0.742.112 Ubuntu 11.04" string2="Ubuntu 11.04 Chromium 12.0.742.112" echo ${string1} | sed "s/.*${command} \([^ ]*\).*$/\1/" echo ${string2} | sed "s/.*${command} \([^ ]*\).*$/\1/" A: The first number? How about: sed 's/[^0-9.]*\([0-9.]*\).*/\1/' A: With cut (assuming you always want the second bit of info on the line): $ echo "Chromium 12.0.742.112 Ubuntu 11.04" | cut -d' ' -f2 12.0.742.112 A: well, if you are using bash, and if what you want is always on 2nd field, $ string="Chromium 12.0.742.112 Ubuntu 11.04" $ set -- $string; echo $2 12.0.742.112 A: The following perl command does it: echo "Chromium 12.0.742.112 Ubuntu 11.04" | perl -ne '/[\d\.]+/ && print $&' A: This will match/output the first occurance of number(s) and dot(s): sed -rn "s/([^0-9]*)([0-9\.]+)([^0-9]*.*)/\2/ p" I've thrown a couple of narly strings at it and it held water :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7516455", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: In spring, how to pass objects from one bean to another bean? I have a row mapper class which implements RowMapper interface. I need to implement the mapRow method in that. The arguments of it are ResulSet and index. I would like to use this ResultSet object in another bean. How do i get it there ? A: Set this object as instance variable. But i would never recommend that for ResultSet. Resultset will be useless once its closed by spring (as spring is managing it). Better extract the data out of ResultSet store the data as some model bean in the instance variable (but keep in mind, by default the beans are singleton, and for each execution storing the data as instance variable would not make much sense either). EDIT-- okay to refine a bit more, i am putting an example here // this is singleton by default, if you want to store data in this bean // mark it as bean either by annotation or thorugh xml // so that it can be accessed through spring context public class MyBeanRowMapper implements RowMapper { // you can store something here, // but with each execution of mapRow, it will be updated // not recommended to store execution result here // or inject other bean here // SomeOtherBean someOtherbean; public Object mapRow(ResultSet rs, int rowNum) throws SQLException { MyBean myBean = new MyBean(); myBean.setId(rs.getInt("BEAN_ID")); myBean.setName(rs.getString("NAME")); // set this bean into gloablly accessible object here // or to the bean in which you want to access the result // something like -->// someOtherBean.setMyBean(myBean) // again be careful if someOtherBean is singleton by default return myBean; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7516458", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Why does MySql Connector.Net work on my Windows box but not on Mono? I have installed Mono (version 2.10.2), mod_mono and have successfully tested it with both an index.html and an index.aspx echoing the date. My problem is that I can't get MySQL to work with Mono; I have downloaded the mysql-connector-net-6.4.3-noinstall.zip file, renamed the dll to MySql.Data.dll, (from v2 folder) I have installed with gacutil -i MySql.Data.dll and edited both machine.config files (for 2.0 and 4.0) adding the following: <add name="MySQL Data Provider" invariant="MySql.Data.MySqlClient" description=".Net Framework Data Provider for MySQL" type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data, Version=6.4.3.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" /> I then edited the web.config file to make sure the PublicKeyToken was lowered case. My index page that has this code behind: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using MySql.Data; using MySql.Data.MySqlClient; namespace gpsmapper { public partial class login : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) {} protected void cmdLogin_Click(object sender, EventArgs e){ string cs = "Server=localhost;" + "Database=gts;" + "User ID=root;" + "Password=root;" + "Pooling=false"; MySqlConnection dbcon = new MySqlConnection(cs); } } } This all runs fine on Windows, but it will ultimately be deployed on a CentOS box. When I run it on the CentOS box it gives me the following error: Compilation Error Description: Error compiling a resource required to service this request. Review your source file and modify it to fix this error. Compiler Error Message: : at System.Reflection.AssemblyName..ctor (System.String assemblyName) [0x00000] in <filename unknown>:0 /gpsmapper/login.aspx How can I solve this? Has anyone faced something similar? As a solution am thinking about using the ODBC driver to access MySQL instead of the mono one. Can this be done? A: I have this working using the lastest connector for .NET/Mono found here. * *Add mysql.data.dll (zip path mysql-connector-net-6.4.4-noinstall/v4) to project references; *Web.Config changes: http://pastebin.com/CsHzwR4M.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516459", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: IE combo box usage, freezing on selection I'm using a combo box to select one of four school houses. Once the selection has been made, I'm using jQuery to run a few functions. One of the required functions utilises our VLE's own custom APIs. A limitation on the specific API I'm using means that we can only retrieve information for 100 users per call. As such, for a school of 1300, I'm having to run 26 calls (one call for each surname initial). It works well enough for how often it will be required. I have a loading GIF which holds place until the information is returned. In FireFox this works as intended, but in Internet Explorer EDIT: VERSION 8 the drop-down simply freezes until the information has been retrieved. Is there any way to rectify this easily? I don't particularly fancy overhauling the majority of the code - this feature won't be used a huge amount. widget.onLoad = function(){ HPAnalysisObject.init(); $('select#house_picker').change( function() { var val = $(this).val(); val = val.split(","); var label = val[0]; var house_id = val[1]; HPAnalysisObject.initHPTotals( house_id, label ); } ); } HPAnalysisObject.initHPTotals = function(house_id, label) { HPAnalysisObject.id_list = []; $('div#display').html('<img src="/user/74/168586.gif" alt="LOADING..." />'); for (var i = 1; i <= 26; i++) { initial = String.fromCharCode(64 + i); Frog.API.get("users.search", { "params": {"surname": initial, "group": house_id}, "onSuccess": HPAnalysisObject.addUsers }); } HPAnalysisObject.setLabel(label); HPAnalysisObject.getHPTotals(); }; There are additional functions in place, but it's this Frog.API.get call which slows everything down (it makes 26 ajax calls... :). So, basically, I'm hoping there will be something I can put in place before that call which allows the combo box to return to its un-dropped-down state, and thus show my loading GIF. Internet Explorer ^^ FireFox ^^ Many thanks. A: The Javascript code runs before the UI is allowed to update. Defer the call to initHPTotals so that the Javascript code executes after the combo box has collapsed, using for example setTimeout. 10 or 20 milliseconds should be fine: $('select#house_picker').change( function() { var val = $(this).val(); val = val.split(","); var label = val[0]; var house_id = val[1]; setTimeout(function() { HPAnalysisObject.initHPTotals( house_id, label ); }, 10); } ); A: Haven't tested this really, but you can try to change HPAnalysisObject.initHPTotals( house_id, label ); to: setTimeout(function() { HPAnalysisObject.initHPTotals( house_id, label ) }, 100); This should allow IE to escape the change event. Also if loading data takes really long then maybe you should change the behavior of the drop down. If some user would make a mistake you would load the data and then load another set. And so you could add a small button near the drop down and load onclick.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516461", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Searching for Number of Term Appearances in Mathematica I'm trying to search across a large array of textual files in Mathematica 8 (12k+). So far, I've been able to plot the sheer numbers of times that a word appears (i.e. the word "love" appears 5,000 times across those 12k files). However, I'm running into difficulty determining the number of files in which "love" appears once - which might only be in 1,000 files, with it repeating several times in others. I'm finding the documentation WRT FindList, streams, RecordSeparators, etc. a bit murky. Is there a way to set it up so it finds an incidence of a term once in a file and then moves onto the next? Example of filelist: {"89001.txt", "89002.txt", "89003.txt", "89004.txt", "89005.txt", "89006.txt", "89007.txt", "89008.txt", "89009.txt", "89010.txt", "89011.txt", "89012.txt", "89013.txt", "89014.txt", "89015.txt", "89016.txt", "89017.txt", "89018.txt", "89019.txt", "89020.txt", "89021.txt", "89022.txt", "89023.txt", "89024.txt"} The following returns all of the lines with love across every file. Is there a way to return only the first incidence of love in each file before moving onto the next one? FindList[filelist, "love"] Thanks so much. This is my first post and I'm largely learning Mathematica through peer/supervisory help, online tutorials, and the documentation. A: In addition to Daniel's answer, you also seem to be asking for a list of files where the word only occurs once. To do that, I'd continue to run FindList across all the files res =FindList[filelist, "love"] Then, reduce the results to single lines only, via lines = Select[ res, Length[#]==1& ] But, this doesn't eliminate the cases where there is more than one occurrence in a single line. To do that, you could use StringCount and only accept instances where it is 1, as follows Select[ lines, StringCount[ #, RegularExpression[ "\\blove\\b" ] ] == 1& ] The RegularExpression specifies that "love" must be a distinct word using the word boundary marker (\\b), so that words like "lovely" won't be included. Edit: It appears that FindList when passed a list of files returns a flattened list, so you can't determine which item goes with which file. For instance, if you have 3 files, and they contain the word "love", 0, 1, and 2 times, respectively, you'd get a list that looked like {, love, love, love } which is clearly not useful. To overcome this, you'll have to process each file individually, and that is best done via Map (/@), as follows res = FindList[#, "love"]& /@ filelist and the rest of the above code works as expected. But, if you want to associate the results with a file name, you have to change it a little. res = {#, FindList[#, "love"]}& /@ filelist lines = Select[res, Length[ #[[2]] ] ==1 && (* <-- Note the use of [[2]] *) StringCount[ #[[2]], RegularExpression[ "\\blove\\b" ] ] == 1& ] which returns a list of the form { {filename, { "string with love in it" }, {filename, { "string with love in it" }, ...} To extract the file names, you simply type lines[[All, 1]]. Note, in order to Select on the properties you wanted, I used Part ([[ ]]) to specify the second element in each datum, and the same goes for extracting the file names. A: Help > Documentation Center > FindList item 4: "FindList[files,text,n] includes only the first n lines found." So you could set n to 1. Daniel Lichtblau
{ "language": "en", "url": "https://stackoverflow.com/questions/7516469", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Problem with Default Document and IIS7.5/Windows 7 I'm having a problem with a component used in a Sitecore solution on our Windows 7 workstations that is driving me batty. In short, the component in question adds <script> tags to the page that load supporting JavaScript files. The src attributes are set to something like: /path/to/scriptgenerator/?r=1234&p=asdf Those paths are not working - I'm getting a 404 back. You might thing "oh ... well, the path doesn't exist." But it does, and it also has a Default.aspx page in it. In fact, if I try the following path, the JS is generated and returned by the server: /path/to/scriptgenerator/Default.aspx?r=1234&p=asdf We're testing the site using IIS7.5, not Visual Studio's debugging web server. Of course, on the production machines, which are Win Server 2008, things work just fine. The component in question is a third-party component and I have no access to the source code, so I can't just modify it to append default.aspx to the SRC path. I have checked to verify that Default.aspx is set up as a default document for the site, and it is. I tried to work around the problem using ISAPI_Rewrite, but for some reason, rules that I set up for /path/to/scriptgenerator are ignored. I've tried the solution described in these questions, and that has no effect on my problem: IIS 7 Not Serving Default Document ASP.NET 2.0 and 4.0 seem to treat the root url differently in Forms Authentication I'm really not sure what to try or look for next ... any suggestions? A: Is this component set up within the same IIS Site as the Sitecore application? If so, have you added path /path/to/scriptgenerator to IgnoreUrlPrefixes setting in web.config?
{ "language": "en", "url": "https://stackoverflow.com/questions/7516472", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Pitch Shift with DirectSound How to do pitchshifting with DirectSound in C#? I didn't find anything useful in Google. SetFrequency isn't good for me, beacuse this changes also the speed of the sound. I don't want to create a wav file for each pitch, beacuse that would result in a very big software. Thank You! A: Take a look at this wikipedia article for getting an overview about timescale-pitch modifications of audio material. And look at this similar so question for more info. And here i found an implementation of the Short-Time Fourier Transform pitch shifter algorithm in C#.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516473", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Confused about the flow of MVC, PHP I have been trying to learn about MVC but i have a few questions about the flow of input to the controller and then to the model. * *Say a user goes to example.com and get to their home page. They then select the search.php link. How does the controller.php know that the user has requested the search.php instead of user.php? *When the controller.php knows the search.php has been selected it will load the model and then the view.php. But when calling these the code will look like this. class Search extends Core_Search_Controller public function inboxSearch(){ $this->view->navigation = $this->navigation(); $this->load->box = $this->box(); } There is no folder or class view and no folder for load or class for load. And I can find function navigation in a different file but its folder is different location. How can it access that file without include or require? * *Once of search.php How does the controller.php know that search.php has requested information? Maybe this is redundant from question number one but im quite confused on this. I know its long, sorry about that. *Edit:*From what i have learned from the project i am on is that all the functions in the controller have Action on the end of them will direct to a view with the corresponding name. such as index.php/.tpl class IndexController extends Zend_Controller_Action{ public function indexAction(){ /** Somecode **/ } } Cheers A: Most MVC frameworks do a lot of behind the scenes magic for you and this is probably what has you confused about how things work. To answer your first question, most frameworks use a .htaccess file with a rewrite rule that will redirect all traffic to your controller. So, when you request search.php, it will actually call the controller and not search.php. From there, the controller can look at what you originally requested (search.php in this case) to figure out the appropriate model and view. I believe the answer to your second question is that it is auto-loading the files as needed. This is another bit of magic, where it can look at the class name and figure out the location of the file and load it. You can read more about this in the PHP manual. http://php.net/manual/en/language.oop5.autoload.php To answer your last question, getting the requested information is often handled by the controller when it looks at the request. For example, if you request "example.com/blog/7263", it will figure out that you want the "blog" model and that the id number is 7263. Depending on what framework you are using, the way that you configure this will be different. I hope that helps a little.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516475", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Jquery - apply method to all elements returned this is probably pretty straightforward but i'm struggling with it - I want to pause all videos I have running in a div container. At the moment, this is what I have: // Doesn't work $("#vid").find("video").get().pause(); // Works $("#vid").find("video").get(0).pause(); What's the best way to apply the pause function to each video element? A for/each loop? A: $('video','#vid').each(function(){ this.pause(); //find all videos in #vid and pause them }); A: $('#vid').find('video').each(function(){ $(this).pause(); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7516476", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Does cocoa limit the overall performance of a C/C++ openGL app? I'm looking to write a first OpenGL app on the Macintosh. Previously I've only done OpenGL programming in Windows. From what I've read, there are basically three choices: Glut Cocoa Carbon Glut is out of the question because I do not like the look of it, and from what I have read, a good share of Carbon is deprecated. Now, regarding Cocoa: A post here: Cocoa OpenGL window in pure C? mentions that Cocoa limits you to a single thread. Is that a single thread for the entire application, or a single thread for the window management? Would I be prohibited from doing multi-threaded programming from within C/C++ itself? Further, does Cocoa slow you down? What kind of window management does Blizzard use? A: Most "pure C" frameworks (including SDL) still use Objective-C and Cocoa to create and manage the OpenGL window. You should not stress over a small amount of Objective-C in your overall application. You can do the bare minimum in Objective-C and build the rest of the application in C. It is in your best interest to use Cocoa because support is improving as time goes on. If you use Carbon, support will worsen over time until suddenly it is flat out removed. You are right about GLUT. Steer clear. There are plenty of superior frameworks. GLUT is good for OpenGL education, and that's it. You will not be restricted from using multiple threads. The discussion of threads you see in that other discussion refer to how all OpenGL calls must happen from "the main thread". In other words, once you create a new thread, you cannot make OpenGL calls from that new thread because the context can only be active in one thread at a time. (There are calls to make the context active in another thread, but the point stands that you still can only work in one thread.) However, the rest of your program can have multiple threads no problem. In short, no, your performance will not be arbitrarily restricted. A: That's not a limitation of Cocoa. All OpenGL implementations I'm aware of only allow you to interact with the OpenGL context on the main thread. Blizzard surely just opens a window as a full screen OpenGL context and draws within that. Cocoa is not going to slow you down.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516478", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PHP memcache problem I am trying to set up memcache server on my localhost. Now before you jump on with me duplicates here is a list of them. Duplicates: * *Memcache connects but doesn't respond to any command *cannot store values into memcache *Super strange PHP error However none of them solves my problem or it just isnt followed anymore. One comment mentiones my telnet issue, but there is no reply to it. This is the setup: * *Xampp 1.7.4 (VC6) *memcache 2.2.5 *memcached 1.2.6 (tried with memcache from 1.2.1-1.4.5 same - problem) I have followed this and many more tutorials http://www.leonardaustin.com/technical/how-to-install-memcached-on-xampp-on-windows-7. Memcached server is running as service, I can connect fine to it, but any command I use ends with the same error: Notice: Memcache::getversion() [memcache.getversion]: Server 127.0.0.1 (tcp 11211) failed with: Failed reading line from stream (0) So I went to check up with telnet if it works. Any command I enter or anything for that matter will return me back to command line without any indication whats going on. There is no log supplied with memcached or any mention in windows event viewer. If I try to use putty and log it, there is nothing in the log except the stats command I typed. I tried to set it up to like 20 different ports. netstat tells me it is listening on that port (tcp and udp). Firewall is disabled. I have really no idea whats going on here and I am about to cry :( ANY kind of advice is highly appreciated. A: i dont know how to fix your problem...sorry :(... but try this class check if it works, the commands are same as memcached (and its memcached not memcache you have append and such stuff) but it uses the socket to connect to memcahed so its not complied with php its a lil bit slower. https://github.com/pompo500/xslib-memcached/blob/master/xslib-memcached.php A: I suppose the problem is in memcached.exe then. Can you confirm that memcached is running? You can test it by executing this on the console: wmic process get description, executablepath | findstr memcached.exe
{ "language": "en", "url": "https://stackoverflow.com/questions/7516480", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Facebook comment plugin for website and registered users I'm using Facebook registration for my website and I'm also using Facebook comments plugin on several pages on my website. I want to only allow registered users to comment. I don't want to simply hide the comments if they're not registered. I want them to see the comments but only be allowed to add comments if they are registered. Any ideas? A: If the user is registered, show the comment plugin like normal. If they aren't registered, you could use the graph api (https://graph.facebook.com/comments/?ids=http://www.example.com) to pull the comments and render them yourself and style them to look similar to the Facebook plugin.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516484", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can get login status of facebook user through facebook application? I am developing a facebook application. In this application I want to get login status of my application users. If any user of my application leave my application without logout to my application, then how can I track that user's Login status? can I use access_token or user id of that user for getting status? A: Well, if I understood you right, you can get the login status using FB.getLoginStatus(function(response) { if (response.authResponse) { // logged in and connected user, someone you know } else { // no user session available, someone you dont know } }); I didnt get the second part of ur question, "........If any user of my application leave my application without logout to my application, then how can I track that user's Login status?......" Whatever case, I guess the above FB Javascript SDK should give the login status b/w facebook and ur app.. https://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/ Hope that helped
{ "language": "en", "url": "https://stackoverflow.com/questions/7516486", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Default to PHP extension on web server Is there a way a .htaccess file can be written so that http://www.mysite.com/about loads about.php and the same goes for any file? I tried RewriteEngine On RewriteRule ^([0-9A-Za-z]+)$ $1.php but it doesn't seem to work. A: This is the most common rule (utilising mod_rewrite -- make sure it is loaded and enabled) -- it will ensure that such .php file does exist before rewriting (yes, it's a bit slower but safer): Options +FollowSymLinks RewriteEngine On # add .php file extension RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME}\.php -f RewriteRule ^(.+)$ $1.php [L] Alternatively just use this: Options +MultiViews This will turn on "content negotiation". But it has some cons. For example: let's assume you have hello.html & hello.php in your website root folder. If you request example.com/hello, with that option enabled Apache will look for alternative names (same name but different extensions) and will serve either hello.html or hello.php (I cannot tell which one will be preferred). But if you only have 1 file with such unique name (e.g. hello.php ONLY) then no problems here at all.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516490", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: jqGrid filterToolbar passing _search:false on search I have been using jqGrid for a few months now, and I have made a handful of data grids with the filterToolbar option: $('#grid_id').jqGrid('filterToolbar'); It has worked perfectly in the past (passing an array of POST variables to the php page defined in the url option in the jqGrid definition, of which there is one variable "_search:true"). The most recent grid I made, after I press enter on the filterToolar, it just reloads the grid... passing "_search:false" to the php script. Does anyone know why this would be happening. here is the script; $('#processed_list').jqGrid({ url:'/phpAJA?&sql=' + sql, editurl: '/phpAJAX?sql=' + sql, height: 225, width: 600, datatype: 'xml', mtype: 'POST', colModel:[ {name:"Invoice Num",index:"InvoiceNum",width:"8"}, {name:"Job Num", index:"JobNum",width:"8"}, {name:"Customer",index:"Customer",width:"16"}, {name:"Emailed To",index:"to_email",width:"16"}, {name:"Date Processed",index:"timestamp",width:"16"} ], pager: '#pager', rowNum:10, rowList:[10,20,30], sortname: 'invid', sortorder: 'desc', viewrecords: true, gridview: true, caption: 'Processed Invoices', editable: false }); $("#processed_list") .jqGrid('navGrid', '#pager', {edit: false,add: false, del: false, search: false, refresh:true},{},{},{},{},{}) .jqGrid('navButtonAdd',"#pager",{ caption:"reprint invoice", buttonicon:"ui-icon-print", onClickButton:function(){ ...some function... }, position: "last", title:"", cursor: "pointer" }) .jqGrid('filterToolbar'); Like I said, it all works except when I try the toolbarFilter search, it just reloads the grid (passing "_search:false" to the php script). Any help would be greatly appreciate. Thanks. A: So I figured out the problem with a little trial and error. The filterToolbar was referencing the column names in the colModel, and not the index, which it should be referencing. So in the colModel option in the jqGrid definition I have to change the names to the real names in the database, and then add the other colName option to reset the column headings in the web page. See the following code: $('#processed_list').jqGrid({ url:'/phpAJAX?sql=' + sql, editurl: '/phpAJAX?sql=' + sql, height: 225, width: 600, datatype: 'xml', mtype: 'POST', colNames:["Invoice Num","Job Num","Customer","Emailed To","Time Sent"], colModel:[ {name:"InvoiceNum",index:"InvoiceNum",width:"8"}, {name:"JobNum", index:"JobNum",width:"8"}, {name:"Customer",index:"Customer",width:"16"}, {name:"to_email",index:"to_email",width:"16"}, {name:"timestamp",index:"timestamp",width:"16"} ], pager: '#pager', rowNum:10, rowList:[10,20,30], sortname: 'invid', sortorder: 'desc', viewrecords: true, gridview: true, caption: 'Processed Invoices', editable: false });
{ "language": "en", "url": "https://stackoverflow.com/questions/7516495", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Read HTML File in iFrame and Converted to PDF Below is my HTML File code <div> <asp:Panel ID="pnlPDF" runat="Server"> <iframe type="application/pdf" src="up/waters 6form.pdf" width="956" height="500"></iframe> </asp:Panel> </div> In this HTML there is a Fill-able PDF... User enters data and submits. when user submits I need to convert into PDF File. assume that pdf file contains Name: __________ Gender: __________ when user enters the detail...how to save as pdf A: It sounds like there's two issues: 1. Transfering the data from the fillable PDF to the ASPX page. This is as trivial as changing the post to the aspx page. 2. Creating a PDF. This will take a little more work, and probably requires a third-party product like PDFSharp. Alternatively, have you looked at FDF? http://www.adobe.com/devnet/acrobat/fdftoolkit.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7516498", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SQL Server: Can the same table exist in multiple schemas I thought that the schemas are namespace instances and hence the same table created under 2 different schemas are 2 different objects from the perspective of the database. One of my colleagues claim that schemas are nothing but a security container, hence we can create the same table in different schemas. Is this true? A: They are 2 different objects, check the object_id A: Yes, it can. Just try it CREATE SCHEMA OneSchema AUTHORIZATION dbo; CREATE SCHEMA TwoSchema AUTHORIZATION dbo; CREATE TABLE dbo.SomeTable (foo int); CREATE TABLE OneSchema.SomeTable (foo int); CREATE TABLE TwoSchema.SomeTable (foo int); A schema is both a securable and part of the "namespace" A: You are correct. CREATE TABLE foo.T ( c int ) and CREATE TABLE bar.T ( c int ) creates 2 separate objects. You could create a synonym bar.T that aliases foo.T though. CREATE SCHEMA foo GO CREATE SCHEMA bar GO CREATE TABLE foo.T(c INT) GO CREATE SYNONYM bar.T FOR foo.T; INSERT INTO foo.T VALUES (1); SELECT * FROM bar.T; A: I guess that you are trying to solve an issue by dividing data with the same data-structure between different tenants. You don't want to use different databases to reduce costs. To my mind, it is better to use row-level security in this case. In this case, data are stored in one table, but one tenant can't access data that were created by another tenant. You could read more in the next article - Row-Level Security A: myschema.table1 is different than yourschema.table1
{ "language": "en", "url": "https://stackoverflow.com/questions/7516502", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: How to make a PHP GET Request method like this "http://somesite.com/games/213123"? Hi guys I'm wondering how to make this kind of requests to the server I looked at many sites and they use this technique. For example gametrailers.com => http://www.gametrailers.com/video/level-six-diablo-iii/**721239**. I know that a GET request is made by using parameters like this: http://somesite.com/page.php?param=1. So how to make it like gametrailers. I hope you understand my question and I doubt that "721239" is a folder on the server with an index page inside of it. A: You need to create a file placed in the folder near your script with name .htaccess In this file you need to define rewriting rules. The contents of the file are: RewriteEngine on RewriteRule ^games/(.*)$ games.php?id=$1 [L] In this case http://somesite.com/games/213123 will be transformed into http://somesite.com/games.php?id=213123 A: The more convinient way is to do url rewriting. (wiki) For example, you can have a .htaccess like this, well explained in this guide from symfony: <IfModule mod_rewrite.c> RewriteEngine On # we skip all files with .something RewriteCond %{REQUEST_URI} \..+$ RewriteCond %{REQUEST_URI} !\.html$ RewriteRule .* - [L] # we check if the .html version is here (caching) RewriteRule ^$ index.html [QSA] RewriteRule ^([^.]+)$ $1.html [QSA] RewriteCond %{REQUEST_FILENAME} !-f # no, so we redirect to our front web controller RewriteRule ^(.*)$ index.php [QSA,L] </IfModule> A: You can achieve this using MultiViews in Apache2 (http://httpd.apache.org/docs/2.0/content-negotiation.html). MultiViews (when enabled) instructs Apache to build a parameter map when a resource doesn't exist, so for www.foo.com/app/game/14, if www.foo.com/app.php exists and app/game and app/game 14 don't, it can be set up to translate that to www.foo.com/app.php?type=game&article=14 Some people also use mod_rewrite, but I'm not sure that's the preferred approach.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516503", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: move an existing frame to a new frame and create a new frame using old name i've used a frame in tcl named frame1 and others also. Now i set a proc to destroy all these frames. what i want to do is to move these frames to a new variable and create new frames of same names. my code looks like this: proc DestroyAll {} { global parent_widget global new_widget destroy .sf.frame.main.xName for {set i 0} {$i < $Count} {incr i} { destroy .sf.frame.main.parameter($i) } destroy .sf.frame.main.buttons destroy .sf.frame.buttons destroy .sf.frame.main destroy .sf.frame destroy .sf } Populatenewdata --->> this proc creates and fills the sf frame I dont want to destroy these frames, but i want to create new frame. Is there any way of doing this as the filling procedure of this frames is very lengthy and cant be done using loop. A: Tk doesn't let you reparent widgets; their names are fixed from the moment you create them to the moment you destroy them. (You can make them visually appear inside different widgets with appropriate -in options to pack and grid, but that's a strictly visual effect.) Is it possible to manage the model backing up your widgets better so that you can easily recreate views onto that model? (The answer depends on the widgets in use — recreating a canvas or text widget is not at all trivial, though with the text you can clone it from 8.5 onwards — but it's usually fairly easy.) Rethinking what you're doing more strongly in terms of MVC will help.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516507", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Expandable List Android Black background while scrolling I'm struggling with the ExpandableList View in Android. I'm using the code provided in the apis demo but I don't know how to solve my problem. I got a white background on my view but when I'm scrolling the list it turns black..why? I don't want this effect...is there a way to change it? is there a way to customize the list using this code? I'm looking for something like this..Hope you could help me! Thank you :) package com.example.android.apis.view; import android.R; import android.app.ExpandableListActivity; import android.os.Bundle; import android.widget.ExpandableListAdapter; import android.widget.SimpleExpandableListAdapter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Demonstrates expandable lists backed by a Simple Map-based adapter */ public class ExpandableList3 extends ExpandableListActivity { private static final String NAME = "NAME"; private static final String IS_EVEN = "IS_EVEN"; private ExpandableListAdapter mAdapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); List<Map<String, String>> groupData = new ArrayList<Map<String, String>>(); List<List<Map<String, String>>> childData = new ArrayList<List<Map<String, String>>>(); for (int i = 0; i < 20; i++) { Map<String, String> curGroupMap = new HashMap<String, String>(); groupData.add(curGroupMap); curGroupMap.put(NAME, "Group " + i); curGroupMap.put(IS_EVEN, (i % 2 == 0) ? "This group is even" : "This group is odd"); List<Map<String, String>> children = new ArrayList<Map<String, String>>(); for (int j = 0; j < 15; j++) { Map<String, String> curChildMap = new HashMap<String, String>(); children.add(curChildMap); curChildMap.put(NAME, "Child " + j); curChildMap.put(IS_EVEN, (j % 2 == 0) ? "This child is even" : "This child is odd"); } childData.add(children); } // Set up our adapter mAdapter = new SimpleExpandableListAdapter( this, groupData, android.R.layout.simple_expandable_list_item_1, new String[] { NAME, IS_EVEN }, new int[] { android.R.id.text1, android.R.id.text2 }, childData, R.layout.simple_expandable_list_item_3, new String[] { NAME, IS_EVEN }, new int[] { android.R.id.text1, android.R.id.text2 } ); setListAdapter(mAdapter); } } A: Add to your listview in the xml file: android:cacheColorHint="#00000000" or in your Java code: getListView().setCacheColorHint(0); A: add android:cacheColorHint="#00000000" to ListView example; <ListView android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/list" android:cacheColorHint="#00000000" /> A: Write this one in your xml you will get the answer android:scrollingCache="false" A: Follow the instructions on this link: Android Developer Ressources: Listview Backgrounds In short: ...To fix this issue, all you have to do is either disable the cache color hint optimization, if you use a non-solid color background, or set the hint to the appropriate solid color value. You can do this from code (see setCacheColorHint(int)) or preferably from XML, by using the android:cacheColorHint attribute. To disable the optimization, simply use the transparent color #00000000. The following screenshot shows a list with android:cacheColorHint="#00000000" set in the XML layout file ... A: I'd just like to point out that there's a more elegant way of expressing #00000000, just use: @android/color/transparent. It's easier to understand if you come back to that code some time later (Yeah, I know that it's just an ARGB number anyway ;-)). A: Simply set your list color, using the methods below: android:cacheColorHint="#000000" or in your Java code: listView.setCacheColorHint(0);
{ "language": "en", "url": "https://stackoverflow.com/questions/7516508", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: PHP: literal \n rather than new line I have a php var which, when echoed, writes a JS function into the source of a page. The function loops through a CSV and so it has the following line within it: $str="var lines = data.split('\n');"; At the present time, when echoed, I get this 'correct' JS written into the source: var lines = data.split(' '); Instead, I want to echo the literal string \n into the source of the page. Can anyone point me in the right direction? Thanks. A: Escape the slash. "\\n" So that it is treated as a slash instead of an escape character. A: Try this: $str="var lines = data.split('\\n');"; A: you can escape \ like this: \\. But I would put the whole JS functionality into a .js file, include that from the generated HTML, and call the specific function when needed. And generate a minimalistic js code, like var config = {....} if I have to communicate some page related information. You almost never need dynamically generated JS code. It's a lot harder to read and you're wasting CPU and network bandwidth... A: Either the solutions in the earlier answers, or invert the quotes by using single quotes as the PHP string delimiter: $str='var lines = data.split("\n");'; Or escape the inner quotes, if you want to keep single quotes for javascript as well when using single quotes as the PHP string delimiter. $str='var lines = data.split(\'\n\');'; See the docs on quoted strings in PHP as well about how single quoted strings and double quoted strings behave differently.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516509", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Salseforce Apex classes support Apache axis Stub authentication We have converted a WSDL file of a Web serivice into the salesforce apex classes. The Web Service is receiving the authentication credentials in Apache axis Stub authentication username and password format. Below is the sample Apache axis Stub authentication username and password code. Service service = new XYZServiceLocator(); URL endpointURL = new URL("https://urllink"); XYZServiceSoapBindingStub stub = new XYZServiceSoapBindingStub(endpointURL, service); stub.setUsername("username");// void org.apache.axis.client.Stub.setUsername(String username) stub.setPassword("password");// void org.apache.axis.client.Stub.setPassword(String Password) QueryResponse qresp = stub.webServiceCall(qr); My question is. Can we get the Apache axis Stub authentication username and password functionality in the salesforce Apex classes. As the Apex Stub support the HTTP Headers authentication does it also support the Apache axis Stub authentication? Below is the Salesforce Apex stub HTTP Headers authentication code String myData = 'username:password'; Blob hash = Crypto.generateDigest('SHA1',Blob.valueOf(myData)); encodedusernameandpassword = EncodingUtil.base64Encode(hash); XYZBillingStub.inputHttpHeaders_x.put('Authorization','Basic ' + encodedusernameandpassword );// SALESFORCE STUB XYZBilling.query(queryReq )// Web Service call Please help me in resolving this issue. A: After converting the apex code to the below code I was successfully able to resolve the issue. String myData = 'username:password'; encodedusernameandpassword = EncodingUtil.base64Encode(Blob.valueOf(myData)); XYZBillingStub.inputHttpHeaders_x.put('Authorization','Basic ' + encodedusernameandpassword );// SALESFORCE STUB XYZBilling.query(queryReq )// Web Service call This was a simple hit and trial solution I got, And I think Salseforce apex functionality only support input HTTP Headers authentication process. If one has some other way to do the authentication please mention it. A: Looks like you already figured out a solution. For reference, have a look at the Sending HTTP Headers on a Web Service Callout section of the online docs for doing basic authentication headers.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516511", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Binding textbox to listbox twoway onewaytosource problems? I use the textName for the user to enter his name. Then typing, the textchanged event updates the listbox with the names that matchs with the input, then the user can click on an item (CompletedName in listbox), and when it happens I need the textbox updates with the item content.. This problem started to happen when I changed the "GivenName" (as a field from the table I query) for the "CompletedName".. (it is a string concat from the query as u see above) I have this LINQ query: var players = from p in context.Player where (p.GivenName.StartsWith(TextName.Text.Trim()) || p.Number.StartsWith(TextName.Text) || p.Surname.StartsWith(TextName.Text) ) select new { CompleteName = p.GivenName + " " + p.Surname + " (" + p.Number + ")"}; Then I make this the source for a listbox named listNames and I have this textbox: <TextBox Name="TextName" Text="{Binding ElementName=listNames, Path=SelectedItem.CompleteName}"/> When I run it, the next error is shown: "A Two Way or OneWayToSource binding cannot work on the read-only property 'CompleteName' of type '<>f__AnonymousType0`1[System.String]'" I understand, of course that it can not be a TwoWay or OneWayToSource. But I need the user can add content to the textName, because it is also a search textbox, without updating the SelectedItem on the listbox. If I add to the textbox the expression Mode=OneWay.. nothing happens in the textName control, I mean it doesnt show the item from the listbox.. What should I do for make it work?? A: You're binding to an instance of an anonymous type, but properties of anonymous types are read-only, so the binding can't update the CompleteName property. Anyway, from what I understand, you're not trying to update the name, the TextBox is actually a search box. In that case the approach you're using cannot work. You need to handle the TextChanged event of the TextBox (or bind it to a property of your ViewModel if you're using MVVM), and use the new value to select the appropriate item in the ListBox. So anyway you won't be able to do this with an anonymous type, since its properties won't be accessible in the method that performs the search... A: I will reply my own answer for next people with the same problem. As I couldn't make it work with the Mode=OneWay i did this: public class CompleteNamesResuls { public String CompleteName { get; set; } } private void TextName_TextChanged(object sender, TextChangedEventArgs e) { var players = from p in context.Player where (p.GivenName.StartsWith(TextName.Text.Trim()) || p.Number.StartsWith(TextName.Text) || p.Surname.StartsWith(TextName.Text)) select new CompleteNamesResuls(){ CompleteName = p.GivenName + " " + p.Surname + " (" + p.Number + ")" }; } That way, instead of using the Anonimous Type that was the OnlyRead source of
{ "language": "en", "url": "https://stackoverflow.com/questions/7516513", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Inline functions in debug build (Visual C++ 2008) The game engine I am working with is too slow in the debug build and is impossible to debug the game. One of the things I would like is for the compiler to inline small functions (especially in Vector/Matrix and container classes). This may or may not speed up the game in debug build. Before profiling heavily and trying to figure out bottlenecks I thought I would try this first as I would have to do minimal work and the results may be promising. So, is there a way to get the Visual C++ compiler to inline functions in debug builds? A: Project options -> C/C++ -> Optimization -> Inline Function Expansion. Turn this to /Ob2. Do this in your Debug configuration. In Release, inline function expansion is implied by other optimization settings, so even though by default all configurations say "Default" for the setting, the behavior is indeed different. I believe Debug builds should have inline expansion behavior the same as release; there's really no reason not to. http://msdn.microsoft.com/en-us/library/47238hez.aspx A: You're confusing two compiler options. /O influences optimization, including inlining. /ZI creates the PDB file for debugging. They can be set independently. It may be useful to clone the "Debug" configuration, though, and create a "Debug-optimized" configuration with both /O1 and /ZI. A: You might try __forceinline. Be sure to read about debug builds on that page (turn off the /Ob0 option). My suspicion is that this will not change the performance very much. Another thing to try if you haven't already is just to add symbols to a release build. It works fairly well for debugging a lot of issues. A: DEBUG is defined by Visual Studio when a project is compiled in Debug mode so: #ifdef DEBUG inline void fn() { #else void fn() { #endif
{ "language": "en", "url": "https://stackoverflow.com/questions/7516515", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: erase from list using JSON reply, using jQuery I have this list of items, and I have a button at the bottom for deleting some of them according to their checkboxes. I also got a response from a jQuery get() with the elements that represent the new list. So, the rest need to be removed. This is how my list is built : <table style="float:left;width:100%"> <tbody> <?php foreach ($items as $item): ?> <tr> <div> <td ?>; <input type="checkbox" name="item_<?php echo $item['NAME'];?>" value="<?php echo $item['ID'];?>" /> </td> </div> </tr> <?php endforeach; ?> </tbody> I use the get() function and get the following reply in json. [{"ID":"2","EMAIL":"xxxxx@hotmail.com","DATETIME":"2011-12-12 03:20:01"},{"ID":"4","EMAIL":"xxxxx@gmail.com","DATETIME":"2011-10-09 01:15:22"}"] All I want to do now is simply eliminate the correspoding where the input value (which is the json's ID) is NOT in the json reply. Any ideas how to do this with jQuery ? Thanks ! A: There are several different ways to do this. I kind of like going through your json response, flagging those that are confirmed, delete those unconfirmed, and remove the confirmed flag. e.g. var json = [{'id':'2','email':... }]; // first, flag what we DO have $.each(json,function(n,r){ var $i = $(':input[value="' + r.ID + '"]'); if ($i.length > 0){ $i.addClass('ajax-confirmed'); } }); // delete what hasn't been flagged $(':input:not(.ajax-confirmed)').each(function(m,r){ var $row = $(r).closest('tr'); $row.remove(); }); // then remove the flag (cleanup) $(':input.ajax-confirmed').removeClass('ajax-confirmed'); Fiddle showing it in action: http://jsfiddle.net/v9paf/ (Or if you want to feel like you're deleting it... http://jsfiddle.net/v9paf/1/)
{ "language": "en", "url": "https://stackoverflow.com/questions/7516518", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: asp.net to have console like window on the page I want to move my console application to asp.net website, where I show some action logs. What kind of control should I use for read-only actions logs? Let say on the button click I have a loop and I want to display actions from inside that loop. Should I use multiline textbox? how do I append lines? should I wrap with update panel control? not sure which controls to pick to replicate console.log view for the website page.. A: You should google about asp.net async pages, there are many examples, you can choose one that fits your technology, for example: ASP.NET Asynchronous label update
{ "language": "en", "url": "https://stackoverflow.com/questions/7516519", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Cannot apply condition for looping through datarow I have apply looping in datarow and i need to check that if user role is admin, i need to apply some condition. Now a user can have multiple roles say User Smith has 3 roles: Admin, Developer and Tester. Hence for smith the condition comes true. For Jane she has 4 roles: Developer, Tester, Analyst & Normal user, so for jane the condition become false (as she is not admin) Now i have written code as // filling up the dataTable. DataTable dtAssignedRoles = (DataTable (Session[GlobalConstants.SESSION_USER_ASSGN_ROLE_DT]); if (dtAssignedRoles != null && dtAssignedRoles.Rows.Count > 0) { foreach (DataRow dr in dtAssignedRoles.Rows) { if (dr["OT_ROLE"].ToString().ToUpper().Equals("ADMIN")) { // apply condition for admin here! } } } // Condition that would execute for Jane if (strICol.Equals("N")) { e.Row.Cells[0].Text = string.Empty; e.Row.Cells[0].Controls.Clear(); Image imgIColumnDesc = new Image(); imgIColumnDesc.ImageUrl = "~/Images/blackcircle.png"; e.Row.Cells[0].Controls.Add(imgIColumnDesc); } Problem: For smith the condition fails as although he is admin, he is also developer and tester. hence 2 conditions get applied; one for admin and another for non-admin (dev + tester) Hence i guess, i need to check in all the rows and if there is one role with admin, the condition should be met. But i don't know how to do it? Please guide. Thanks A: If, after you apply the condition for the admin, you add the statement break;, this will break out of the loop and move onto the next step in the process. A: You can use this helper function to determine if a user has a particular role... public bool hasRole(string role, DataTable dtAssignedRoles) { if (dtAssignedRoles != null && dtAssignedRoles.Rows.Count > 0) { foreach (DataRow dr in dtAssignedRoles.Rows) { if (dr["OT_ROLE"].ToString().ToUpper().Equals(role)) { return true; } } } return false; } EDIT: OR with Linq public bool hasRole(string role, DataTable dtAssignedRoles) { return dtAssignedRoles.AsEnumerable().Any(a => a["OT_ROLE"].ToString().ToUpper().Equals(role.ToUpper())); } Then to use... if(hasRole("ADMIN",dtAssignedRoles)) { //DO stuff } else if (hasRole("TESTER", dtAssignedRoles)) { //Do Other Stuff }
{ "language": "en", "url": "https://stackoverflow.com/questions/7516520", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Running a javascript function when Facebook has finished loading I'm writing a facebook app that uses badgeville to award points to players. Sometimes points need to awarded when the page loads, however I also have some facebook social plugins on the page like a comment box and like button. It appears that because the page is waiting for these to load it doesn't load the badgeville stuff intime to allow the function that awards the points to run correctly. Is there any event I can use to run the function once facebook has finished doing it's things? I found "FB.Canvas.setDoneLoading();" but am not sure how to implement it. Thanks A: Sure, you probably have something like this: <script> window.fbAsyncInit = function() { FB.init({ appId : 'YOUR APP ID', status : true, // check login status cookie : true, // enable cookies to allow the server to access the session xfbml : true, // parse XFBML channelUrl : 'http://www.yourdomain.com/channel.html', // Custom Channel URL oauth : true //enables OAuth 2.0 }); FB.Canvas.setDoneLoading( function () { alert("Done loading"); }); }; (function() { var e = document.createElement('script'); e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js'; e.async = true; document.getElementById('fb-root').appendChild(e); }()); </script> This will sure that setDoneLoading() is not called until the FB functions are setup an initialized. A: Assuming you are doing Server-side Login, You should use FB.Event.subscribe. if you are initializing FB object with status: true then auth.statusChange or auth.authResponseChange event will fire after FB object initialized. FB.Event.subscribe('auth.statusChange', function(response) { if(response.status == 'connected') { runFbInitCriticalCode(); } }); FB.init({ appId : 'appId', status : true, // check login status cookie : true, // enable cookies to allow the server to access the session xfbml : true // parse XFBML });
{ "language": "en", "url": "https://stackoverflow.com/questions/7516524", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Transform a set of 2d images representing all dimensions of an object into a 3d model Given a set of 2d images that cover all dimensions of an object (e.g. a car and its roof/sides/front/read), how could I transform this into a 3d objdct? Is there any libraries that could do this? Thanks A: These "2D images" are usually called "textures". You probably want a 3D library which allows you to specify a 3D model with bitmap textures. The library would depend on platform you are using, but start with looking at OpenGL! OpenGL for PHP OpenGL for Java ... etc. A: I've heard of the program "Poser" doing this using heuristics for human forms, but otherwise I don't believe this is actually theoretically possible. You are asking to construct volumetric data from flat data (inferring the third dimension.) I think you'd have to make a ton of assumptions about your geometry, and even then, you'd only really have a shell of the object. If you did this well, you'd have a contiguous surface representing the boundary of the object - not a volumetric object itself. What you can do, like Tomas suggested, is slap these 2d images onto something. However, you still will need to construct a triangle mesh surface, and actually do all the modeling, for this to present a 3D surface. I hope this helps. A: What there is currently that can do anything close to what you are asking for automagically is extremely proprietary. No libraries, but there are some products. This core issue is matching corresponding points in the images and being able to say, this spot in image A is this spot in image B, and they both match this spot in image C, etc. There are three ways to go about this, manually matching (you have the photos and have to use your own brain to find the corresponding points), coded targets, and texture matching. PhotoModeller, www.photomodeller.com, $1,145.00US, supports manual matching and coded targets. You print out a bunch of images, attach them to your object, shoot your photos, and the software finds the targets in each picture and creates a 3D object based on those points. PhotoModeller Scanner, $2,595.00US, adds texture matching. Tiny bits of the the images are compared to see if they represent the same source area. Both PhotoModeller products depend on shooting the images with a calibrated camera where you use a consistent focal length for every shot and you got through a calibration process to map the lens distortion of the camera. If you can do manual matching, the Match Photo feature of Google SketchUp may do the job, and SketchUp is free. If you can shoot new photos, you can add your own targets like colored sticker dots to the object to help you generate contours. If your images are drawings, like profile, plan view, etc. PhotoModeller will not help you, but SketchUp may be just the tool you need. You will have to build up each part manually because you will have to supply the intelligence to recognize which lines and points correspond from drawing to drawing. I hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516527", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Not able to resolve a leak detected by leaks tool. Can i ignore it? I am not able to find a way to remove a leak detected by leaks tool. Here is my problem... I have a singleton object in my delegate which stores data on a global level. Now, I have a array of objects which i maintain here and add or modify it from controllers. Below is a function which fills the objects and sets the above global array, Now, the highlighted lines(marked by //LEAK) are where the leaks tool tell me its a leak. I require this array for my session. I release the array at the end when i logout. Should i be worried about this kind leak? -(LayoutInfo *) fillLayout: (GDataXMLElement *) layoutElement { LayoutInfo *layout = [[LayoutInfo alloc] init]; layout.dataTableCount = 0; layout.chartsCount = 0; NSArray *templateNameArr = [layoutElement elementsForName:@"TemplateName"]; NSMutableArray *chartElements = [[NSMutableArray alloc] init]; // LEAK NSMutableArray *dtElements = [[NSMutableArray alloc] init]; NSArray *charts = [layoutElement elementsForName:@"chart"]; // LEAK if (charts.count > 0) { for (GDataXMLElement *singleChart in charts) { chart *chartInfo = [[chart alloc] init]; // LEAK layout.chartsCount = layout.chartsCount + 1; NSArray *imageName = [singleChart elementsForName:@"imageName"]; if (imageName.count > 0) { GDataXMLElement *imageNameStr = (GDataXMLElement *) [imageName objectAtIndex:0]; chartInfo.imageName = imageNameStr.stringValue; // LEAK } NSArray *imagePath = [singleChart elementsForName:@"imagePath"]; if (imagePath.count > 0) { GDataXMLElement *imagePathStr = (GDataXMLElement *) [imagePath objectAtIndex:0]; chartInfo.imagePath = imagePathStr.stringValue; // LEAK } NSArray *imageFileName = [singleChart elementsForName:@"imageFileName"]; if (imageFileName.count > 0) { GDataXMLElement *imageFileNameStr = (GDataXMLElement *) [imageFileName objectAtIndex:0]; chartInfo.imageFileName = imageFileNameStr.stringValue; } ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:chartInfo.imagePath]]; [request setDownloadDestinationPath:[[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:chartInfo.imageFileName]]; [request setDidFinishSelector:@selector(fillLayout_requestDone:)]; [request setDidFailSelector:@selector(fillLayout_requestWentWrong:)]; [request startSynchronous]; NSString *imagePath1 = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:chartInfo.imageFileName]; if([[NSFileManager defaultManager] fileExistsAtPath:imagePath1]) { NSLog(@" --- IMAGE SAVED -- %@", imagePath1); } [chartElements addObject:chartInfo]; } //for layout.chartElement = chartElements; // THIS IS WHERE I ASSIGN THE GLOBAL ARRAY //[chartElements release]; } return layout; } A: -(LayoutInfo *) fillLayout: (GDataXMLElement *) layoutElement { LayoutInfo *layout = [[LayoutInfo alloc] init]; layout.dataTableCount = 0; layout.chartsCount = 0; NSArray *templateNameArr = [layoutElement elementsForName:@"TemplateName"]; NSMutableArray *chartElements = [[NSMutableArray alloc] init]; // LEAK //NSMutableArray *dtElements = [[NSMutableArray alloc] init]; NSArray *charts = [layoutElement elementsForName:@"chart"]; // LEAK if (charts.count > 0) { for (GDataXMLElement *singleChart in charts) { chart *chartInfo = [[chart alloc] init]; // LEAK layout.chartsCount = layout.chartsCount + 1; NSArray *imageName = [singleChart elementsForName:@"imageName"]; if (imageName.count > 0) { GDataXMLElement *imageNameStr = (GDataXMLElement *) [imageName objectAtIndex:0]; chartInfo.imageName = imageNameStr.stringValue; // LEAK } NSArray *imagePath = [singleChart elementsForName:@"imagePath"]; if (imagePath.count > 0) { GDataXMLElement *imagePathStr = (GDataXMLElement *) [imagePath objectAtIndex:0]; chartInfo.imagePath = imagePathStr.stringValue; // LEAK } NSArray *imageFileName = [singleChart elementsForName:@"imageFileName"]; if (imageFileName.count > 0) { GDataXMLElement *imageFileNameStr = (GDataXMLElement *) [imageFileName objectAtIndex:0]; chartInfo.imageFileName = imageFileNameStr.stringValue; } ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:chartInfo.imagePath]]; [request setDownloadDestinationPath:[[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:chartInfo.imageFileName]]; [request setDidFinishSelector:@selector(fillLayout_requestDone:)]; [request setDidFailSelector:@selector(fillLayout_requestWentWrong:)]; [request startSynchronous]; NSString *imagePath1 = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:chartInfo.imageFileName]; if([[NSFileManager defaultManager] fileExistsAtPath:imagePath1]) { NSLog(@" --- IMAGE SAVED -- %@", imagePath1); } [chartElements addObject:chartInfo]; [chartInfo release]; // it's retained in chartElements until removed, or until chartElements is deallocced } //for if(layout.charElement){ [layout.charElement release]; // you should however consider in making charElement property as retain; layout.charElement = nil; // this isn't required here (since you're assigning it a new value), but you should usually set it to nil after a release to prevent EXC_BADACCESS } layout.chartElement = chartElements; // THIS IS WHERE I ASSIGN THE GLOBAL ARRAY //[chartElements release]; } return [layout autorelease]; // in case you don't want it autoreleased you should call your method something like: createFilledLayout ('create' is usually used so anyone that uses the method knows it's responsible for releasing the return value) } you should have a look at Memory Management Programming Guide
{ "language": "en", "url": "https://stackoverflow.com/questions/7516531", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SQL Server all Errors List? I am trying to capture a list of all SQL Server errors so my calling C# (.NET 4.0) can do different things based on what occurs. I am trying to get all of the things in http://technet.microsoft.com/en-us/library/cc645611.aspx and all of the other related pages. Obviously SQL Server has these in a table somewhere already, but where? Thanks. A: SELECT message_id, severity, text FROM sys.messages WHERE language_id = 1033; -- assuming US English
{ "language": "en", "url": "https://stackoverflow.com/questions/7516535", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Get previous value of an entity I need to get previous value of an entity. My requirement is like; I have some input fields in an edit page. 1 User can enter some values there and press save button at this time the user should be able to save it. 2 User can enter some values there and press Cancel button at this time the page should be reloaded with whatever values were there before the user start editing the page. My question is that can entity frame work, help us in getting previous value of an object? Is self tracking is something related to this? A: You mentioned "page" so I guess you are talking about web application. In such case you should simply load entity from the database again because pushing Cancel button will make a new request to your web application. You should use a new context per request so you don't have any previous data or entity to reload - you will run a new query and get last data persisted to database. A: What you would want to do is: myContext.Refresh(RefreshMode.StoreWins, myObject); This will ask the context to reload the entity removing any changes to the object and replacing the property values from the data store.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516537", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Php using str_replace for strange template string? Not sure if this is possible, but on my template I have this in the code: Title Here<!--firstTitle--> I am wondering if there is a way to use str_replace to output this: <h2>Title Here</h2> I can do one side, but not the other?? Thanks in advance! A: No, not with str_replace But if Title is start of the line, try preg_replace preg_replace('~^(.*?)<!--firstTitle-->~', '<h2>$1</h2>', $string);
{ "language": "en", "url": "https://stackoverflow.com/questions/7516539", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Core Data: Sorting results from an abstract entity based on entity type Is it possible to sort results from Core Data based on the entity type, but: * *without resorting to adding a fake attribute called something like entityType, and *without adversely affecting performance by using KVO/KVC tricks such as introducing -(NSString*)typeOfEntity or similar? I currently have: * *TradeDocument as an abstract entity, with *QuoteTradeDocument and InvoiceTradeDocument as entities based on it. I want to display entity type and/or allow NSTableView to be sorted based on this. I use Cocoa Bindings on OS X. Note: I am explicitly trying to avoid faulting each object. A: Ivan, The only limit with an abstract entity is that you can't instantiate one. You can still fetch them. Then it is a rather simple matter of testing against which subclass each managed object is. Sorting on type is not something a sort descriptor can do but a function can, as with -sortUsingFunction:context:. Andrew
{ "language": "en", "url": "https://stackoverflow.com/questions/7516540", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: link_to - make 2 object values become a link I need to make a link with the following: '@grp.id -- @grp.captain.name' I tried the code below: <%= link_to @grp.id--@grp.captain.name, :controller => :groups, :action => :edit_grp, :id => @grp.id %> But am getting the following error message: wrong number of arguments (2 for 0) My question is how do i make the 2 obj values a link? Thanks for any suggestion A: <%= link_to "#{@grp.id}--#{@grp.captain.name}", edit_group_path(@grp) %> should do what you need in any recent version of rails.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516543", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why is 'object slice' needed in C++ ? Why it is allowed ? For more bugs? Why C++ standard allow object slice ? Please don't explain c++ object slice concept to me as I knew that. I am just wondering what's the intention behind this c++ feature(object slice) design ? To get novice more bugs? Wouldn't it be more type safe for c++ to prevent object slice ? Below is just a standard and basic slice example: class Base{ public: virtual void message() { MSG("Base "); } private: int m_base; }; class Derived : public Base{ public: void message() { MSG("Derived "); } private: int m_derive; }; int main (void) { Derived dObj; //dObj get the WELL KNOWN c++ slicing below //evilDerivedOjb is just a Base object that cannot access m_derive Base evilDerivedOjb = dObj; //evilDerivedObj is type Base evilDerivedOjb.message(); //print "Baes" here of course just as c++ standard says } Thanks in advance. ================================================================================= After reading all the answers and comments I think I should express my question better in the first place but here it comes: When there is a is-a relationship(public inheritnace), instead of private/protected inheritance , you can do the following: class Base{ public: virtual void foo(){MSG("Base::foo");} }; class Derived : public Base{ public: virtual void foo(){MSG("Derived::foo");} }; int main (void) { Base b; Derived d; b = d; //1 Base * pB = new Derived(); //2 Base& rB = d; //3 b.foo(); //Base::foo pB->foo(); //Derived::foo rB.foo(); //Derived::foo } It's well known that only 2 & 3 works polymorphically while one is the infamous object slicing which produce nothing but a bug ! Note 1, 2 and 3 NEED is-a relationship to work. If you are using private/protect inheritance, you will get compile error for all of them : 'type cast' : conversion from 'Derived *' to 'const Base &' exists, but is inaccessible 'type cast' : conversion from 'Derived *' to 'Base *' exists, but is inaccessible 'type cast' : conversion from 'Derived *' to 'Base &' exists, but is inaccessible So my question(original intention) was to ask would it be better if c++ standard make 1 a compile error while keep allowing 2 and 3 ? Hope I have expressed my question better this time. Thanks A: How would you prevent object slicing within the language? If a function is expecting 16 bytes on the stack (as a parameter for example) and you pass a bigger object that's say 24 bytes how on Earth would the callee know what to do? C++ isn't like Java where everything is a reference under the hood. The short answer is that there's just no way to avoid object slicing assuming that C++, like C, allows value and reference semantics for objects. EDIT: Sometimes you don't care if the object slices and prohibiting it outright would possibly prevent a useful feature. A: Object slicing is a natural consequence of inheritance and substitutability, it is not limited to C++, and it was not introduced deliberately. Methods accepting a Base only see the variables present in Base. So do copy constructors and assignment operators. However they propagate the problem by making copies of this sliced object that may or may not be valid. This most often arises when you treat polymorphic objects as value types, involving the copy constructor or the assignment operator in the process, which are often compiler generated. Always use references or pointers (or pointer wrappers) when you work with polymorphic objects, never mix value semantics in the game. If you want copies of polymorphic objects, use a dynamic clone method instead. One half-solution is to check the typeid of both the source and the destination objects when assigning, throwing an exception if they do not match. Unfortunately this is not applicable to copy constructors, you can not tell the type of the object being constructed, it will report Base even for Derived. Another solution is to disallow copying and assigning, by inheriting privately from boost::noncopyable or making the copy constructor and assignment operator private. The former disallows the compiler generated copy constructor and assignment operator from working in all subclasses as well, but you can define custom ones in subclasses. Yet another solution is to make the copy constructor and assignment operator protected. This way you can still use them to ease the copying of subclasses, but an outsider can not accidentally slice an object this way. Personally I derive privately from my own NonCopyable, which is almost the same as the Boost one. Also, when declaring value types, I publicly and virtually derive them from Final<T> (and ValueType) to prevent any kind of polymorphism. Only in DEBUG mode though, since they increase the size of objects, and the static structure of the program doesn't change anyway in release mode. And I must repeat: object slicing can occur anywhere where you read the variables of Base and do something with them, be sure your code does not propagate it or behave incorrectly when this occurs. A: I think you're looking at it backwards. Nobody sat down and said "OK, we need slicing in this language." Slicing in itself isn't a language feature; it's the name of what happens when you meant to use objects polymorphically but instead went wrong and copied them. You might say that it's the name of a programmer bug. That objects can be copied "statically" is a fundamental feature of C++ and C, and you wouldn't be able to do much otherwise. Edit: [by Jerry Coffin (hopefully Tomalak will forgive my hijacking his answer a bit)]. Most of what I'm adding is along the same lines, but a bit more directly from the source. The one exception (as you'll see) is that, strangely enough, somebody did actually say "we need slicing in this language." Bjarne talks a bit about slicing in The Design and Evolution of C++ (§11.4.4). Among other things he says: I'm leery of slicing from a practical point of view, but I don't see any way of preventing it except by adding a very special rule. Also, at the time, I had an independent request for exactly these "slicing semantics" from Ravi Sethi who wanted it from a theoretical and pedagogical point of view: Unless you can assign an object of a derived class to an object of its public base class, then that would be the only point in C++ where a derived object can't be used in place of a base object. I'd note that Ravi Sethi is one of the authors of the dragon book (among many other things), so regardless of whether you agree with him, I think it's easy to understand where his opinion about language design would carry a fair amount of weight. A: It's allowed because of is-a relationship. When you publicly1 derive Derived from Base, you're annoucing to the compiler that Derived is a Base. Hence it should be allowed to do this: Base base = derived; and then use base as it is. that is: base.message(); //calls Base::message(); Read this: * *Is-A Relationship 1. If you privately derive Derived from Base, then it is has-a relationship. That is sort of composition. Read this and this. However, in your case, if you don't want slicing, then you can do this: Base & base = derived; base.message(); //calls Derived::message(); From your comment : Wouldn't it better for C++ to prevent object slicing while only allow the pointer/reference to work for is-a relationshp ??? No. Pointer and Reference doesn't maintain is-a relationship if the base has virtual function(s). Base *pBase = &derived; pBase->message(); //doesn't call Base::message(). //that indicates, pBase is not a pointer to object of Base type. When you want one object of one type to behave like an object of it's base type, then that is called is-a relationship. If you use pointer or reference of base type, then it will not call the Base::message(), which indicates, pointer or reference doesn't have like a pointer or reference to an object of base type. A: Exactly what access does the base object have to m_base? You can't do baseObj.m_base = x; It is a private member. You can only use public methods from the base class, so it is not much different to just creating a base object.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516545", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: how to convert date and time to timeago format in jquery I am trying to display facebook newsfeed and displaying them on mobile web app. It is working fine but the problem is that it does not display time in timeago format(i.e. 2 days ago) on mobile web browser, on the other hand it does display properly on desktop. The format of the date and time is 2011-09-13T11:28:19+0000. on mobile it displays NaN years ago. here is my code for timeago function timeAgo('2011-09-13T11:28:19+0000'); function timeAgo(date_time) { //to get unix timestamp var currentDate = Math.round(+new Date()/1000); var tweetDate = Math.round(+new Date(date_time)/1000); //alert(tweetDate); var diffTime = currentDate - tweetDate; //alert(diffTime); if (diffTime < 59) return 'less than a minute ago'; else if(diffTime > 59 && diffTime < 120) return 'about a minute ago'; else if(diffTime >= 121 && diffTime <= 3600) return (parseInt(diffTime / 60)).toString() + ' minutes ago'; else if(diffTime > 3600 && diffTime < 7200) return '1 hour ago'; else if(diffTime > 7200 && diffTime < 86400) return (parseInt(diffTime / 3600)).toString() + ' hours ago'; else if(diffTime > 86400 && diffTime < 172800) return '1 day ago'; else if(diffTime > 172800 && diffTime < 604800) return (parseInt(diffTime / 86400)).toString() + ' days ago'; else if(diffTime > 604800 && diffTime < 12089600) return '1 week ago'; else if(diffTime > 12089600 && diffTime < 2630880) return (parseInt(diffTime / 604800)).toString() + ' weeks ago'; else if(diffTime > 2630880 && diffTime < 5261760) return '1 month ago'; else if(diffTime > 5261760 && diffTime < 31570560) return (parseInt(diffTime / 2630880)).toString() + ' months ago'; else if(diffTime > 31570560 && diffTime < 63141120) return '1 year ago'; else return (parseInt(diffTime / 31570560)).toString() + ' years ago'; } How can I solve this problem? A: I had a similar problem and i fixed it using the following function. function relative_time(date_str) { if (!date_str) {return;} date_str = $.trim(date_str); date_str = date_str.replace(/\.\d\d\d+/,""); // remove the milliseconds date_str = date_str.replace(/-/,"/").replace(/-/,"/"); //substitute - with / date_str = date_str.replace(/T/," ").replace(/Z/," UTC"); //remove T and substitute Z with UTC date_str = date_str.replace(/([\+\-]\d\d)\:?(\d\d)/," $1$2"); // +08:00 -> +0800 var parsed_date = new Date(date_str); var relative_to = (arguments.length > 1) ? arguments[1] : new Date(); //defines relative to what ..default is now var delta = parseInt((relative_to.getTime()-parsed_date)/1000); delta=(delta<2)?2:delta; var r = ''; if (delta < 60) { r = delta + ' seconds ago'; } else if(delta < 120) { r = 'a minute ago'; } else if(delta < (45*60)) { r = (parseInt(delta / 60, 10)).toString() + ' minutes ago'; } else if(delta < (2*60*60)) { r = 'an hour ago'; } else if(delta < (24*60*60)) { r = '' + (parseInt(delta / 3600, 10)).toString() + ' hours ago'; } else if(delta < (48*60*60)) { r = 'a day ago'; } else { r = (parseInt(delta / 86400, 10)).toString() + ' days ago'; } return 'about ' + r; }; A: this will help you alot: someone already did it for you in a jquery plugin http://timeago.yarp.com/
{ "language": "en", "url": "https://stackoverflow.com/questions/7516548", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: SPListItem Save conflict while Update (1) var list1 = web.GetList("/lists/list1"); (2) var item1 = list1.GetItemById(10001); (3) ... take breakpoint here, open item with ID = 10001 for edit, change 'Title' fields and save it. Then run code follow: (4)item1[SPBuiltInFieldId.Title] = "some text"; (5)item1.Update(); row (5) throws save conflict exception. How can to lock item for edit at line (3)? Or any other approach to avoid conflict? A: You have to check the SPListItem manually try { var item = list.GetItemById(3); item["MyField"] = "FooBar"; item.Update(); } catch(SPException conflictEx) { // handle conflict by re-evaluating SPListItem var item = list.GetItemById(3); // .. } I don't know any other mechanism atm. A: // *create a new SPWeb object for each list modification otherwise we'll get Save Conflict* from the following URL http://platinumdogs.me/2010/01/21/sharepoint-calling-splist-update-causes-save-conflict-spexception/ exceptions using (var thisWeb = featSite.OpenWeb(featWeb.ID)) { try { var listUpdate = false; var theList = thisWeb.Lists[att.Value]; // change list configuration // ..... // commit List modifications if (listUpate) theList.Update(); } catch { // log the event and rethrow throw; } } } } A: Another approach is using Linq to SharePoint, Linq to SharePoint offers you a conflict resolution mechanism A: SharePoint's LINQ provider is querying for concurrent changes when you try to save changes you've made using the SubmitChanges method. When a conflict has been found, a ChangeConflictException will be thrown. foreach(var notebook in spSite.Notebooks) { notebook.IsTopNotebook = true; } try { spSite.SubmitChanges(ConflictMode.ContinueOnConflict); } catch(ChangeConflictException ex) { foreach(ObjectChangeConflict occ in spSite.ChangeConflicts) { if (((Notebook)occ.Object).Memory > 16) { foreach (MemberChangeConflict field in occ.MemberConflicts) { if (field.Member.Name == "IsTopNotebook") { field.Resolve(RefreshMode.KeepCurrentValues); } else { field.Resolve(RefreshMode.OverwriteCurrentValues); } } } else { occ.Resolve(RefreshMode.KeepCurrentValues); } } spSite.SubmitChanges(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7516553", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Multiple AVPlayers with AVPlayerLayers disappears second time push viewcontroller I have a viewcontroller with four (4) AVPlayers (with AVPlayerLayers like APPLE example). If I pop this viewcontroller and the push a new instance of the same type. I'm not able to play video in one or two AVPlayers. No errors and code runs fine, AVPlayerLayers also says it has a superLayer. And to the most strange thing if I push home button, coming back to springboard and the enter the app all video players like magic start playing. It's like it rerender the view tree or something. Any hints or clues? PS. I wait for assets to be ready using loadValuesAsynchronouslyForKeys. A: We had a similar problem. Following answer lead to the solution: AVplayer not showing in ScrollView after 2-3 times You have to call: [AVPlayer replaceCurrentItemWithPlayerItem:nil]; when your viewcontroller gets unloaded. This might be tricky as you might have added an observer or used addBoundaryTimeObserverForTimes:queue:usingBlock: Also you have to be careful when checking agaings superlayer: Better check against uiview.window when determing whether your view is still attached to the view hierarchy. yours phil
{ "language": "en", "url": "https://stackoverflow.com/questions/7516557", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Problem: Tabbar Controller + Navigation Controller: Programmatically Hello guys, I trying to make a app with tabbar controller and navigation controller. But i get some problems... When i try to popViewController on my second view, the app crash. Some one knows what's going on? My Delegate: // -- PranchetaAppDelegate.m - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.tabBarController = [[UITabBarController alloc] init]; NSMutableArray *localControllersArray = [[NSMutableArray alloc] initWithCapacity:1]; PlayersViewController* playersViewController = [[PlayersViewController alloc] initWithTabBar]; self.navigationController = [[UINavigationController alloc] initWithRootViewController:playersViewController]; [localControllersArray addObject:self.navigationController]; [self.navigationController release]; self.tabBarController.viewControllers = localControllersArray; [self.window addSubview:self.tabBarController.view]; [self.window makeKeyAndVisible]; [self.navigationController release]; [localControllersArray release]; return YES; } My First View: // -- PlayersViewsController.m - (id)initWithTabBar { if (self) { self.title = @"Players"; self.tabBarItem.image = [UIImage imageNamed:@"PlayersTabBarIcon.png"]; CustomNavigationBarButton *addButtonView = [[CustomNavigationBarButton alloc] initWithImage:@"AddButton.png" withSelected:@"AddButtonSelected.png"]; [addButtonView addTarget:self action:@selector(gotoCreatePlayers) forControlEvents:UIControlEventTouchUpInside]; UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithCustomView:addButtonView]; self.navigationItem.rightBarButtonItem = addButton; [addButton release]; [addButtonView release]; } return self; } - (void)gotoCreatePlayers { CreatePlayersViewController *createPlayer = [CreatePlayersViewController new]; [self.navigationController pushViewController:createPlayer animated:YES]; [createPlayer release]; } When i push my second view, i try to go back into the navigation. But the app crash... Error appointed: // -- main.m int main(int argc, char *argv[]) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; int retVal = UIApplicationMain(argc, argv, nil, nil); [pool release]; return retVal; } Thanks guys! A: try this: change: CreatePlayersViewController *createPlayer = [CreatePlayersViewController new]; to: CreatePlayersViewController *createPlayer = [CreatePlayersViewController alloc]; also if there are any init methods to call than it should look like this CreatePlayersViewController *createPlayer = [[CreatePlayersViewController alloc]init]; try somthing like this: ADD THIS TO THE .h FILE: CreatePlayersViewController *createPlayer then replace your code above with this: if (createPlayer ==nil) { CreatePlayersViewController *nextView = [[CreatePlayersViewController alloc] initWithStyle:UITableViewStylePlain]; self.createPlayer = nextView; [nextView release]; } self.meetTheTeam.view.hidden = NO; [self.navigationController pushViewController:self.meetTheTeam animated:YES];
{ "language": "en", "url": "https://stackoverflow.com/questions/7516558", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Padding on TableViewCell I want to add padding to my table view cells. Thought I could do something like this but that didnt work. -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath]; return cell.frame.size.height + 20; } A: See the below link. Explains the basics of getting a variable height (for cells) UITableView along with proper padding that your require. Example just includes text. Change it to suit your requirements within the cell. http://www.cimgf.com/2009/09/23/uitableviewcell-dynamic-height/ A: Are you sure you placed this method in your delegate? it also depends on which cells. There are other methods... // UITableViewDelegate Method - (CGFloat) tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section { } // UITableViewDelegate Method - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section { } also, if you are using the contentView of the cell then you will need to change the frame of your custom view A: When adding your cells you will need to set the y value of the cell's frame to half your padding to make it start at the right place. Also ensure that the cell does not have flexible height or it will expand to fill the height of the row.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516560", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to remote deploy the K2 package to K2 Server? I am working on a K2 project and use the TeamCity as Continuous Integration tool. I built a code to get the K2 project and create K2 deployment package, it is working fine. When I try to run the MSBuild to deploy the K2 deployment package to K2 server. msbuild "DeploymentPackage\Workflow.msbuild" /p:TestOnly=True /p:Environment=Development I got below error information: [SourceCode.DeploymentTasks.ExportProcessTask] Deploy Process: Task Error: Connection string has not been initialized. Connection to Host Server cannot be established. I run the MSBuild on K2 server is ok, I want to know how to run the MSBuild and deploy the K2 deployment package from other server (TeamCity Server)? how to setup the MSBuild parameter and which type user authority is required? A: I would check the Host value in your K2 connection strings for the target environment in the generated MSBuild file. For example: <Field Name="Workflow Management Server" Value="Integrated=True;IsPrimaryLogin=True;Authenticate=True;EncryptedPassword=False;Host=dlx;Port=5555" /> Keep in mind that is just one of many that may need to be changed. I hope this helps you. A: As an alternate solution You have to import K2 SourceCode Snapin in PowerShell, once imported you can call K2 deploy package command to install K2 package via PowerShell. You can configure Team City's build step to call PowerShell command which will install the K2 package. I hope this helps you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516563", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I hide the connect_widget_user_action class in like facebook button? I have a facebook like button in my web site in the home page. The code for it is: <div><iframe id="ifFacebook" src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.MYSITE.com%2F&amp;layout=standard&amp;show_faces=false&amp;width=450&amp;action=like&amp;colorscheme=light&amp;height=80;" scrolling="no" frameborder="0" style="margin-top:0px; overflow:hidden; width:250px; height:80px;" allowTransparency="true"></iframe></div> If I am not logged in Facebook, then I have the option to click the Like button. I click the button, I get the facebook pop up window for login, I login and then for some seconds I can see a text regarding my actions, which is fade out and replaced by "You and x others like this. Add Comment" I want to always hide the text about my actions, and don't make it visible even for seconds. I see that is is in the connect_widget_user_action class in facebook iframe. Does anyone know how can I disable this? Thanks A: You can't. Content loaded in an iframe is not accessible from the parent document for security reasons. Depending on the browser, it might allow access if both documents are served from the same domain, but that's not the case here. You could try using an older social plugin like the fan box which allowed to specify a CSS file and trim that down. I don't know if those still work. They might stop doing so at any time.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516568", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: preg_match_all question about number I have this line: preg_match_all("/<data_[0-9]>(.*?)<\/data_[0-9]>/",$xml_report,$xml); and for some reason he takes me only the 10 first rows 0 until 9 but he didn't take the 10+ rows.. what I need to change the [0-9] ? A: [0-9] selects only one occurrence of the numbers 0-9. Use [0-9]+ The + means one or more of the preceding element vs * or . which is zero or more. A: if you append + (plus) after ] it'll find for multiple occurences preg_match_all("/<data_[0-9]+>(.*?)<\/data_[0-9]+>/",$xml_report,$xml); A: You only check for one occurence of the number, try this: preg_match_all("/<data_[0-9]+>(.*?)<\/data_[0-9]+>/",$xml_report,$xml);
{ "language": "en", "url": "https://stackoverflow.com/questions/7516572", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C# unsafe context / pointer type of LPWStr suppose we have an unsafe context, because I want to have a pointer to a wchar_t parameter which is passed from a unmanaged C++ code. For example: unsafe public(int* A, ???* B) { _myInt = A; _myString = B; } Everything is fine with the int parameter, but what about the ???* type? I know that to marshal a wchar_t to a C# string type for this method, one can write [MarshalAs(UnmanagedType.LPWStr)] before the parameter B. But I need some kind of a native pointer type for B in order to link this pointer to _myString field. Is there something like wchar_t in C# or what else can I do to have the pointer B stored elsewhere in the class? Thanks, Jurgen A: Unless you have a problem with c# copying the string behind the pointer during the construction of a string... you can pull it off like this: public static unsafe int Strlen(char* start) { var eos = start; while (*(eos++) != 0); return (int) ((eos - start) - 1); } unsafe public(int* A, char* B) { _myInt = A; _myString = new String(B, 0, Strlen(B)); } The constructor used here is documented in MSDN
{ "language": "en", "url": "https://stackoverflow.com/questions/7516577", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: is Location.X equal to Top,Left in a ListBox? I am confused a little bit: with a code like this: lets assume the list box is inside a panel and panel is inside a tableLayout and,etc... Point myLocation = PointToClient(myListBox.Location); so it returns a Point.X and Point.Y, but what are these X and Y ? are they X and Y of the Top,Left corner of my list box according to the whole form? A: Yes, Location.X = Left and Location.Y = Top. Left and Top are just shortcuts provided for convenience. A: Your call to PointToClient is incorrect. PointToClient takes a point in screen coordinates and converts them to coordinates relative to the control you are calling PointToClient on. myListBox.Location is returning client coordinates relative to its container, not screen coordinates. If you are looking to convert to screen coordinates, look at using PointToScreen().
{ "language": "en", "url": "https://stackoverflow.com/questions/7516579", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: python -- trying to change the contents of a file i have a file named "hello.txt" which has the content "Hello,there!". I want to remove the "," and "!" and then print the new content. With the code i made ,the program runs without errors but ,it erases all the contents and leaves an empty file. def myfunc(filename): filename=open('hello.txt','r') lines=filename.readlines() filename.close() filename=open('hello.txt','w') for line in lines: for punc in ".!": line=line.replace(punc,"") filename.close() myfunc("hello") Please,don't use high level commands. Thanks! A: you should print the modified content line by line, not only at the end. for line in lines: for punc in ",!": # note that we're assigning to line again # because we're executing this once for # each character line=line.replace(punc,"") # write the transformed line back to the file once ALL characters are replaced # # note that line still contains the newline character at the end # python 3 # print(line,end="") # python 2.x print >> filename, line, # python 2.x alternative # filename.write(line) By the way, naming a file handle filename is confusing. A: You're changing lines in your program but not writing to the file. After making changes in lines, try filename.writelines(lines). A: You can use the regex module. It's easy to make substitutions: import re out = re.sub('[\.!]', '', open(filename).read()) open(filename, 'w').write(out)
{ "language": "en", "url": "https://stackoverflow.com/questions/7516580", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Coming from XNA, what is Corona's 'Update' mechanism (GameTime, gameTime)? I'm trying to get the hang of Corona SDK, I don't know much about the Lua language as I'm coming from a C# and XNA background. The question I have is I want to do some acceleration on an object when a touch arrow is touched on the screen. In XNA your variable changes and the code for it would be done in the Update section, but I'm not entirely sure how to do it in Corona. At the moment the arrow just moves at a constant speed with this code. function button:touch() motiony = -speed end button:addEventListener("touch", button) Any help or pointers in the right direction would be appreciated. A: Make a variable to store acceleration. When you touch the button, change the acceleration value, and apply it to the object's speed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516585", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: TSQL Sort Order Based On Order In The In Clasuse The scenario is first run an expensive sorted query and save the first 100,000 Primary Key (Int32) in a .NET List. Then retrieve detail 100 rows at a time from about a dozen tables. The format of of the detail query is: select ... from DetailA where PK in (sorted list of 100 PK). The problem is the return is not sorted by the order in the in clause. Need the detail to be sorted. Don't want apply the sort that was used to create 100,000 master list as that is an expensive and messy sort. My thought is to load the 100 PK into #tempSort table and use that for the sort. Is there a better approach? Currently getting the detail one row at a time using SQLDataReader and that takes about 2 seconds. Tested getting all at once using a DataSet with multiple DataTables and that was slower than one row at a time using a SQLDataReader by a factor of 3. This data is being loaded into objects so need for advanced features of a DataSet. I do not want to save the 100,000 master results in a #temp as this is a big active database and need to move load to the client. Trying the Table-Value Parameters as suggested. Is this the proper syntax? CREATE TYPE sID100 AS TABLE ( sID INT, sortOrder INT ); GO /* Declare a variable that references the type. */ DECLARE @sID100 AS sID100; /* Add data to the table variable. */ INSERT INTO @sID100 (sID, sortOrder) values (100, 1), (200,2), (50,3); Select * from @sID100; select docSVsys.sID, docSVsys.addDate from docSVsys join @sID100 as [sID100] on [sID100].sID = docSVsys.sID order by [sID100].sortOrder GO Drop TYPE sID100 Above is not optimal. I am learning but in C# can create a DataTable and pass it to a stored procedure using Tabel-Value Parameters. Exactly what Martin said in the comment but it took some research before I understood his words. A: The order of the PKs in the IN clause is irrelevant. Only the outermost ORDER BY matters: any order is arbitrary if not specified select ... from DetailA where PK in (sorted list of 100 PK) ORDER BY PK From MSDN ORDER BY When ORDER BY is used in the definition of a view, inline function, derived table, or subquery, the clause is used only to determine the rows returned by the TOP clause. The ORDER BY clause does not guarantee ordered results when these constructs are queried, unless ORDER BY is also specified in the query itself. Edit, after feedback and including Martin Smith's idea select ... from DetailA A JOIN TVPorTemptable T ON A.PK = T.PK ORDER BY T.OrderByCOlumn
{ "language": "en", "url": "https://stackoverflow.com/questions/7516589", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is Facebook Connect with the new JS SDK the way to go for an "App on Facebook"? Now that FBML is being deprecated, it seems to me that the new JS SDK and FB Connect will be sufficient to have an iframe app on FB. Is this understanding correct? Previous answers to this question were based on FBML that still was supported back then Facebook App vs. Facebook Connect site For example all the old invite FBMLs can be replaced now with dialogs based on FB Connect JS as described here http://developers.facebook.com/docs/reference/dialogs/ A: Right now You should choose between the JS and PHP SDK or a combination of both depending on what you are building. We usually work with the PHP SDK for Authentication and use JS for Feed Dialgos (posting to the wall for example). If you need a couple of starting points Thinkdiff.net has two great post with downloadable source and demo that might help you decide what works better for your project. Here is the JS Example: http://thinkdiff.net/facebook/new-javascript-sdk-oauth-2-0-based-fbconnect-tutorial/ Here is the PHP Example: http://thinkdiff.net/facebook/php-sdk-3-0-graph-api-base-facebook-connect-tutorial/ A: Facebook Connect applies to web sites outside of Facebook, not to canvas or tab apps. Usually, you will need to use the JavaScript and PHP SDKs, or something else for your preferred PHP alternative.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516591", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Access SQL ignore warning about type conversion I want to insert some values from a table to another in a sql query. But My tables don't have the same format in the fields, for instance I ask to transfert a text to a numeric. It asks me whether or not I want to change the fields type inside my destination table. I don't want this warning box to appear, I want it to automatically convert the type without asking the user. Most of all, I don't want to change the SQL Query to include cdbl() , IsNumeric() or other stuffs My code looks like strSQL = "Delete * FROM DestinationTable;" DoCmd.RunSQL strSQL strSQL = "INSERT INTO DestinatonTable(Month, Date, Number1, Name, ShortName, Partner, Number2 .... and so on .....)" strSQL = strSQL & " SELECT StartTable.F1, StartTable.F2, StartTable.F3, ...... and so on ..." strSQL = strSQL & " FROM StartTable WHERE (IsNumeric([F14])<>0);" DoCmd.RunSQL strSQL Thank you all for reading and help A: You could try turning warnings off before you run the query DoCmd.SetWarnings False ' do stuff here DoCmd.SetWarnings True
{ "language": "en", "url": "https://stackoverflow.com/questions/7516601", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using shell script parameters with colons in awk I have a file which contains rows having this format: 2011/09/14 12:00:23.525 text I wrote a shell script which searches for a given expression in text and sorts all the matching rows by day and time. At the end, I would like to discard the entries referring to an instant which is older than that passed as parameter. I use awk to make this kind of filtering. The script looks like this: search=$1 file=$2 day=$3 time=$4 zgrep -h "$search" $file | sort -k1,1 -k2,2 | awk -v da="$day" ti="$time" '($1 >= day) && ($2>= ti) {print $0}' > out.$$ If I invoke: myScript searchThis file1.txt 2011/09/20 09:16:52.130 I get this error: awk: ti=09:16:52.130 awk: ^ syntax error Can you please help me to solve this? Thanks a lot! Bye A: can you wrap the para value in "? I tested this under bash and zsh, both worked: kent$ cat a 2011/09/20 09:16:52.130 2011/08/20 10:16:52.130 2011/07/20 05:16:52.130 kent$ d="2011/08/30 00:23:23" #here used ".." to wrap the date and time kent$ awk -v d="$d" '$0>d' a 2011/09/20 09:16:52.130 don't know if it helps... A: Kent's answer didn't work for me. I'm using GNU Awk 4.1.3 in cygwin. I eventually found this awk: passing variables from bash where dubiousjim mentioned that you can specify the variable value after the action. It won't be available in the BEGIN rule but that was fine for my case. So you can change your script to something like: search=$1 file=$2 day=$3 time=$4 zgrep -h "$search" $file | sort -k1,1 -k2,2 | awk '($1 >= day) && ($2>= ti) {print $0}' da="$day" ti="$time" > out.$$
{ "language": "en", "url": "https://stackoverflow.com/questions/7516602", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Use COM interface without statically linking to library This may be a bit of a newbie question, but I just don't know! To use a function in a DLL that might not be present on the system I can use LoadLibrary and then GetProcAddress. But how can I do the same thing for a COM interface? I can include the header file for the declarations, IID's, and so on.. but I don't want to link against the accompanying library using #pragma comment(lib, "blabla.lib"). (I'm trying to use the WICImagingFactory interface, and that requires linking against windowscodecs.lib to compile) Thanks A: There's no need to fight against linking windowscodecs.lib. Linking against it doesn't result in implicit linking as you would get for a non-COM library. You still need to call CoCreateInstance() just as you would for any COM object. Think of this as being runtime binding equivalent to GetProcAddress.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516609", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Rails select_tag problem in show and index actions I have a select_tag to pick items from a list here's the code: <%= select_tag "Drinks", options_for_select([ "Water", "Soda", "Beer" ], "Water") %> After submiting "water" for exemple, it doesn't show up on the index and show views, on the "Drinks" section. What am I doing wrong? Controllers create and update methods def create @facture = Facture.new(params[:facture]) respond_to do |format| if @facture.save format.html { redirect_to @facture, :notice => 'Facture was successfully created.' } format.json { render :json => @facture, :status => :created, :location => @facture } else format.html { render :action => "new" } format.json { render :json => @facture.errors, :status => :unprocessable_entity } end end end def update @facture = Facture.find(params[:id]) respond_to do |format| if @facture.update_attributes(params[:facture]) format.html { redirect_to @facture, :notice => 'Facture was successfully updated.' } format.json { head :ok } else format.html { render :action => "edit" } format.json { render :json => @facture.errors, :status => :unprocessable_entity } end end end A: You should use this: select_tag "facture[drinks]", options_for_select([ "Water", "Soda", "Beer" ], "Water") The create method is using the values sent in params[:facture] and using "facture[drinks]" will include it as params[:facture][:drinks]. A: Here's how I proceed(thanks to miligraf): 1- let the code in controllers/factures intact 2- change the code in views/factures/_form.html.erb: before <%= select_tag "facture", options_for_select([ "Water", "Soda", "Beer" ], "Water") %> after <%= select_tag "facture[drinks]", options_for_select([ "Water", "Soda", "Beer" ], "Water") %>
{ "language": "en", "url": "https://stackoverflow.com/questions/7516610", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Map on Scalaz Validation failure import scalaz._ import Scalaz._ "abc".parseInt This will return a Validation[NumberFormatException, Int]. Is there a way I can apply a function on the failure side (such as toString) to get a Validation[String, Int]? A: There is a pair of methods <-: and :-> defined on MAB[M[_,_], A, B] that map on the left and right side of any M[A, B] as long as there is a Bifunctor[M]. Validation happens to be a bifunctor, so you can do this: ((_:NumberFormatException).toString) <-: "123".parseInt Scala's type inference generally flows from left to right, so this is actually shorter: "123".parseInt.<-:(_.toString) And requires less annotation. A: There is a functor on FailProjection. So you could do v.fail.map(f).validation (fail to type as FailProjection, validation to get out of it) Alternatively v.fold(f(_).failure, _.success) Both a bit verbose. Maybe someone more familiar with scalaz can come up with something better
{ "language": "en", "url": "https://stackoverflow.com/questions/7516613", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "18" }
Q: Android Webview Image Render to Center rather than top-left corner The image render in webview starts from the top-left corner of my image which is larger than webview so its scrollable. I'd like to center the image rather than it rendering to top-left corner...is there any way to do this? A: Instead of calling myWebView.loadUrl, you can use plain CSS and call myWebView.loadData instead. Just make sure to URL Encode any extraneous characters. Example: myWebView.loadData("<html><head><style type='text/css'>body{margin:auto auto;text-align:center;} img{width:100%25;} </style></head><body><img src='www.mysite.com/myimg.jpeg'/></body></html>" ,"text/html", "UTF-8");
{ "language": "en", "url": "https://stackoverflow.com/questions/7516623", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How can I disableDefaultUI in Google Maps API v2? I have a script that renders a Google maps and uses the API v2. I am trying to disable the Zoom functions/map type/etc but I can't seem to figure out where to instert disableDefaultUI function initialize() { if (GBrowserIsCompatible()) { map = new GMap2(document.getElementById("map")); map.addControl(new GLargeMapControl()); map.addControl(new GMapTypeControl()); map.setCenter(new GLatLng(37.4419, -122.1419), 14); map.enableScrollWheelZoom(); geocoder = new GClientGeocoder(); GEvent.addListener(map, "click", clicked); } } A: Just remove these two lines: map.addControl(new GLargeMapControl()); map.addControl(new GMapTypeControl());
{ "language": "en", "url": "https://stackoverflow.com/questions/7516626", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Cannot find -lsrc (gcc compilation failure) I am trying to build a C++ project in Netbeans and in the output console I am having the below compilation error that results from a missing file named -lsrc (marked with ###) I am using Suse Linux (SLED 11) and does anyone know what package I should download in the package installer so that I can overcome this gcc compilation issue? g++ -o dist/Debug/GNU-Linux-x86/cppthriftserverv1 build/Debug/GNU-Linux-x86/_ext/1338215927/test_types.o -lsrc #### HERE #### /usr/lib/gcc/i586-suse-linux/4.3/../../../../i586-suse-linux/bin/ld: cannot find -lsrc collect2: ld returned 1 exit status #### HERE ##### gmake[2]: *** [dist/Debug/GNU-Linux-x86/cppthriftserverv1] Error 1 gmake[2]: Leaving directory `/home/TRYOUT/THRIFT/CPPSERVER/CPPServerProject/CPPThriftServerV1' gmake[1]: *** [.build-conf] Error 2 gmake[1]: Leaving directory `/home/TRYOUT/THRIFT/CPPSERVER/CPPServerProject/CPPThriftServerV1' gmake: *** [.build-impl] Error 2 BUILD FAILED (exit value 2, total time: 614ms) A: I think the IDE tries to link against some library in the src folder of your project. Do you include a library in the source code? You can creating a Makefile so you can try compiling from the console and see the errors from the compiler.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516628", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Merge git branch without moving branch pointer I'm looking for a solution to apply a feature branch to the development branch in git without actually moving the branch pointer. Essentially, I'd like to create a single commit off of the feature branch and make sure it's pointing at the originating branch somehow (mention in the log might be enough). I know that stacked git should offer something like that, although that would introduce new commands to the standard workflow which I'd rather avoid. What I'm trying to achieve is some sort of feature management which allows us to apply / remove whole features, while keeping the visibility of the patch branch itself. If I do merge the branch, most commands trying to diff the change will not do what I want because the branch is already merged into develop. I cannot really follow the upstream - sometimes there are concurrent changes which are easier to correct by getting new tag and reapplying only needed features, rather than resolving conflicts and reverting redundant features - so this way of work is not possible. On the other hand I do want to see the change, so that I can either rework it to match new version, or submit upstream at a later time. A: Actually, there is an easier method. The git merge command has an option --squash, which just accumulates all the changes from the branch to be merged, and adds them to the staging area. So, you can do what you want with the following commands (when you are on master, and want to merge feature branch feature-foobar): $ git merge --squash feature-foobar $ git commit -m "Implemented feature: foobar" A: To what I understand, you may use git rebase -i to achieve your goal. Below is the scenario you want to achieve... A--B--C(develop) \ \D--E--F(feature) you can combine D-E-F as a single commit named as G the final outcome will be A--B--C--G(develop) \ \D--E--F(feature) G is a single commit that have all the things in D-E-F, and you can easily take it off from the develop branch. So in order to process this surgery, you can do.... git checkout feature_branch make a temp branch... git checkout -b temp git rebase -i develop_branch and interactive editor will be prompted out... mark commit D and E as squash, retain the last line(commit) as your last single commit save and quit then a commit G will rebase on to your developement branch. A--B--C(develop)--G(temp) \ \D--E--F(feature) Reset your development onto commit G and delete temp branch if you want. git checkout develop_branch git reset --hard <shaSum of commit G> git -D temp That's it!
{ "language": "en", "url": "https://stackoverflow.com/questions/7516632", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Knockout.js Templates Foreach - force complete re-render By default, KO "will only render the template for the new item and will insert it into the existing DOM". Is there a way to disable this feature (as in, force KO to render all items anew)? A: If you use jQuery.tmpl's native {{each koObservableArray()}} syntax Knockout cant update single items but must rerender the entire template see more here: http://knockoutjs.com/documentation/template-binding.html the template engine’s native ‘each’ support: after any change, the template engine is forced to re-render everything because it isn’t aware of KO’s dependency tracking mechanism. You only get the "default" behavior if you use the foreach template mode, i.e.: <div data-bind='template: { name: "personTemplate", foreach: someObservableArrayOfPeople }'> </div> A: I came across a similar problem today and was able to solve it for my team's issue by replacing the template with a custom binding that first clears all ko data and empties the container before rendering. http://jsfiddle.net/igmcdowell/b7XQL/6/ I used a containerless template like so: <ul data-bind="alwaysRerenderForEach: { name: 'itemTmpl', foreach: items }"></ul> and the custom binding alwaysRerenderForEach: ko.bindingHandlers.alwaysRerenderForEach = { init: function(element, valueAccessor) { return ko.bindingHandlers.template.init(element, valueAccessor); }, update: function(element, valueAccessor, allBindings, viewModel, context) { valueAccessor().foreach(); // touch the observable to register dependency ko.utils.domData.clear(element); // This will cause knockout to "forget" that it knew anything about the items involved in the binding. ko.utils.emptyDomNode(element); //Because knockout has no memory of this element, it won't know to clear out the old stuff. return ko.renderTemplateForEach(valueAccessor().name, valueAccessor().foreach, {}, element, context); } }; Obviously a little late as an answer to your query, but may help others who hit this off a search (as I did).
{ "language": "en", "url": "https://stackoverflow.com/questions/7516636", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: VB .Net Windows Service Console Messages I have a .Net Console application which displays thousands of lines on the console each minute. I want to convert it to a Windows Service, however I still need a way of viewing these messages. There are far too many messages to write them to the event log or even a standard log file. I was wondering if there were a way to write a systray app that could simply intercept these messages from the service and display them in a console window. I have no need to save older messages, I only need to see current activity. A: The service will need to write to shared memory of some sort in order to communicate with another program that displays the output. I think your best bet is to output to a SQL table or something and clear out older entries so there is never more than, say, 1000 records in the table at a time. Then ping the table a couple times a second in the viewer app and display a streaming view of the output. A: Sounds like the System.Diagnostics.Trace type would be perfect for this. Implement your changes in two phases: For phase 1, you add a ConsoleTraceListener to your app, and convert all of your current calls to Console to write to Trace instead. This will only maintain your existing behavior, but it sets you up to easily make the change to your new output. For phase 2, you implement a new TraceListener you can attach instead of the ConsoleTraceListener that does whatever you want with the messages. This might include listening for a connection from your proposed systray or console app. Even better, I bet a bit of googling will show you a TraceListener that already does what you want. As for the actual mechanism for communicating the message, my recommendation is to use the standard SysLog approach. This has the advantages of working existing software for the client, makes it more likely you'll find an existing TraceListener, and many of the existing syslog clients will bring along some automated data mining as a bonus.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516638", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: adjusting width of google plus 1 button I am trying to figure out how to modify the width of the Google plus 1 button... In the documentation it says you can set a width. Currently, when I examine the element using Firebug... it says the width is set to 90px, which I would like to set to 70px... is that possible? <!-- Place this tag where you want the +1 button to render --> <g:plusone size="medium"></g:plusone> <!-- Place this render call where appropriate --> <script type="text/javascript"> (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })(); </script> A: You can pick from a couple of height settings at the code generator, but you can't pick an arbitrary size value. A: The ID isn't always the same if you are using more than one button, so you can use this bit of CSS to catch multiple buttons: [id^=___plusone] { width:72px !important; } Which applies to all elements that have an Id that starts with ___plusone, which seems to be Google's namespace for the button A: Don't know if the iframe id is always the same but if it is you can use css + !important to override the element style. Something like: /* this overrides 90px to 72px width to +1 button */ #___plusone_0{ width:72px !important; } Hope it helps. A: I was frustrated by the buttons not all being the same size as well so I managed through css + javascript to get a 32x32 +1 button working. You can get the details here: http://bashireghbali.com/technology/google-plus-one-button-32x32/ note that on page reload it will not show +1ed state (no callback for that yet unless someone knows of a yet unannounced one) A: I found that if you're not trying to change the width of the physical button, but just trying to make the width smaller to adjust positioning. The best way is to set: #id_of_button { position: relative; left: (whatever works best)px } Hope that helps. A: The answer here are getting old so I wanted to drop a note on the possibility to align right the content of the google plus one button. So if like me you are trying to force width to whatever size to align on right forget it and use align="right" instead! <g:plusone align="right" size="medium"></g:plusone> More info here: https://developers.google.com/+/web/+1button/
{ "language": "en", "url": "https://stackoverflow.com/questions/7516647", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: Method and Constructor> both inherit from Member, both having a getExceptionTypes() method. How to avoid code duplication in this scenario? I have both these methods in my code base, which I'd like to merge in some way to avoid code duplication: protected IJavaType[] getExceptionTypes(Method method) { Class<?>[] declaredExceptions = method.getExceptionTypes(); IJavaType[] exceptions = new IJavaType[declaredExceptions.length]; for (int i = 0; i < declaredExceptions.length; i++) { exceptions[i] = getType(declaredExceptions[i]); } return exceptions; } protected IJavaType[] getExceptionTypes(Constructor<?> c) { Class<?>[] declaredExceptions = c.getExceptionTypes(); IJavaType[] exceptions = new IJavaType[declaredExceptions.length]; for (int i = 0; i < declaredExceptions.length; i++) { exceptions[i] = getType(declaredExceptions[i]); } return exceptions; } Is there any way to factor out the code repetition (other than using subclassing with template pattern)? A: How about simply: private IJavaType[] getExceptionTypes(Class<?>[] declaredExceptions) { IJavaType[] exceptions = new IJavaType[declaredExceptions.length]; for (int i = 0; i < declaredExceptions.length; i++) { exceptions[i] = getType(declaredExceptions[i]); } return exceptions; } protected IJavaType[] getExceptionTypes(Method method) { return getExceptionTypes(method.getExceptionTypes()); } protected IJavaType[] getExceptionTypes(Constructor<?> c) { return getExceptionTypes(c.getExceptionTypes()); } A: Well you can extract most of it fairly easily: protected IJavaType[] getExceptionTypes(Method method) { return getExceptionTypesImpl(method.getExceptionTypes()); } protected IJavaType[] getExceptionTypes(Constructor<?> c) { return getExceptionTypesImpl(c.getExceptionTypes()); } private void getExceptionTypesImpl(Class<?>[] declaredExceptions) { IJavaType[] exceptions = new IJavaType[declaredExceptions.length]; for (int i = 0; i < declaredExceptions.length; i++) { exceptions[i] = getType(declaredExceptions[i]); } return exceptions; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7516650", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to separate the first string before @";" in an Array? I'd like to split a string in an array: NSString *test = @"How are you;<random>[Good;Bad]"; NSArray *howareyou = [test componentsSeparatedByString:@";"] But then it splits <random>[Good and Bad]... I just want to split the How are you and <random>[Good;Bad] How can I do this?? A: NSString *test = @"How are you;<random>[Good;Bad]"; NSRange colonRange = [test rangeOfString:@";"]; if (colonRange.location != NSNotFound){ NSString *firstHalf = [test substringToIndex:colonRange.location]; NSString *secondHalf = [test substringFromIndex:NSMaxRange(colonRange)]; NSLog(@"%@ - %@", firstHalf, secondHalf); }else{ NSLog(@"No luck"); } A: NSString *test = @"How are you;<random>[Good;Bad]"; NSArray *howareyou = [test componentsSeparatedByString:@";"]; NSString *desired = [howareyou objectAtIndex:0]; NSString *rest = [[howareyou subarrayWithRange:NSMakeRange(1, [howareyou count]-1)] componentsJoinedByString:@";"]; Doesn't get much less efficient (or brittle -- no error checking, range checking, length checking, etc...) than that. Perfectly fine for a few strings here and there of limited length, probably unacceptable for large input and the like. Measure first. Optimize after.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516651", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Can not enable "Continuously Updates Value" in NSTextView attributedString binding In Xcode 3 Interface Builder, when I check "Continuously Updates Value" in NSTextView attributedString binding, the checkbox is automatically unchecked. Can "Continuously Updates Value" be enabled ? If so, what may cause this problem ? A: Had the same problem. I deleted the NSTextView and created a new one. Now I could enable the "Continuously Updates Value"
{ "language": "en", "url": "https://stackoverflow.com/questions/7516658", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to structure a table for fast search on a large number of columns I have a table with a large number of columns (~60), which will eventually have a large number of rows (~10 000), and I'm going to need to be able to search efficiently on several column values at once. I'm not sure whether the searches will be exact-match (LIKE 'value', and not LIKE '%value%'), although LIKE 'value%' might be an acceptable compromise. A few solutions have been proposed. I'm not very familiar with database design principles, so it's not obvious to me which is the best: * *Index on every column individually. The users will be able to search on any combination of columns, so no more complicated indexes will work. There will be a lot more reads than writes on the database, so the write-speed slowdown shouldn't be a problem. *Make another table just for searching that looks like this: obj_id col_num col_name col_value ------------------------------------- 1 1 'name' 'joe' 1 2 'job' 'engineer' 2 1 'name' 'bill' etc. I think the col_num and col_name columns are redundant, but presumably one is better than another. I have no idea what this is called, although it sounds like the Entity-Attribute-Value model (see also this question). From what I can tell, the main difference from an EAV model is that this table would not be sparse; all entities will have most or all attributes. *Make another table for an inverted index on the first table. I know how to do this in theory, but it would be a huge amount of work. Also, we'd probably lose information about which column each datum is from, which is not great. Also also, this feels like it would be redundant with solution 1, but I don't actually know how table indexes are created. Those are the solutions that we have come up with so far. If it's relevant, we're using an Oracle db, which is not really optional, but I have the permissions to refactor the database in any way necessary. So, what is the best solution here? "None of the above" is a totally acceptable answer, of course. None of these tables actually exist yet, so there's nothing to wipe out and remake. Thanks! A: How about using Oracle's fulltext search features? Your needs seem to fit the purpose for CTXCAT. See Indexing with Oracle Text for an overview of the different fulltext indexing options in Oracle. A: The examples you mention are indeed a better match for full text searching (as Bill Karwin suggests). Without seeing a (draft) table definition, it's hard to see if that's actually the case. The good news is that 10K records is a trivial amount for a well-tuned Oracle server. If that's the largest your table will grow, I would avoid any exotic solutions in favour of maintainability. EAV basically makes boolean operators into a huge pain in the backside, and makes supporting specific datatypes (text, dates, numbers etc.) into an equally big pain. I'd build a sample of your table with your best guess at the indexing scheme, populate it with representative dummy data, and run queries along the lines of the ones you expect to need. Measure performance, and see if you have a problem; optimize your indices and queries, and only go to a refactoring if you really need to.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516659", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Confusion about C# Namespace Structure I am little confused about the structure of Namespace in C# I'm new to C# and WPF When i create a new project of WPF, by default these Namespaces are included at the top using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; I'm confused understanding the structures of these. I understand that using System; Means that im referring to System namespace But what about the others like using System.Text; What that means? * *I'm accessing a single namespace named as "System.Text" ? *or I'm accessing "Text" namespace nested inside "System" namespace ? Also if "Text" is nested inside "System" why only "using System" includes all the namespaces ? should we have to explicitly include every namespace we use ? A: Namespaces are, by and large, not hierarchical in their meaning to the computer. The types under System.Text (e.g. System.Text.StringBuilder) are not considered to be in System - so you'd need to list them separately if you wanted types from both: using System; using System.Text; The only time when they're considered as a hierarchy as far as the compiler is concerned - that I can think of, anyway - is when it comes to the namespace you declare something in: namespace Foo.Bar.Baz { class Test { } } Within Test, it's as if you've imported Foo, Foo.Bar and Foo.Bar.Baz. Now of course namespaces do form hierarchies from a human understanding point of view - the make it easy to find things. But the compiler and runtime don't use that hierarchical view of things, by and large. A: Does using System.Text; mean that I'm using a single namespace named as "System.Text" or that I'm using the "Text" namespace nested inside "System" namespace? The latter. You are using the "Text" namespace that is nested inside the "System" namespace. Note that when you say namespace Foo.Bar.Blah { class C { ... That is just a short form way of writing namespace Foo { namespace Bar { namespace Blah { class C { ... Namespaces only have "simple" names. should we have an explicit 'using' directive for every namespace we use? Typically you do, yes. There are some situations in which you might want to not do so. For example, if you have two namespaces that both contain a type of the same name and you want to use types from both namespaces; in that case it might be too confusing to have a "using" of two namespaces. Also, "using" brings extension methods into play; if there are extension methods that you do not want to bind to, do not include the namespace that contains them. if "Text" is nested inside "System" why only "using System" includes all the namespaces? I do not understand the question the way it is worded. I think maybe you are asking: Why does using System; not make the simple name Text resolve to the nested namespace? That is, why does this not work: namespace Foo { namespace Bar { class Blah {} } } In a different file: using Foo; class Abc : Bar.Blah {} The using Foo; only includes the types declared directly inside Foo. It does not bring in namespaces declared directly inside Foo. The designers of C# thought that it was too confusing to bring namespaces "into scope" like this; typically people use using directives to bring types "into scope". A: should we have to explicitly include every namespace we use ? Yes, or fully qualify the type-names. The 2 namespace usings using System; using System.Text; are totally independent. Their names suggest a relation but from outside those namespaces that can be considered symbolical. You cannot use members of System.Text when you only have the first using. And you don't need the first in order to use the second. Only when you write code that belongs to a nested namespace you see some effect. namesapce A { namespace B { class Foo { } } namespace C { class Bar { private B.Foo f; } // B is a 'relative' ns } } A: using System.Text imports all declarations inside System.Text, but nothing in its folders. There's no System.Text.* equivalent like in Java like in an imaginary language. An easy way to deal with namespaces is to just write your code normally and CTRL+. over undefined keywords to tell VS.NET to automatically add the using reference for you. A: You are accessing the Text Namespace nested inside the System Namespace. And yes, you need to include every namespace you use. A namespace structure can look something like the following: namespace Parent { namespace Child { public class ChildClass { } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7516661", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How to design a db that has many 2 many relationship It's been a long time since I designed a database and just want to make sure that I am designing it properly. I have an Entity which has a name and description. This Entity can have many subEntities which are of type Entity. So its like a recursive relationship. Now sure how to design the db properly. Do I create a second table or what? Update: One entity can only have a single parent entity or no parents. A: In a relational database, you'd use a join table, end of story. entity ====== id name description xref_entity_subentities ======================= parent_entity_id (FK references entity) child_entity_id (FK references entity) I can't speak to Core Data. A: For a Many-to-Many relationship you'll want an intersection table to delegate the relationships between itself For Example, Entities OtherEntities -------- ------------- ID ----> EntityID1 Name <---- EntityID2 Descrip A: For relational databases: Your entity should not have a sub-entity which is another entity (or the db wont be in normal form) it can contain a relationship (depending on your needs either one-to-one, one-to-many, many-to-many) to the same table/entity. A: Edit: Based on the update to the question, my suggested solution is in bold, below: First, let's be clear whether this is really a many-to-many situation because it's not clear from your description whether that's true or not. You describe a tree structure in which an entity can have "nested" entities and, presumably, those nested entities can each have their own nested entities. But this is only a many-to-many question if a single entity can belong, simultaneously to multiple parents. In either case, you will store all the entities in a single table. If you want to represent a "simple" tree of nested entities without multiple-parentage then you can add a parent_entity_id column to the entities table which points to the entity_id of the parent. Top level entities would have either a flag value (for instance, -1) or a NULL in this column. In this case, you need only one more column and no new tables to represent the relationship. If it's really a many-to-many relationship with multiple-parentage then you will create a new table entity_links with columns parent_entity_id and child_entity_id. You manage the relationships by inserting and deleting rows in this table.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516663", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Home automation in C#? I want to develop a small C# application to control various components of a central heating. First, I would like to be able to retrieve values ​​from a temperature sensor. I must not be the first C# developer looking to get this kind of stuff. I would then try to control thermostatic valves. Microsoft or others vendors delivers GUI libraries, Mathematics libraries, database access libraries, ... I'm just looking for a Home Automation Library or something similar. Could you redirect me to the hardware components compatible or information sites on the subject. Thank you, A: Microsoft released a microcontroller that is programmable in .NET about a month ago. It is called Gadgeteer A: I'm a little late to the party, but these guys have been doing some interesting work. I downloaded the source and poked around a bit, and have chatted on their site: http://www.opensourceautomation.com/ A lot of out of the box functionality, open source, and active. A: While this is not in C#, you can use an Arduino to do this kind of thing. There is lots of help out there for Arduinos. They can be very powerful. They use a C++ ish language which is similar enough to C# that you could pick it up. Some sites: http://diyistheway.blogspot.com/2009/03/thermosmart.html http://arduino.cc/en/Tutorial/HomePage A: I'm playing around with a .NET development board with great fun for home automation. They come in all price ranges(some very simple and there are the ones with screens, wifi and so on) and support a compact .net framework and have a lot of sensors and relays to add on to it! NetDuino My own project at home is that I just had a on/off switch for my warm water. I do control it with my netduino board by a fixed times but I can also switch it on from a web browser. Next version is for it to not switch on if there have been no movement in my apartment for a while so if I go off for holiday I don't have to switch it off. Also bought an servo to open my window if temp go over a certain degree :).. Next will be to have some kind recognition if a lady enters to start the soft music and the disco ball spinning! A: CRESTRON their whole product line is based of software developed in .net (probably c# but could be vb) and all they do is control systems (hvac, lighting, etc....) most of the systems they control run on three different types of interfaces: serial (232, terminal), digital (usually over tcp/ip), or analog you need to find out what kind of interface your hvac system has, then find a way to plug your computer up to it, then program in c# using that protocal A: Telldus provide interfaces to wireless control and they have c# libraries A: Crestron is in the process of release a new SDK that uses a sandboxed version of C# to control their extensive selection of home automation hardware. Unfortunately, using their software requires special permission and training.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516666", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "31" }
Q: Alternatives to PL/SQL? Are there any other programming language/IDE combos that offer autocomplete and syntax validation for (Oracle) SQL queries? I'm looking for an alternative to PL/SQL. PL/SQL is mediocre at best but I haven't found anything that's even close to matching its productivity when writing Oracle database-centric scripts. So, are there any other programming languages that offer any of the following features? * *Natively handle SQL queries (SQL treated as code, not as a string). *Autocomplete for table & column names. *SQL is validated against DB at compile time. *Edit: I'm well aware of, and use, IDEs for SQL and PL/SQL that offer autocomplete. I'm merely wondering if there exists any other programming language out there that lets you intermingle SQL and code in a similar way to PL/SQL. A: "Awkward exception handling, a lack of many built-in datatypes and functions that you take for granted in most languages, lack of anything resembling proper support for multi-threaded programming, inability to access the filesystem of the person running the script (SSH access to prod DB servers is often out of the question), hugely awkward for OOP, dealing with packages can be a PITA, doesn't respect role-base grants, etc... PL/SQL is awesome when it comes to integration with the DB, but beyond that it's a fairly poor language once you go past a certain level of complexity." One by one. Awkward exception handling Awkwardness is in the eye of the beholder but I'll give you that one. Too much is left up to the individual developer. a lack of many built-in datatypes ... that you take for granted in most languages It has the same datatypes as SQL, plus BOOLEAN. What more can you want? lack of anything resembling proper support for multi-threaded programming Multithreading is a tricky concept to combine with read-consistency in a multi-user environment. The Aurora JVM doesn't support mult-threaded Java in Java Stored Procedures either. It's not a limitation of PL/SQL. inability to access the filesystem of the person running the script Again, that's not a PL/SQL issue. Ask your network administrator to map a fileshare on your PC to the network. hugely awkward for OOP Yeah well, OOP is on its way out, everybody's down with functional programming these days. dealing with packages can be a PITA Personal opinion. I love packages. doesn't respect role-base grants Again, that's not PL/SQL, it's the database security model. Views don't respect role-based grants either. once you go past a certain level of complexity Write it in Java and call if from a Java Stored Procedure. Or write it on C and call it from an extproc. A: I guess there is plenty of alternatives with various level of conformance to your set of requirements. Take a look e.g to: * *Squeryl for Scala *HaskellDB for Haskell *LINQ for .NET A: TOAD is pretty good -- works for PL/SQL, TSQL etc. http://www.quest.com/toad/ SQL Complete is an add-in for SSMS (TSQL): http://www.devart.com/dbforge/sql/sqlcomplete/ Redgate SQL Prompt: http://www.red-gate.com These 3 above are pretty main-stream, well-liked, well-supported. But otherwise, just pick your desired sql dialect, and google for it -- i.e. "tsql auto-complete" or "pl/sql auto-complete" to find more. Your question also asks about a good language... I wouldn't exactly call pl/sql mediocre (unless I was trying to get a rise out of one of our tech guys anyway :-). TSQL is also good, and getting more and more 'mature', as they say, though it's still often compared to pl/sql in the context of "is tsql as mature as pl/sql yet...". But whatever you choose, "good" just means is it appropriate to your application and skillset more than anything.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516669", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: sequentially send stdout from subprocess.Popen via socket I know this has been anwered many times before, but I haven't find a working way to do this in my scenario... I hope you will help. I want to output the data from stdout and/or stderr from a Popen call in real time, to a socket connection, not to stdout. So sys.stdout.flush() don't work for me. data=sok.recv(512) #the command to execute p = subprocess.Popen(data, shell=True, stdout=subprocess.PIPE stderr=subprocess.PIPE) #this work.. but not how i spected, if the subprocess ends too fast, i only get the first line while p.poll() is None: sok.send(p.stdout.readline()) #this only send the last line for i in p.stdout.readline(): sok.send(i) sys.stdout.flush() #why sys.stdout? i don't use it p.stdout.flush() #same result A: p.poll() indicates whether the process is executing. So it returns false as soon as the program exits. So that's not what you should be checking. your code: for i in p.stdout.readline(): reads a single line and then iterates over each letter in that line. Not what you wanted. Use: for i in p.stdout.readlines(): which will return each line. But that will read the entire file before producing any lines, probably not what you wanted. So use: for line in p.stdout: Which should give you each line, line by line, until there is nothing more to read
{ "language": "en", "url": "https://stackoverflow.com/questions/7516672", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Hiding of anchor tags before the page load I have a list of permission URLs which are links to certain pages and this list comes from the database. Now, there are jsp pages all across the application and they have certain links which display. These jsps are older jsps and the code is all there. Right now, Based upon the list of permissions I retrieve from database, I would like to either show or hide these links. Is there any centralized way of doing this either using a javascript snippet or jsp or combination which can be put in all jsps? The authorization part to these urls is already taken care, the display of the URLs which are usually anchor tags should be taken care, other than the way of actually going into each and every jsp and checking in session. A: What I did was create my own tag definition that take in security roles and include or exclude links in the page if the role validation passes. If you do it in javascript and only hide the links you can still inspect the page and access the urls.. Hope this helps A: You can make all anchor tags without a "show" class hidden by default using a single CSS expression: a:not(.show) { display: none; } and then at the point you wish to show them (I'd say in your case this would be the document ready function), simply add the CSS class "show" which will invalidate the rule above. JavaScript: var anchors = document.getElementsByTagName("a"); for (var i = 0; i < anchors.length; i++) { anchors[i].className = "show"; } A: Use JSP tag libs. Wrap the URL link in the taglib. For example spring security has something like this <security:authorize access="hasRole('ROLE_ADMIN')"> // display something </security:authorize> in the taglib, you will check if the user is logged in and he has certain permissions or roles and if he has you will either write it or skip it... A: If you send a javascript array of your permitted pages to the browser, you could then loop over all links to check and see if they are in the list. You probably have some links that are not secured so you would have to handle those somehow too. A: Without going through each page you could probably set up a combination of Java and JavaScript to accomplish this task. I would personally use jQuery. Set a JavaScript variable based on permission level, then use jQuery to loop through all your anchor/link to parse off of link name or common attribute to remove or hide them. var permissionLevel = <%=bean.getPermissionLevel()%> switch(permissionLevel ){ case 0: $("a").each(function(){ var link = $(this).attr("href"); if(link == 'myLinkName'){ $(this).remove(); } }) } In this example I used a numeric value as the permission level. You could easily use a string value and use if statements instead of a case state, but this shows the general idea.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516673", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java: How to count the no. of lines in a file? Possible Duplicate: Number of lines in a file in Java I need to count the number of lines of a txt file that is passed to java through a command line argument. I know how to read from a file but i am having trouble doing the rest. any help would be appreciated. here is what i have so far: import java.util.*; import java.io.*; public class LineCounter { public static void main (String [] args) throws IOException{ Scanner file = new Scanner(new File("myFlile.txt")); int count = 0; while(file.hasNext()){ boolean s = file.hasNext(); int count = file.nextInt(); } System.out.println(count); } } A: Why are you pulling nextInt() and saving hasNext() inside the loop? If you are in there, you already know another line exists, so why not do something like: while (file.hasNextLine()) { count++; file.nextLine(); } A: You should check javadoc for the java.util.Scanner class: http://download.oracle.com/javase/6/docs/api/java/util/Scanner.html Scanner has methods hasNextLine and nextLine that you can use for this. hasNextLine() checks if there are still lines in the files and nextLine() reads one line from the file. Using those methods you get an algorithm like this: let the amount of lines be 0 as long as there are lines left in file read one line and go to the next line increment amount of lines by 1 Your code could be something like this int count = 0; while(file.hasNextLine()) { count++; file.nextLine() } A: You can do it this way: FileInputStream fstream = new FileInputStream("filename"); BufferedReader br = new BufferedReader(new InputStreamReader(fstream)); String strLine; int count = 0; while ((strLine = br.readLine()) != null) { count++; } A: BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(filename)); long count = 0; while ((line = reader.readLine()) != null) { count++; } } catch (Exception e) { // do something } A: I wrote a little project analyser, some time ago. It's not really an answer, but I wanted to share my solution. There is no main() method yet. Just create one like this: MainFrame mf = new MainFrame(); mf.setVisible(true); It supports for filtering files on file extensions. So you can specify for example C++. This will accept all .h and .cpp files. You have to specify a folder and it will recursively count files, lines and bytes. import java.awt.event.ItemEvent; import java.io.BufferedReader; import java.io.File; import java.io.FileFilter; import java.io.FileReader; import javax.swing.DefaultComboBoxModel; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.SwingWorker; import javax.swing.filechooser.FileNameExtensionFilter; /** * * @author martijncourteaux */ public class MainFrame extends javax.swing.JFrame { private File root; private volatile int _files; private volatile int _lines; private volatile long _bytes; /** Creates new form MainFrame */ public MainFrame() { initComponents(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); btnSelectRoot = new javax.swing.JButton(); lblRoot = new javax.swing.JLabel(); cmbExtensions = new javax.swing.JComboBox(); jLabel2 = new javax.swing.JLabel(); btnAnalyse = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Project Analyser"); setLocation(new java.awt.Point(40, 62)); jLabel1.setText("Project Root:"); btnSelectRoot.setText("Select"); btnSelectRoot.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSelectRootActionPerformed(evt); } }); lblRoot.setText(" "); cmbExtensions.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "[Any]", "h;cpp", "java", "xml", "Customize..." })); cmbExtensions.addItemListener(new java.awt.event.ItemListener() { public void itemStateChanged(java.awt.event.ItemEvent evt) { cmbExtensionsItemStateChanged(evt); } }); jLabel2.setText("Extensions:"); btnAnalyse.setText("Analyse"); btnAnalyse.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnAnalyseActionPerformed(evt); } }); org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(layout.createSequentialGroup() .addContainerGap() .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(cmbExtensions, 0, 352, Short.MAX_VALUE) .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup() .add(jLabel1) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(lblRoot, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 174, Short.MAX_VALUE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(btnSelectRoot)) .add(jLabel2) .add(btnAnalyse, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 352, Short.MAX_VALUE)) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(layout.createSequentialGroup() .addContainerGap() .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(jLabel1) .add(btnSelectRoot) .add(lblRoot)) .add(18, 18, 18) .add(jLabel2) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(cmbExtensions, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) .add(btnAnalyse, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 90, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void btnSelectRootActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_btnSelectRootActionPerformed {//GEN-HEADEREND:event_btnSelectRootActionPerformed JFileChooser fc = new JFileChooser(root.getParentFile()); fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); int option = fc.showDialog(this, "Select"); if (option == JFileChooser.APPROVE_OPTION) { this.root = fc.getSelectedFile(); this.lblRoot.setText(root.getParentFile().getName() + "/" + root.getName()); } }//GEN-LAST:event_btnSelectRootActionPerformed private void cmbExtensionsItemStateChanged(java.awt.event.ItemEvent evt)//GEN-FIRST:event_cmbExtensionsItemStateChanged {//GEN-HEADEREND:event_cmbExtensionsItemStateChanged if (cmbExtensions.getSelectedIndex() == cmbExtensions.getItemCount() - 1 && evt.getStateChange() == ItemEvent.SELECTED) { evt.getStateChange(); String extensions = JOptionPane.showInputDialog(this, "Specify the extensions, seperated by semi-colon (;) and without dot."); if (extensions == null) { cmbExtensions.setSelectedIndex(0); return; } DefaultComboBoxModel model = (DefaultComboBoxModel) cmbExtensions.getModel(); model.insertElementAt(extensions, cmbExtensions.getSelectedIndex()); cmbExtensions.validate(); cmbExtensions.setSelectedIndex(cmbExtensions.getItemCount() - 2); } }//GEN-LAST:event_cmbExtensionsItemStateChanged private void btnAnalyseActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_btnAnalyseActionPerformed {//GEN-HEADEREND:event_btnAnalyseActionPerformed if (root == null) { JOptionPane.showMessageDialog(this, "Please select a root."); return; } _files = 0; _lines = 0; _bytes = 0L; btnAnalyse.setHorizontalAlignment(JButton.LEFT); updateButtonText(); final int i = cmbExtensions.getSelectedIndex(); final String[] extensions = cmbExtensions.getSelectedItem().toString().toLowerCase().split(";"); final FileFilter ff = new FileFilter() { @Override public boolean accept(File file) { if (i == 0) return true; if (file.isDirectory()) { return true; } String name = file.getName().toLowerCase(); for (String ext : extensions) { if (name.endsWith(ext)) { return true; } } return false; } }; final SwingWorker<Void, Void> sw = new SwingWorker<Void, Void>() { @Override protected Void doInBackground() throws Exception { scan(root, ff); updateButtonText(); return null; } }; sw.execute(); final SwingWorker<Void, Void> sw2 = new SwingWorker<Void, Void>() { @Override protected Void doInBackground() throws Exception { while (!sw.isDone()) { updateButtonText(); } return null; } }; sw2.execute(); }//GEN-LAST:event_btnAnalyseActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnAnalyse; private javax.swing.JButton btnSelectRoot; private javax.swing.JComboBox cmbExtensions; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel lblRoot; // End of variables declaration//GEN-END:variables private void updateButtonText() { String txt = "<html>"; txt += "Files: " + _files + "<br>\n"; txt += "Lines: " + _lines + "<br>\n"; txt += "Bytes: " + _bytes + "\n"; btnAnalyse.setText(txt); } private void scan(File folder, FileFilter ff) { File[] files = folder.listFiles(ff); try { for (File f : files) { if (f == null) { continue; } if (f.isDirectory()) { scan(f, ff); } else { analyse(f); } } } catch (Exception e) { } } private void analyse(File f) { if (f.exists()) { _files++; _bytes += f.length(); try { BufferedReader r = new BufferedReader(new FileReader(f)); while (r.readLine() != null) { _lines++; } r.close(); } catch (Exception e) { } } } } A: You can use a BufferedReader to read complete lines or a LineNumberReader which does the counting itself.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516682", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Listview DeleteButton onclick broken? I don't know if I'm just being stupid but I can't get bloody Javascript in my asp buttons onclick event :( <asp:Button ID="DeleteButton" runat="server" CommandName="Delete" Text="Delete" onclick="Javascript:returnConf();" /> I've tried variations including things like: <asp:Button ID="DeleteButton" runat="server" CommandName="Delete" Text="Delete" onclick="<%= GetMyStupidCode() %>" /> but the compiler keeps picking it up as code it should interpret or something and gives me errors such as: Identifier expected Invalid expression term ) Missing ) I'm lost, how do I do it? Thanks in advance, A: Just write OnClientClick="return confirm('This will delete the user permanently. Are you sure?');"
{ "language": "en", "url": "https://stackoverflow.com/questions/7516685", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }