text
stringlengths
8
267k
meta
dict
Q: Resizing an Image using Imagemagick convert I have a YUV420 image of size 1280x720. I am trying to resize it to 720x576 using convert (Imagemagick) using below commandline options. But the generated output file doesnot seem to be a proper resized YUV420 image(I want the resized output also to be in YUV420 format): convert -size 1280x720 -depth 8 -sampling-factor 2x2 test_1280x720_yuv420.yuv -filter lanczos -resize 720x576 -depth 8 -sampling-factor 2x2 720x576_yuv420.yuv //Here the output file size is not what it should be of a 720x576 YUV420 file which is 720x576x1.5 bytes. Qiestion: What is the format of this output file then? Also tried -sample option as, but same result. Incorrect sized output file. I even tried to display the generated resized file, but it sure is not a YUV420 file, as could not view it correctly at all. convert -size 1280x720 -depth 8 -sampling-factor 2x2 test_1280x720_yuv420.yuv -sample 720x576 -depth 8 -sampling-factor 2x2 720x576_yuv420.yuv Question: Would convert be able to do what I am trying to get done? IF yes, what are the options? Question: Any other tool(freeware,shareware) which could help me resize YUV files(different formats YUV420, YUV444) to YUV format output files? A: Try to ignore aspect ration! Ignore Aspect Ratio ('!' flag) If you want you can force "-resize" to ignore the aspect ratio and distort the image so it always generates an image exactly the size specified. This is done by adding the character '!' to the size. Unfortunately this character is also sometimes used for special purposes by various UNIX command line shells. So you may have to escape the character somehow to preserve it. Example: convert image.gif -resize 64x64\! resized_image.gif //Resized Image with ignore ratio option
{ "language": "en", "url": "https://stackoverflow.com/questions/7553690", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: own ORM: database records in case of JOIN? We are doing our own framework with ORM capability. The database tables are classes now, but how about records? Lets imagine two tables: Users ID,USERNAME Emails USER_ID,ADDRESS so, a record object will have getID(), getUSERNAME() methods, etc but if the two tables are JOIN-ed, it cant have two types right? Since there is no multiple inheritance. And what about field collision? A: I think every class should represent a record and a whole table should be an array (or some other collection) of objects. Take a look at http://www.doctrine-project.org/ to get some ideas. And for JOIN, you should have some mechanism for defining aliases. That way, you can deal with field collision. And for getters and setters, you can use __call, __get and __set. See http://php.net/manual/en/language.oop5.overloading.php for more info. A: DBIx::Class handles this by having a Class for each table, and joins are represented by a method that gets an object matching the other table.. $myAddress = $myUser->emails->address; A: I'm providing some insight based on the Model/ORM implementation of this PHP UI Framework . Here are some suggestions from me: * *Don't decide blindly to map functions into fields. Why not use get('field') and set('field'). There is no downside (apart from lack of IDEs hinting), but you can avoid code generation or catch-all which usually is slower. *When joining you wouldn't necessarily want multiple objects. In my ORM a single Model can work with joined tables. This introduces transparency and when you call $model->set('address') it might be associated with joined table. Im still using sub-instance of a dynamic query for sub-selects but for joins there is no need. *I've see a lot of power of inheritance and ability to re-shape parent models in parent model. Each table can have multiple models depending on your business uses. *Models and ORM should be separated but should play together very closely. I've also managed to make everything play well with generic views and generic controllers, which is a great time-saver. Hopefully this would help find your own way or to decide on not implementing your own ORM. It's not an easy task.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553692", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Creating unique id with jquery to use in bxslider I guess this is pretty simple but I have no experience with jquery whatsoever. I'm using bxslider in every post I post in my wordpress theme and need the jquery to point to numerous unique id's, not only to work1, but work2, work3 and so on. The markup is this: <ul id="work1"> <li></li> <li></li> </ul> <ul id="work2"> <li></li> <li></li> </ul> ... And the code: <script type="text/javascript"> jQuery(document).ready(function(){ jQuery('#work1').after('<div class="work-pager"></div>'); jQuery('#work1').bxSlider({ mode: 'horizontal', infiniteLoop: false, speed: 500, pause: 8000, auto: false, pager: true, controls: false, pagerSelector: '.work-pager' }); }); </script> A: function findNewId() { var i = 0; while(1) { if($('#work'+i).size()==0) return 'work'+i; i++; } } $('ul').each(function() { $(this).attr('id',findNewId()); }); This should do the trick. JSFIDDLE
{ "language": "en", "url": "https://stackoverflow.com/questions/7553694", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: ImportError: No module named paramiko I have installed "python-paramiko" and "python-pycrypto" in Red hat linux. But still when i run the sample program i get "ImportError: No module named paramiko". I checked the installed packages using below command and got confirmed. ncmdvstk:~/pdem $ rpm -qa | grep python-p python-paramiko-1.7.6-1.el3.rf python-pycrypto-2.3-1.el3.pp My sample program which give the import error: import paramiko ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy( paramiko.AutoAddPolicy()) ssh.connect('127.0.0.1', username='admin', password='admin') A: Actually all these packages were installed outside the python folder. And all I did was linking the packages from python folder to packages folder. It worked perfectly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553700", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Know user's twitter applications installed first of all, I'm spanish so sorry about my English. It's my first question, so I hope do it correctly. I have been looking for in the searcher and google but I didn't find solution about my problem. I need to know who of my friends have installed one app via API (I have twitter4j lib.). I have a friend's list id and I need to know if one per one have or not permission to one app. I have seen all the methods in twitter4j but I don't know how do it. It seems easy... so sorry if the answer is stupid, I have tried to search everywhere I have could. Thanks, A: This is possible via twitters settings page, however there's no API available for this. If you mean source of the tweets? Like Web, Mobile Web, Twitter for Blackberry Source of tweets (Application user tweeted with) is returned for each tweet gotten. https://dev.twitter.com/docs/api/1/get/statuses/show/%3Aid
{ "language": "en", "url": "https://stackoverflow.com/questions/7553703", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Retriving a setting in a Web.Config I have this code in my Web.Config file: <configSections> <section name="myWebAppSettings" type="System.Configuration.SingleTagSectionHandler" /> </configSections> <myWebAppSettings isTestEnvironment="true"/> I need retrieve my value isTestEviroment from Global.asax At the moment I use with no sucess: bool isTestEnvironment = ConfigurationManager.AppSettings.GetValues["isTestEnvironment"]; What I'm doing wrong here? NOTES: I do not assume my Web.Config file is right so please feel free to change it if I did not written correctly. Thanks for your help on this! A: ConfigurationManager.AppSettings retrieves values from the AppSettings configuration element, not your custom section. You need to use: var section = (HashTable)ConfigurationManager.GetSection("myWebAppSettings"); bool isTest = Boolean.Parse(section["isTestEnvironment"].ToString());
{ "language": "en", "url": "https://stackoverflow.com/questions/7553708", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Evicting eager associations without cascade="evict" Is there any way to make Hibernate evict both an entity and all of its eager or one-to-one associations without having to evict associations manually one by one? (And without setting cascade="evict" on the association). I usually find these kind of needs once the persistence layer is built and working, and I don't feel confident about adding this kind of configuration globally for those associations. I just want to cascade eviction in a particular case. Also, it would be fine if there was a way to retrieve an entity from the DB without getting it (and its eager associations) attached to the session. I want to do this to perform some comparison logic between an UI-modified entity and its current DB state. After the comparison logic, the UI-modified entity will always be saved. The logic behind the comparison doesn't have anything to do with the eager or one-to-one associations. A: The answer to your first question is no. I don't see why, in your second problem, you don't want to have the entity attached to the session. I can see why you don't want to load some associations, but that's precisely the goal of setting the associations as lazy instead of eager. Just don't make them eager, and they won't be loaded in the session. A: What about writing a new function that does the comparison in DB directly and returns something? That is suitable for your needs I think.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553711", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: With facebook offline acces token send friend request I am playing around all the different apis for facebook friend request.. I want to have any method which can send request for friendship with app_id ,user_id and offline access token of user . Using no java script and no fbml methods.. I want just request to be send friendship request method . Is there any get method for that? A: I don't think this is possible. Also why would you do that?! Things to remember: Usage Notes This feature is intended to help users become friends on Facebook with people that they are connected to in real life. You should not use this feature to encourage users to friend other users that they are not connected to in real life. If your app is found to be encouraging this behavior, your usage of this feature may be disabled. Also Facebook encourage user-initiated actions (refer, publish_stream permission): However, please note that Facebook recommends a user-initiated sharing model. A: There is no API to allow apps to send friend requests.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553712", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Problemswith DropDownList in customized ASP.NET CreateUserWizard I am using a customized ASP.NET CreateUserWizard in my web application. Here I used a dropdownlist to populate the countries when user registering. In the page load its populate the countries as expected. var query = GetNationality(); var national = (DropDownList)RegisterUser.CreateUserStep.ContentTemplateContainer.FindControl("Nationality"); national.DataSource = query; national.DataTextField = "CountryName"; national.DataValueField = "Id"; national.DataBind(); var item = new ListItem("Select Country", ""); national.Items.Insert(0, item); But when I trying to obtain the values from dropdownlist in the OnCreatedUser event it generating me an error saying System.FormatException: Input string was not in a correct format What I am doing in the is OnCreatedUser is var national = (DropDownList)RegisterUser.CreateUserStep.ContentTemplateContainer.FindControl("Nationality"); var nationality = Convert.ToInt32(national.SelectedValue); <<-(where the error is) The complete code of the page is below protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { FillDropdown(); } } protected void RegisterUser_CreatedUser(object sender, EventArgs e) { var newUser = Membership.GetUser(RegisterUser.UserName); var newUserId = (Guid)newUser.ProviderUserKey; var name1 = (TextBox)RegisterUser.CreateUserStep.ContentTemplateContainer.FindControl("fname"); var name2 = (TextBox)RegisterUser.CreateUserStep.ContentTemplateContainer.FindControl("lname"); var comp = (TextBox)RegisterUser.CreateUserStep.ContentTemplateContainer.FindControl("Company"); var post = (TextBox)RegisterUser.CreateUserStep.ContentTemplateContainer.FindControl("Position"); var birth = (TextBox)RegisterUser.CreateUserStep.ContentTemplateContainer.FindControl("Bday"); var mob = (TextBox)RegisterUser.CreateUserStep.ContentTemplateContainer.FindControl("Mobile"); var aphone = (TextBox)RegisterUser.CreateUserStep.ContentTemplateContainer.FindControl("altPhone"); var aemail = (TextBox)RegisterUser.CreateUserStep.ContentTemplateContainer.FindControl("altEmail"); var national = (DropDownList)RegisterUser.CreateUserStep.ContentTemplateContainer.FindControl("Nationality"); var news = (CheckBox)RegisterUser.CreateUserStep.ContentTemplateContainer.FindControl("Newsletter"); var title = tit.Text.Trim(); var nationality = national.Text; var preferred = method.Text.Trim(); var newsleter = news.Checked; FormsAuthentication.SetAuthCookie(RegisterUser.UserName, false /* createPersistentCookie */); var continueUrl = RegisterUser.ContinueDestinationPageUrl; if (String.IsNullOrEmpty(continueUrl)) { continueUrl = "~/"; } Response.Redirect(continueUrl); } public void FillDropdown() { var query = GetNationality(); var national = (DropDownList)RegisterUser.CreateUserStep.ContentTemplateContainer.FindControl("Nationality"); national.DataSource = query; national.DataTextField = "CountryName"; national.DataValueField = "Id"; national.DataBind(); var item = new ListItem("Select Country", ""); national.Items.Insert(0, item); } } Any ideas will be appreciate. Thanks A: Can you put the code that populates DropDownList in Page_Load method under !IsPostBack? protected void Page_Load(object sender, EventArgs e) { if(!IsPostBack) { var query = GetNationality(); var national = (DropDownList)RegisterUser.CreateUserStep.ContentTemplateContainer.FindControl("Nationality"); national.DataSource = query; national.DataTextField = "CountryName"; national.DataValueField = "Id"; national.DataBind(); var item = new ListItem("Select Country", ""); national.Items.Insert(0, item); } } It could be that when you postback, your DropDownList gets re-bound, so you always get the first item and you tried to convert empty string to an int which gives you the error message.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553713", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Read custom action from the Open Graph beta Is it possible to read the actions & objects created with the new Open Graph? A: I might be wrong (did not test) but according to these docs you'd need the following extended permissions user_actions.{vertical_name} friends_actions.{vertical_name} or user_actions:{app_namespace} friends_actions:{app_namespace}
{ "language": "en", "url": "https://stackoverflow.com/questions/7553714", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: warning occurring following move from classic to integrated on IIS7 I have migrated my c# asp.net web application from .net 3.5 to .net 4.0 and also changed the IIS7 application pool it runs to be Integrated rather than classic. The site runs fine but I have found the following warning been recorded in the server event log: Event code: 3005 Event message: An unhandled exception has occurred. Event time: 26/09/2011 11:19:10 Event time (UTC): 26/09/2011 10:19:10 Event ID: 5e750da6db8544feaede11ed88c072f6 Event sequence: 2 Event occurrence: 1 Event detail code: 0 Application information: Application domain: /LM/W3SVC/3/ROOT-2-129615059474458846 Trust level: Full Application Virtual Path: / Application Path: << REMOVED >> Machine name: << REMOVED >> Process information: Process ID: 5864 Process name: w3wp.exe Account name: << REMOVED >>\app_user Exception information: Exception type: NullReferenceException Exception message: Object reference not set to an instance of an object. at System.Web.HttpApplication.set_AsyncResult(HttpAsyncResult value) at System.Web.HttpApplication.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) at System.Web.HttpRuntime.ProcessRequestInternal(HttpWorkerRequest wr) Request information: Request URL: http://127.0.0.1/dummy.context Request path: /dummy.context User host address: 127.0.0.1 User: Is authenticated: False Authentication Type: Thread account name: << REMOVED >>\app_user Thread information: Thread ID: 22 Thread account name: << REMOVED >>\app_user Is impersonating: False Stack trace: at System.Web.HttpApplication.set_AsyncResult(HttpAsyncResult value) at System.Web.HttpApplication.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) at System.Web.HttpRuntime.ProcessRequestInternal(HttpWorkerRequest wr) Custom event details: Any ideas what may be causing this as I am stumped as to what it might be? A: (tech difficulty: I'm having trouble to add a comment to yr question but it seems I can add it as an ansewer) I am experiencing the same error. In this link https://jira.springsource.org/browse/SPRNET-1456 they say it's a bug that "won't be fixed" A: I had this error and looked in the Event Viewer. Among several other errors, I had this one and another (which was an Information) : Information 14/11/2011 13:54:04 Windows Error Reporting 1001 None details: Fault bucket , type 0 Event Name: CLR20r3 Response: Not available Cab Id: 0 Problem signature: P1: w3wp.exe P2: 7.5.7601.17514 P3: 4ce7afa2 P4: mscorlib P5: 4.0.0.0 P6: 4e1823db P7: f5 P8: 9 P9: System.StackOverflowException P10: Attached files: These files may be available here: C:\ProgramData\Microsoft\Windows\WER\ReportQueue\AppCrash_w3wp.exe_426513163e392f7b5e2712abb67e65a456d0f5_015c843b Analysis symbol: Rechecking for solution: 0 Report Id: b8a9aec0-0ebf-11e1-86d9-001d927c2d4c Report Status: 0 So it was a stackoverflow. I guess that the error you see is just an artifact of another error. You should try to investigate for this other error. I don't say it will be a stackoverflow like mine, but it could be something else.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553715", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Using composition over inheritance when overriding If I have a class that I would like to customise by overriding one if its methods the only I can do this is by using inheritance (sub-classing and overriding method) ? Is it possible to use composition in some way to achieve same goal ? A: Yes, you can use delegation. Instead of deriving from Foo in the example below, Bar contains a Foo and delegates to it where it chooses. interface SomeMethods { void doSomething(); void doSomethingElse(); } class Foo implements SomeMethod { public void doSomething() { // implementation } public void doSomethingElse() { // implementation } } class Bar implements SomeMethod { private final Foo foo = new Foo(); public void doSomething() { foo.doSomething(); } public void doSomethingElse() { // do something else! } } A: Using composition instead of inheritance is a design choice. Either your class has been designed with inheritance in mind (i.e. it provides non-final public and protected methods, intended to be overridden by subclasses), or it has been designed with composition or delegation in mind (by using the strategy pattern, for example). If the class has not been designed for customization at all, you might be able to customize it using inheritance, but not using a composition/delegation mechanism. A: Sure. You can use the following patterns. Simple overriding of method method Template method pattern class Base { public void foo() { // do something bar(); // do something } protected abstract void bar(); } class Child { protected void bar() { // do something. } } Delegation class Base { private Runnable r; protected Base(Runnable r) { this.r = r; } public void foo() { r.run(); } } class Child extends Base { Child() { super(new Runnable() { /* implementation */}) } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7553719", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: setup of Pyramid on Google App Engine Following these steps produces the following: $ python2.5 ../appengine-monkey/appengine-homedir.py --gae $GAE_PATH pyramidapp New python executable in pyramidapp/bin/python2.5 Also creating executable in pyramidapp/bin/python ERROR: The executable pyramidapp/bin/python2.5 is not functioning ERROR: It thinks sys.prefix is '/System/Library/Frameworks/Python.framework/Versions/2.5' (should be '/Users/lostdorje/Development/workspace/pyramidapp') ERROR: virtualenv is not compatible with this system or executable I see some others are having similar problems. Any thoughts? A: I wrote a Pyramid on Google App Engine example. Its based on zc.buildout and on the tutorial mentioned in the question, but it is running with Pyramid 1.4 and some helper recipes.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553721", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: When should I not use regular expressions? After some research I figured that it is not possible to parse recursive structures (such as HTML or XML) using regular expressions. Is it possible to comprehensively list out day to day coding scenarios where I should avoid using regular expressions because it is just impossible to do that particular task using regular expressions? Let us say the regex engine in question is not PCRE. A: I'll plagiarize myself from my blog post, When to use and when not to use regular expressions... Public websites should not allow users to enter regular expressions for searching. Giving the full power of regex to the general public for a website's search engine could have a devastating effect. There is such a thing as a regular expression denial of service (ReDoS) attack that should be avoided at all costs. HTML/XML parsing should not be done with regular expressions. First of all, regular expressions are designed to parse a regular language which is the simplest among the Chomsky hierarchy. Now, with the advent of balancing group definitions in the .NET flavor of regular expressions you can venture into slightly more complex territory and do a few things with XML or HTML in controlled situations. However, there's not much point. There are parsers available for both XML and HTML which will do the job more easily, more efficiently, and more reliably. In .NET, XML can be handled the old XmlDocument way or even more easily with Linq to XML. Or for HTML there's the HTML Agility Pack. Conclusion Regular expressions have their uses. I still contend that in many cases they can save the programmer a lot of time and effort. Of course, given infinite time & resources, one could almost always build a procedural solution that's more efficient than an equivalent regular expression. Your decision to abandon regex should be based on 3 things: 1.) Is the regular expression so slow in your scenario that it has become a bottleneck? 2.) Is your procedural solution actually quicker & easier to write than the regular expression? 3.) Is there a specialized parser that will do the job better? A: My rule of thumb is, use regular expressions when no other solution exists. If there's already a parser (for example, XML, HTML) or you're just looking for strings rather than patterns, there's no need to use regular expressions. Always ask yourself "can I solve this without using regular expressions?". The answer to that question will tell you whether you should use regular expressions. A: Don't use regular expressions when: * *the language you are trying to parse is not a regular language, or *when there are readily available parsers specifically made for the data you are trying to parse. Parsing HTML and XML with regular expressions is usually a bad idea both because they are not regular languages and because libraries already exist that can parse it for you. As another example, if you need to check if an integer is in the range 0-255, it's easier to understand if you use your language's library functions to parse it to an integer and then check its numeric value instead of trying to write the regular expression that matches this range.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553722", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Issues with dropdown navigation menu using jquery in IE I am having some problems with the jquery drop down navigation menu , its working fine with all the browsers apart from IE 7,8. Below I have attached the 2 images and have included the css and markup for it , Any assistance will be highly appreciated, regards Dropdown Navigation image display with all other browsers(required output) Dropdown Navigation image display with IE (submenu is starting below company , it should start just below the products) CSS: .hide { display:none; } .nave { width:960px; padding:10px 0px 0px 10px; margin:0 auto; } .quiklinks { margin: 0px 0px 0px 0px; padding: 0px 0px 0px 0px; height: 45px; font-family: Tahoma, Arial; font-size: 12px; text-align: center; clear: both; float: left; width: 960px; background: url('../Images/navebg.png') no-repeat left top; } .quiklinks ul { margin:0px; padding:0px; } .quiklinks li { margin: 0px; padding: 0px; float: left; display: block; background: url('../Images/divider.png') no-repeat left top; height: 45px; float: left; } .quiklinks li a { display:block; height:41px; text-decoration:none; color:#ebeaea; font-weight:bold; line-height:35px; padding:2px 20px 0px 20px; float:left; } .quiklinks li a:hover { display:block; height:41px; text-decoration:none; font-weight:bold; line-height:35px; padding:2px 20px 0px 20px; float:left; } /*style the sub menu*/ .quiklinks .ul-links li ul { position:absolute; visibility: hidden; margin: 0; padding: 0; z-index: 100; top: 52px; } .quiklinks .ul-links li ul li { display: inline; height: 35px; float: none; margin: 0; padding: 0; background-image: none !important; } .quiklinks .ul-links li ul li a:link, .quiklinks .ul-links li ul li a:visited { background: url('../Images/nav-ul-li.png') repeat-x left top; width: 100px; text-decoration: none; font-size: 12px; color: #FFFFFF; height: 35px; font-weight: bold; } .quiklinks .ul-links li ul li a:hover { background: url('../Images/nav-ul-li-hover.png') repeat-x 0px 0px; } Html Markup: <script type="text/javascript"> $(document).ready(function () { $('.ul-links > li').bind('mouseover', openSubMenu); $('.ul-links > li').bind('mouseout', closeSubMenu); function openSubMenu() { $(this).find('ul').css('visibility', 'visible'); }; function closeSubMenu() { $(this).find('ul').css('visibility', 'hidden'); }; }); </script> <div class="nave"> <div class="quiklinks"> <ul class="ul-links"> <li><a href="/" id="quiklinks_01">Home</a><span class="hide">Home</span></li> <li><a href="#" rel="nofollow" id="quiklinks_02">News</a><span class="hide">About us</span></li> <li><a href="/business-customers.aspx" rel="nofollow" id="quiklinks_03">Products</a><span class="hide">Business Customers</span></li> <li><a href="/security.aspx" rel="nofollow" id="quiklinks_04">Latest Products</a><span class="hide">Security</span> <ul> <li> <a href="/products/carpets.aspx" >Product1</a> </li> <li> <a href="/products/laminates.aspx" >Product2</a> </li> <li> <a href="/products/vinyls.aspx" >Product3</a> </li> </ul> </li> <li><a href="/shippingInfo.aspx" rel="nofollow" id="quiklinks_06">Company</a><span class="hide">Delivery Information</span></li> <li><a href="/articles.aspx" id="quiklinks_09">Ordering</a><span class="hide">Articles & Reviews</span></li> <li><a href="/help.aspx" rel="nofollow" id="quiklinks_08">Contact</a><span class="hide">Help</span></li> <li><a href="/contactus.aspx" rel="nofollow" id="quiklinks_07">Links</a><span class="hide">Contact Us</span></li> </ul> A: @Mr A; as ricky said give left:0; to your .quiklinks .ul-links li ul & give position:relative to it's parent css: .quiklinks .ul-links li ul{ position:absolute; left:0; top: 52px; } .quiklinks .ul-links li{ position:relative; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7553723", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android Index out of bounds I am trying to get the bold text next to the hour scheldule ( from http://golfnews.no/golfpaatv.php )put it in a String array , then , show it on my device's screen. I've put the Internet Access permission , so that is not the problem.The application crashes on my device . Reason : index out of bounds . I don't understand where's the problem . My code is : package com.work.webrequest; import java.io.IOException; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; public class WebRequest extends Activity { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); String trax; String aux[] = new String[10]; setContentView(R.layout.main); TextView txt = (TextView) findViewById(R.id.textView1); trax=getPage(); aux= title (trax); txt.setText(" Here I will display every title!!!"); } private String[] title (String trax) { String result[] = new String[10]; int ok=1; int s1,s2; int i=0; while(ok==1) { System.out.println("INDEX = "+trax.indexOf("<h2>")); ok=0; if(trax.indexOf("<h2>")!=-1) { ok=1; s1 =trax.indexOf("<h2>"); s2 = trax.indexOf("</h2>"); result[i] = trax.substring(s1+4,s2); i++; trax = trax.substring(trax.indexOf("</h2>")); } } return result; } private String getPage() { String str = "***"; try { HttpClient hc = new DefaultHttpClient(); HttpPost post = new HttpPost("http://www.golfnews.no/feed.php?feed=1"); HttpResponse rp = hc.execute(post); if(rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { str = EntityUtils.toString(rp.getEntity()); } }catch(IOException e){ e.printStackTrace(); } return str; } } The number of <h2> and </h2> is below 10 . My application crashes at the 2nd iteration . I am a beginner in android , so I don't know much . Could you give me a hint ? I would really appreciate it . Thank you ! PS : I know what Index Out of bounds means , I just don't know why I get the error here . A: You get IndexOutOfBoundsException when you want to access an array index which is out of range. For example: String[] myArray = new String[10]; myArray[10] = "test"; // 10 is out of limits(0-9) Would produce such an exception. Check the stacktrace for the line that this exception originates from. It tells you the class name/method name/line number that this problem comes from. In your case I suspect there are more than 10 <h2> in the trax, so you get this exception. Initially you don't know the number of <h2>'s so change this line: String result[] = new String[10]; with this: ArrayList<String> result= new ArrayList<String>(); Then you can add elements to this list with the following: // result[i] = trax.substring(s1+4,s2); result.add(trax.substring(s1+4,s2)); EDIT1 Also I think you mean this: //trax = trax.substring(trax.indexOf("</h2>")); trax = trax.substring(s2 + 5); EDIT2 Also I realized you allocate arrays wrong, you are allocating a String of 10 chars instead of an array of 10 Strings: //String aux[] = new String[10]; String[] aux = new String[10]; //String result[] = new String[10]; String[] result = new String[10]; A: try this one too.. if(trax.indexOf("<h2>")!=-1&&i<10) { ok=1; s1 =trax.indexOf("<h2>"); s2 = trax.indexOf("</h2>"); result[i] = trax.substring(s1+4,s2); i++; trax = trax.substring(trax.indexOf("</h2>")); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7553724", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: blender: how to export shape keys using python? I want to export shape keys for some object. How can i get access to a shape key's mesh ? I'm using blender 2.59. Thanks A: i did it. Here is the script. maybe it would be helpful for someone: import bpy import xml.dom.minidom path = "/Users/x/Documents/y/game_projects/test.xml" dom = xml.dom.minidom.getDOMImplementation() tree = dom.createDocument(None, "document", None) root = tree.documentElement root.setAttribute("version", "0.1") for object in bpy.data.objects: if object.type == 'MESH' and object.data.shape_keys: objectElement = tree.createElement("object") objectElement.setAttribute("name", object.name) root.appendChild(objectElement) keysElement = tree.createElement("shape_keys") objectElement.appendChild(keysElement) keyBlocks = object.data.shape_keys.key_blocks for block in keyBlocks: keyElement = tree.createElement("key") keyElement.setAttribute("name", block.name) keysElement.appendChild(keyElement) for data in block.data: vertex = data.co element = tree.createElement("vertex") element.setAttribute("x", str(vertex.x)) element.setAttribute("y", str(vertex.y)) element.setAttribute("z", str(vertex.z)) keyElement.appendChild(element) file = open(path, "w", encoding="utf8") tree.writexml(file, encoding = "UTF-8", indent = "\n", addindent = "\t") file.close()
{ "language": "en", "url": "https://stackoverflow.com/questions/7553726", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Best strategy to read file only once at launch? I am reading a file datafile at the launch of my application.This is just self learning drill. On apple developers website under the heading Minimize File Access at Launch Time it says If you must read a file at launch time, do so only once. So my question is that is there a standard or preferred way of doing this. At the moment I have an instance varible NSArray and I populate that in - (void)viewDidUnloadand never garbage collect it. Is that good enough ? or Should I be making use of application Object (I am not even sure if it is logical to say this.). A: There is no standard way to optimize. But there are some guidelines. One basic idea of optimization is to do less. E.g. as the advice you cited where the data of a file may be needed at multiple points in your code, it is better to read it from disk once and then distribute a data pointer within your program. If the file is big enough to cause a stutter when you start your application, i.e. it takes more than 20ms to read and parse the file, you should consider reading the file in a background thread/task and adding a ‘loading…’-state to display to the user.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553735", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java:How to call Implemented method from interface name I don't know how interface works for my problem but I have read that its possible by interface here Problem: I have created an interface which has All the declaration of the methods its around 3000+ I am implementing these methods in 3 different classes, now I want to call the methods from Interface in my main file, reason I can need any method from any class and I cant extend more than one class so i thought about using interface. Can I do this Answers are appreciated. Update: using extend I can use super.methodName(); So that i am not creating an object. I can split these methods in different interfaces or different classes but I must access the methods without creating the object Please the link to understand what i want to do. Update2: Interface ABC // public int go() function is declared here Class XYZ implements ABC method go(object imp) {.....} Another class Class PQR extends/implements ABC { // some code int ret = super.go(this); OR int ret = obj.go(this) } // What Should I use I now ABC is my interface but dont know where is it implemented so i want to call the go function how can I do this Please Explain what should i use. Thanks A: When you call a method on an interface, it actually calls the implementing method on the concrete class. It doesn't matter that you have an insane number of methods or how many classes you have. e.g. List list = new ArrayList(); list.size(); // actually calls ArrayList.size() BTW: There is only a relatively small number of classes which have 3000 lines, let alone 3000 methods. I assume this is generated code. A: Let be an interface Z and classes A and B implementing Z. Z has a method m1(). Z z1 = new A(); Z z2 = new B(); z1.m1(); // actually calls m1 as implemented in A even if the object is declared as Z. z2.m1(); // different implementation of the same method m1 You declare z1 as being of type Z, but the implementation is A. Same thing for z2 but for B. A: If you're are talking about generated code I think what you need is to load a class at run-time. You can't call the methods of an interface without having those methods implemented in a concrete class and (without having) an interface "reference object" that points to an instantiated object (that implements that interface). So a solution would be the use of Reflection, over which I suggest you take a look. This will give you an idea how to load a class, call methods and pass arguments at run-time, not at compile time. (i.e. you can call those methods after the dinosaur class was generated) A small example can be found at: http://java.sun.com/developer/technicalArticles/ALT/Reflection/
{ "language": "en", "url": "https://stackoverflow.com/questions/7553737", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: OpenGL ES OBJ Loading Transparency Issues Hi I am working on an OBJ loader for use in iOS programming, I have managed to load the vertices and the faces but I have an issue with the transparency of the faces. For the colours of the vertices I have just made them for now, vary from 0 - 1. So each vertex will gradually change from black to white. The problem is that the white vertices and faces seem to appear over the black ones. The darker the vertices the more they appeared covered. For an illustration of this see the video I posted here < http://youtu.be/86Sq_NP5jrI > The model here consists of two cubes, one large cube with a smaller one attached to a corner. A: How do you assign a color to vertex? I assume, that you have RGBA render target. So you need to setup color like this: struct color { u8 r, g, b, a; }; color newColor; newColor.a = 255;//opaque vertex, 0 - transparent //other colors setup
{ "language": "en", "url": "https://stackoverflow.com/questions/7553741", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to Count the all nodes(inside )of my current Node using XSLT 2.0? This is my Xml File <w:body> <w:p><w:r><w:t>para1</w:t></w:r></w:p> <w:p><w:r><w:t>para2</w:t></w:r></w:p> <w:p><w:r><w:t>para3</w:t></w:r></w:p> <w:p><w:r><w:t>para4</w:t></w:r></w:p> <w:p><w:r><w:t>para5</w:t></w:r></w:p> <w:tbl><w:tr><w:tc><w:p><w:r><w:t>para6</w:t></w:r></w:p></w:tc> <w:tc><w:p><w:r><w:t>para7</w:t></w:r></w:p></w:tc> <!-- Assume This is my Current Node --> <w:tc><w:p><w:r><w:t>para8</w:t></w:r></w:p></w:tc> </w:tr> </w:tbl> </w:body> So, Now i want to get the count of all <w:p> inside <w:body> and also previous <w:p> of the current node inside <w:tbl>. So, For this scenario, my Expected count is 7 at this time... how i do it?help me to get this... A: Use: count($vtheNode/preceding::w:p) where $vtheNode is your node. XSLT (both 1.0 and 2.0) solution: <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:w="w:w"> <xsl:output omit-xml-declaration="yes" indent="yes"/> <xsl:strip-space elements="*"/> <xsl:variable name="vtheNode" select= "/w:body/w:tbl/w:tr/w:tc[last()]"/> <xsl:template match="/"> <xsl:value-of select="count($vtheNode/preceding::w:p)"/> </xsl:template> </xsl:stylesheet> when this transformation is applied on the provided XML document (with namespace defined to make it well-formed): <w:body xmlns:w="w:w"> <w:p> <w:r> <w:t>para1</w:t> </w:r> </w:p> <w:p> <w:r> <w:t>para2</w:t> </w:r> </w:p> <w:p> <w:r> <w:t>para3</w:t> </w:r> </w:p> <w:p> <w:r> <w:t>para4</w:t> </w:r> </w:p> <w:p> <w:r> <w:t>para5</w:t> </w:r> </w:p> <w:tbl> <w:tr> <w:tc> <w:p> <w:r> <w:t>para6</w:t> </w:r> </w:p> </w:tc> <w:tc> <w:p> <w:r> <w:t>para7</w:t> </w:r> </w:p> </w:tc> <!-- Assume This is my Current Node --> <w:tc> <w:p> <w:r> <w:t>para8</w:t> </w:r> </w:p> </w:tc> </w:tr> </w:tbl> </w:body> the wanted, correct result is produced: 7 Do note: Because the preceding:: and ancestor:: axes are not overlapping, a more general solution that doesn't depend on the structure of the document and takes into account the possibility that some of the wanted to count nodes could be ancestors, is: count($vtheNode/preceding::w:p | ($vtheNode/ancestor::w:p)
{ "language": "en", "url": "https://stackoverflow.com/questions/7553743", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: asp.net auto generated textboxes ID on webform I am using C# on Visual Studio. I want to generate a webform with auto numbered Textboxes depending on the input from the previous page. What is the best way to do this loop? For example: Input is 4 The next page should generate textboxes with ID of * *"name1" *"name2" *"name3" *"name4" Something like this : <asp:TextBox ID="name1" runat="server"></asp:TextBox> <asp:TextBox ID="name2" runat="server"></asp:TextBox> <asp:TextBox ID="name3" runat="server"></asp:TextBox> <asp:TextBox ID="name4" runat="server"></asp:TextBox> Part 2 of my question is that if I want to call them when a Button is click, how should I use a loop the get those ID? A: Use for loop and PlaceHolder control to create dynamic TextBox controls <asp:PlaceHolder ID="phDynamicTextBox" runat="server" /> int inputFromPreviousPost = 4; for(int i = 1; i <= inputFromPreviousPost; i++) { TextBox t = new TextBox(); t.ID = "name" + i.ToString(); } //on button click retrieve controls inside placeholder control protected void Button_Click(object sender, EventArgs e) { foreach(Control c in phDynamicTextBox.Controls) { try { TextBox t = (TextBox)c; // gets textbox ID property Response.Write(t.ID); } catch { } } } A: You could create those controls in the Page Init event handler by say loop for the number of times the control needs to made available. Please remember since these are dynamic controls they need to be recreated during postbacks and will not be done automatically. Further Dynamic controls and postback A: Check this code. In first page... protected void Button1_Click(object sender, EventArgs e) { Response.Redirect("Default.aspx?Name=" + TextBox1.Text); } In second page you can get the value from querystring and create controls dynamically protected void Page_Load(object sender, EventArgs e) { if (Request.QueryString["Name"] != null) Response.Write(Request.QueryString["Name"]); Int32 howmany = Int32.Parse(Request.QueryString["Name"]); for (int i = 1; i < howmany + 1; i++) { TextBox tb = new TextBox(); tb.ID = "name" + i; form1.Controls.Add(tb); } } A: for ( int i=0; i<4; i++ ) { TextBox t = new TextBox(); t.ID = "name" + i.ToString(); this.Controls.Add( t ); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7553745", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Different color for code comments and XML comments in VB.NET I've noticed that in C# XML comments and code comments can have different colors by changing the settings in Tools > Options > Environment > Fonts and Colors > Display Items: - Comment: controls code comments - XML comment: controls XML comments This works well in C# ///<summary>This XML comment is green</summary> //This code comment is red But not in VB.NET '''<summary>This XML comment appears red too even though it's configured as green</summary> 'This code comment is red Is there a way to fix this? A: I don't know which IDE you're using to develop in. For Visual Studio 2010, Click on Tools > Options > Environment > Fonts and Colors. In the Show settings for drop down list, select Text Editor. In Display Items: select Comment. This will change the color of the comments within code. Next in Display Items: select VB XML Comment. This will change the color of the XML comments which are used. There may be 2 items with the same name; I had to change the second one. A: The coloring settings for VB and C# are different for each language. Here's a partial list of the corresponding settings between the two: C# VB Comment Comment XML Doc Attribute VB XML Attribute XML Doc Comment VB XML Comment (the second one) XML Doc Tag VB XML Doc Tag
{ "language": "en", "url": "https://stackoverflow.com/questions/7553746", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Changing the Nhibernate entity to point to new table I am using FLH and recently I changed the name of the table. I dont want to propagate the changes all the way across my layers. Is there a way, where I can retain the same entity name and just change the mapping. For example, my current entity name is Issuer and the table name is also issuer. However, the table name is changed to "counterparty" and I want to retain the entity name as Issuer. How can I achieve this? I found the answer for the above problem. I made use of IAutomappingOverride interface. The sample code is below public class IssuerMap : IAutoMappingOverride<Issuer> { public void Override(AutoMapping<Issuer> mapping) { mapping.Table("Counterparty"); } } Also found some related links Fluent Nhibernate - How to specify table name A: You would need to have a Table("Counterparty") clause in your classmap, as in How to specify table name in Fluent NHibernate ClassMap class?
{ "language": "en", "url": "https://stackoverflow.com/questions/7553747", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is an opaque pointer in C? May I know the usage and logic behind the opaque pointer concept in C? A: Opaque as the name suggests is something we can’t see through. E.g. wood is opaque. Opaque pointer is a pointer which points to a data structure whose contents are not exposed at the time of its definition. Example: struct STest* pSTest; It is safe to assign NULL to an opaque pointer. pSTest = NULL; A: Opaque pointers are used in the definitions of programming interfaces (API's). Typically they are pointers to incomplete structure types, declared like: typedef struct widget *widget_handle_t; Their purpose is to provide the client program a way to hold a reference to an object managed by the API, without revealing anything about the implementation of that object, other than its address in memory (the pointer itself). The client can pass the object around, store it in its own data structures, and compare two such pointers whether they are the same or different, but it cannot dereference the pointers to peek at what is in the object. The reason this is done is to prevent the client program from becoming dependent on those details, so that the implementation can be upgraded without having to recompile client programs. Because the opaque pointers are typed, there is a good measure of type safety. If we have: typedef struct widget *widget_handle_t; typedef struct gadget *gadget_handle_t; int api_function(widget_handle_t, gadget_handle_t); if the client program mixes up the order of the arguments, there will be a diagnostic from the compiler, because a struct gadget * is being converted to a struct widget * without a cast. That is the reason why we are defining struct types that have no members; each struct declaration with a different new tag introduces a new type that is not compatible with previously declared struct types. What does it mean for a client to become dependent? Suppose that a widget_t has width and height properties. If it isn't opaque and looks like this: typedef struct widget { short width; short height; } widget_t; then the client can just do this to get the width and height: int widget_area = whandle->width * whandle->height; whereas under the opaque paradigm, it would have to use access functions (which are not inlined): // in the header file int widget_getwidth(widget_handle_t *); int widget_getheight(widget_handle_t *); // client code int widget_area = widget_getwidth(whandle) * widget_getheight(whandle); Notice how the widget authors used the short type to save space in the structure, and that has been exposed to the client of the non-opaque interface. Suppose that widgets can now have sizes that don't fit into short and the structure has to change: typedef struct widget { int width; int height; } widget_t; Client code must be re-compiled now to pick up this new definition. Depending on the tooling and deployment workflow, there may even be a risk that this isn't done: old client code tries to use the new library and misbehaves by accessing the new structure using the old layout. That can easily happen with dynamic libraries. The library is updated, but the dependent programs are not. The client which uses the opaque interface continues to work unmodified and so doesn't require recompiling. It just calls the new definition of the accessor functions. Those are in the widget library and correctly retrieve the new int typed values from the structure. Note that, historically (and still currently here and there) there has also been a lackluster practice of using the void * type as an opaque handle type: typedef void *widget_handle_t; typedef void *gadget_handle_t; int api_function(widget_handle_t, gadget_handle_t); Under this scheme, you can do this, without any diagnostic: api_function("hello", stdout); The Microsoft Windows API is an example of a system in which you can have it both ways. By default, various handle types like HWND (window handle) and HDC (device context) are all void *. So there is no type safety; a HWND could be passed where a HDC is expected, by mistake. If you do this: #define STRICT #include <windows.h> then these handles are mapped to mutually incompatible types to catch those errors. A: An opaque pointer is one in which no details are revealed of the underlying data (from a dictionary definition: opaque: adjective; not able to be seen through; not transparent). For example, you may declare in a header file (this is from some of my actual code): typedef struct pmpi_s *pmpi; which declares a type pmpi which is a pointer to the opaque structure struct pmpi_s, hence anything you declare as pmpi will be an opaque pointer. Users of that declaration can freely write code like: pmpi xyzzy = NULL; without knowing the actual "definition" of the structure. Then, in the code that knows about the definition (ie, the code providing the functionality for pmpi handling, you can "define" the structure: struct pmpi_s { uint16_t *data; // a pointer to the actual data array of uint16_t. size_t sz; // the allocated size of data. size_t used; // number of segments of data in use. int sign; // the sign of the number (-1, 0, 1). }; and easily access the individual fields of it, something that users of the header file cannot do. More information can be found on the Wikipedia page for opaque pointers.. The main use of it is to hide implementation details from users of your library. Encapsulation (despite what the C++ crowd will tell you) has been around for a long time :-) You want to publish just enough details on your library for users to effectively make use of it, and no more. Publishing more gives users details that they may come to rely upon (such as the fact the size variable sz is at a specific location in the structure, which may lead them to bypass your controls and manipulate it directly. Then you'll find your customers complaining bitterly when you change the internals. Without that structure information, your API is limited only to what you provide and your freedom of action regarding the internals is maintained.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553750", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "98" }
Q: problem of using ssh_connect API in windows I have tested a simple code using libssh on OS X and it worked simply find. But when I port this code on Windows7 using vc10 it doesn't work correctly. The ssh_connect API blocks and not progress any more. The following code is part of the my test program. #include <libssh/libssh.h> ... int _tmain(..) { ssh_session session; session = ssh_new(); if (session == NULL) exit(EXIT_FAILURE); ssh_options_set(session, SSH_OPTIONS_HOST, "localhost"); int port = 1234; ssh_options_set(session, SSH_OPTIONS_PORT, &port); // <-block here !!! int rc = ssh_connect(session); if (rc != SSH_OK) { ... } } I downloaded include, lib and dll files from www.libssh.org no compile and link errors. What's wrong with my code or do I miss something important? A: Maybe it blocks cause the port is wrong? The timeout is 30 min by default iirc. libssh 0.6 will have better timeout handling.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553751", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: JavaScript Communication I was reading about Flex- JavaScript communication via ExternalInterface. But I had a doubt, it said that the javascript code should be written in the HTML file of the application ? Now which is this HTML file ? Is it the index.template.html file per project or the HTML file created per MXML application ? A: You should better use the index.template.html, since this is the file used as a template for the HTMLs generated for each MXML application. Otherwise a simple clean on the project might delete the code you've added to the HTML file created per MXML application. A: Yes, or if it's a lot of javascript, you could externalize it by including a script tag in the index.template.html file. The index.template.html file is used to generate the index.html files in bin-debug and bin-release folders. A: this pages describe external interface very well. Most important thing to not forget is <param name="allowScriptAccess" value="sameDomain" /> And for better flash embeding, use http://code.google.com/p/swfobject/ . http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/external/ExternalInterface.html?filter_flash=cs5&filter_flashplayer=10.2&filter_air=2.6
{ "language": "en", "url": "https://stackoverflow.com/questions/7553754", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Exclude one JS file for a particular page I have two JS files: mail.js and prototype.js prototype.js is from Lightbox plug-in and mail.js is validator and ajax for the contact us page. the problem is mail.js won't work when prototype.js is load before or after it. However I want to remove the prototype.js for contact page only where there's no need for lightbox. I'm using php include as header. Is there a way to set the prototype.js as unload for the contact page only? Thanks A: In the header inlude, can't you just do an if statement like so: if($_SERVER[’PHP_SELF’]!="contact_us.php"){ echo '<script type="text/javascript" src="js/prototype.js"></script>'; } Obviously replace the paths with the correct path. PHP_SELF is relative to domain, so if its in /pages/ then $_SERVER['PHP_SELF'] would equal /pages/contact_us.php Correct answer was if($_SERVER['REQUEST_URI']!="contact_us.php"){ echo '<script type="text/javascript" src="js/prototype.js"></script>'; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7553756", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Custom WordPress Options Function What is in my functions: $var = get_option('to_twitter_feed'); array( "name" => "Twitter Username", "desc" => "Enter your Twitter username for the Twitter feed", "id" => $shortname."_twitter_feed", "type" => "text", "std" => ""), In my WordPress options I have a custom twitter widget. I want users to be able to simply type their name in the input and have it inserted into the widget code. Most of this code is complete: basically, I just need to know how to put the what is called in first code below into the second code. How I call it: <?php echo get_option('to_twitter_feed'); ?> The code I need to put it into (where it says THEUSERNAME): <script type='text/javascript'> jQuery(function($){ $(".tweet").tweet({ username: "THEUSERNAME", join_text: "auto", avatar_size: 32, count: 3, auto_join_text_default: "said,", auto_join_text_ed: "we", auto_join_text_ing: "we were", auto_join_text_reply: "replied to", auto_join_text_url: "was checking out", loading_text: "loading tweets..." }); }); </script> A: if you get twitter username by <?php echo get_option('to_twitter_feed'); ?> then you can set twitter username in java script like this <script type='text/javascript'> jQuery(function($){ $(".tweet").tweet({ username: "<?php echo get_option('to_twitter_feed'); ?>", join_text: "auto", avatar_size: 32, count: 3, auto_join_text_default: "said,", auto_join_text_ed: "we", auto_join_text_ing: "we were", auto_join_text_reply: "replied to", auto_join_text_url: "was checking out", loading_text: "loading tweets..." }); }); </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/7553758", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MessageDigest digest() method Shouldn't the digest() method in MessageDigest always give the same hash value for the same input? I tried this and I am getting different set of hashvalues for the same input everytime md5 = MessageDigest.getInstance("MD5"); System.out.println(md5.digest("stringtodigest".getBytes())); System.out.println(md5.digest("stringtodigest".getBytes())); System.out.println(md5.digest("stringtodigest".getBytes())); Update: Changed the param to digest() method A: You're seeing the results of calling byte[].toString() - which isn't showing you the actual hash of the data. You're basically getting a string which shows that you've called toString on a byte array (that's the [B part) and then the hash returned by Object.hashCode() (that's the hex value after the @). That hash code doesn't take the data in the array into account. Try System.out.println(Arrays.toString(md5.digest(byteArrayToDigest))); to see the actual data. EDIT: Quick note about creating an MD5 digest from string data - you should always use the same encoding, explicitly, when hashing. For example: byte[] hash = md5.digest(text.getBytes("UTF-8"));
{ "language": "en", "url": "https://stackoverflow.com/questions/7553760", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Check if Windows imaging components is installed (wic registry) How to check whether windows imaging component is installed or not on 64 bit XP machine. A: Windows imaging component gets installed along with the MSOFFICE. if not check in registry >> HKEY_LOCAL_MACHINE\Software\Microsoft\Windows Imaging Component Check for InstalledVersion in that regdirectory. If that key is present then windows imaging component is installed else not A: Check : C:\Windows\System32\WindowsCodecs.dll If Windows Imaging Component (WIC) not Installed then Install Windows Imaging Component before installing SSR 2013 on Windows 2003 or XP system. 32-bit: www.microsoft.com/en-us/download/details.aspx?id=32 64-bit: http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=1385 A: Check the existence of C:\Windows\System32\WindowsCodecs.dll A: I found the registry located at: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\WIC A: Try to create instance by: CComPtr<IWICImagingFactory> pImagingFactory; HRESULT hr = CoCreateInstance(CLSID_WICImagingFactory, 0, CLSCTX_INPROC_SERVER, IID_IWICImagingFactory, (void**)&pImagingFactory); if (SUCCEEDED(hr) && pImagingFactory != NULL) { pImagingFactory.Release(); pImagingFactory = NULL; return false; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7553764", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: jQuery ui-effects-wrapper is chopping off the bottom of a divs content whilst using .show("slide", I am using $('#account-slide').show("slide", {direction: "right"}, 1000); to display a div when a button is clicked. The problem is the ui-effects-wrapper class that is applied to the div when the button is clicked cuts of the div whilst it is moving. Once the div reaches it's destination the div returns to it's normal state and you can see it in it's entirety. Any ideas why the ui-effects-wrapper class would be causing this? Thanks for your help. A: I had a very similar issue where as the element would slide in and the element would be clipped on the bottom because of a height defined by jQuery directly to the animated element during the animation (in my case 28px). There are two ways you can go about fixing this that I've found -- * *Set an explicit height to the wrapper div, then set the inner div (or element) to have a height of height: 100% !important; *Set an explicit height to the actual element, as specific as possible in the css, by doing height: 32px !important; Thanks for your solution Max, mine is a bit of a refinement for my particular case based on your initial conclusion. A: Ok, in the end I just needed to ensure everything contained within the div I wanted to slide was set to height: 100% This is because the ui-effects-wrapper doesn't seem to like auto heights whilst sliding a containing div.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553768", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to replace text in a makefile in a way that works with make AND dmake? I've got this makefile: ALL = ../lib/Mo.pm \ ../lib/Mo/builder.pm \ ../lib/Mo/default.pm \ ../lib/Mo/has.pm \ all: $(ALL) $(ALL): Mo.pm compress.pl Makefile perl compress.pl $(@:../lib/%=%) > $@ What it's meant to do is something like this: $ make -n perl compress.pl Mo.pm > ../lib/Mo.pm perl compress.pl Mo/builder.pm > ../lib/Mo/builder.pm perl compress.pl Mo/default.pm > ../lib/Mo/default.pm perl compress.pl Mo/has.pm > ../lib/Mo/has.pm However with dmake on Windows this happens: d:\mo-pm\src>dmake -n perl compress.pl ..\lib\Mo.pm > ..\lib\Mo.pm perl compress.pl ..\lib\Mo\builder.pm > ..\lib\Mo\builder.pm perl compress.pl ..\lib\Mo\default.pm > ..\lib\Mo\default.pm perl compress.pl ..\lib\Mo\has.pm > ..\lib\Mo\has.pm I've been trying out various combinations of s/// and subst to make it work in dmake, and found out that it wants the path to have \s, which means a double substitution against both variants of the path (../lib/ and ..\lib) could work, but i can't figure out how to make it work for both make variants. Any ideas or other ways to do this? A: It's not only that the dir separator chars are different for both versions, moreover the dmake syntax seems to be deliberately designed to be incompatible with GNU make. The only part of the syntax that is actually compatible is pattern substitution, so this is the way to go: all: $(ALL) $(ALL) : Makefile compress.pl ../lib/%.pm : %.pm perl compress.pl $< > $@ dmake actually substitutes the / for directory separator chars for you here. I've tested this Makefile with an echo instead, and it writes to the right directory. Explanation: The pattern rules define rules for a particular file to be re-made when it matches a regular expression (the ../lib/%.pm part) and a prerequisite of a similar name is found (%.pm). The % in the prerequisite is replaced by the matching part of the % in the target. The extra rule with Makefile and compress.pl is needed because dmake doesn't like extra prerequisites in a pattern rule. As usual, $< and $@ are make's special variables for source and target file. So, the core difference is that your original rule said "the files named in this list can be made with the following rule), while the pattern rule says "any file looking like ../lib/%.pm can be made from a matching file in the current directory" and then gives a list of pm files to make. Pattern rules are actually quite powerful, useful to know. Unfortunately, some makes don't know them, only the older suffix rules. Further details of what's going on can be obtained by running make -rdn
{ "language": "en", "url": "https://stackoverflow.com/questions/7553770", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to show popover on selecting an image I am trying to show a popover on selection of a image in my iPad.So how can i do it? A: Put a transparent button on the image and of the size of the image and then use the UIPopoverController to launch a pop over view... hope this helps. A: - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *mousePoint = [touches anyObject]; CGPoint point = [mousePoint locationInView:self.view]; _didClickMark=CGRectContainsPoint(mImageView.frame, point); if(_didClickMark) // show popover } This might help you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553777", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to sort dates by some particular order from the data [iphone] I have got some dates for some events and their ascending order from the database . Now , I want want some buttons .. in this structure ... --######## Last Week #####---- --######## yesterday #####---- --######## today #####---- --######## tomorrow #####---- --######## Next Week #####---- Now when I press the respected buttons .. the events in that respected duration should be shown up .. I mean all the data should be compared with today and all the data should be shorted by this order.. can anyone give me a idea or logic for this ? A: The best way to deal with dates is by using NSDateComponents. for example, to get the date for tomorrow use: NSCalendar *cal = [NSCalendar currentCalendar]; NSDateComponents *comp = [[[NSDateComponents alloc] init] autorelease]; [comp setDay:1]; NSDate *today = [NSDate date]; NSDate *tomorrow = [cal dateByAddingComponents:comp toDate:today options:0]; So, what you need to do is: * *Get the dates for all the relevant date categories *When you push a button, build a predicate to retrieve only the objects between the two dates. For example, getting all the objects in the "tomorrow" category: NSPredicate *pred = [NSPredicate predicateWithFormat:@"date > %@ AND date < %@", tomorrow, nextWeek]; You can use a small convenient method for getting the dates, by adding a category to NSDate with this method: @implementation NSDate (Components) -(NSDate *) dateByAddingCalendarUnit:(NSCalendarUnit)calendarUnit andCount:(NSInteger) count { NSDateComponents *comp = [[NSDateComponents alloc] init]; switch (calendarUnit) { case NSSecondCalendarUnit: [comp setSecond:count]; break; case NSMinuteCalendarUnit: [comp setMinute:count]; break; case NSHourCalendarUnit: [comp setHour:count]; break; case NSDayCalendarUnit: [comp setDay:count]; break; case NSWeekCalendarUnit: [comp setWeek:count]; break; case NSWeekdayCalendarUnit: [comp setWeekday:count]; break; case NSWeekdayOrdinalCalendarUnit: [comp setWeekdayOrdinal:count]; break; case NSMonthCalendarUnit: [comp setMonth:count]; break; case NSYearCalendarUnit: [comp setYear:count]; break; case NSEraCalendarUnit: [comp setEra:count]; break; default: break; } NSCalendar *cal = [NSCalendar currentCalendar]; NSDate *newDate = [cal dateByAddingComponents:comp toDate:self options:0]; [comp release]; return newDate; } @end And use this method like this: NSDate *lastWeek = [[NSDate date] dateByAddingCalendarUnit:NSWeekCalendarUnit andCount:-1];
{ "language": "en", "url": "https://stackoverflow.com/questions/7553778", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Remove case from code config.php define('DB_TYPE', 'MYSQL'); dbManager.php incude_once('config.php'); switch ( DB_TYPE ) { case 'MYSQL': $this->_dataObject = MySqlDB::_getInstance(); break; case 'PGSQL': $this->_dataObject = PostgreDB::_getInstance(); break; case 'SQLITE': $this->_dataObject = SqliteDB::_getInstance(); break; } Can this piece of code be rewritten without the case? Something like: $this->_dataObject = DB_TYPE::_getInstance(); This gives me an error Fatal error: Class 'DB_TYPE' not found .... in line ... A: maybe $DBClassName = 'MySqlDB'; $this->_dataObject = $DBClassName::_getInstance(); A: Try: $c = TYPE; $this->_dataObject = $c::_getInstance(); however, this code looks like it could benefit from dependency injection class YourClass { public function __construct(DataObject $dataObject) { $this->_dataObject = $dataObject; } } then pass the dataobject to your class while instantiating it A: $dbClasses = array( 'MYSQL' => 'MySqlDB', 'PGSQL' => 'PostgreDB', 'SQLITE'=> 'SqliteDB', }; $dbClass = $dbClasses[DB_TYPE]; $this->_dataObject = $dbClass::_getInstance();
{ "language": "en", "url": "https://stackoverflow.com/questions/7553791", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Installing pow rack server from source on 32bit CPU Found out about pow just now and trying to install it on a laptop with a 32bit processor. I am running into (hopefully) a minor error. During the installation from source I get the following error: *** Installing local configuration files... mkdir: /Users/username/Library/Application Support: Permission denied node.js:134 throw e; // process.nextTick error, or 'error' event on first tick ^ Error: Command failed: mkdir: /Users/username/Library/Application Support: Permission denied at ChildProcess.exithandler (child_process.js:102:15) at ChildProcess.emit (events.js:67:17) at Socket.<anonymous> (child_process.js:172:12) at Socket.emit (events.js:64:17) at Array.<anonymous> (net.js:837:12) at EventEmitter._tickCallback (node.js:126:26) pow@0.3.2 /usr/local/lib/node_modules/pow ├── log@1.2.0 ├── async@0.1.8 ├── coffee-script@1.1.2 ├── nack@0.13.1 (netstring@0.2.0) └── connect@1.7.1 I have tried to change the permissions on the application support folder using: sudo chmod 777 ~/Library/Application\ Support/ and can verify the permissions using: ls -la ~/Library/ | less I get the following: drwxrwxrwx+ 15 username blah 510 26 Sep 19:16 Application Support Can anyone point me in the right direction as I seem to have hit a brick wall thanks A: From completly unrelated git issue: sudo chown -R $USER /usr/local/ & then run install without sudo npm -g install Worked for me...
{ "language": "en", "url": "https://stackoverflow.com/questions/7553795", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Multiple validators on one field with JSF bean validation i am trying to make multiple validation one one field @NotBlank(message = "{name.required}") @Max(value = 25, message = "{long.value}") public String name; JSF: <h:inputText id="name" value="#{person.name}" size="20"> </h:inputText> <h:message for="name" style="color:red" /> but when i leave the field empty, it shows both error messages. any ideas how to handle both cases, validate the empty, and maximum length independently. A: If your JSF 2 configuration interpret empty submitted values as "" and not null then : The @NotBlank validator returns false because your annotated string is empty. The @Max validator returns false because according to hibernate implementation (I guess you are using hibernate implementation base on your previous posts). public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) { //null values are valid if ( value == null ) { return true; } try { return new BigDecimal( value ).compareTo( BigDecimal.valueOf( maxValue ) ) != 1; } catch ( NumberFormatException nfe ) { return false; } } In your case the value String parameter contains an empty value ("") and the BigDecimal(String) constructor throws an exception and then the validator returns false. You have two possible solutions: * *Configure JSF to interpret empty submitted values as null (or) *Change your field name type to numerical instead of String.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553796", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: I have got a problem in evaluation of a code I have something like this "This" + " " + "is" + " " + "the" + " " + row["Message"].ToString() + " " + "test" + " " + "sms" + " " + "to" + " " + row["Name"].ToString(); which is constructed when the code executes A: Not really sure what your question is but might I recommend you use string.Format? var message = string.Format("This is the {0} test sms to {1}", row["Message"], row["Name"]); A: this is an horrible string concatenation practice, not easily readable and a mess to understand and maintain, I suggest you to replace it with something like this using string.Format method: var result = String.Format("This is the '{0}' test sms to '{1}'", row["Message"].ToString(), row["Name"].ToString());
{ "language": "en", "url": "https://stackoverflow.com/questions/7553799", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-5" }
Q: django 1.3 upgrade problem I recently updgraded to django 1.3. After the upgrade, I get the following error whenever I used request.POST: Traceback (most recent call last): File "/usr/lib/python2.4/site-packages/django/core/handlers/base.py", line 86, in get_response response = None File "/public/gdp/trunk/src/ukl/lis/process/utils/error_handler.py", line 15, in __call__ return self.function(*args, **kwargs) File "/usr/lib/python2.4/site-packages/django/views/decorators/cache.py", line 30, in _cache_controlled # and this: File "/public/gdp/trunk/src/ukl/lis/process/authentication/views.py", line 438, in login form = loginForm(request.POST) File "/usr/lib/python2.4/site-packages/django/core/handlers/modpython.py", line 101, in _get_post self._load_post_and_files() AttributeError: 'ModPythonRequest' object has no attribute '_load_post_and_files' Once I reverted back to django 1.0 the error is fixed. Why is django 1.3 alone throwing this error? How to correct it? A: Stepping from Django 1.0 to Django 1.3 is a big jump, a lot of items might have been deprecated or no longer used, I recommend you to just check some of the documentation for the middleware_classes Django Middleware documentation A: I tried re-installing my mod-python and now the error is fixed. Now thinking of migrating to mod_wsgi.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553802", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Webkit @font-face not working properly fonts.css: @font-face { font-family: 'ubuntu'; src: url('../fonts/Ubuntu-Regular.ttf') format('truetype'); } @font-face { font-family: 'ubuntu-bold'; src: url('../fonts/Ubuntu-Bold.ttf') format('truetype'); } @font-face { font-family: 'ubuntu-medium'; src: url('../fonts/Ubuntu-Medium.ttf') format('truetype'); } @font-face { font-family: 'ubuntu-mediumitalic'; src: url('../fonts/Ubuntu-MediumItalic.ttf') format('truetype'); } The elements get the correct font-family attribute, however the styles are messed up. For example ubuntu-medium gets displayed as regular weight, and ubuntu-bold gets displayed with medium weight fonts. I tried to set the font-weight property at element level and in @font-face too, but it did not bring success. Works properly in Chrome or Firefox. Is there a way to fix this? A: found an article on this issue: WEBKIT (SAFARI 3.1) AND THE CSS @FONT-FACE DECLARATION
{ "language": "en", "url": "https://stackoverflow.com/questions/7553803", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Disabling the 'Save' and 'Save and continue editing' buttons for a model in the Django admin I'm writing the admin view for the model in my Django application. This admin view should a be a read-only view. I don't want anyone creating or deleting records either. I've managed to prevent user's from creating and deleting records. Here's my model's admin class: class EmailAdmin(admin.ModelAdmin): """ Admin part for managing the the Email model """ list_display = ['to', 'subject', 'ok',] list_filter = ['ok'] readonly_fields = ['when', 'to', 'subject', 'body', 'ok'] search_fields = ['subject', 'body', 'to'] def has_delete_permission(self, request, obj=None): return False def has_add_permission(self, request): return False When the user clicks on a record in the admin, it takes him to the detail view where he can't edit anything as all the fields are read-only but he continues to see two buttons on the lower-right hand side of the admin console that read 'Save' and 'Save and continue editing'. Is it possible to remove these links? I'd like to have a total read-only admin view. Thanks.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553809", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ListView onItemClick area is different on phone & tablet I have a ListView which has been constructed, styled and had an adapter set from code which is common across both devices. Curiously however, on my phone (2.3.4) only the text is clickable. On the Tablet (3.1) the entire ListView item is clickable. On the tablet the text is also right aligned. The only difference is that on the Tablet the ListView has had it's LayoutParams width set programmatically to "240dp". So far I haven't added any listeners to either the Views from the adapter (a SimpleCursorAdapater) or on the ListView itself. Has anyone run into this before? A: Bit ready to end it all at this point, I eventually stumbled upon the solution in my investigations: I changed the XML governing the ListView - It was set to "wrap_content" (so the width of the ListView was the width of the largest element of the list). I instead set it's width to "match_parent" to stretch across it's container. Apparently each item of a ListView set to "match_parent" will inherit the initial attributes of their parents, not their current attributes (at least not in terms of width/height). Broken unintuitive logic if you ask me.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553813", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: None jquery placeholder fallback? I'm looking for a javascript project that provide fallback for the html5 placeholder, but all projects I found are in the form of a jquery plugin, are there any pure JavaScript implement out there? A: I wrote one myself, and put it on Google Code: http://code.google.com/p/placeholder-fixer/
{ "language": "en", "url": "https://stackoverflow.com/questions/7553816", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Extracting specific data from a Mutable Dictionary I have a Mutable Dictionary which allows people to choose a selection of days of the week. Once a day has been selected the state is updated using numberWithBool. When I NSLog the output it looks something like this: { day = Monday; isSelected = 1; }, { day = Tuesday; isSelected = 0; }, { day = Wednesday; isSelected = 0; }, { day = Thursday; isSelected = 0; }, { day = Friday; isSelected = 0; }, { day = Saturday; isSelected = 0; }, { day = Sunday; isSelected = 1; } I would like to be able to extract the chosen days and produce the output in the form of a string. So in this example the output would be: Monday, Sunday How can I do this? My code for creating the dictionary is below: NSMutableArray * tempSource = [[NSMutableArray alloc] init]; NSArray *daysOfWeek = [NSArray arrayWithObjects:@"Monday", @"Tuesday", @"Wednesday", @"Thursday", @"Friday", @"Saturday", @"Sunday",nil]; for (int i = 0; i < 7; i++) { NSString *dayOfWeek = [daysOfWeek objectAtIndex:i]; NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:dayOfWeek, @"day", [NSNumber numberWithBool:NO], @"isSelected",nil]; [tempSource addObject:dict]; } [self setSourceArray:tempSource]; [tempSource release]; A: You can loop thru all of your items in the array and build a side-array only containing names of the day (1), or you can use a predicate and then KVC to extract the days directly (2). Then join the components of the filtered array into a string. Solution 1: NSMutableArray selectedDays = [[NSMutableArray alloc] init]; for(NSDictionary* entry in sourceArray) { if (([entry objectForKey:@"isSelected"] boolValue]) { [selectedDays addObject:[entry objectForKey:@"day"]]; } } NSString days = [selectedDays componentsJoinedByString:@", "]; [selectedDays release]; Solution 2: NSPredicate* filter = [NSPredicate predicateWithFormat:@"SELF.isSelected == 1"]; // not sure about the exact format (no mac here to test right now so you may adapt a bit if it does not work directly) // get the array of dictionaries but only the ones that have isSelected==1 NSArray selectedEntries = [sourceArray filteredArrayUsingPredicate:filter]; NSArray selectedDays = [selectedEntries valueForKey:@"day"]; // extract the "days" keys of the dictionaries. We have a NSArray of strings then. NSString days = [selectedDays componentsJoinedByString:@", "]; As a side note, your way of doing this is quite strange. Why having an NSArray of NSDictionaries for this? As this is simple and a static-size array containing only BOOL, you may instead for this particular case simply use C array BOOL selected[7] and nothing more. Then to have the name of the weekdays you should instead use the methods of NSCalendar/NSDateFormatter/NSDateComponents to get the standard names of the weekdays (automatically in the right language/locale of the user): create an NSDate using a NSDateComponent for which you simply define the weekday component, then use an NSDateFormatter to convert this to a string, choosing a string format that only display the weekday name. -(void)tableView:(UITableView*)tv didSelectRowAtIndexPath:(NSIndexPath*)indexPath { // selectedDays is an instance variable in .h declared as // BOOL selectedDays[7]; selectedDays[indexPath.row] = ! selectedDays[indexPath.row]; [tv reloadData]; } -(UITableViewCell*)tableView:(UITableView*)tv cellForRowAtIndexPath:(NSIndexPath*)indexPath { static NSString* kCellIdentifier = @"DayCell"; UITableViewCell* cell = [tv dequeueReusableCellWithIdentifier:kCellIdentifier]; if (!cell) { cell = [[[UITableViewCell alloc] initWithStyle:... identifier:kCellIdentifier]; autorelease]; // configure here every property that is common to all for your cells (text color, etc) } // configure here things that will change from cell to cell cell.accessoryType = selectedDays[indexPath.row] ? UITableViewCellAccessoryTypeCheckmarck : UITableViewCellAccessoryTypeNone; cell.textLabel.text = weekdayName(indexPath.row); return cell; } // Simple C function to return the name of a given weekday NSString* weekdayName(int weekday) { #if WAY_1 /**** Solution 1 ****/ // Optimization note: You may compute this once for all instead of recomputing it each time NSDateComponents* comp = [[[NSDateComponents alloc] init] autorelease]; [comp setWeekday:weekday+1]; // weekdays start at 1 for NSDateComponents NSDate* d = [[NSCalendar currentCalendar] dateFromComponents:comp]; NSDateFormatter* df = [[[NSDateFormatter alloc] init] autorelease]; [df setDateFormat:@"EEEE"]; // format for the weekday return [[df stringFromDate:d] capitalizedString]; #else /**** Solution 2 ****/ NSDateFormatter* df = [[[NSDateFormatter alloc] init] autorelease]; NSArray* weekdayNames = [df weekdaySymbols]; // or maybe one of its sibling methods? check what is returned here to be sure return [weekdayNames objectAtIndex:weekday]; #endif } A: Is there a reason that you avoid NSMutableIndexSet? It may simplify your code to: NSArray *daysOfWeek = ...; NSMutableIndexSet *indexesOfSelectedDays = ...; NSArray *selectedDays = [daysOfWeek objectsAtIndexes:indexesOfSelectedDays]; A: Use NSPredicate to create a predicate that selects the items in the array where isSelected is true, and use that to filter the array using NSArray's -filteredArrayUsingPredicate: method. (@Miraaj posted a good example of using a predicate faster than I could type it.) Then take that filtered array and pick out the days, like this: NSArray *selectedItems = [sourceArray filteredArrayUsingPredicate:somePredicate]; NSArray *days = [selectedItems valueForKey:@"day"]; NSString *daysString = [days componentsJoinedByString@", "];
{ "language": "en", "url": "https://stackoverflow.com/questions/7553820", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MVC non-area route problems (alongside areas) How should I configure the following non area routes? /foo/{controller}/{action}/{id} maps to controllers in namespace myapp.foo. /{controller}/{action}/{id} maps to controllers in namespace myapp. I also have 2 areas, bar and baz, they are registered with registeraAllAreas. My current setup This is my current setup. It gives the problem below when I use the url /Home/Index. routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.IgnoreRoute("myapp/elmah.axd/{*pathInfo}"); AreaRegistration.RegisterAllAreas(); routes.MapRoute( "foo", // Route name "foo/{controller}/{action}/{id}", // URL with parameters new { action = "Index", id = UrlParameter.Optional }, // Parameter defaults new string[] { "myapp.Controllers.foo" } ); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // Parameter defaults new string[] { "myapp.Controllers" } ); Multiple types were found that match the controller named 'Menu'. This can happen if the route that services this request ('foo/{controller}/{action}/{id}') does not specify namespaces to search for a controller that matches the request. The request for 'Menu' has found the following matching controllers: myapp.Controllers.MenuController myapp.Areas.bar.Controllers.MenuController myapp.Areas.baz.Controllers.MenuController Clearly there's something I'm doing the wrong way. Update I also get the wrong adress generated when I use: <% using (Ajax.BeginForm("SaveSomething", "Home", ... It renders <form target="/foo/Home/SaveSomething" I'm guessing that one cannot reliably use {controller} in two routes in the same area. Update 2 It seems to work much better when I put the /foo route registration at the bottom. This raises the question, what is considered a/the default route? (As the default route is reccomended to be put at the very end.) A: You have two controllers that has the name MenuController so MVC doesn't know which one to use if you don't give it more information. In you areas you probably have a files named something like <YourAreaName>AreaRegistration. Open those files and update the RegisterArea method so you route the request to the right controller. From your error message it seems like the route is getting mapped to foo/{controller}/{action}/{id}, which doesn't have a MenuController. My guess is that you have a action link on a page under foo something something. That will generate an incorrect link if you don't specify the area for the link. Try this to use the default route with ActionLink: @Html.ActionLink("Some text", "action", "controller", new { area = "" }, null) If you want the request to go to a specific area just write it down in the call. UPDATE: The problem is that when you write something like Ajax.BeginForm("SaveSomething", "Home",...) it will match the first route. You can't solve this by putting the area in the BeginForm statement as I suggested before since the foo route is not an area. You have two options, 1: move the foo part to an area, 2: put the foo route after the default route. If you put the default route before the foo route you will get a hard time rendering urls as long as you have foo in the same area as the default route (the default area), since the route engine will always find the default one first. However, you will be able to catch request to the foo route. So my best suggestion is to put the foo route in an area.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553823", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to add task to run parallel selenium tests in build.gradle In our project we are using gradle to nuke the DB and also using gradle to run the selenium test cases in different suites. I am trying to run selenium test casses parallely. How to add task for that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553831", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: In MVC how to debug what the database doesn't like when it breaks on db.SaveChanges(); I've always wondering about this as from time to time I've encountered it with no clear indication where the problem lies. Typically I've solved this by a process of elimination but I was hoping someone could help me with a better way which I could ideally use to provide clearer/more precise error handling? Any help would be much appreciated. thx. p.s. in case it helps I'm developing in C#. A: I use sql server profiler for figuring out issues with edmx queries. And for finding out select queries being generated for linq-to-entity, like in following case, var linqquery = from s in db.Employees where s.name = "john" select s; you can use string logQuery = ((System.Data.Objects.ObjectQuery)linqquery).ToTraceString(); EDIT Dont know anything that MVC provides for EF logging. Even EF does not have a logging built in! (LINQ-to-SQL has a Log property). Found these links which allows you to add logging to EF. http://blogs.msdn.com/b/jkowalski/archive/2009/06/11/tracing-and-caching-in-entity-framework-available-on-msdn-code-gallery.aspx or http://codeclimber.net.nz/archive/2010/12/08/Logging-all-SQL-statements-done-by-Entity-Framework.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7553832", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What does hh23 mean on oracle I read a lot of tutorial which uses hh23 and hh24 interchangeably. to do to_char on oracle. Is the hh23 a legacy syntax? I tried doing it on simple query and it causes an error. select to_char(sysdate, 'hh23'), to_char(sysdate, 'hh24') from dual I'm trying to find a reference to this but there is none. Or is the tutorial just written wrong? For example on http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:59412348055. A: It is just a typing error in untested code. 'hh23' will always give an error. A: I think it's just a typo. SQL> select to_char(sysdate, 'hh23:mi:ss') from dual 2 / select to_char(sysdate, 'hh23:mi:ss') from dual * ERROR at line 1: ORA-01821: date format not recognized SQL> select to_char(sysdate, 'hh24:mi:ss') from dual 2 / TO_CHAR( -------- 11:25:21 SQL>
{ "language": "en", "url": "https://stackoverflow.com/questions/7553834", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Would that be possible to add a JavaScript file to the page conditionally without using Server side code? I have 2 javascript files; Project.js and Project-debug.js. When my ASP.NET is running in DEBUG mode the later should be loaded and when in RELEASE mode, the former. Would that be possible to do something like this in html to add my script? e.g. <script src="iif(DEBUG,../Scripts/Project-debug.js,../Scripts/Project.js" type="text/javascript"></script> A: Have a look at Conditionally Load external javascript A: Yes, it can be done: <script type="text/javascript"> var fileref = document.createElement('script'); fileref.setAttribute("type", "text/javascript"); if (DEBUG) { fileref.setAttribute("src", "Project-debug.js"); } else { fileref.setAttribute("src", "Project.js"); } document.getElementsByTagName("head")[0].appendChild(fileref); </script> add this inside your head tag
{ "language": "en", "url": "https://stackoverflow.com/questions/7553835", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: how to embed javadb or hsqldb into java application with hibernate using netbeans? I successfuly embedded javadb in my application using the classpath ,but here's the problem : I want hibernate to be able to work with the database,but I always get an error in netbeans sayng "enable to establish connection ". AnyHelp please ? A: The URL for a local HSQLDB database is jdbc:hsqldb:file:file_path_name The file_path_name is usually an absolute path with a name at the end. The database engine will then create a few files with the given name, but predefined extensions. An example of this is: jdbc:hsqldb:file:/mydata/mydb which will produce mydb.properties , mydb.script and a couple other files in the /mydata directory.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553840", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there a Silverlight equivalent of ITypedList? I have a collection of objects, each of which holds a set of name-value pairs. The names are the same across all objects. I'd like to show these as columns in a data grid. In Winforms/WPF I'd use ITypedList with some PropertyDescriptor instances to provide some fake properties to the runtime. However this type does not seem to be available in Silverlight. So, is there an alternative, or does this not exist in Silverlight? EDIT adding some code to frame the scenario better public class Cell { public string Name { get; private set; } public string Value { get; private set; } } public class Row { public IEnumerable<Cell> Cells { get; private set; } } public class ViewModel { public IEnumerable<Row> Rows { get; private set; } } <sdk:DataGrid ItemsSource="{Binding Rows}" /> How can I get the row/cell lookup to work and populate the DataGrid? Specifically I want the grid to update via binding once the Rows property changes (assume it raises a change event that the binding responds to.) A: In the end I was able to solve this issue by using bindings and a string indexer. public class Row { public RowData Data { get; private set; } } public class RowData { public string this[string name] { get { return ...; } } } Then build the grid columns manually: foreach (var column in Columns) { _grid.Columns.Add(new DataGridTextColumn { Binding = new Binding(string.Format("Data[{0}]", column.Name)), Header = column.Name, IsReadOnly = true }); } This meant that the data updated automatically, because in my case the entire Data property was replaced, and INotifyPropertyChanged implemented to notify the binding.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553847", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Blackberry Package Project for Multiple OS Targets/Versions I'm using the Eclipse plug-in and my app runs on the following simulators: 9800, 9700, 8900 ,i.e, it is compatible with OS versions 5 and 6. However , when I package the application to run it on a device, the .alx file is generated correctly but there is also a folder called '6.0.0' with all the other files like .cod, .jar, etc. My question is, shouldn't there be a similar folder '5.0.0' with files for OS version 5? And if yes, then how do I go about generating it?Please help! A: Just Check the project properties, it will be 6.0 JRE. To be clear, you need to install the 5.0 in Eclipse by going through Help menu-Install Software, and add the Blackberry update site: http://www.blackberry.com/go/eclipseUpdate/3.6/java. Download the required OS from there. Then, right click in the project, go to properties of the project and in it go Java Build Path, and under it, go to Libraries tab, you will find JRE to be 6.0, you need to change it to 5.0. A: Ok just incase someone else is as frustrated by this as I was here's the solution: Changing BlackBerry JRE to an Older Version (Eclipse Plug-in)
{ "language": "en", "url": "https://stackoverflow.com/questions/7553851", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Accessing forms from different locations in WPF Still getting used to WPF from a win forms programmer. I have multiple forms in an application that can be accessed from multiple locations, so I need to keep the forms "global" as I'm not sure of a better terminology. For instance "Details" can be opened from a "Main Menu" but can also be opened from a grid in "Search", I'd like the details returned from the search to be displayed in the "Details" page even if it was pre-opened from the main menu. I've come across Application.Current.Properties and have started storing a few forms in it but it just feels plain wrong to set: Vehicle vehicleForm = new Vehicle(); Application.Current.Properties["frmVehicle"] = vehicleForm; And then to access it: if (Application.Current.Properties["frmVehicle"] == null) Application.Current.Properties["frmVehicle"] = new frmVehicle(); Vehicle vehicleFrm = (Vehicle)Application.Current.Properties["frmVehicle"]; vehicleFrm.Show(); vehicleFrm.Activate(); I have just discovered Application.Current.Windows as well which has thrown me a little. What is the most efficient/industry standard way of dealing with form like this? A: I would just check whether Application.Current.Windows contains an instance of your window. If so then you give it focus, if not then you create an instance. A: I'm not sure if I understand how are you opening the window correctly. But if all you want to do is to have one instance of the window through the whole run time of the application, you can use the Singleton pattern. Basically, the window class has a static property that holds the only instance. If you don't need to keep any state in the window, you can just create new instance of it every time you want to show it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553855", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: SQL Server - Stored procedure execution time issue Recently on our PRODUCTION SERVER - we have started to face issues - where query which use to take just 5 mins are taking more than 30 mins to complete. And sometimes they are back to normal. I have checked nothing change in Data volume but still query run sometimes slow and sometimes fast. How to diagnose these type of issues. Regards A: Sounds like parameter sniffing (several SO links) The quick way to check is run sp_updatestats and see if it fixes the issue. This will invalidate all query plans and confirm (or not) parameter sniffing For more, read "Slow in the Application, Fast in SSMS?" by Erland Sommarskog A: Did you see , the break down of query by using, estimated execution plan in SQL Management Studio for your query.. While running your Query? It will give the % of time spent in executing your query. A: put the following line after each step in your proc it will help you find out which part is taking how much time. So you can figure out the reasons. It helps me all the time print convert(varchar(50),getdate(),109) P.S. after executing your proc see the message tab there it will show you datetime with millisecs
{ "language": "en", "url": "https://stackoverflow.com/questions/7553859", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to assign multiple UIButtons to a UITextView I want to assign two UIButtons to UITextView so that when one of the buttons is pressed the textview content should change from what it had when the previous button was pressed. A: MyViewController.h: @interface MyViewController : UIViewController { NSString* savedText; } @property(nonatomic, retain) IBOutlet UITextView* textView; - (IBAction)buttonOnePressed:(id)sender; - (IBAction)buttonTwoPressed:(id)sender; @end Connect the view controller's textView outlet to the text view in the xib file. Connect the buttons to the corresponding actions. (See Apple's Xcode tutorial if you don't know how to do this.) MyViewController.m: - (void)buttonOnePressed:(id)sender { [savedText release]; savedText = [textView.text copy]; } - (void)buttonTwoPressed:(id)sender { textView.text = savedText; } (These aren't the complete files, of course, just the bits to make it do what you're asking.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7553860", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Addressbook + UITableView indexing iPhone I just want to retrieve all Address book contacts and display that in UITableView. Display that all contacts as shown in image. I don't know how to do this. Please suggest me to solve this problem. Thanks in advance... A: Your frined is ABAddressBook: http://developer.apple.com/library/mac/#documentation/UserExperience/Reference/AddressBook/Classes/ABAddressBook_Class/Reference/Reference.html It has (NSArray *)people that returns you all contacts. You can use that as the source for your table. I do not have complete sample code available but I think that is not the point of Stack Overflow. Search here at SO to find how to implement UITableView. A: Here is the solution that you are looking for. In that, you will get required data from the method -(void)collectContacts. A: Yeah, I got the solution... Use this code // creating the picker ABPeoplePickerNavigationController *picker = [[ABPeoplePickerNavigationController alloc] init]; // place the delegate of the picker to the controll picker.peoplePickerDelegate = self; // showing the picker [self presentModalViewController:picker animated:NO]; // releasing [picker release]; and It will display all contacts from iPhone as shown in figure..but not display that type of view in simulator..you have to run it in device... Happy Coding...
{ "language": "en", "url": "https://stackoverflow.com/questions/7553862", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Haskell. MongoDB driver or Aeson charset problem Good day, i have mongodb database filled with some data, i ensured that data stored in correct charset, to fetch data i use following snippet: {-# LANGUAGE OverloadedStrings #-} import Network.Wai import Network.Wai.Handler.Warp (run) import Data.Enumerator (Iteratee (..)) import Data.Either (either) import Control.Monad (join) import Data.Maybe (fromMaybe) import Network.HTTP.Types (statusOK, status404) import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as L import Data.ByteString.Char8 (unpack) import Data.ByteString.Lazy.Char8 (pack) import qualified Data.Text.Lazy as T import Data.Text (Text(..)) import Control.Monad.IO.Class (liftIO, MonadIO) import Data.Aeson (encode) import qualified Data.Map as Map import qualified Database.MongoDB as DB application dbpipe req = do case unpack $ rawPathInfo req of "/items" -> itemsJSON dbpipe req _ -> return $ responseLBS status404 [("Content-Type", "text/plain")] "404" indexPage :: Iteratee B.ByteString IO Response indexPage = do page <- liftIO $ processTemplate "templates/index.html" [] return $ responseLBS statusOK [("Content-Type", "text/html; charset=utf-8")] page processTemplate f attrs = do page <- L.readFile f return page itemsJSON :: DB.Pipe -> Request -> Iteratee B.ByteString IO Response itemsJSON dbpipe req = do dbresult <- liftIO $ rundb dbpipe $ DB.find (DB.select [] $ tu "table") >>= DB.rest let docs = either (const []) id dbresult -- liftIO $ L.putStrLn $ encode $ show $ map docToMap docs return $ responseLBS statusOK [("Content-Type", "text/plain; charset=utf-8")] (encode $ map docToMap docs) docToMap doc = Map.fromList $ map (\f -> (T.dropAround (== '"') $ T.pack $ show $ DB.label f, T.dropAround (== '"') $ T.pack $ show $ DB.value f)) doc main = do pipe <- DB.runIOE $ DB.connect $ DB.host "127.0.0.1" run 3000 $ application pipe rundb pipe act = DB.access pipe DB.master database act tu :: B.ByteString -> UString tu = DB.u . C8.unpack Then the result is suprprising, DB.label works well, but DB.value giving me native characters as some escape codes, so the result is look like: curl http://localhost:3000/items gives: [{"Марка": "\1058\1080\1087 \1087\1086\1076", "Model": "BD-W LG BP06LU10 Slim \1058\1080\1087 \1087\1086\1076\1082\1083\1102\1095\1077\1085\1080\1103"}, ... ] This happens in case i trying to print data and also in case i return data encoded as JSON Any idea how correctly extract values from MongoDB driver ? A: Everything is working as expected -- only your expectations are wrong. =) What you're seeing there are not raw Strings; they are String's which have been escaped to exist purely in the printable ASCII range by the show function, called by print: print = putStrLn . show Never fear: in memory, the string that prints as "\1058" is in fact a single Unicode codepoint long. You can observe this by printing the length of one of the Strings you're interested in and comparing that to the number of Unicode codepoints you expect. A: The following line confirms that aeson's encoding works properly (using the utf8-string library to read utf8 data off the lazy bytestring back to a haskell string: > putStrLn $ Data.ByteString.Lazy.UTF8.toString $ encode $ ("\1058\1080\1087 \1087\1086\1076",12) ["Тип под",12] Looking at your code more closely I see the real problem. You're calling T.pack $ show $ DB.value -- this will render out as literal codepoints, and then pack those into a text object. The fix is to switch from show to something smarter. Look at this (untested) smartShow :: DB.Value -> Text smartShow (String s) = Data.Text.Encoding.decodeUtf8 $ Data.CompactString.UTF8.toByteString s smartShow x = T.pack $ show x Obviously to handle the recursive cases, etc. you need to be smarter than that, but that's the general notion... In fact, the "best" thing to do is to write a function of BSON -> JSON directly, rather than go through any intermediate structures at all.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553865", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Algorithm for sum-up to 0 from 4 set I have 4 arrays A, B, C, D of size n. n is at most 4000. The elements of each array are 30 bit (positive/negative) numbers. I want to know the number of ways, A[i]+B[j]+C[k]+D[l] = 0 can be formed where 0 <= i,j,k,l < n. The best algorithm I derived is O(n^2 lg n), is there a faster algorithm? A: Ok, Here is my O(n^2lg(n^2)) algorithm- Suppose there is four array A[], B[], C[], D[]. we want to find the number of way A[i]+B[j]+C[k]+D[l] = 0 can be made where 0 <= i,j,k,l < n. So sum up all possible arrangement of A[] and B[] and place them in another array E[] that contain n*n number of element. int k=0; for(i=0;i<n;i++) { for(j=0;j<n;j++) { E[k++]=A[i]+B[j]; } } The complexity of above code is O(n^2). Do the same thing for C[] and D[]. int l=0; for(i=0;i<n;i++) { for(j=0;j<n;j++) { AUX[l++]=C[i]+D[j]; } } The complexity of above code is O(n^2). Now sort AUX[] so that you can find the number of occurrence of unique element in AUX[] easily. Sorting complexity of AUX[] is O(n^2 lg(n^2)). now declare a structure- struct myHash { int value; int valueOccuredNumberOfTimes; }F[]; Now in structure F[] place the unique element of AUX[] and number of time they appeared. It's complexity is O(n^2) possibleQuardtupple=0; Now for each item of E[], do the following for(i=0;i<k;i++) { x=E[i]; find -x in structure F[] using binary search. if(found in j'th position) { possibleQuardtupple+=number of occurrences of -x in F[j]; } } For loop i ,total n^2 number of iteration is performed and in each iteration for binary search lg(n^2) comparison is done. So overall complexity is O(n^2 lg(n^2)). The number of way 0 can be reached is = possibleQuardtupple. Now you can use stl map/ binary search. But stl map is slow, so its better to use binary search. Hope my explanation is clear enough to understand. A: I disagree that your solution is in fact as efficient as you say. In your solution populating E[] and AUX[] is O(N^2) each, so 2.N^2. These will each have N^2 elements. Generating x = O(N) Sorting AUX = O((2N)*log((2N))) The binary search for E[i] in AUX[] is based on N^2 elements to be found in N^2 elements. Thus you are still doing N^4 work, plus extra work generating the intermediate arrays ans for sorting the N^2 elements in AUX[]. I have a solution (work in progress) but I find it very difficult to calculate how much work it is. I deleted my previous answer. I will post something when I am more sure of myself. I need to find a way to compare O(X)+O(Z)+O(X^3)+O(X^2)+O(Z^3)+O(Z^2)+X.log(X)+Z.log(Z) to O(N^4) where X+Z = N. It is clearly less than O(N^4) ... but by how much???? My math is failing me here.... A: The judgement is wrong. The supplied solution generates arrays with size N^2. It then operates on these arrays (sorting, etc). Therefore the Order of work, which would normaly be O(n^2.log(n)) should have n substituted with n^2. The result is therefore O((n^2)^2.log(n^2))
{ "language": "en", "url": "https://stackoverflow.com/questions/7553876", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: ipad disable select options w/o jquery There is a way,plugin or code snippet that i could use to make <select><option disable="disable">....</option></select> options in safari on ipad to be disabled ? latter edit: here is the code: function getSelectedValues(ids) { var selectedValues = [] , $selected = $('.selector').children('option:selected'); $selected.each(function(){ if(this.value != 0){ if(ids == true){ selectedValues.push(this.value+'-'+$(this).parent().attr('id')); } else { selectedValues.push(this.value); } } }); return selectedValues; } function clearDisabled() { $('.selector').children(':disabled').attr('disabled', false); } function disableSelected(selectedValues,id) { sv = selectedValues || []; if(id === true){ var selectedIds = []; var selectedVals = []; $.each(selectedValues, function(key, value) { values = value.split('-'); selectedVals.push(values[0]); selectedIds.push(values[1]); }); for (var i=0;i<selectedVals.length;i++) { $('.selector').each(function(){ if($(this).attr('id') == selectedIds[i]){ $('option[value=' + selectedVals[i] + ']',this).not(':selected').attr('disabled', true); } }); } } } $(document).ready(function(){ $('.selector').change(function(){ selectedValues = getSelectedValues(true); clearDisabled(); disableSelected(selectedValues, true); }); var selectedValues = getSelectedValues(true); disableSelected(selectedValues, true); }); I did some digging and i realize that this is a limitation of safari mobile... A: It is more complicated to get a cross browser implementation, safari for iPad and iPhone, ie6 and I presume some other browser just ignore the disabled options. You need to remove them. So, keep a copy of it and rebuild the options whenever you want. This is an example where you can enable/disable options based on their value var $select = $("select#myselect"); $select.data("copy", $select.find("option")) function disableOption($option) { var optionVal = $option.val(); $select.empty() $select.data("copy").each(function(){ var $currentOption = $(this); if (optionVal !== $currentOption.val() && $currentOption.attr("disabled")!=="disabled") $select.append($currentOption); else $currentOption.attr("disabled", "disabled"); }); } function enableOption($option) { var optionVal = $option.val(); $select.empty() $select.data("copy").each(function(){ var $currentOption = $(this); if (optionVal === $currentOption.val()) $currentOption.removeAttr("disabled") if ($currentOption.attr("disabled")!=="disabled") $select.append($currentOption); }); } A: $("select option[disable='disable']").attr("disabled","disabled"); or if you are using jquery 1.6 or higher $("select option[disable='disable']").prop("disabled",true);
{ "language": "en", "url": "https://stackoverflow.com/questions/7553880", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to move, resize and return to original position a subview present in the main view? In some of the applications, I have seen that we can drag a view outside of its position using two fingers(in smooth motion). We are also able to resize, rotate and move it further. And when I take my fingers off the screen it just resized(also rotates) and go backs to its original position by itself in a smooth motion. How can I do this kind of animation? Is there any sample available? OR just telling me how the flow actually is will also be really helpful. A: UIViews are animatable simply by setting properties. [UIView animateWithDuration:0.5 animations:^{ myView.frame = CGRectMake(50, 50, 100, 200); myView.layer.affineTransform = CGAffineTransformMakeRotation(M_PI); }]; Look up animateWithDuration in the docs for more options and examples.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553882", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Instantiating an object in a background worker causes the UI to freeze up This is what i have at the moment, but when i call Dispatcher.BeginInvoke(), my UI freezes up: BackgroundWorker backgroundWorker = new BackgroundWorker(); backgroundWorker.WorkerSupportsCancellation = true; backgroundWorker.WorkerReportsProgress = true; ViewModel.GenerateReport(backgroundWorker, Dispatcher); ViewModel: backgroundWorker.DoWork += delegate(object s, DoWorkEventArgs args) { try { ReportViewModel reportViewModel = new ReportViewModel(SessionContext, Mediator, reportDashboardViewModel.ReportRequest, false); dispatcher.BeginInvoke((Action)(() => { ReportPreviewView reportPreviewView = new ReportPreviewView(reportViewModel); reportPreviewView.ReportName = reportDashboardViewModel.ReportRequest.Report.ReportName; ReportView = reportPreviewView; })); } catch (Exception exception) { backgroundWorker.ReportProgress(0, "There Was an Error generating the report"); backgroundWorker.CancelAsync(); throw; } }; backgroundWorker.RunWorkerAsync(); The first line in dispatcher.BeginInvoke causes my UI to freeze up. ReportPreviewView reportPreviewView = new ReportPreviewView(reportViewModel); Note: ReportPreviewView creates the relevant view for the report request. May it be Devexpress, C1 or pivot reports. As soon as i remove the dispatcher.BeginInvoke, i get this error: The calling thread must be STA, because many UI components require this. So my question is, what do i need to do to get around this? The whole reason for using a BackgroundWorker was so that my UI stays responsive at all times. I am new to multithreading,so maybe i got the structure all wrong... A: Disptacher.BeginInvoke launches the code you encapsulated withing an Action ansynchronoulsy, but the Do_Work handler is also updated async by the BackgroundWorker, so you should't use it. The main problem is that you are trying to access an UI instance from another thread, and windows disallow that: only the main thread can access an UI element instance. The correct way to do it is using Control.Invoke if you are using windows Forms. A deep article about the winforms threading model A: Moral of the story, all UI elements needs to be created on the UI thread! That being said, if the creation of the UI element takes a long time, the UI will freeze up. Take all the heavy lifting and put it in a Task or BackgroundWorker. Then you will have a more responsive UI.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553884", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Tkinter Optionmenu callback not working For some reason I can't get this optionmenu so call the callback function. Is there some special treatment those widgets require? (The function itself works and I can call it from i.e. a button.) self.shapemenu=Tkinter.OptionMenu(self.frame,self.shape,"rectangle", "circular", command=self.setshape) self.shape is a Tkinter.StringVar and obviously setshape is the callback function. What am I doing wrong here? A: The optionmenu is designed to set a value, not perform an action. You can't assign a command to it, and if you do, you will break its default behavior of setting the value -- it uses the command option internally to manage its values . If you want something to happen when the value changes, add a trace on the StringVar.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553885", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Submit form issue. Posted data is a collection My form keys are: Request.Form.AllKeys {string[9]} [0]: "__RequestVerificationToken" [1]: "stud.LastName[0]" [2]: "stud.FirstName[0]" [3]: "stud.Number[0]" [4]: "stud.LastName[1]" [5]: "stud.FirstName[1]" [6]: "stud.Number[1]" They all have values. My action looks like this: [ValidateAntiForgeryToken] [HttpPost] public ActionResult Add(Student[] stud) Student class has properties :FirstName, LastName, Number. The problem is that stud is null? Isn't a way to get it populated with submitted data, o or have to take the data from Request.Form A: Try using [ValidateAntiForgeryToken] [HttpPost] public ActionResult Add(List<Student> students) A: You should have this kind of values (note the changed [] location) Request.Form.AllKeys {string[9]} [0]: "__RequestVerificationToken" [1]: "stud[0].LastName" [2]: "stud[0].FirstName" [3]: "stud[0].Number" [4]: "stud[1].LastName" [5]: "stud[1].FirstName" [6]: "stud[1].Number" Something wrong is going on in your views - generated inputs(and when submitted, form values) do not have '[]' in right places in thier names. Take a look at this article by Phil Haack about model binding to a list.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553888", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Define color of row checking two dates within same cell and text in other cell. Excel macros? I have the following problem..... ---------------------------------------------------------- Column1 | Column2 | Column3 | Column4 | Column5 ---------------------------------------------------------- Bla bla | 26/09/2011 10:00 | blabla | Complete| blabla | | | | bla bla | 26/09/2001 11:00 | blabla | | ---------------------------------------------------------- Bla bla | 26/09/2011 11:00 | blabla | | blabla | | | | bla bla | 26/09/2001 11:30 | blabla | | ---------------------------------------------------------- Bla bla | 26/09/2011 12:00 | blabla | Started | blabla | | | | bla bla | 26/09/2001 13:00 | blabla | | ---------------------------------------------------------- Bla bla | 26/09/2011 22:00 | blabla | | blabla | | | | bla bla | 26/09/2001 23:00 | blabla | | ---------------------------------------------------------- In **Column2 each cell have two dates with times(when should start and when should finish), and in column4 I have the status of the task. The conditions to set the color of the row is based on Column2 and Column4. The color code would simulate a traffic light Green for OK, Orange for Aware, and Red for Bad. If first date of the cell in Column2 is greater than current then color row is Orange. If first date of the cell in Column2 is greater than current and Column4 is "Started" then color row is green. If second date of the cell in Column2 is greater than current and text in Column4 is not "Complete" then color row is Red. If text is "Complete" then color row Green. One more thing to consider is that the second date is not a date, but text like TBC and other things..... I know if it was one date time on the cell I could use conditional formatting, because there are two dates on the same cell, I think I need the help of a excel macro expert. Thanks in advance. A: You can use conditionitional formatting: Eg for cell B2, use these formula =DATEVALUE(LEFT(B2,FIND(CHAR(10),B2)-1))>NOW() for first date in cell greater than current =DATEVALUE(MID(B9,FIND(CHAR(10),B9)+1,99))>NOW() for second date in cell greater than current The rest (layering the conditions, factoring in the status) should be straight forward A: Ok I got sort of confused reading your request but basically you want to conditionally format the cell if the time/date is different from first to second. What you need is something like the following With Worksheets("Sheet1") If .Range("B2") > Now And .Range("D2") <> "Started" Then .Range("B2").Interior.Color = vbOrange Else .Range("B2").Interior.Color = vbGreen End If End with Now if you're not comfortable or used to VBA this is a little more complex. But basically you can change the range and sheet names to do whatever you need it to. The "Interior.Color" function will work with vbGreen,vbRed,vbOrange and several more. More than enough to suit your needs. Hopefully that can get you started. Let me know if you need more help.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553893", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Backbone.js collection and sortedIndex always returning 0 I'm having trouble getting the sortedIndex underscore method to return a useful value. I have a collection with a comparator, and that's adding models correctly in order. I would just like to know the potential index of a new model, and the sortedIndex method is return 0 matter what I try. var Chapter = Backbone.Model; var chapters = new Backbone.Collection; chapters.comparator = function(chapter) { return chapter.get("page"); }; chapters.add(new Chapter({page: 9, title: "The End"})); chapters.add(new Chapter({page: 5, title: "The Middle"})); chapters.add(new Chapter({page: 1, title: "The Beginning"})); var foo = new Chapter({ page: 3, title: 'Bar' }); // Will always return 0 no matter the value of page in foo. console.log(chapters.sortedIndex(foo)); I know there's something wrong in there, or perhaps that's no the intention of sortedIndex but I'm unsure either way. A: The problem is Underscore.js knows nothing about the comparator function of the collection and expects comparator as an argument of sortedIndex function. This will work as expected: console.log(chapters.sortedIndex(foo, chapters.comparator));
{ "language": "en", "url": "https://stackoverflow.com/questions/7553895", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: .NET Service to monitor web page changes I want to create a service that will monitor changes to web pages i.e. the page content has been updated. I am trying to think of the best way to achieve this and at present I am considering a couple of options. Note that there could be hundreds of pages to monitor and the interval for checking could be seconds or hours (configurable). * *Create a windows service for each page to monitor *Create a windows service that spawns a thread for each page to monitor Now, I am concerned which of these is the best approach and whether these is an alternative I haven't considered. I thought 1 would have the benefit of isolating each monitoring task but would come at the expense of overhead in terms of physical resources and effort to create/maintain. The second would be slightly more complex but cleaner. Obviously it would also lose isolation in that if the service fails then all monitoring will fail. A: I have done something similar and I solved it by having a persisted queue (a SQL Server table) that would store the remote Uri along with the interval and a DateTime for the last time it ran. I can then get all entries that I want to run by selecting the ones that has lastRun + interval < now. If your smallest interval are in the region of seconds, you probably want to use a ThreadPool, so that you can issue several request at the same time. (Remember to adjust the maxConnections setting in your app.config accordingly). I would use one Windows service (have a look at the TopShelf project for that) and I would then have Quartz.Net trigger the jobs. With Quartz, you can control whether it has to wait for previous jobs to finish etc. A: Creating one Windows Service is the way to go... regarding the failure of this windows Service there are several measures you could take to deal with that - for example configure windows to automatically restart the Windows Service on failure... I would recommend using a thread pool approach and/or a System.Threading.Timer in combination with a ConcurrentDictionary or ConcurrentQueue .
{ "language": "en", "url": "https://stackoverflow.com/questions/7553898", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to create log in specific location when using log4j in java desktop application I am using log4j in Eclipse for logging messages in a java desktop application. I want that the log should be created in a specific folder (Specifically, in the folder which contains source folder 'src' and classes folder 'bin'). Is it possible to set this in log4j.properties? How to ensure that log is created at this location only? A: Assuming you are using the RollingFileAppender, you could set something like this in your log4j.properties file (below I am setting C:/myapp/src/mylog.log as my target location - you can change this to your desired location): log4j.appender.rollingFile=org.apache.log4j.RollingFileAppender log4j.appender.rollingFile.File=C:/myapp/src/mylog.log ... (other configurations) ... A: I would go with Saket's reply. But instead of hardcoding the location its always better to have a relative path. If you started your application from a main method from a class called Launcher for example and this is the structure of your Eclipse Project directory: Java Project src bin Then just give your location to be log4j.appender.R.File=./log/Logfile.log This will create the file under a directory log: Java Project src bin log LogFile.log Hope you got it.. :) A: Yes it is possible to set it in property file. One example is: log4j.appender.rollingFile=org.apache.log4j.RollingFileAppender log4j.appender.rollingFile.File=D:/myapp/mylog.log log4j.appender.rollingFile.MaxFileSize=2MB log4j.appender.rollingFile.MaxBackupIndex=2 log4j.appender.rollingFile.layout = org.apache.log4j.PatternLayout log4j.appender.rollingFile.layout.ConversionPattern=%p %t %c - %m%n log4j.appender.rollingFile.File=D:/myapp/mylog.log can be modified to any path on your disk. A: It is not good to create log in a project folder since it gets bigger and bigger in size. Rather you can create it in user directory from which your application is running. Eg: should be ${user.home}/appName/MyWEB.log , user generally has right to write in home dir works for both windows and linux environment.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553899", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Declaring a variable and setting its value from a SELECT query in Oracle In SQL Server we can use this: DECLARE @variable INT; SELECT @variable= mycolumn from myTable; How can I do the same in Oracle? I'm currently attempting the following: DECLARE COMPID VARCHAR2(20); SELECT companyid INTO COMPID from app where appid='90' and rownum=1; Why this is not working? A: SELECT INTO DECLARE the_variable NUMBER; BEGIN SELECT my_column INTO the_variable FROM my_table; END; Make sure that the query only returns a single row: By default, a SELECT INTO statement must return only one row. Otherwise, PL/SQL raises the predefined exception TOO_MANY_ROWS and the values of the variables in the INTO clause are undefined. Make sure your WHERE clause is specific enough to only match one row If no rows are returned, PL/SQL raises NO_DATA_FOUND. You can guard against this exception by selecting the result of an aggregate function, such as COUNT(*) or AVG(), where practical. These functions are guaranteed to return a single value, even if no rows match the condition. A SELECT ... BULK COLLECT INTO statement can return multiple rows. You must set up collection variables to hold the results. You can declare associative arrays or nested tables that grow as needed to hold the entire result set. The implicit cursor SQL and its attributes %NOTFOUND, %FOUND, %ROWCOUNT, and %ISOPEN provide information about the execution of a SELECT INTO statement. A: Not entirely sure what you are after but in PL/SQL you would simply DECLARE v_variable INTEGER; BEGIN SELECT mycolumn INTO v_variable FROM myTable; END; Ollie. A: One Additional point: When you are converting from tsql to plsql you have to worry about no_data_found exception DECLARE v_var NUMBER; BEGIN SELECT clmn INTO v_var FROM tbl; Exception when no_data_found then v_var := null; --what ever handle the exception. END; In tsql if no data found then the variable will be null but no exception A: ORA-01422: exact fetch returns more than requested number of rows if you don't specify the exact record by using where condition, you will get the above exception DECLARE ID NUMBER; BEGIN select eid into id from employee where salary=26500; DBMS_OUTPUT.PUT_LINE(ID); END; A: For storing a single row output into a variable from the select into query : declare v_username varchare(20); SELECT username into v_username FROM users WHERE user_id = '7'; this will store the value of a single record into the variable v_username. For storing multiple rows output into a variable from the select into query : you have to use listagg function. listagg concatenate the resultant rows of a coloumn into a single coloumn and also to differentiate them you can use a special symbol. use the query as below SELECT listagg(username || ',' ) within group (order by username) into v_username FROM users;
{ "language": "en", "url": "https://stackoverflow.com/questions/7553901", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "54" }
Q: Conflict when using ajaxStart & ajaxStop on 2 different text inputs I'm stuck a little with ajaxStart / ajaxSend and their end methods. I have 2 different AJAX calls using jQuery.post running on 2 text inputs. The first one is for getting certain names list from my database, and I'm using ajaxStart / ajaxStop to show and hide a spinner. This works fine. The next AJAX call, is used to check an email status, again in my DB. I'm using ajaxStart / ajaxStop again to display a div with a message that the process is in progress, and then after the process is complete. Now, my problem is, when I type in the first text input, the ajaxStart for the 2nd input is called, and I can see the div! I tried using ajaxSend and ajaxComplete, but no luck! Code: //First request jQuery('.company-name input').keyup(function(event){ //get the alphabets and post them using jQuery.post. }); jQuery('.company-name input').ajaxStart(function(){ //Show the spinner }); jQuery('.company-name input').ajaxStop(function(){ //hide the spinner }); //Second Request jQuery('.reviewer-email input').blur(function(){ //check the email rights using jquery.post }); jQuery('.reviewer-email input').ajaxStart(function(){ //Show the warning }); jQuery('.reviewer-email input').ajaxStop(function(){ //hide the warning }); when the first key up event occurs, the 'Show the warning' part runs! I tried ajaxSend and ajaxComplete too, but didn't work! Any ideas how I can call them separately on my input boxes? Thanks A: As described in .ajaxStart() documentation all handlers that have been registered with the .ajaxStart() method are executed when ajaxStart event is triggered. One possible solution in your case would be to just leave out the ajaxStart/ajaxStop methods: //First request jQuery('.company-name input').keyup(function(event){ //Show the spinner //get the alphabets and post them using jQuery.post. //in jQuery.post success handler hide the spinner }); //Second Request jQuery('.reviewer-email input').blur(function(){ //Show the warning //check the email rights using jquery.post //in jQuery.post success handler hide the warning });
{ "language": "en", "url": "https://stackoverflow.com/questions/7553903", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is it possible for us to download a file to a sandboxed location using File API available in HTML 5? I wanted to ensure the documents I let user download are programmatically manipulated throughout program. I came to know that File API does give Apps the opportunity to manipulate them. But how can we store the Files in the sandboxed location? A: You cannot directly read or write anything to the file system. You always have to go through either the usual upload/save dialog, or rely on desktop drag-and-drop (you can drag files into most modern browsers, and out of Google Chrome, at least). A: It seems you can't let the browser download the file directly into File API's sandbox now. You have to fetch the file by yourself in JavaScript and write it to a file through File API. If the file is from the same origin, you can just fetch it by XHR.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553908", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to access function from every controller in codeigniter Hi friends hi have this function in one controller , how can i access it from every other controller ?pls help public function click_add($ads_id){ //some statement here redirect($ads_site['url']); } A: One solution would be to create your own library. A: There are a few possibilities: * *Define a helper *Create a parent controller class from which all other controllers in your application extend *Create a library *Use ModularExtensions to allow calling one controller inside another It all depends on what exactly the function should do. If it shouldn't access the model, then you could go for the first three options. Otherwise I'd suggest the latter two.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553912", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can i convert this javascript function into java let say i have fallowing javascript function- function isDigit (c) { return ((c >= "0") && (c <= "9")) } function isAlphabet (c) { return ( (c >= "a" && c <= "z") || (c >= "A" && c <= "Z") ) } How can i write same thing in java. Thanks. A: Use java.lang.Character class methods. A: public boolean isDigit(char c) { return ((c >= '0') && (c <= '9')); } public boolean isAlphabet(char c) { return ( (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ); } A: Respectively: java.lang.Character.isLetter(c); java.lang.Character.isDigit(c); But if you want to make your own implementations: boolean isAlpa(char c) { return c >= 'A' && c <= 'Z'; /* single characters are enclosed with single quotes */ }
{ "language": "en", "url": "https://stackoverflow.com/questions/7553916", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Clear hash and parameters from Redirect in aspnet mvc? Consider the following code within a controller: protected override void OnActionExecuting(System.Web.Mvc.ActionExecutingContext filterContext) { if (!this.IsAuthorized) { filterContext.Result = RedirectToAction("Index", "Home", new { area = "" }); //filterContext.Result = Redirect(Url.Content("~/Home/Index")); // Gives same result as the previous row return; } base.OnActionExecuting(filterContext); } If I enter the follwing url when not authorized: somecontroller/someaction#/?tab=Foo I get redirected to: /Home/Index#/?tab=Foo How come the hash isn't stripped from the url? How can I get rid of it serverside? A: This is not possible. The named anchor (#/?tab=Foo) is not part of the request, the browser does not send the named anchor to the server. Take a look at named anchors are not sent to the web server
{ "language": "en", "url": "https://stackoverflow.com/questions/7553919", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Push a view from a nib file using a right navigation bar button As described in the title, i would like to push a view, from a known NIB, using a button on the navigation bar. I'm working on a UINavigationController app. I already added the right button in IB and i linked it to the method that is in the RootViewController I have searched everywhere but I couldn't find a way to do this method... -(IBAction)addItems:(id)sender { ? } I also tried this solution, but it isn't working either... A: For example: -(IBAction)addItems:(id)sender { CustomController *controller = [[CustomController alloc] initWithNibName:@"CustomController" bundle:nil]; [self.navigationController pushViewController:controller animated:YES]; [controller release]; } Where * *CustomController name of your custom controller class. *@"CustomController" name of your xib file A: If you just need the view from nib file, then try this.. NSArray* nibViews = [[NSBundle mainBundle] loadNibNamed:@"QPickOneView" owner:self options:nil]; UIView* myView = [ nibViews objectAtIndex: 0]; self.view = myView; If you want to push a ViewController..Then go with the Nekto's Answer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553923", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Rspec with rails 3.1 gives DEPRECATION WARNING ActiveRecord::Associations::AssociationCollection is deprecated? I upgraded to rails 3.1 and I have some problems with my tests now that worked perfectly before. I get the following warning before the tests: DEPRECATION WARNING: ActiveRecord::Associations::AssociationCollection is deprecated! Use ActiveRecord::Associations::CollectionProxy instead. (called from at /home/user/rails_projects/project/config/environment.rb:5) How can I use CollectionProxy instead of AssociationCollection? Here is my Gemfile: source 'http://rubygems.org' gem 'rails', '3.1.0' gem 'jquery-rails' gem "therubyracer", "~> 0.9.4" gem 'carrierwave', '0.5.6' gem 'haml', '~>3.1.2' gem 'mysql2', '0.3.7' gem 'rmagick', '2.13.1' gem 'sitemap_generator', '2.0.1' gem 'whenever', '0.6.8', :require => false gem 'will_paginate', '3.0.pre2' group :assets do gem 'sass-rails', " ~> 3.1.0" gem 'coffee-rails', "~> 3.1.0" gem 'uglifier' end group :development do gem 'rspec-rails', '2.6.1' gem 'annotate-models', '1.0.4' gem 'faker', '0.9.5', :require => false gem 'ruby-debug19', '0.11.6' end group :test do gem 'rspec-rails', '2.6.1' gem 'webrat', '0.7.3' gem 'factory_girl_rails', '1.0' gem 'spork', '~> 0.9.0.rc' end This is my environment.rb: # Load the rails application require File.expand_path('../application', __FILE__) # Initialize the rails application Project::Application.initialize! Thank you! A: I had the same problem and fixed it by upgrading to the latest version of will_paginate. So, change this: gem 'will_paginate', '3.0.pre2' to this: gem "will_paginate", "~> 3.0.2" Save your Gemfile then do bundle install.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553929", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Isn't got anyway to insert by descending? What I need to insert is by descending record. my code: mysql_query("INSERT INTO entertainment VALUES ('','$result','$date')"); result: id result date 1 a 26/9/2011 2 b 25/9/2011 3 c 24/9/2011 What I want is: id result date 1 c 24/9/2011 2 b 25/9/2011 3 a 26/9/2011 Isn't possible do it ? here is my full code, what i doing now i rss grabbing,once i grab all the result i will insert the result to my database: $content = file_get_contents($feed_url); $xml = new SimpleXmlElement($content); foreach($xml->channel->item as $entry){ $title = mysql_real_escape_string(strip_tags($entry->title)); $description = mysql_real_escape_string(strip_tags($entry->description)); mysql_query("INSERT INTO entertainment VALUES ('','$entry->pubDate','$title','$description')"); } A: No. This is a really bad idea. The (autoincrement) ID column should not be significant for your data - so you really shouldn't care about its value. Furthermore, how would MySQL know where to start from? If you insert three, it should start from 3 and count to 1, but what if you insert more later? Instead of changing the order while inserting, you should probably change the query that reads the data later. Have that query return the data really the way you want it. SELECT * FROM entertainment ORDER BY result DESC A: Yes, insert the data in any way, and use SELECT * FROM entertainment ORDER BY date Desc at the time of retrieval. A: INSERT INTO orders (id result date) select id result date from tablename order by id desc
{ "language": "en", "url": "https://stackoverflow.com/questions/7553930", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: Is it safe to host a website outside public_html I am hosting a website where i host my main site in the /home/username/public_html while i host my blog in /home/username/blog is it safe that i host the blog in a different folder (/home/username/blog ) A: There is nothing special about a directory called "public_html" other than that the web server are often configured to look for content there (and some web servers do so by default). The name is just a convention.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553931", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Is exposing my DTO to the view considered incorrect? This question has been round my head the last weeks or months, and I don't really know what's the best solution. With the MVVM patter we use the View Models to expose data to a View. For example, if I want to show to a user the details of a product I will create certain propeties inside the View Model and populate them. Then through bindings, the view will be able to get the data from those properties. Something like this: <StackPanel> <TextBlock Text="Prodcut Name:" FontWeight="Bold" /> <TextBlock Text="{Binding Path=ProductName}" /> <TextBlock Text="Price:" FontWeight="Bold"/> <TextBlock Text="{Binding Path=Price}"/> <TextBlock Text="Added Date:" FontWeight="Bold" /> <TextBlock Text="{Binding Path=Date}"/> </StackPanel> In the view model I will retrieve the data that I want to display. I will get this data like a Product DTO, which will have the needed properties in the view. this.productDTO = getData(); So my question is, can we bind directy from the view model to the dto? View Model: private ProductDTO product; public string ProductName { get { return this.product.Name; } set { this.product.Name = value; } } public string Price { get { return this.product.Price; } set { this.product.Price = value; } } I have the idea that exposing the DTO is not a good thing.. but if It will save me from having to map all the properties from the DTO to the view model.. A: If you do not need to 'shape' your DTO in order to bind your view, there is absolutely nothing wrong with exposing your DTO directly to your view. You can always introduce a view model at some point in the future if required. You can also use patterns like the mini-ViewModel (which I describe on my blog) to add localised View Models to shape parts of your model. Wrapping your DTO in a view model as you have done, adds code that does not provide any benefit. It increases the size of your code-base and the risk of bugs. KISS - Keep it simple! A: private ProductDTO product; public string ProductName { get { return this.product.Name; } set { this.product.Name = value; } } the only problem i can see is that, when your Name property of your dto changed its not simply reflected in your UI. so i would prefer this: public ProductDTO Product {...} <TextBlock Text="{Binding Path=Product.Name}" /> this of course requires that your DTO implement INotifyPropertyChanged A: Technically both ways are possible, however a DTO typically is not meant for viewing and thus will probably not fire any change notification events. You'll have to either code that into your DTO or risk possible UI synchronization issues. I would advise against "enriching" your DTOs in such a way. From an architecture standpoint DTO object should be cheap and small objects. They don't require a lot of effort to instantiate or destroy and you shouldn't pass them very far up your call stack let alone let them remain in memory for very long. In general they're meant to be data capsules and they're purpose is only to bring the data from A to B. ViewModels on the other hand have behavior and implement a richer set of interfaces. The only thing they have in common with DTOs is that they also have data properties. So, in your case I'd advise not to keep the DTO in your view model as a private member, but set the view models properties upon retrieving the DTO and then forget about the DTO again. As a general advise, don't let your DTOs lifetime extend very far past the method with the service call.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553933", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to calculate sha1 hash for image Hi i am trying to calculate sha1 hash for image. Is there any function available to calulate hash of image directly? Sorry i forgot to mention .. its in c++ i am trying. A: Read the image file into memory, then call the SHA1 function on that. Python: from hashlib import sha1 h = sha1(open(image_file, 'rb').read()).hexdigest() This will give you the SHA1 of the image, including the headers, comments, etc. that are stored with it in the file. Remember that SHA1 just transforms a string of bits to a different, fixed-size string of bits. There's nothing magical about images as far as it is concerned. EDIT: ok, C++. Get hashlib2plus, construct a sha1wrapper, feed it the image block-by-block using updateContext and finally hashIt.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553950", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Crystal report SetDatasource issue I am working on a Classic ASP page with VB6 code. We are in a process of converting the crystal report and iis server for migration. We are not able to generate the report. When i debugged till the point i call the "Database.SetDataSource CDOSet, 3,1" it works fine. When i comment that single line i'm able to get the report without any data. We are also using the .ttx file for database connection(Field Definitions Only). Kindly suggest me were could have been the mistake. What all things i need to check for the migrating? *crystal report 9 to Crystal report 2008, iis 5 to iis 6 A: First thing I'd suggest you look at is the Schema for the dataset and make sure it matches exactly with what the report is expecting. Is it possible that while migrating some of the datatypes have changed and thats whats causing your problem now? if so it might be a simple fix to change the datatype in the report to match the new dataset A: I don't have any experience with your setup, but my first guess would be a permissions issue. I would try looking at the event viewer on the server for more information, then the IIS logs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553955", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: The image becomes larger when it is added to a WPF page? I've got an image with 400 * 400 pixels. Now, when I add it to the WPF page: <Image Source="Resources\about.png" Stretch="None"/> its size become larger: Any idea why this behavior happens? A: Specify the width and height explicitly: <Image Source="Resources\about.png" Width="400" Height="400" /> (Also, in your screenshot, it looks like HorizontalAlignment and VerticalAlignment are set to Stretch?)
{ "language": "en", "url": "https://stackoverflow.com/questions/7553957", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is there a PHP library that facilitates manipulating html elements in a similar fashion to jquery? PHP string manipulation functions are very counterintuitive and clunky, at least for me, and everytime I need to manipulate some html code before outputting it it takes too much time. I was wondering if there was any PHP library that helps with this, preferably in a similar way to jQuery: retrieving and manipulating element attributes, selecting all the attributes with a given class, etc. A: you can use phpquery or querypath. Here is a comprehensive tutorial about querypath. A: There is a Dom Parser in PHP : http://php.net/manual/en/class.domdocument.php A: Sounds like you should be manipulating the HTML as a DOMdocument and using XPath (quite similar to jQuery selectors) to select the nodes. A: Next to what silent answered, there is also FluentDOM which is not exactly jQuery mimicking, but provides fluent interfaces based on DomDocumentDocs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553965", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Getting a value from HttpServletRequest.getRemoteUser() in Tomcat without modifying application (Using Java 6 and Tomcat 6.) Is there a way for me to get HttpServletRequest.getRemoteUser() to return a value in my development environment (i.e. localhost) without needing to modify my application's web.xml file? The reason I ask is that the authentication implementation when the app is deployed to a remote environment is handled by a web server and plugged-in tool. Running locally I obviously do not have the plugged-in tool or a separate web server; I just have Tomcat 6. I am trying to avoid adding code to my application merely to support development on my localhost. I am hoping there is a modification I can make to the context.xml or server.xml files that will let me set the remote user ID or that will try to pull it from a HTTP header or something. A: Here is a proof of concept Valve implementation which does it: import java.io.IOException; import java.security.Principal; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import org.apache.catalina.connector.Request; import org.apache.catalina.connector.Response; import org.apache.catalina.realm.GenericPrincipal; import org.apache.catalina.valves.ValveBase; public class RemoteUserValve extends ValveBase { public RemoteUserValve() { } @Override public void invoke(final Request request, final Response response) throws IOException, ServletException { final String username = "myUser"; final String credentials = "credentials"; final List<String> roles = new ArrayList<String>(); // Tomcat 7 version final Principal principal = new GenericPrincipal(username, credentials, roles); // Tomcat 6 version: // final Principal principal = new GenericPrincipal(null, // username, credentials, roles); request.setUserPrincipal(principal); getNext().invoke(request, response); } } (Tested with Tomcat 7.0.21.) Compile it, put it inside a jar and copy the jar to the apache-tomcat-7.0.21/lib folder. You need to modify the server.xml: <Host name="localhost" appBase="webapps" unpackWARs="true" autoDeploy="true"> <Valve className="remoteuservalve.RemoteUserValve" /> ... I suppose it works inside the Engine and Context containers too. More information: * *The Valve Component *Valve javadoc A: Use a local, file-based realm for testing. Check your conf/tomcat-users.xml and create roles and users for your application and enable the security constraints in your web.xml. There are good examples in the tomcat-users.xml.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553967", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: How i can change the uid and pid of my app? I was tryng to reboot my device with my app, but it throws an exception with Error message "The app with xxxx uid and with xxxx pid you can't reboot the device". So, if I can search what is the pid or uid that can, may be like a pid of alarm or other can do that, because are from the OS. Thanks for all A: How i can change the uid and pid of my app? This is not possible. The thing is that i try to reboot my app You do not "reboot" an "app". You reboot a device. but he throw a exception and the messages say that with xxxx uid and with xxxx pid you cant reboot Only applications considered part of the firmware can hold the necessary permissions to reboot a device. If you wish to reboot a device, build your own custom firmware. A: You can request superuser privileges on rooted devices thru the su command and reboot the device with reboot.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553968", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Problem with Startup() SingleFrameApplication Warning: getApplicationResourceMap(): no Application class I created a project with NetBeans. I did a class that checkForUpdates. If there are it does the updgrade otherwise it starts main project class. The problem is when i Create object of MyClassApp and i launch with myClass.startup() i got those errors....I thought that was my update class so I tryed with a normal main without anything just create MyClassApp and launch startup() but it gets the same errors. How can i fix it? 26-set-2011 12.34.32 org.jdesktop.application.ResourceManager getApplicationResourceMap WARNING: getApplicationResourceMap(): no Application class 26-set-2011 12.34.36 org.jdesktop.application.SingleFrameApplication initRootPaneContainer WARNING: couldn't restore sesssion [mainFrame.session.xml] java.lang.NullPointerException at org.jdesktop.application.LocalStorage.getApplicationId(LocalStorage.java:195) at org.jdesktop.application.LocalStorage.getDirectory(LocalStorage.java:234) at org.jdesktop.application.LocalStorage$LocalFileIO.openInputFile(LocalStorage.java:330) at org.jdesktop.application.LocalStorage.openInputFile(LocalStorage.java:76) at org.jdesktop.application.LocalStorage.load(LocalStorage.java:138) at org.jdesktop.application.SessionStorage.restore(SessionStorage.java:382) at org.jdesktop.application.SingleFrameApplication.initRootPaneContainer(SingleFrameApplication.java:231) at org.jdesktop.application.SingleFrameApplication.show(SingleFrameApplication.java:463) A: I don't know what causes this error, but I have a solution. You probably have a class as defined below: public class MyClassApp extends SingleFrameApplication { ... @Override protected void startup() { show(new MyClassApp (this)); } ... public static MyClassApp getApplication() { return Application.getInstance(MyClassApp.class); } ... } If you start your application with MyClassApp.getApplication().startup(); You probably won't get any error.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553970", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using TransactionScope multiple times Is this the correct way to use a transaction scope: I have an object which represents part of a thing: public class ThingPart { private DbProviderFactory connectionFactory; public void SavePart() { using (TransactionScope ts = new TransactionScope() { ///save the bits I want to be done in a single transaction SavePartA(); SavePartB(); ts.Complete(); } } private void SavePartA() { using (Connection con = connectionFactory.CreateConnection() { con.Open(); Command command = con.CreateCommand(); ... command.ExecuteNonQuery(); } } private void SavePartB() { using (Connection con = connectionFactory.CreateConnection() { con.Open(); Command command = con.CreateCommand(); ... command.ExecuteNonQuery(); } } } And something which represents the Thing: public class Thing { private DbProviderFactory connectionFactory; public void SaveThing() { using (TransactionScope ts = new TransactionScope() { ///save the bits I want to be done in a single transaction SaveHeader(); foreach (ThingPart part in parts) { part.SavePart(); } ts.Complete(); } } private void SaveHeader() { using (Connection con = connectionFactory.CreateConnection() { con.Open(); Command command = con.CreateCommand(); ... command.ExecuteNonQuery(); } } } I also have something which manages many things public class ThingManager { public void SaveThings { using (TransactionScope ts = new TransactionScope) { foreach (Thing thing in things) { thing.SaveThing(); } } } } its my understanding that: * *The connections will not be new and will be reused from the pool each time (assuming DbProvider supports connection pooling and it is enabled) *The transactions will be such that if I just called ThingPart.SavePart (from outside the context of any other class) then part A and B would either both be saved or neither would be. *If I call Thing.Save (from outside the context of any other class) then the Header and all the parts will be all saved or non will be, ie everything will happen in the same transaction *If I call ThingManager.SaveThings then all my things will be saved or none will be, ie everything will happen in the same transaction. *If I change the DbProviderFactory implementation that is used, it shouldn't make a difference Are my assumptions correct? Ignore anything about object structure or responsibilities for persistence this is an example to help me understand how I should be doing things. Partly because it seems not to work when I try and replace oracle with SqlLite as the db provider factory, and I'm wondering where I should spend time investigating. A: Answering your bullets (and I've assumed Microsoft SQL Server 2005 or later): * * Connections will not be new and reused from the pool * *This depends - e.g. the SAME connection will be reused for successive steps in your aggregate transaction if all connections are to the same DB, with the same credentials, and if SQL is able to use the Lightweight transaction manager (SQL 2005 and later). (but SQL Connection pooling still works if that was what you were asking?) *Atomic SavePart - yes, this will work ACID as expected. *Yes nesting TransactionScopes with the same scope will also be atomic. Transaction will only commit when the outermost TS is Completed. *Yes , also atomic, but note that you will be escalating SQL locks. If it makes sense to commit each Thing (and its ThingParts) individually, this would be preferable from a SQL concurrency point of view. *The Provider will need to be compatable as a TransactionScope resource manager (and probably DTC Compliant as well). e.g. don't move your database to Rocket U2 and expect TransactionScopes to work. Just one gotcha - new TransactionScope() defaults to isolation level READ_SERIALIZABLE - this is often over pessimistic for most scenarios - READ COMMITTED is usually more applicable.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553971", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: MVC3 & EF. Interface for TDD Can somebody please explain: * *I am using MVC3/C#/Razor to build a project to get used to using MVC. *I am using the inbuilt account controller. *I am storing the account data in my local SQL database using Entity Framework to connect. How can I easily generate interfaces for EF? *SO FAR I am using the plugin from: http://blog.johanneshoppe.de/2010/10/walkthrough-ado-net-unit-testable-repository-generator/#step1 This allows me to have an interface for my entities already created. However, I know that I have to change my HomeController arguments to accept either the real repository or a fake one for testing. I am completely lost! A: Have a look at these. They will help and get you started : http://www.asp.net/entity-framework/tutorials/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application http://msdn.microsoft.com/en-us/library/gg416511(VS.98).aspx For dependency injection, you can follow these steps : Install-Package Ninject.MVC3 with nuget to your ASP.NET MVC 3 project (if your app is on version 3). This will basically do everything. Then have the following on your controller : private IMyModelRepository _myrepo; public HomeController(IMyModelRepository myrepo) { _myrepo = myrepo; } Go to NinjectMVC3.cs file inside App_Start folder and add the following code to inside RegisterServices method : private static void RegisterServices(IKernel kernel) { kernel.Bind<IMyModelRepository>().To<MyModelRepository >(); } Fire up your app and you should be up and running.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553973", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: very specific java constructors and Object class problem I have an array at actionTable.get(state). When I go to add an onject to the array, namely the Reduce, the properties of the reduce don't seem to go with it. The array is of type Action[] where Action is the superclass of Reduce, could this be the reason? Adding the reduce to the array: actionTable.get(state)[t] = new Reduce(st.items.get(item).prod); Checking to see if the field head is defined before adding it: System.out.println(Prod.prods.get(st.items.get(item).prod).head); Checking to see if the newly added reduce has the correct head field: System.out.println(actionTable.get(state)[t].prod.head); A NullPointerException occurs on the last print statement. The .prod part is defined but the .prod.head is null, even though the original prod object had a defined head. This is the constructor for Reduce: Reduce(int pr) { p = pr; length = Prod.prods.get(pr).length; prod = Prod.prods.get(pr); } All of the RHS of the assignments in the constructor are defined. So, I don't understand why the head field, within the prod object that the new Reduce has access to is not defined when you access it through the actionTable. A: Trust inheritance and all. Most likely with arrays is, that different array instances are involved (if you enlarge/copy array references). Some more System.out.println's will help there. A: The first thing you always should do is this: got to your break points view in your IDE, check "stop on Exception thrown" and perhaps give the name NullPointerException. Then run your code in the debugger and it will stop exactly at the point where the NullPointerException is thrown.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553974", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to implement an integration rule ? Suppose I've checked the identity below, how to implement it in Mathematica ? (* {\[Alpha] \[Element] Reals, \[Beta] \[Element] Reals, \[Mu] \[Element] Reals, \[Sigma] > 0} *) Integrate[CDF[NormalDistribution[0, 1], \[Alpha] + \[Beta] x] PDF[ NormalDistribution[\[Mu], \[Sigma]], x], {x, -\[Infinity], \[Infinity]}] -> CDF[NormalDistribution[0, 1], (\[Alpha] + \[Beta] \[Mu])/Sqrt[1 + \[Beta]^2 \[Sigma]^2]] A: Most ways to do what you request would probably involve adding rules to built-in functions (such as Integrate, CDF, PDF, etc), which may not be a good option. Here is a slightly softer way, using the Block trick - based macro: ClearAll[withIntegrationRule]; SetAttributes[withIntegrationRule, HoldAll]; withIntegrationRule[code_] := Block[{CDF, PDF, Integrate, NormalDistribution}, Integrate[ CDF[NormalDistribution[0, 1], \[Alpha]_ + \[Beta]_ x_] PDF[ NormalDistribution[\[Mu]_, \[Sigma]_], x_], {x_, -\[Infinity], \[Infinity]}] := CDF[NormalDistribution[0, 1], (\[Alpha] + \[Beta] \[Mu])/ Sqrt[1 + \[Beta]^2 \[Sigma]^2]]; code]; Here is how we can use it: In[27]:= withIntegrationRule[a=Integrate[CDF[NormalDistribution[0,1],\[Alpha]+\[Beta] x] PDF[NormalDistribution[\[Mu],\[Sigma]],x],{x,-\[Infinity],\[Infinity]}]]; a Out[28]= 1/2 Erfc[-((\[Alpha]+\[Beta] \[Mu])/(Sqrt[2] Sqrt[1+\[Beta]^2 \[Sigma]^2]))] When our rule does not match, it will still work, automatically switching to the normal evaluation route: In[36]:= Block[{$Assumptions = \[Alpha]>0&&\[Beta]==0&&\[Mu]>0&&\[Sigma]>0}, withIntegrationRule[b=Integrate[CDF[NormalDistribution[0,1],\[Alpha]+\[Beta] x] PDF[NormalDistribution[\[Mu],\[Sigma]],x],{x,0,\[Infinity]}]]] Out[36]= 1/4 (1+Erf[\[Alpha]/Sqrt[2]]) (1+Erf[\[Mu]/(Sqrt[2] \[Sigma])]) where I set \[Alpha] to 0 in assumptions to make the integration possible in a closed form. Another alternative may be to implement your own special-purpose integrator.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553975", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Avoid hardcoding in switch statement I have an object with has two properties: Text and Type. To avoid hard-coding the Types, I put them in the database, so they can be added to in future. At the moment the types are URL, Username and ID. However, I now want to run a Utility method to clean up the object's Text field based on which Type the object is (e.g. add 'http://' if its a URL). Is there a way to do this in the Utilities class without hard-coding the types in a switch statement/if else block. switch (type) { case 1: TidyUrl(); case 2: TidyUsername(); case 3: TidyID(); default: break; } In this example I'm hardcoding the IDs from the database ('Type' table), which can never be a good thing! Is there a better way to do this? A: You can use an enum to help with readability. enum MyTypes { URL = 1, UserName = 2, Id = 3, } switch (myType) { case MyTypes.URL: TidyUrl(); case MyTypes.UserName: TidyUsername(); case MyTypes.Id: TidyID(); default: break; } This enum will need to be kept coordinated with the database. A: One way is to use polymorphism. You'd have separate classes for each of your "types" and they'd implement a common interface (or have a common base class) with a method like Tidy, where each would do its own logic. A: Traditionally this is handled using a common interface, and dynamically constructing a concrete implementation to do the actual work. for example: public interface ITidy { string Tidy(string input); } then the implementations public class UrlTidy : ITidy { public string Tidy(string input) { // do whatever you need to the url } } And so on for the other types of tidying. Now you need a way of instantiating the right concrete class (UrlTidy, IdTidy etc) from the type you are looking at. One way to do this might be to put the class name in the database along side the type, and use reflection to instantiate the right implementation of ITidy. Another wat would be to have a Factory class which uses some other method to instantiate the right ITidy based on type. A: You could use enum Type but their constant values will have to determined at compile time. You can put a class invariance check in the enum to ensure that the are consistent with the database. But how does having them in the database make it extendible? A: As Oded said, use an enum: public enum Types { Type1 = 1, Type2 = 2, Type3 = 3 } You can then cast your type variable to the enum, having the integers map to the database IDs: switch ((Types)type) { case Types.Type1: break; case Types.Type2: break; ... } Hope that helps
{ "language": "en", "url": "https://stackoverflow.com/questions/7553979", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Login Failed for user Domain\MachineName$ on IIS 7.5 with an ApplicationPoolIdentity Actually I was expecting a SqlExcpetion like Login Failed for user IIS AppPool\My AppPool Name exception instead of Domain\MachineName$. I've created an Application Pool that is using * *Manged Pipeline Mode : Integrated *Identity : ApplicationPoolIdentity This AppPool is assigned to the Web Application (MVC3) in question. But somehow it seems that the WebApp is using somehow the NetworkService for the connection to SqlServer. Any Idea why or what I should change? A: Turns out that I forgot to change the connection string to SqlServer. So they where pointing to another machine in the Network, as IIS AppPool\My AppPool Name is only valid on the local Server, IIS takes automatically the Network Service to access stuff in the Network, that's why it was showing Domain\MachineName$.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553981", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: android -- wait for user input I'm creating a spades app with 1 human player and 3 computer players. The problem that I am having is, the play must happen sequentially (clockwise) and I need my program to wait on the player input. I can't use wait() and notify(). I have tried while loops to check whether the user has selected a card but those stop the program from running. I've tried recursive methods that won't return anything until the player has chosen a card. That too does not work. So what do I do? I'm stuck. My method goes like this (leaving out the non-pertinent code) private void game(){ while(there are more tricks to be played) while(each player has not played){ if(human turn) get input from player else computer plays } } A: Maybe you should change a little bit your game controller. Instead of waiting for anything, have your program continuously paint the screen. If user inputs nothing, same screen is paint all the time. Once he presses a key (or clicks a card or whatever events you have), simply modify the paint method's argument (the screen to be painted). Thus you will separate painting the screen and input handling. It's a common technique called MVC model. Maybe this will help (it's my game creating blog, and the links inside it are also helpful): http://m3ph1st0s.blogspot.ro/2012/12/create-games-with-libgdx-library-in.html You don't need to adapt all your game to the game described there, only the technique of separating input from painting. As a general technique, you should NOT have input determine painting. Hope it helps. Don't hesitate to request further help. A: You can try to add Event Handlers. It will try triger a event every time the user selects a card. A: Try this. Create one thread and in that threat call sleep(1000);
{ "language": "en", "url": "https://stackoverflow.com/questions/7553987", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to set .as and .hx files to open with FDT Powerflasher Is it possible to set .as and .hx to open with FDT Powerflasher? Settings it to open with what seems to be a previously detected by Windows eclipse.exe (my Java one). A: Nothing special with as/hx files, same procedure as with any other file extension: * *Right click on file *Open with... *Choose the application *Check "Always use the selected program ..." *Ok.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553996", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How does DateTimeOffset deal with daylight saving time? I am storing schedules in the database as a day of the week, hour and minute. When the data is read we create a DateTime object for the next occurrence of that day, hour and minute, but I need to modify this to be DST-aware. I am able to modify the database if necessary. I know that DateTimeOffset stores a UTC date/time and an offset. I also know from this MSDN blog entry that DateTimeOffset should be used to "Work with daylight saving times". What I'm struggling to understand is exactly how DateTimeOffset "work(s) with daylight saving times". My understanding, little that there is, is that daylight saving times are a political decision and cannot be inferred from purely an offset. How can it be that this structure is DST friendly if it only stores an offset and not a named timezone or country? A: DateTimeOffset itself isn't really DST-aware, but TimeZoneInfo is. A DateTimeOffset represents a fixed instant in time - so you get to a DateTimeOffset via something that is time zone aware. In other words, if I asked for a DateTimeOffset now in the UK, I'd end up with something with an offset of +1 hour from UTC. If I asked for a DateTimeOffset for some time in December in the UK, I'd end up with something with an offset of 0 hours from UTC. If you change your database to include the offset and you create the DateTimeOffset from the user's chosen DateTime (which should be of kind "unspecified") and their time zone, then that should give you the correct offset taking DST into account. One thing to be aware of though: if I schedule something now for "2 years time" and you determine the offset now, that offset may not be correct in the future - for example, the government could change when DST applies, and obviously that's not going to change what's stored in your database.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553997", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "28" }
Q: Facebook JS SDK: Displaying oAuth dialog in iframe I am trying to display a Facebook UI dialog inside my iframe app, so that I can get an extended permission that we don't presently have. This was easily achieved using the old SDK. However, using the new library, I get a Facebook iframe dialog that appears modally, but never stops loading. Changing the method to "page" means I get a popup browser window that simply says "An error has occured". My code follows: var attachment = { display: 'iframe', method: 'oauth', scope: perms, access_token: '<?php echo $this->accessToken; ?>' // this is definitely valid access token }; FB.ui(attachment, function(response){ pr(response); }); I'm hoping this is possible using the new SDK, the docs certainly state that iframe is a valid display param. Thanks in advance. G A: iframe is not a valid display param for oauth dialog because of the risk of clickjacking. Also I'd suggest to use FB.login to get an extended permission: https://developers.facebook.com/docs/reference/javascript/FB.login/ hope this helps A: This has been broken for a while. (Take a look at the bugtracker with "FB.ui permission" as search words.) A work-around is to use FB.login instead of FB.ui. This means getting a pop-up instead of an iframe, of course.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553999", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Keep focus on another control while selecting items in a ListBox I have TextBox which should always be in focus. At the same time I have as list box. When user clicks on certain item in this listobox the item clicked gets focus. I tried to set Focusable="false" for each ListBoxItem in my ListBox but in this case no item can be selected. I found following code using dotPeek: private void HandleMouseButtonDown(MouseButton mouseButton) { if (!Selector.UiGetIsSelectable((DependencyObject) this) || !this.Focus()) return; ... } Is there any way to solve my problem? A: You could handle PreviewMouseDown on the ListBoxItems and mark the event as Handled which will stop the focus being transferred. You can set e.Handled = true because MouseButtonEventArgs is a RoutedEventArgs. This demo works to keep focus on the TextBox: XAML <Window x:Class="WpfApplication1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <StackPanel FocusManager.FocusedElement="{Binding ElementName=textBox}"> <TextBox x:Name="textBox" /> <ListBox x:Name="listBox"> <ListBoxItem PreviewMouseDown="ListBoxItem_PreviewMouseDown">1</ListBoxItem> <ListBoxItem PreviewMouseDown="ListBoxItem_PreviewMouseDown">2</ListBoxItem> <ListBoxItem PreviewMouseDown="ListBoxItem_PreviewMouseDown">3</ListBoxItem> </ListBox> </StackPanel> </Window> Code Behind using System.Windows; using System.Windows.Controls; using System.Windows.Input; namespace WpfApplication1 { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void ListBoxItem_PreviewMouseDown(object sender, MouseButtonEventArgs e) { var item = sender as ListBoxItem; if (item == null) return; listBox.SelectedItem = item; e.Handled = true; } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7554004", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why do I get a DuplicateKeyException in Linq2Sql after I checked for the keys existence? I have a program that adds a lot of new data to a database using Linq2SQL. In order to avoid DuplicateKeyExceptions, I check for the existence of the key, before trying to add a new value into the database. As of now, I can't provide an isolated test-case, but I have simplified the code as much as possible. // newValue is created outside of this function, with data read from a file // The code is supposed to either add new values to the database, or update existing ones var entryWithSamePrimaryKey = db.Values.FirstOrDefault(row => row.TimestampUtc == newValue.TimestampUtc && row.MeterID == newValue.MeterID); if (entryWithSamePrimaryKey == null) { db.Values.InsertOnSubmit(newValue); db.SubmitChanges(); } else if(entryWithSamePrimaryKey.VALUE != newValue.VALUE) { db.Values.DeleteOnSubmit(entryWithSamePrimaryKey); db.SubmitChanges(); db.Values.InsertOnSubmit(newValue); db.SubmitChanges(); } Strangely enough, when I look at the exceptions in the application log, as to which items cause trouble, I am unable to find ANY of them in the database. I suspect this happens within the update code, so that the items get removed from the database, but not added again. I will update my code to deliver more information, and then update this post accordingly. A: If the error is generated in the update block, you can merge the object in the update case without deleting entryWithSamePrimaryKey, but valorizing it with the property value of newValue and than save the changes.
{ "language": "en", "url": "https://stackoverflow.com/questions/7554008", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to set default devices for sis creation An error occured during sis creation via command window. Which says: "To use new symbian OS tools specify a default device using devices -setdefault(otherwise unset EPOCROOT and specify a device explicitly)" A: Set your EPOCROOT variable. If your environment is at something like: C:\Nokia\devices\Nokia_Symbian3_SDK_v1.0\ Then on your command line call: set EPOCROOT=\Nokia\devices\Nokia_Symbian3_SDK_v1.0\ Or set it in your environment variables. Note the drive letter is omitted and it ends with a slash. To set a default devices, first check what you have installed with the devices command, for example: C:\Nokia\devices\Nokia_Symbian3_SDK_v1.0\>devices Nokia_Symbian3_SDK_v1.0:com.nokia.symbian S60_5th_Edition_SDK_v1.0:com.nokia.s60 - default If I wanted to change it to make the S^3 SDK default, use devices -setdefault @deviceID: C:\Nokia\devices\Nokia_Symbian3_SDK_v1.0\>devices -setdefault @Nokia_Symbian3_SDK_v1.0:com.nokia.symbian A: I added the following in the xml and it worked C:\Program Files\Common Files\Symbian\devices.xml <?xml version="1.0"?> <devices version="1.0"> <device id="Nokia_Symbian_Belle_SDK_v1.0" name="com.nokia.symbian" default="yes" userdeletable="yes"> <epocroot>C:\Nokia\devices\Nokia_Symbian_Belle_SDK_v1.0</epocroot> <toolsroot>C:\Nokia\devices\Nokia_Symbian_Belle_SDK_v1.0</toolsroot> </device> </devices>
{ "language": "en", "url": "https://stackoverflow.com/questions/7554012", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: retrieve the value of datagridview inside the panel in splitcontainer I have a split container control in c#. inside the right panel there is a datagridview. i have a button in panel outside the datagridview. when the button is clicked i want to get the datagridview's selected row value. how to do it? A: For example dataGridView.SelectedRows[0].DataBoundItem or dataGridView.SelectedRows[0].Cells[x].Value where x is the column index or sensorDataGridView.CurrentCell.Value
{ "language": "en", "url": "https://stackoverflow.com/questions/7554022", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }