text
stringlengths
8
267k
meta
dict
Q: unrecognized selector sent to instance (iOS) Possible Duplicate: unrecognized selector sent to instance Well... like so many others, I have gotten a "unrecognized selector sent to instance" error... The problem occurs when I press a button, e.g. in this case: -(IBAction)gotoTone:(id)sender { if(self.tone == nil) { Tone *toneMain = [[Tone alloc] initWithNibName:@"Tone" bundle:[NSBundle mainBundle]]; self.tone = toneMain; [toneMain release]; } [self.navigationController pushViewController:tone animated:YES]; } The error is: Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Tone gotoTone:]: unrecognized selector sent to instance 0x531caa0' The error started occurring after I inserted a new view as the first view presented to the user... Also, I use a navigation bar and at first I had forgotten to go into MainWindow.xib and change the Navigation Controller to the new view, but that is fixed now. You can see my entire code her: The .h in which the file occurs: http://snipt.org/xnoO The .m in which the file occurs: http://snipt.org/xnoM Don't mind all the out-commented lines, that's just until I get this fixed... I've tried finding a solution to this by reading other cases of "unrecognized selector sent to instance", but I guess I'm just not seeing the solution. I've checked my IB-connects, I've cleaned the project and such... Any help would be greatly appreciated A: I met this issue and solved it just by reconnected the Button to the IBAction whose name was modified before. So embarrassing. A: I think the issue is that you are sending the method gotoTone: to a Tone object, however this method is defined within the Forside object. I'm not sure exectly why this is happening, however I suggest checking the connections within you xib file. A: You haven't provided any information about how your button is configured, but if the button is in your nib file, it seems likely that the identity of the button's target is set to the wrong class. So make sure that the class of the object the button sends its message to is Forside rather than Tone.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583291", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Trouble with if statement I'm a noob so please be patient I have to test an array, so that I check if it exists and to see if the numbers in it are ok. In every case a message must be put out...for example...if the array is full and the numbers are ok I should get a message like (Array is full, Num are ok). But I use If after If and I get into trouble because.....well..take a look for yourself. public static function getTest($ids){ $input_result = array(); foreach ($ids as $id) { $input_result['result']['Id '.$id] = $id; } if((!empty($ids))){ //echo "You have inputted some data in the Api_Books_Book::getTest<br/>"; $input_success = "Successful!"; $input_message = "Array OK"; } else { //echo "There is no data<br/>"; $input_success = "Not Successful"; $input_message = "Have inputed anything in the array?"; } if(okNum($ids)) { //echo "You have inputted some data in the Api_Books_Book::getTest<br/>"; $input_success = "Successful!"; $input_message = "numbers OK"; } else { //echo "There is no data<br/>"; $input_success = "Not Successful"; $input_message = "numbers not OK"; } $result=array('status'=>$input_success,'message'=>$input_message,'result'=> $input_result); rdie($result); return $result; } A: On first glance you appear to be missing an else just before this code: { //echo "There is no data<br/>"; $input_success = "Not Successful"; $input_message = "Have inputed anything in the array?"; } A: if((!empty($ids))){ //echo "You have inputted some data in the Api_Books_Book::getTest<br/>"; $input_success = "Successful!"; $input_message = "Array OK"; } { //echo "There is no data<br/>"; $input_success = "Not Successful"; $input_message = "Have inputed anything in the array?"; } This looks like your problem (although you haven't actually told us what issue you are getting). The above isn't an else so the "Not Successful" code will always run. You should note also that the result of the if(okNum($ids)) will wipe whatever value you previously set $input_success to. It's hard to say without seeing the okNum method but it looks like this returns true if the array is empty.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583294", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Exception when accessing a class defined in library project from another project I have 2 projects in Eclipse. One is a library project (the base project) and one is the project that will be released as the free version of the app. The free project has only 1 activity in it: a LaunchActivity. Everything else is in the library project. I try to debug the free project and the 1st time I try to reference a class defined in the Library project, I get a java.lang.NoClassDefFoundError. At one point I couldn't even use the library classes in the free project until I went on the free project, right-clicked Properties > Java Build Path > Projects tab and included the library project (although I figured this would be taken care of by adding the library project as a reference in Properties > Android and adding the reference). I have even tried Properties > Project References and added the library proj as a reference here too but without success. Any ideas? Many many thanks, Sean A: You have to define your activities that are defined in library Project's AndroidManifest.xml into Main projects AndroidManifest.xml also. And ,include library project as a reference through Properties->Android->Add->Apply
{ "language": "en", "url": "https://stackoverflow.com/questions/7583296", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CGRectMake did not work perfectly in landscape mode? when I draw a UIView in landscape mode of ipad , it gives wrong width and wrong height,i have mentioned as follows - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { return (interfaceOrientation==UIInterfaceOrientationLandscapeRight); } rightView.view.frame = CGRectMake(598, 700, 60, 171); but width is very high,height is very low…any help please? A: When in landscape mode, as the frame is in the coordinates system of its parent view and the parent view has a CGAffineTransform applied (to apply the interface orientation), with and height are inverted. See this other question that also deals with related issues A: YOu may set frame like. it will give you a require result. CGRectMake(self.view.size.width-426 ,self.view.size.height-100 , self.view.size.width-366, self.view.size.height-497); A: just write below line rightView.view.frame = CGRectMake(598, 700, 171, 60);
{ "language": "en", "url": "https://stackoverflow.com/questions/7583297", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using Proxy Webservice with Adobe AIR/BlazeDS I am trying to call a webservice using proxy. My settings for proxy-config on blazeds side are as below: <destination id="ws-catalog"> <properties> <wsdl>http://feeds.adobe.com/webservices/mxna2.cfc?wsdl</wsdl> <soap>*</soap> </properties> <adapter ref="soap-proxy"/> </destination> On Adobe AIR side, my code is: <?xml version="1.0" encoding="utf-8"?> <s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/mx" creationComplete="loadConfiguration()"> <s:layout> <s:VerticalLayout/> </s:layout> <fx:Script> <![CDATA[ import mx.messaging.ChannelSet; import mx.messaging.channels.AMFChannel; import mx.rpc.events.FaultEvent; import mx.rpc.events.ResultEvent; [Bindable] private var cs:ChannelSet; private function loadConfiguration():void { var amfChannel:AMFChannel = new AMFChannel("my-amf", 'http://localhost:8400/messagebroker/amf'); cs = new ChannelSet(); cs.addChannel(amfChannel); } protected function ws_resultHandler(event:ResultEvent):void { var obj:Object = event.result; } protected function ws_faultHandler(event:FaultEvent):void { var faultObj:Object = event.fault; } protected function button1_clickHandler(event:MouseEvent):void { ws.getOperation('getFeeds').send(); } ]]> </fx:Script> <fx:Declarations> <s:WebService id="ws" channelSet="{cs}" useProxy="true" destination="ws-catalog" showBusyCursor="true" result="ws_resultHandler(event)" fault="ws_faultHandler(event)" /> </fx:Declarations> <s:Button label="CallWebService" click="button1_clickHandler(event)"/> </s:WindowedApplication> But now, whenever I launch my AIR app, am getting following error: faultCode: InvokeFailed faultDetail: Unable to load WSDL. If currently online, please verify the URI and/or format of the WSDL (null) faultString: [MessagingError message='Destination 'ws-catalog' either does not exist or the destination has no channels defined (and the application does not define any default channels.)'] Can somebody help me OR point me to a similar solution? Thanks. A: Hard to say without knowing all the configuration. You can check a couple of reasons like: -failure to declare the proxy-config.xml file in services.xml -failure to include services.xml in the project -failure to declare a channel for your destination The best way to learn how to invoke webservices using BlazeDS as a proxy is to download the blazeds turnkey installation and to take a look at the samples. After uncompressing the archive you can find the samples folder in blazedsrootfolder/tomcat/webapps/samples. You will find one example showing what you are trying to do. A: Please check the code below. It works on my machine. You need to wait a couple of seconds, getFeeds returns a lot of data. <?xml version="1.0" encoding="utf-8"?> <fx:Script> <![CDATA[ import mx.messaging.ChannelSet; import mx.messaging.channels.AMFChannel; import mx.rpc.events.FaultEvent; import mx.rpc.events.ResultEvent; import mx.rpc.soap.LoadEvent; import mx.rpc.soap.mxml.*; import mx.rpc.wsdl.WSDLOperation; [Bindable] private var cs:ChannelSet; [Bindable] var gateway:WebService private function loadConfiguration():void{ var amfChannel:AMFChannel = new AMFChannel("my-amf", 'http://localhost:8400/samples/messagebroker/amf'); cs = new ChannelSet(); cs.addChannel(amfChannel); gateway = new WebService(); gateway.channelSet = cs; gateway.destination = "ws-catalog"; gateway.useProxy = true; gateway.addEventListener(ResultEvent.RESULT,ws_resultHandler); gateway.addEventListener(FaultEvent.FAULT,ws_faultHandler); gateway.loadWSDL(); } protected function ws_resultHandler(event:ResultEvent):void{ var obj:Object = event.result; trace("ok"); } protected function ws_faultHandler(event:FaultEvent):void{ var faultObj:Object = event.fault; trace("nok"); trace(faultObj); } protected function button1_clickHandler(event:MouseEvent):void{ gateway.getFeeds(); } ]]> </fx:Script> <s:Button label="CallWebService" click="button1_clickHandler(event)"/>
{ "language": "en", "url": "https://stackoverflow.com/questions/7583303", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SVN: switch from nonexistent path? I have a repository which was moved, path renamed and then logs truncated. So I don't have old path in it. When I try to do svn switch https://new.repo/new/path svn complains "Cannot replace a directory from within". How do I avoid this? P.S. Recreating old path is not an option. A: If it's still the same repo, and it's just the path to the repo that's changed, then you should be passing the --relocate option to svn switch. Does that help? i.e. svn switch --relocate https://new.repo/new/path (Warning: If it's not the same repo, then using --relocate will break things) A: checkout from new location and copy the contents of old working copy over your new Working copy A: Problem was solved. I've created a script that changed path in all .svn/entries. Everything works. A: Well, already solved but svn --relocate https://old.repo/old/path https://new.repo/new/path should do the trick nicely A: I had this same issue and was not able to get it to work with either "switch" or "switch --relocate". As the original question states, I got the error "Cannot replace a directory from within" with the former and with the latter "Relocate can only change the repository part of an URL" As I am on CentOS I was able to use sed to manually update the url in the .svn/entries files by running the following from the root of my working directory: find . -type f -name entries -exec sed "s/old\/path/new\/path/" -i {} \;
{ "language": "en", "url": "https://stackoverflow.com/questions/7583304", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: php gd GRAYSCALE i have a code in php with the GD library and it gives error here is the code : <?php header('content-type: image/png'); $image = imagecreatefrompng('a.png'); imagefilter($image, IMG_FILTER_GRAYSCALE); imagepng($image); imagedestroy($image); ?> and here is the error : the image localhost/image/gdimg.php cannot displayed because it contains errors what is wrong here? A: remove line header('content-type: image/png'); and you will see php error.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583306", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why does CakePHP use this method name in a MySQL query rather than return the result? In applying the answer from a previous question, I tried overriding one of CakePHP's built-in pagination methods: function paginateCount($conditions = null, $recursive = 0, $extra = array()) { if (isset($extra['group'])) { for ($i=0; $i<count($extra['group']);$i++) { if (strpos(strtolower($extra['group'][$i]),'having')!==false) unset($extra['group'][$i]); } exit(); } $count = parent::paginateCount($conditions, $recursive, $extra); return $count; } The problem is that this seems to cause Cake to do a MySQL query consisting simply of the name of the method. Obviously this doesn't work and throws an error: SQL Error: 1064: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'paginateCount' at line 1 Since I have debugging enabled, I can see that where there would normally be the paginateCount() query: 1: SELECT COUNT(*) AS `count` FROM `tournaments` AS `Tournament` WHERE 1 = 1 I just get: 1: paginateCount I've obviously misunderstood PHP's inheritance operators. My function seems to be returning the name of the function it is overriding rather than it's value. How can I fix this? A: This usually happens when CakePHP can't find the method in the model or attached behaviors. It then passes the call to the datasource (hoping it has the method and knows what to do) and that's why you get this error. I would check things are what they seem (is the method in the right model, is Cake making an automodel because of incorrect filenaming, etc.) A: I've fixed this without really addressing the question I asked. Instead of passing the adjusted parameters up the chain as I wanted to do in my above example, I've used them to do the same job directly: return $this->find('count', compact($conditions, $recursive, $extra)); This works OK, but doesn't explain the odd behaviour that caused me to ask the question in the first place. My guess is that Cake is doing something funky with virtual/"automagic" methods.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583307", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Jquery autocomplete with json input + rails3 $(function() { $('.autocomplete_address').autocomplete({ minLength: 0, delay: 600, source: function(request, response) { $.ajax({ url: "/welcome.js", dataType: "json", data: {search: request.search}, success: function( data ) { var data_obj = jQuery.each(data,function(i, key) { }); response( $.map(data_obj, function( item ) { return { label: item.area, value: item.area } })); } }); } }); }); Using jquery-ui-186's autocomplete The autocomplete part works But it shows the same results for any data entered In the server side code looks like this: class WelcomeController < ApplicationController def index @area = Address.search params[:search] @area = @area.as_json(:include => :state) @area = @area.to_json respond_to do |format| format.html format.js {render :json => @area} end end end Where am i going wrong!!!!!! Any help is greatly appreciated. A: The request object has a term property, not a search property. Update your AJAX call: /*Snip */ data: { search: request.term }, /*Snip */ A: Update: make from the docs: success: function( data ) { response( $.map( data.geonames, function( item ) { return { label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName, value: item.name } })); } So yours might look like this: success: function( data ) { response( $.map(data_obj, function( item ) { return { label: item.area, value: item.area } }); } It looks like you're not actually doing anything with the results of your .each().
{ "language": "en", "url": "https://stackoverflow.com/questions/7583322", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Zend Framework - do not treat /public/directory as a controller Is it possible to request a directory over http in the Zend /public/ directory without it being treated as a controller? Eg, I have a directory, /public/facebook/ that contains facebook app data but Zend is (as default expected behaviour) giving "facebook controller missing" error when I request http://mysite.com/facebook. A: This is because the default RewriteRules provided with Zend are redirecting all requests to the Zend Framework Bootstrapper (index.php). The best thing to do, IMHO, is to add an exception to this Rule. Then there's more than one way to do it. You could use RewriteCond (and for example avoid the general redirect for existing directory or files in /public). But you could maybe filter it in the RewriteRule expression as well. This is an example with exception in the RewritreRule, so withoutt RewriteCond: RewriteRule !(public/facebook/(.*\.php))|(public/(.*\.pdf))|(externalauthent\.php)|(favicon.ico)|(images/(.*\.(ico|gif|jpg|png|bmp|JPG|JPEG|BMP|GIF|PNG)))|(css/(.*\.css))|(js/(.*\.*))$ /index.php [L] A: If you have content in this url, ZF don't try to found facebook controller, You need add a folder named facebook, and a file index.php into this folder A: This work for me: RewriteEngine On RewriteCond %{REQUEST_FILENAME} -s [OR] RewriteCond %{REQUEST_FILENAME} -l [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^.*$ - [NC,L] RewriteCond %{REQUEST_URI} !^/public_directory_name RewriteRule ^.*$ index.php [NC,L] Just replace 'public_directory_name' with the name of the directory you don't want Zend to treat as a controller. Answered in a different worded question: htaccess - do not rewrite in this case
{ "language": "en", "url": "https://stackoverflow.com/questions/7583323", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jquery template loaded from distant server I am using jquery templates on several projects. Thing is, in order to get a consistent feel, I was planning to put all the common templates on a CDN server, and then load them from different services with (in head): <script id="errorPage" src="http://www.mycdn.com/error-page.html" type="text/x-jquery-tmpl"></script> Then (in page ready handler), I use the following code to render my template: $("#errorPage").tmpl("errorPage", {'message': 'Permission denied'}).prependTo("body"); Thing is ... it doesn't work !? nothing is rendered ... I don't know if it is even possible. I am very new to jquery-template, so I might also be missing something obvious !!! Any idea ? A: How does your template look like? Is browser processing it as html or as javascript? Try putting it in .js file or loading your templates as a string variables in javascript file. Instead of <script id="errorPage" src="http://www.mycdn.com/error-page.html" type="text/x-jquery-tmpl"></script> load some .js file which has something like this: var errorPage = "<html><body>error: ${message}</body></html>"; //replace with your template ... $.template( "errorPage", errorPage); You can have one or more js files with templates, but should have javascript as a source, not html. UPDATE after I tried your scenario: When loaded the way how you tried, contents of error-page.html are not parsed as jquery template and you get empty errorPage variable. A: You can create the templates in external files and call them with $.getScript. For instance: example.html <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.4.min.js"></script> <script src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.js"></script> <script> $(function() { $.getScript('./template.js', function(data) { $.tmpl("message", { id:1, msg:"Some Message!" } ).appendTo('#output'); }); }); </script> <body> <div id="output"></div> </body> template.js $.template("message", '<a href="/message/${id}">${msg}</a>'); The only problem with testing this is that browsers don't usually allow file access for AJAX requests, so you'll have to throw it into a local web server to try it out. edit: You can apparently also force html-only requests: $.get('./template2.js', function(data) { $.template("message2", data); $.tmpl( "message2", { id:1, msg:"Some Message!" } ).appendTo('#output'); }, 'html'); template2.js <p id="script2"> <a href="/message/${id}">${msg}</a> </p> Notice how after the callback in $.get, I'm explicitly specifying 'html'.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583325", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: ssis execute package task showing as red, but child packages showing all green When running a package that contains multiple 'execute package tasks' the 'child' packages are automatically opened in vs.net (BIDS). All of the tasks in both of the first two (child) packages turn green i.e. success So why is the parent package showing red tasks (and then the whole thing grinds to a halt) ? A: For anyone following this thread: @DavidBenham has shared good advice--that is to enable logging. Short of that, since it sounds like you are debugging the package through the IDE, you can disable/enable the components called. This would allow you to look at specific flows until you isolate the problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583328", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: how to do ajax or jquery with django1.3 I am absolutely new to django framework and new to web development and python. Currently I'm trying to implement ajax in my project. I am not able to find any working sample. I need help with putting ajax or jquery in a django1.3 project. Now I'm trying to implement ajax using dojango' app. I install it successfully and trying this tutorial. urls.py: (r'^dojango/', include('dojango.urls')), (r'^simple/', 'views.simple'), (r'^simple-ajax-set/', 'views.simple_ajax_set'), views.py: from django.shortcuts import render_to_response from dojango.decorators import json_response @expect_post_request @json_response def simple_ajax_set(request): ret = {} firstname = request.POST['firstname'] surname = request.POST['surname'] if len(surname)<3: ret['error'] = 'Surname is too short.' ret['success'] = False if ret['success']: # Store the data here pass return ret simple.html {% extends "dojango/base.html" %} {% block dojango_page_title %}Simple AJAX with dojango{% endblock %} {% block dojango_header_extra %} <script type="text/javascript"> function userFormSubmit(){ var form = dojo.byId("userForm"); dojo.xhrPost({url:form.action, handleAs:"json", content:{surname:form.surname.value, firstname:form.firstname.value }, load:function(response, ioArgs){ if (response.success){ dojo.byId("info").innerHTML = "Submitted successfully"; } else { dojo.byId("info").innerHTML = "Error: "+response.error; } }, error:function(data){ // This happens on a 500 error or alikes. dojo.byId("info").innerHTML = "Error sending data."; } }); } </script> {% endblock %} {% block dojango_content %} <form id="userForm" onsubmit="userFormSubmit(); return false;" action="/simple-ajax-set/"> First name: <input id="firstname" /><br /> Surname: <input id="surname" /><br /> <input type="submit" value="Submit" /> <span id="info"></span> </form> {% endblock %} When I run I got the exception NameError at /simple-ajax-set/ name 'expect_post_request' is not defined So I change my code as in the first part of the above tutorial, and I got the following exception 'MultiValueDictKeyError at /simple-ajax-set/' , "Key 'firstname' not found in <QueryDict: {}>" when click on the submit button at simple.html. Please help me to find out the problem sand also share some links or codes containg ajax/jquery which works with django1.3. and python 2.7, Can any one suggest working a hello world ajax or jquery example for django1.3? A: "Pure" jQuery and django here. That made me happy when i was on your place. Good luck!
{ "language": "en", "url": "https://stackoverflow.com/questions/7583331", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Keeping a hidden input box name the same using c# I am trying to integrate with a payment gateway. They require a set of hidden input boxes to be posted to their gateway like: <input id="orderref" name="orderref" type="hidden" runat="server"/> I have added runat="server" so I can dynamically populate the boxes with values. However, of course at runtime the input box name gets changed to: <input name="ctl00$ContentPlaceHolder1$orderref" type="hidden" id="ContentPlaceHolder1_orderref" value="9" /> I'm in a catch 22. If I remove runat="server" all is fine with regards to the name, but I then can't populate the input box with values! Is there a means to force the name of the field to stay the same? A: Depending on what .NET version you are using the control over this differs: basically, pre-.NET4 you can only alter the container prefix by implementing your own, but from .NET4 you can omit the container prefixes using ClientIDMode. Alternatively, you may expose methods, say, on your page or master page and then call them using inline-scripting (<%=MyMethodReturningValue() %>) which is evaluated at the time of render. EDIT: To elaborate a little on my second suggestion, you can define a method in your pages code-behind that can be executed in an inline manner by use of embedded code blocks; the referenced link gives simple examples of this, but the methods needn't be in <script> blocks of the page itself (as I previously touched on) so that you can keep your logic separated, such as: Define a method in your page's code-behind: public string RenderMessage() { return "This need not be a hard-coded string!"; } Write out your input element, omitting the runat attribute, and adding the embedded code block in place of where the value would be (think of this as a place holder); this code block is going to call the specified method on pre-render, and essentially be replaced by the returning value: <input id="orderref" name="orderref" type="hidden" value='<%=RenderMessage() %>'/> A: If you are using ASP.NET 4.0, you can set clientidmode="Static" on the <input> which will cause the ID to stay exactly as you set it. There are caveats to this, but in general should work for your needs. Documentation on ClientIDMode Edit: As it turns out, they need the name attribute to be static, which ClientIDMode does not control, and can not be set programatically in ASP.NET, it only controls the id attribute. A: Use the following code: Page.ClientScript.RegisterHiddenField("orderref", "9") This creates the following hidden input: <input id="orderref" name="orderref" type="hidden" value="9" /> For more details see System.Web.UI.ClientScriptManager.RegisterHiddenField on MSDN A: I also struggled with this issue and eventually found the following solution: In the markup I have the following: <%=html %> In the codebehind I have a protected variable: protected string html; I then set this variable as follows: html = "<input id='Express_Receipt_Email' type='hidden' value='" + sessionUser.EmailAddress + "' name='Express_Receipt_Email'>";
{ "language": "en", "url": "https://stackoverflow.com/questions/7583335", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Library function capabilities of Mathematica I am trying to use CUSP as an external linear solver for Mathematica to use the power of the GPU. Here is the CUSP Project webpage. I am asking for some suggestion how we can integrate CUSP with Mathematica. I am sure many of you here will be interested to discuss this. I think writing a input matrix and then feeding it to CUSP program is not the way to go. Using Mathematica's LibrarayFunctionLoad will be a better way to pipeline the input matrix to the GPU based solver on the fly. What will be the way to supply the matrix and the right hand side matrix directly from Mathematica? Here is some CUSP code snippet. #include <cusp/hyb_matrix.h> #include <cusp/io/matrix_market.h> #include <cusp/krylov/cg.h> int main(void) { // create an empty sparse matrix structure (HYB format) cusp::hyb_matrix<int, float, cusp::device_memory> A; // load a matrix stored in MatrixMarket format cusp::io::read_matrix_market_file(A, "5pt_10x10.mtx"); // allocate storage for solution (x) and right hand side (b) cusp::array1d<float, cusp::device_memory> x(A.num_rows, 0); cusp::array1d<float, cusp::device_memory> b(A.num_rows, 1); // solve the linear system A * x = b with the Conjugate Gradient method cusp::krylov::cg(A, x, b); return 0; } This question gives us the possibility to discuss compilation capabilities of Mathematica 8. It is also possible to invoke the topic of mathlink interface of MMA. I hope people here find this problem worthy and interesting enough to ponder on. BR A: If you want to use LibraryLink (for which LibraryFunctionLoad is used to access a dynamic library function as a Mathematica downvalue) there's actually not much room for discussion, LibraryFunctions can receive Mathematica tensors of machine doubles or machine integers and you're done. The Mathematica MTensor format is a dense array, just as you'd naturally use in C, so if CUSP uses some other format you will need to write some glue code to translate between representations. Refer to the LibraryLink tutorial for full details. You will want to especially note the section "Memory Management of MTensors" in the Interaction with Mathematica page, and choose the "Shared" mode to just pass a Mathematica tensor by reference.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583336", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: How to embed tag in a list in a wiki I am trying to embed a <pre> tag in within an ordered list, of the form: # Some content #: <pre> Some pre-formatted content </pre> But it doesn't work. Can someone please let me know on how to achieve what I am trying to do? A: You can use a regular HTML list: <ol> <li>Some Content</li> <li><dl><dd><pre>Some pre-formatted content</pre></dd></dl></li> </ol> A: This is the better answer for continuing a numbered list after using the <pre> tag without resorting to html: # one #:<pre> #:some stuff #:some more stuff</pre> # two Produces: *1. one some stuff some more stuff *2. two
{ "language": "en", "url": "https://stackoverflow.com/questions/7583337", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Get Current User from root mode? I am writing a login item and I am trying to find if its possible to get the current user. Lets say, I have logged in with user "Test" and when I execute the exe with root privileges and if I use char *user = getenv("USER"); user is "root". My expected answer is "Test". How can I get it? I don't know if I can put objective c code in login item? Is it possible to NSUserName in login item. NSString *user = NSUserName(); A: You want the SCDynamicStoreCopyConsoleUser function. QA1133 gives some relevant details and caveats. A: Login items can be Cocoa applications, so you can use NSUserName() (which is in Foundation by the way). Maybe also look at getuid() / geteuid()
{ "language": "en", "url": "https://stackoverflow.com/questions/7583338", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Running Java application as a service We have a java application that's essentially a long running process. It's deployed on JBoss 6.1. We have to start it by going to the url http://ip.ip.ip.ip:8080/MyApp/Monitor Is there a way we could run it as a service via the cli with some ability to start / stop / restart as needed? A: If it is the only application running on the JBoss instance, you could configure your JBoss to automatically start you application when it starts and then follow the steps in http://community.jboss.org/wiki/JBossSystemService to run JBoss as a service. If you have other applications on the JBoss instance or you want to start/stop only the application and not the whole server, you could write a Java application that connects to your JBoss instance remotely using Java Management Extensions and use the JMX Beans provided by JBoss to start/stop your application. More about JBoss JMX interface can be found in http://docs.jboss.org/jbossas/jboss4guide/r2/html/ch2.chapter.html I know this is of JBoss 4 but I don't think they dropped JMX support in newer versions. A: Make it a console application? public static void main(String [] args) { doStuffThatMyAppMonitorNormallyDoes(); } A: Fire a call to your application directly from the console using the java command. Example: public class MonitorService{ .. public static void main(String[] args) { if(args[0].equalsIgnoreCase("-start") { //Do start routine } else if(args[0].equalsIgnoreCase("-stop") { //Do stop routine } } ... } Run the program as the follows. Java MonitorService -start A: You can turn it to windows/unix service using java service wrapper A: I would recommend using Apache Commons Daemon (or maybe YAJSW) to create your own wrapper controller class. An example of this is shown here. The wrapper controller extends the Daemon class of Commons-Daemon and it could be ran on the command line in the form of : java -cp . WrapperController.class -windowsStop java -cp . WrapperController.class -windowsStart java -cp . WrapperController.class -verify You could also of course, extend the example to have its own SysTray object. You could also implement your controller class as a Beanshell script so that it need not be a pre-compiled class to run.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583339", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Can Google Checkout support the Parallel Payments like Paypal I have created a Event website and here registered user can create event and their tickets and when an event is created then other users purchases tickets. when customer pays for the tickets then the payment goes to the two person ie. 1(Ticket Owner),2(Website Owner). there are two payment gateways one is Paypal and second is Google Checkout. I have implement Paypal Parallel Payments for this and want to know that there are any options in Google Checkout like Paypal for this type payment. please let me know as soon aspossible. Thanks A: As far as I know there is no equivalent to PayPal Parallel Payments in Google Checkout.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583343", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: if else changing a text field I have this code and it is not working It is just for testing. HTML <a id="sp">test</a></li> JavaScript document.getElementById('sp').innerHTML = 'test1'; var a == 'undefined' IF (a == "undefined"){ document.getElementById('sp').innerHTML = 'inline'; }ELSE{ document.getElementById('sp').innerHTML = 'inline1'; } The code is not entering the if. Can anyone help me? A: The quoted code has at least three significant, basic syntax errors. It's not just not entering the if, it's not doing anything at all. Look in your JavaScript console for the error messages, trust me they're there. document.getElementById('sp').innerHTML = 'test1'; // 1. You want =, not ==, below. And a semicolon would be good. var a == 'undefined' // 2. IF should be in all lower case (if) IF (a == "undefined"){ document.getElementById('sp').innerHTML = 'inline'; // 3. ELSE should be in all lower case (else) }ELSE{ document.getElementById('sp').innerHTML = 'inline1'; } A: Please note that the string 'undefined' is not the same as being actually undefined. if and else are lower case. document.getElementById('sp').innerHTML = 'test1'; var a = 'undefined'; if (a === 'undefined') { document.getElementById('sp').innerHTML = 'inline'; } else { document.getElementById('sp').innerHTML = 'inline1'; } If you are actually trying to work out if a is properly undefined, use... if (typeof a === 'undefined') { document.getElementById('sp').innerHTML = 'inline'; } else { document.getElementById('sp').innerHTML = 'inline1'; } A: If you are writing your code in head section, move it to body tag.. secondly, remove one "=" from var a=='undefined'. here is the working code example <html><head></head> <body> <a id="sp">test</a> <script language="javascript"> document.getElementById('sp').innerHTML = 'test1'; var a = 'undefined' if (a == "undefined") { document.getElementById('sp').innerHTML = 'inline'; } else { document.getElementById('sp').innerHTML = 'inline1'; } </script> </body> A: In the assigning you change to var a = "undefined" and not ==
{ "language": "en", "url": "https://stackoverflow.com/questions/7583346", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-4" }
Q: Problem with Navigation Property naming convention in EDMX My Foreign Key Name in SQL is FK_Employee_Departmemt_Source FK_Employee_Departmemt_Status but when i add Employee and Department table in EDMX, Entity Framework automatically change their names to Department Department1 I want it to be remain the same, Kindly help. Thanks A: You want it to remain FK_Employee_Departmemt_Status? You should really read something about naming conventions in .NET. Never mind as I know you cannot change this behavior and you must modify names manually after updating from database. Moreover in this case you have a big change you will have to do it after each update of the entity containing that FK.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583352", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to use 9 patch images in android for different-2 densities(like mdpi,ldpi,hdpi).? I am creating an android application in which I want multiple screen support.For these I have used 9 patch images. But my question is this whether using 9 patch images will be enough for different-2 density's devices or I will need to create different-2 9 patch images for varying densities(like mdpi,ldpi,hdpi). Thanks in advance A: From documentation: nine patch A NinePatchDrawable graphic is a stretchable bitmap image, which Android will automatically resize to accommodate the contents of the View in which you have placed it as the background. An example use of a NinePatch is the backgrounds used by standard Android buttons — buttons must stretch to accommodate strings of various lengths. A NinePatch drawable is a standard PNG image that includes an extra 1-pixel-wide border. It must be saved with the extension .9.png, and saved into the res/drawable/ directory of your project. the answer is no. you nine patch will scale between different screen size A: I recently found out myself in the same situation so let me pitch in and expand on what has been said already... Yes, 9-patch images will scale, that's what they exist for. But if you should use a 9-patch image for all screen densities, that depends on the image really. 9-patch images are more commonly used, for instance, buttons. You can have different sized buttons in your app and a 9-patch image will help deal with them, no matter how you size your button (as long as the 9-patch image is properly created). But let's say your button design has some really round corners for the hdpi version. You create your 9-patch image without messing the corners but when you look at it in the ldpi version, you'll realize your corners are too big for that low resolution. For this situation, you'll need a different 9-patch image with less round corners, that look better on that resolution. So, the final answer is, it really depends on your image. If you can create a 9-patch image that looks good in all densities, than fine, use it, as you only need one image to handle all densities. But if it doesn't look good, because of corners, gradients, or whatever, than you'll need one 9-patch image for each screen density. Hopefully it's clearer now. A: Short answer is YES. Check this: By default, Android scales your bitmap drawables (.png, .jpg, and .gif files) and Nine-Patch drawables (.9.png files) so that they render at the appropriate physical size on each device. For example, if your application provides bitmap drawables only for the baseline, medium screen density (mdpi), then the system scales them up when on a high-density screen, and scales them down when on a low-density screen. This scaling can cause artifacts in the bitmaps. To ensure your bitmaps look their best, you should include alternative versions at different resolutions for different screen densities. from Android Developer Official Doc
{ "language": "en", "url": "https://stackoverflow.com/questions/7583359", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Find out character at particular console location Is there any way to read a character from a specific location on the console? For example Read_Console_Char(10, 40);? A: I don't know if there is a standard way to do this, but in Windows environment you can do that. I've never read from arbitrary location, just writing to it with the use of SetConsoleCursorPosition and GetStdHandle. I Just looked on MSDN and there are related API's to get the contents, such as ReadConsoleOutput. Here is the link to it: ReadConsoleOutput example. Hope that helps
{ "language": "en", "url": "https://stackoverflow.com/questions/7583361", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to abstract from pycurl the correct way I would like to write a pseudo module that makes one do a GET request that keeps on going (pretty much like the one to consume the Twitter Streamming API), but making unnecessary to give in all the parameters everytime someone wants to call a function to make that same GET request. In my module.py I have class viewResults(): def __init__(self,username,password,keyname,consume): self.buffer = "" self.consume = consume self.conn = pycurl.Curl() self.conn.setopt(pycurl.USERPWD, "%s:%s" % (username, password)) self.conn.setopt(pycurl.URL, "http://crowdprocess.no.de/"+keyname+"/results") self.conn.setopt(pycurl.WRITEFUNCTION, self.on_receive) # self.conn.setopt(pycurl.VERBOSE, 1) # self.conn.setopt(pycurl.DEBUGFUNCTION, self.debug) self.conn.perform() # def debug(self,debug_type,debug_message): # print 'type: '+str(debug_type)+' message'+str(debug_message) def on_receive(self, data): self.buffer += data if data.endswith("\r\n") and self.buffer.strip(): content = json.loads(self.buffer) self.consume(content) self.buffer = "" And on index.py I have from module import viewResults def consume(content): print content viewResults('username','password','keyname',consume) So I wanted to pass only the parameters username, password, keyname and the "consume" function that should be called when the buffer is full of valid JSON data... What's happening is that the request is actually made, if VERBOSE is on I can see all the data arriving, but that "higher level consume" function get's nothing... How can I achieve this ? Thanks. A: As I understand you want to archive debug data? Create your custom debug function to store you data: custom_debug(debug_type, debug_msg) >>> import human_curl as hurl >>> import json >>> r = hurl.get("http://crowdprocess.no.de/"+keyname+"/results"", ... debug=custom_debug, auth=('username', 'password'),) >>> consume(json.loads(r.content)) A: I could not see in your post code that on_receive(self, data): print something. Add to it sys.stderr.write("%s\n" % data) def on_receive(self, data): # -- print data to stderr -- import sys sys.stderr.write("%s\n" % data) # -- end -- self.buffer += data if data.endswith("\r\n") and self.buffer.strip(): content = json.loads(self.buffer) self.consume(content) self.buffer = ""
{ "language": "en", "url": "https://stackoverflow.com/questions/7583362", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to set listener for bitmaps in a canvas in my custom view...? I have a custom view in which i am drawing many bitmaps, Now i want to change image bitmap when user clicks on it. How to do this...? here is my onDraw method of custom view. public void onDraw(Canvas canvas) { super.onDraw(canvas); Bitmap mBitmap = null; int x = row * 20; int y = clm * 20; System.out.println("the x=" + x + "y=" + y); int counter = 0; for (int a = 0; a <= x; a += 20) for (int b = 0; b <= y; b += 20) { mBitmap = BitmapFactory.decodeResource(getResources(),R.drawable.test); canvas.drawBitmap(mBitmap, a, b, null); counter++; } } A: View.SetOnClickListner() works for any View, just replace View with your customView here. you get access to the view on which the click occurred. then you can change the bitmap of the view. A: To make more than one bitmap clickable, you are going to need to use a ViewGroup class as OnClickListener is implemented to the view. UPDATE You do realize views go inside layouts. when you see 5 buttons on a screen, they are 5 views inside Layout(ViewGroup). The listeners you add are on the views. If you got multiple bitmaps you want to click, you need to make the as imageviews and add them to the layout. If you want to layout them in a particular order you need to create a custom viewgroup. With a custom view, you can only set click to the whole view and not parts of the view. Maybe you can overide a view onTouch event and capture the x,y cordinates of the touch and find which part clicked by a lot of calculations. But thats a big hack and view group is the natural way of doing things.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583363", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Custom date validator in asp.net mvc I have a problem ... I have a user registration form .. in this form I have 3 fields that represent the day, month and year of birth. I like to have 3 fields distinct (3 menus). how can I create a validator that allows me to check if a valid date? (not accept dates like 30/02/2011) I could do it in JavaScript (client side), but even if I wanted to have the validator as usual in model-vew-controller? A: You can bind validators to classes instead of properties. I would do something like that: //The Model [DateValidator] public class Date { public string Month { get; set; } public string Day { get; set; } public string Year { get; set; } } //The DataAnnotation [AttributeUsage(AttributeTargets.Class)] class DateValidatorAttribute : ValidationAttribute { public override bool IsValid(object value) { var date = value as Date; Debug.Assert(date != null); var dateString = date.Month + date.Day + date.Year; DateTime dateTime; var isValid = DateTime.TryParseExact(dateString, "ddMMyyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime); return isValid; } } Edit DateTime.TryParseExact DOES check the validity of a DateTime (i.e. it will return false if you try to parse 30/02/2011). A: Create your model binder which will get those 3 fields from context and validate them altogether.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583367", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Extjs panel extend I have an extjs panel. I need to induce a drag and resizing property for this panel. This is the code for creating the panel: var childPanel = new Ext.Panel({ draggable: true, layout: 'fit', ................ }); I have achieved drag and resizing properties using the code: Ext.override(Ext.Panel, { // private initEvents: function () { if (this.draggable) { this.initDraggable(); } this.resizer = new Ext.Resizable(this.el, { animate: true, duration: '.6', easing: 'backIn', handles: 'all', pinned: false, transparent: true }); this.resizer.on("resize", this.onResizer, this); }, onResizer: function (oResizable, iWidth, iHeight, e) { this.setHeight(iHeight); this.setWidth(iWidth); } }); As you can see I am overriding the property. Therefore all the panels that I create have these properties. I don't want it like that. I know that Ext.extend is the method to use but each time I am getting some errors. What I need is an extended panel with the above code. Can anybody help me to achieve this? A: Have you tired extending? what were the errors? Your should remmeber to call the superclass constructor from the extended methods. MYDRAGRESIZEPANEL = Ext.extend(Ext.Panel,{ // private initEvents: function () { **MYDRAGRESIZEPANEL.superclass.constructor.call(this);** if (this.draggable) { this.initDraggable(); } this.resizer = new Ext.Resizable(this.el, { animate: true, duration: '.6', easing: 'backIn', handles: 'all', pinned: false, transparent: true }); this.resizer.on("resize", this.onResizer, this); }, onResizer: function (oResizable, iWidth, iHeight, e) { this.setHeight(iHeight); this.setWidth(iWidth); } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7583368", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: rapidshare like site loading How can i make pages load like rapidshare without reloading window? for example: https://rapidshare.com/#!home if you browse through pages, browser window is not reloading, it just change last parameter of url like #!myrs_overview, #!buyrapids, #!help etc when i see it in firebug it is giving that parameter name, i.e from above (home,buyrapids) http://screensnapr.com/v/wPJtCY.png Thanks A: #! is called a hashbang, and it's the standard for allowing Google to crawl ajax pages. They're simply using AJAX to repopulate the page information and then updating the hash url: Take the following example navigation link: <a href="contact.php" title="Contact Us" id="contact-us">Contact</a> If we don't want the page to redirect to contact.php but we want to load the content, we could do this instead: <a href="#!contact" class="nav-link" rel="contact.php" title="Contact Us" id="contact-us">Contact</a> Then with JQuery: $('.nav-link').click(function(){ var $this = $(this); $.ajax({ url: $this.attr('rel'), success: function(data){ $('body').fadeOut().html(data).fadeIn(); } }); }); If someone enters your site with the hashbang in the url, we simply detect it and load the appropriate page; something like this would work: $(function(){ if(window.location.hash){ if(window.location.hash.indexOf('#!') === 0){ $.ajax({ url: window.location.hash.replace('#!','') + '.php', success: function(data){ $('body').fadeOut().html(data).fadeIn(); } }); } } }); A: The term you are looking for is AJAX. The "last parameter" is not a GET-Parameter but an anchor, which is read by JavaScript. Some tips on starting with this technique can be found on ajaxprojects.com
{ "language": "en", "url": "https://stackoverflow.com/questions/7583369", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Combine DataView and Carousel Is there a way in Sencha Touch to create a DataView that loads data from a store and displays it as a Carousel (or at least behaves as a panel with layout: 'card'), where each item is an entry from the store? Obviously, that means that the number of items is always different. A: See this example posted by me: http://www.sencha.com/forum/showthread.php?148378-Dynamic-Carousel-how-to-push-thumbnails-12-per-page-Examples-included At the moment I am stuck getting the thumbnails split 12 per page instead of all on one carousel. :-)
{ "language": "en", "url": "https://stackoverflow.com/questions/7583371", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: JAXB2 Maven Plugin cannot generate annotations or inject-code I currently have an ant task that does a great job of generating my domain objects from xsd and xjb binding files. It creates the annotations and injects code where I need it based upon a custom Plugin. Now I'm trying to move all of this to Maven and while I can generate the objects I cannot get the code to inject or add the annotations. My POM plugin entry is as follows: <plugin> <groupId>org.jvnet.jaxb2.maven2</groupId> <artifactId>maven-jaxb2-plugin</artifactId> <version>0.8.0</version> <executions> <execution> <goals> <goal>generate</goal> </goals> </execution> </executions> <configuration> <bindingDirectory>src/main/resources/jaxb/bindings</bindingDirectory> <generatePackage>com.noush.web.domain.model.data</generatePackage> <extension>true</extension> <verbose>true</verbose> <args><!-- <arg>-XtoString</arg> --> <!-- I want to use commons-lang-plugin to generate toString but this can wait <arg>-Xcommons-lang</arg> <arg>-Xcommons-lang:ToStringStyle=SIMPLE_STYLE</arg> --> <arg>-Xannotate</arg> <arg>-Xinject-code</arg> </args> <plugins> <plugin> <groupId>noush</groupId> <artifactId>code-expander-plugin</artifactId> <version>1.0</version> </plugin> <plugin> <groupId>org.jvnet.jaxb2_commons</groupId> <artifactId>jaxb2-basics-annotate</artifactId> <version>0.6.0</version> </plugin> </plugins> </configuration> </plugin> The objects get created but without any injected code or annotations. The output doesn't give any indication that anything is wrong. If it helps here is my working ant config: <target name="defineXjcTask"> <taskdef name="xjc" classname="com.sun.tools.xjc.XJCTask" classpathref="xjcLib" /> </target> <target name="generateJaxb"> <xjc target="${build.generated}" package="${noushweb.domain.model.jaxb.package}"> <arg value="-verbose"/> <arg value="-extension"/> <arg value="-Xcommons-lang"/> <arg value="-Xcommons-lang:ToStringStyle=SIMPLE_STYLE"/> <arg value="-Xinject-code"/> <arg value="-Xannotate"/> <schema dir="${build.directory}/jaxb/bindings" includes="${matmWS.mmmws.data.filename}" /> <binding dir="${build.directory}/jaxb/bindings" includes="${matmWS.mmmws.binding.filename}"/> <produces dir="${build.generated}/${noushweb.domain.model.jaxb.package.dir}" includes="**/*.java" /> </xjc> </target> <path id="xjcLib"> <pathelement location="${lib.dir}/jaxb-ri-2.0.5/lib/jaxb-xjc.jar" /> <pathelement location="${ib.dir}/jaxb-ri-2.0.5/lib/jaxb-api.jar" /> <pathelement location="${lib.dir}/jaxb-ri-2.0.5/lib/jaxb-impl.jar" /> <pathelement location="${lib.dir}/jaxb-ri-2.0.5/lib/activation.jar" /> <pathelement location="${lib.dir}/jaxb-ri-2.0.5/lib/jsr173_1.0_api.jar" /> <pathelement location="../lib/stax-api-1.0-2.jar" /> <pathelement location="../lib/jaxb-commons-lang-plugin-2.2.jar" /> <pathelement location="${lib.dir}/commons-lang-2.4/lib/commons-lang-2.4.jar" /> <pathelement location="../lib/code-expander-plugin.jar" /> <pathelement location="../lib/jaxb2-basics-runtime-0.6.0.jar" /> <pathelement location="../lib/jaxb2-basics-tools-0.6.0.jar" /> <pathelement location="../lib/jaxb2-basics-annotate-0.6.0.jar" /> <pathelement location="../lib/annox-0.5.0.jar" /> <pathelement location="${lib.dir}/axis-1_4/lib/commons-logging-1.0.4.jar" /> <pathelement location="${lib.dir}/hibernate-validator-4.1.0.Final/hibernate-validator-4.1.0.Final.jar"/> <pathelement location="${lib.dir}/hibernate-validator-4.1.0.Final/validation-api-1.0.0.GA.jar"/> </path> I guess I could use a antrun kind of setup but I was hoping I could get this to work. Any thoughts would be most welcome. Thanks Noush
{ "language": "en", "url": "https://stackoverflow.com/questions/7583372", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to do a HTTP post to a web service? I need to do a HTTP post to a web service.. If I place this into a web browser like this http://server/ilwebservice.asmx/PlaceGPSCords?userid=99&longitude=-25.258&latitude=25.2548 then is stores the values to our DB on the server.. In Eclipse, using Java programming for android.. The url will look like http://server/ilwebservice.asmx/PlaceGPSCords?userid="+uid+"&longitude="+lng1+"&latitude="+lat1+" with uid, lng1 and lat1 being assigned as strings.. How would I run this? Thanks A: try { HttpClient client = new DefaultHttpClient(); String getURL = "http://server/ilwebservice.asmx/PlaceGPSCords?userid="+uid+"&longitude="+lng1+"&latitude="+lat1+"; HttpGet get = new HttpGet(getURL); HttpResponse responseGet = client.execute(get); HttpEntity resEntityGet = responseGet.getEntity(); if (resEntityGet != null) { //do something with the response Log.i("GET RESPONSE",EntityUtils.toString(resEntityGet)); } } catch (Exception e) { e.printStackTrace(); } A: For http post use name value pair. See below code - List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); nameValuePairs.add(new BasicNameValuePair("longitude", long1)); nameValuePairs.add(new BasicNameValuePair("latitude", lat1)); HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(url); httppost.setEntity(new UrlEncodedFormEntity(nameValuePair)); HttpResponse response = httpclient.execute(httppost); A: Infact I had done already what you are going to do. So try this stff. You can create a method like this what I have and pass your URL with lat, long. This is return you the response of the HTTP connection. public static int sendData(String url) throws IOException { try{ urlobj = new URL(url); conn = urlobj.openConnection(); httpconn= (HttpURLConnection)conn; httpconn.setConnectTimeout(5000); httpconn.setDoInput(true); } catch(Exception e){ e.printStackTrace();} try{ responseCode = httpconn.getResponseCode();} catch(Exception e){ responseCode = -1; e.printStackTrace(); } return responseCode; } A: I'm not sure I understood your question, but if I did I think you can use java.net.UrlConnection : URL url = new URL("http://server/ilwebservice.asmx/PlaceGPSCords?userid="+uid+"&longitude="+lng1+"&latitude="+lat1); URLConnection conn = url.openConnection(); conn.connect();
{ "language": "en", "url": "https://stackoverflow.com/questions/7583378", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Grails domain class: unique constraint for multiple columns Suppose a simple Grails domain class: class Account { String countryId; String userName; String password; static constraints = { ...???... } } It is required that user names are unique for a particular countryId, thus there must be a unique contraint on two columns. How to express this in the constraints definition? A: userName(unique: ['countryId']) You can include as many other properties in the array that make up the other properties that must be considered in the "unique" constraint on the username. So, for example if you wanted to make userName unique within a countryId and provinceId it would look like this: userName(unique: ['countryId', 'provinceId']
{ "language": "en", "url": "https://stackoverflow.com/questions/7583380", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "53" }
Q: Login Server Side Logic This question has more to do with how I am setting up my server side code for a simple login script. I'm interested in the best way to achieve my goal, which is of course to verify a users username and password against a database and present them with either a successful login, a registration page, or a username or password found, but the alternative is wrong. Right now, I have it set up where my sql query scans the database for both the user and pass: SELECT * FROM test WHERE userName='" + userName + "' AND pass='" + password + "'" Problem with this approach is it either returns a true or false...I cannot tell if one of the inputs was correct and the other wasn't. It either finds the record, or it doesn't. So I could query based on the username alone, and if found check the record for the correct password before passing the user onto a successful login. That way I know if the password is wrong, but I have no idea if the password is right and the user simply types the wrong username. Alternatively, I could extend on that, and if the user isn't found, requery the database based on the password and determine if I can find a record but the username doesn't match. It seems like a lot of back and forth with the database, which is fine. But i'd like to hear from some experts on whether or not this is a proper approach. A: I have not much idea wether stored procedure is supported in my sql or not. If it is supported then you can make SP like this way to check all cases. Below is code for MSSQL, you can check it with my sql : IF EXISTS(SELECT [id] FROM [dbo].[users] WHERE [user_name] = @user_name AND [password] = @password) BEGIN SELECT 1 AS RETURNVAL --Valid User END ELSE IF NOT EXISTS(SELECT [id] FROM [dbo].[users] WHERE [user_name] = @user_name) BEGIN SELECT 0 AS RETURNVAL -- User doesn't exist END ELSE BEGIN SELECT -1 AS RETURNVAL -- Password Not Correct END A: You don't want to disclose too many information to people with bad intents trying to probe your system for available usernames (or even – god forbid – passwords that are in use). When a login attempt failed, simply display a message stating: Username and/or password mismatch. As an aside, use prepared statements, rather than string concatenation when working with your database; it protects you from SQL injection attacks. Plus – although it's not entirely clear from your code snippet – don't store plain passwords or plain password hashes. Rely on one of the many available and well tested encryption/hashing libraries e.g. PHP's crypt function (make sure you select a proper hashing function such as SHA512). Your code in the most simplest form would then look like this: // coming from your login page $dbh = new PDO(…); $sth = $dbh->prepare('SELECT `digest` FROM `users` WHERE `name` = :name LIMIT 1'); $sth->prepare(array( ':name' => $_POST['username'] )); $result = $sth->fetch(); if($result !== FALSE && crypt($_POST['password'], $result['digest']) === $result['digest']) { printf('You logged in successfully as %s', htmlspecialchars($_POST['username'])); } else { echo 'Sorry, username and/or password did not match! Please try again.'; sleep(1); exit; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7583381", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Data Entry Tracking (Database Design) I have developed a website (PHP) that allow staffs to add records on to our system. Staffs will be adding thousands of records into our database. I need a way to keep track of what record have been done and the process/status of record. Here a number of Teams I could think of: * *Data Entry Team *Proof Reading Team *Admin Team When staff (Data Entry Team) completed a record - he/she will then click on the Complete button. Then somehow it should asssign to 'Proof Reading Team' automatically. A record need to be checked twice from a Proof Reading Team. If StaffB finish proof reading then another member from Proof Reading Team need to check it again. When Proof reading is done, Admin Team will then assign "Record Completed" In a few months later record might need to be updated (spelling mistake, price change, etc) - Admin might to assign record to Data entry team. Is this good data entry management solution? How do I put this into Database Design perspective? Here what I tried: mysql> select * from records; +----+------------+----------------------+ | id | name | address | +----+------------+----------------------+ | 1 | Bill Gates | Text 1 Text Text 1 | | 2 | Jobs Steve | Text 2 Text 2 Text 2 | +----+------------+----------------------+ mysql> select * from staffs; +----+-----------+-----------+---------------+ | id | username | password | group | +----+-----------+-----------+---------------+ | 1 | admin1 | admin1 | admin | | 2 | DEntryA | DEntryA | data_entry | | 3 | DEntryB | DEntryB | data_entry | | 4 | PReadingA | PReadingA | proof_reading | | 5 | PReadingB | PReadingB | proof_reading | +----+-----------+-----------+---------------+ mysql> select * from data_entry; +----+------------+-----------+------------------------+ | id | records_id | staffs_id | record_status | +----+------------+-----------+------------------------+ | 1 | 2 | 3 | data_entry_processiing | | 2 | 2 | 3 | data_entry_completed | | 3 | 2 | 4 | proof_read_processing | | 4 | 2 | 4 | proof_read_completed | | 5 | 2 | 5 | proof_read_processing | | 6 | 2 | 5 | proof_read_completed | +----+------------+-----------+------------------------+ Is there alternative better solution of database design? A: i think design it's well done. but may be you want to separate group into groups table, and record_status into status table. If you're storing a lot of records you would store a lot of useless information, at least create an enum type for record_status field and group field table: groups id - name 1 - admin 2 - data_entry 3 - proof_reading ... table: status id - name 1 - data_entry_processing ... and if you want the users to be in different groups at a time, you could create users_group table table: user_groups group_id - user_id 1 - 1 2 - 1 1 - 4 3 - 4 4 - 4 .... Hope this helps
{ "language": "en", "url": "https://stackoverflow.com/questions/7583393", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Problem related to NSURLConnection today, I encountered a problem with NSURLConnection. I want to download the contents of the URL http://api.wunderground.com/api/fs3a45dsa345/geolookup/q/34.532900,-122.345.json. If I simply paste the URL into Safari, I get the correct response. However, if I do the same thing with NSURLConnection, I get a "not found" response. Here's the code I'm using: NSURL *requestURL = [[NSURL alloc] initWithString:@"same url as above"]; NSURLRequest *urlRequest = [[NSURLRequest alloc] initWithURL:requestURL]; NSURLConnection *urlConnection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self startImmediately:YES]; What's the problem here? A: Make sure you're escaping any special characters in the URL string by sending it a stringByAddingPercentEscapesUsingEncoding: message, for example: NSString *s = [@"some url string" stringByAddingPercentEscapesUsingEncoding:NSUTFStringEncoding]; NSURL *requestURL = [NSURL URLWithString:s]; EDIT It turns out the web service request is failing because the User-Agent header doesn't get set by default. To set it, use an instance of NSMutableURLRequest rather than NSURLRequest to create the request, as shown below: NSMutableURLRequest *myRequest = [NSMutableURLRequest requestWithURL:myURL]; [myRequest setValue:@"My App" forHTTPHeaderField:@"User-Agent"]; A: Where is the delegate code? For async NSURLConnection there needs to be a delegate method to receive the returned data. Other options include sendSynchronousRequest: or if it must be async wrapping sendSynchronousRequest in a GCD block.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583396", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: multimodule maven gwt project - dependency resolution in hosted mode problem Recently I've split my GWT 2.4 application into two maven modules: domain and webapp. Domain module (according to its name) contains domain classes and webapp contains all other GWT-related stuff. Webapp depends on domain. Everything is almost the same as described here: http://mojo.codehaus.org/gwt-maven-plugin/user-guide/multiproject.html When I run (from reactor): mvn clean package maven builds application WAR appropriately: first it compiles domain, then webapp, next creates war file which can be deployed on tomcat and works fine. However, if I try to run application in the hosted mode: mvn gwt:run maven tries to resolve dependency to domain module in my local repository and remote repositories. Since I've deleted it from my local repo, maven can not find it and build (hosted mode) fails. Of course I can install domain module into my local repo first, but it's smells like a dirty workaround for me. Domain has been removed from local maven repository intentionally in order to make sure that hosted mode runs with the old (outdated) version taken from local repo, instead of working with the previously built domain artifact. If domain module was installed in my local repository, after mvn clean package completed, webapp target directory contains exploded WAR with the recent version of domain JAR. When I run gwt:run, new version of domain artifact (in target) is replaced with the outdated one taken from local repo (I can see changes)! How is this possible? Is it a bug in gwt maven plugin? Is there any way to avoid such strange plugin behavior? A: might this be a solution for you? http://mojo.codehaus.org/gwt-maven-plugin/user-guide/productivity.html For me it works. I have different modules as well. With the help of the link I can make changes in the domain module and simply restart the hosted mode. Doesn't work for all changes though.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583399", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Why are the functions making Vector an instance of Functor, Monad, Applicative, Alternative, Foldable and Traversable slow? The changelog for version 0.8 of vector lists the following change with a warning: Functor, Monad, Applicative, Alternative, Foldable and Traversable instances for boxed vectors (WARNING: they tend to be slow and are only provided for completeness). Could someone explain why this is the case? Is it just the normal cost of typeclass specialization, or something more interesting? Update: Looking at some particular instances, one sees for example: instance Foldable.Foldable Vector where {-# INLINE foldr #-} foldr = foldr and similarly for the other folds. Does this mean that folding is slow for Vectors in general? If not, what makes a non-specialized fold slow enough to warrant a warning? A: I've just had a quick look at the source code and the implementations don't look excessively slow. I'd argue the authors added this warning because when you're writing a program in the Vector monad, you're working from such a high-level point of view that it's easy to forget that every >>= is, in fact, a concatMap, which tends to be inherently slow. Another thing: Vector is particularly fast for unboxed types. So a user might be attracted to use the monad notation (for convenience), while he should actually be using an unboxed type (for speed). A: I submitted the original set of these instances to Roman a year and a half ago and have maintained vector-instances since then. (I had to remove these instances from vector-instances once they migrated into vector, and now maintain it solely for the really exotic stuff). His concern was that if folks used these instances polymorphically then the RULES that make Vectors fuse away can't fire unless the polymorphic function gets inlined and monomorphized. They exist because not every bit of code on the planet is Vector-specific and even then it is nice to sometimes use the common names. Slow here is relative. The worst case is they perform like anybody else's folds, binds, etc. but Roman takes every single boxed value as a personal insult. :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7583403", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: PHP Contact Form - Image uploading to temp but not attatching to email I was just wondering if anyone could help out with what should be a fairly simple fix (obviously not for me) for a contact form with image upload. The image DOES get uploaded to the temporary folder, but doesn't appear when I receive the email into my account. I think the form is nearly there, just can't figure out why the image is not attatching to the email when i receive it - guessing the problem is somewhere in the last 10 lines of code. I would really appreciate if someone could figure what's going wrong. <?php ini_set("sendmail_from", "darren@mywebsite.co.uk"); ini_set("SMTP", "smtp.myhostingcompany.co.uk"); if($name = filter_var($_POST['name'])) if($address = filter_var($_POST['address'])) if($postcode = filter_var($_POST['postcode'])) if($phone = filter_var($_POST['phone'])) if($email = filter_var($_POST['email'])) if($details = filter_var($_POST['details'])) if($contactby = filter_var($_POST['contactby'])) /* Subject and Email Destinations */ $emailSubject = 'Work Email!'; $webMaster = 'darren@mywebsite.co.uk'; /* Gathering Data Variables */ $nameField = $_POST['name']; $addressField = $_POST['address']; $postcodeField = $_POST['postcode']; $phoneField = $_POST['phone']; $emailField = $_POST['email']; $detailsField = $_POST['details']; $contactbyField = $_POST['contactby']; $allowed_filetypes = array('.jpg','.gif','.bmp','.png'); $max_filesize = 524288; // Maximum filesize in BYTES (currently 0.5MB) $upload_path = './uploads/'; $filename = $_FILES['userfile']['name']; $ext = substr($filename, strpos($filename,'.'), strlen($filename)-1); if(!in_array($ext,$allowed_filetypes)) die('The file you attempted to upload is not allowed.'); if(filesize($_FILES['userfile']['tmp_name']) > $max_filesize) die('The file you attempted to upload is too large.'); if(!is_writable($upload_path)) die('You cannot upload to the specified directory, please CHMOD it to 777.'); if(move_uploaded_file($_FILES['userfile']['tmp_name'],$upload_path . $filename)) echo 'Your file upload was successful, view the file <a href= "' . $upload_path . $filename . '" title="Your File">here</a>'; // It worked. else echo 'There was an error during the file upload. Please try again.'; // It failed $body = <<<EOD Name: $name Address: $address Postcode: $postcode Phone: $phone Email: $email Details: $details Contactby: $contactby EOD; $headers = "From: $email\r\n"; $headers .= "Contact-type: text/html\r\n"; $attachment = chunk_split(base64_encode(file_get_contents($temp_file))); $tmp_file = $_FILES['userfile']['tmp_name']; $success = mail($webMaster, $attatchment, $body, $headers, "-fdarren@mywebsite.co.uk"); /* Results rendered as HTML */ $theResults = <<<EOD SENT SENT SENT EOD; echo "$theResults" ?> A: Your mail headers are wrong, you need to use MIME to define the different content types (The body of the email and the attachment). I have some code somewhere that I use for emailing uploads, if this isn't answered for you in about 10-20 minutes I'll try and find it for you. Good luck! I managed to dig up the code! It's not the cleanest code ever but it gets the job done. There will be a few tweaks you will have to do as this was originally written to email CSV files, but I've commented it all as much as I can for you. //The recipient(s) who will receive this email. $mail_recipients = 'example@email.com'; //This is the subject line of the email. $mail_subject .= 'A new CVS has arrived!'; //This is the emails body. $message .= 'A new CVS file has been generated and sent to you, please find it attached to this email. <br />'; //This is the full path to the file you want to attach. $full_path = '/example/path/file.csv'; //The file type of the attachment. $file_type = 'text/csv'; //Create a file handle to open the file. $file = fopen($full_path,'rb'); //Read all of the files contents into a variable. $data = fread($file, filesize($full_path)); //encode and split the contents. $data = chunk_split(base64_encode($data)); //Close the file, we don't need it anymore! fclose($file); //Create a unique boundary $new_boundary = md5(time()); //This is your basic header information such as who the email is from and the date it was sent. $mail_header .= 'From: CSV Admin <noreply@website.co.uk>' . "\r\n"; $mail_header .= 'Date: ' . date('r') . "\r\n"; //This part of the header first defines to the email client that it is a multipart message and adds the emails content/body. $mail_header .= 'Content-Type: multipart/mixed; boundary="' . $new_boundary . '"' . "\r\n\r\n"; $mail_header .= 'MIME-Version: 1.0' . "\r\n"; $mail_header .= 'This is a multi-part message in MIME format' . "\r\n"; $mail_header .= '--' . $new_boundary . "\r\n"; $mail_header .= 'Content-Type:text/html; charset="iso-8859-1"' . "\r\n"; $mail_header .= 'Content-Transfer-Encoding: 7bit' . "\r\n\r\n"; $mail_header .= $message . "\r\n\r\n"; //This part of the header is for the attachment and includes the contents of the file, the files name and other information. $mail_header .= '--' . $new_boundary . "\r\n"; $mail_header .= 'Content-Type: ' . $file_type . '; name="' . $file_name . '"' . "\r\n"; $mail_header .= 'Content-Transfer-Encoding: base64' . "\r\n"; $mail_header .= 'Content-Disposition: attachment; filename="' . $file_name . '"' . "\r\n\r\n"; $mail_header .= $data . "\r\n\r\n"; //This is needed to stop any rendering errors by email clients and signifies the end of the emails header. $mail_header .= '--' . $new_boundary . '--' . "\r\n"; //This mails out all of the above. mail($mail_recipients, $mail_subject, '', $mail_header); //And we should be done! A: You have three distinct errors: * *The headers for multipart email are a bit more complex. *The parameters to the mail function are incorrect. *You’re passing an undefined variable to file_get_contents. $mime_boundary = md5(time()); $headers = "From: $email\r\n"; $headers .= "MIME-Version: 1.0\r\n"; $headers .= "Content-Type: multipart/mixed;\r\n"; $headers .= "--".$mime_boundary."--\r\n"; $message .= "This is a multi-part message in MIME format.\r\n\r\n"; $message .= "--".$mime_boundary."--\r\n"; $message .= "Content-Type: text/plain; charset=\"iso-8859-1\"\r\n"; $message .= "Content-Transfer-Encoding: 7bit\r\n"; $message .= "\r\n"; $message .= "$body\r\n"; $message .= "--".$mime_boundary."--\r\n"; $message .= chunk_split(base64_encode(file_get_contents($_FILES['userfile']['tmp_name']))); mail($webMaster, 'email subject text', $message, $headers); SitePoint has an in-depth article on Advanced email in PHP Article that you may find beneficial. A: Like the guys said your content type is incorrect and you have: $attachment = chunk_split(base64_encode(file_get_contents($temp_file))); $tmp_file = $_FILES['userfile']['tmp_name']; It should be $tmp_file = $_FILES['userfile']['tmp_name']; $attachment = chunk_split(base64_encode(file_get_contents($temp_file)));
{ "language": "en", "url": "https://stackoverflow.com/questions/7583405", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Test type of NSNotification I need to check whether an object is an NSNotification. It is not enough to know if it is a subclass, as I want to differentiate between whether it is an NSNotification or a subclass of NSNotification. So to elaborate I need to differentiate between the following: * *An NSConcreteNotification *A Subclass of NSNotification (But not NSConcreteNotification) The problem is that NSNotifications are actually NSConcreteNotifications and NSConcreteNotification is a private class so I can't use it to test against. [object isMemberOfClass: [NSNotification class]] // returns NO in both cases [object isKindOfClass: [NSNotification class]] // returns YES in both cases A: There is no reason to subclass NSNotification the way you're describing. First, NSNotification already carries a userInfo dictionary. You can put any data you want in there. You can use category methods to read and write into that dictionary if you like (I do this all the time). For example, a very common thing I want to do is pass along some object, say the RNMessage. So I create a category that looks like this: @interface NSNotificationCenter (RNMessage) - (void)postNotificationName:(NSString *)aName object:(id)anObject message:(RNMessage *)message; @end @interface NSNotification (RNMessage) - (RNMessage *)message; @end static NSString * const RNMessageKey = @"message"; @implementation NSNotificationCenter (RNMessage) - (void)postNotificationName:(NSString *)aName object:(id)anObject message:(RNMessage *)message { [self postNotificationName:aName object:anObject userInfo:[NSDictionary dictionaryWithObject:message forKey:RNMessageKey]; } @end @implementation NSNotification (RNMessage) - (RNMessage *)message { return [[self userInfo] objectForKey:RNMessageKey]; } As @hypercrypt notes, you can also use associated references to attach data to any arbitrary object without creating an ivar, but with NSNotification it's much simpler to use the userInfo dictionary. It's much easier to print notification using NSLog. Easier to serialize them. Easier to copy them. Etc. Associated references are great, but they do add lots of little corner cases that you should avoid if you can get away with it. A: To test id object is an NSNotification use: [object isMemberOfClass:[NSNotification class]];` To test if it is a NSConcreteNotifications use [object isMemberOfClass:NSClassFromString(@"NSConcreteNotifications")]; Change the string to the name of a different class as needed... You can then combine the two check for 'A Subclass of NSNotification (But not NSConcreteNotification'. Either: if ([object isMemberOfClass:NSClassFromString(@"NSConcreteNotifications")]) { // It's a NSConcreteNotifications... } else if ([object isKindOfClass:[NSNotification class]]) { // It's an NSNotification (or subclass) but not an NSConcreteNotifications } Or if ([object isKindOfClass:[NSNotification class]] && ![object isMemberOfClass:NSClassFromString(@"NSConcreteNotifications")]) { /* ... */ } If you want to add properties to NSNotifications you should look into Associative References. The basic idea is: static const char objectKey; - (id)object { return objc_getAssociatedObject(self, &objectKey); } - (void)setObject:(id)object { objc_setAssociatedObject(self, &objectKey, object, OBJC_ASSOCIATION_RETAIN); } A: That sounds like a really bad idea. When you first receive the notification, you already know what type it is, because it's passed as an explicit argument to a notification callback method. Consider storing the notification as a strongly typed property of another object, or inserting in a dictionary under an appropriate key if you're adding it to a collection, or passing it to other methods that don't preserve the type information to make it easier to identify later. Creating dependencies on private API (including the names of private classes) will make your code more fragile, and much more likely to break in a future release. Obviously, one of the reasons these classes are private is to make it easier for Apple's engineers to change them as they see fit. For example, the concrete subclasses used by NSArray and NSMutableArray just changed in a recent release of the SDK. A: As others have pointed out, it is a bad idea to rely on the name of a private class. If you are looking for one specific subclass, you could just explicitly check for that class. [notification isMemberOfClass:[MyNotificationSubclass class]]; You could use multiple statements to check for multiple subclasses, but that would be a little cluttered. This method also requires changes every time you add a new class to look for. It may be better to define a readonly property which indicates whether a notification supports the feature you are looking for, so you aren't relying on the class so much as the ability of the class. You could use a category on NSNotification which simply returns NO for this property, and any subclasses which have the feature would override the method to return YES. @interface NSNotification (MyFeature) @property (readonly) BOOL hasMyFeature; @end @implementation NSNotification (MyFeature) - (BOOL)hasMyFeature { return NO; } @end In the subclasses which support it: - (BOOL)hasMyFeature { return YES; } - (void)performMyFeature { ... } This would also allow you to change whether or not a notification has the feature enabled by changing a flag which is returned for hasMyFeature, and your checking code would simply be: if(notification.hasMyFeature) [notification performMyFeature];
{ "language": "en", "url": "https://stackoverflow.com/questions/7583414", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: JSON Object returns a null pointer I want to insert some items into the database. In the main activity, I retrieve information from the user and pass it to the another class to do some parsing. My JSONObject keeps showing up as NULL. I am sorry if I am not clear with the question . I've tried to explain it as much as possible. Below is the code your inputs are welcome public class MainActivity extends Activity { /** THE FOLLOWING STRINGS WILL BE DISPLAYED IN LOGCAT */ final String TAG = "########-------MAIN ACTIVITY: LOGIN--------######"; final String URL = "http://46.51.193.32/timereport/ses/sessions"; UserHelper userAdapter; UserHelper db; EditText edit_password,edit_username,edit_company; String regName; int duration = Toast.LENGTH_LONG; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); db = new UserHelper(this); userAdapter = new UserHelper(this); edit_password = (EditText)findViewById(R.id.password); edit_username = (EditText)findViewById(R.id.user_name); edit_company = (EditText)findViewById(R.id.company_string); Button login = (Button)findViewById(R.id.login_button); login.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { JSONObject jsonobj = new JSONObject(); try{ JSONObject subJson = new JSONObject(); subJson.put("username", edit_username.getText().toString()); subJson.put("password", edit_password.getText().toString()); subJson.put("company", edit_company.getText().toString()); jsonobj.put("user", subJson); } catch(JSONException e) { Log.i("","#####-----error at catch jsonexception-----#####"); } HandleJSON.SendHttpPost(URL, jsonobj); String regNameSplit[] = regName.split("-"); try{ userAdapter.openDatabase(); long id = db.insertIntoDatabase(edit_username.getText().toString(),edit_company.getText().toString(), edit_password.getText().toString(),regNameSplit[0], regNameSplit[2]); Toast.makeText(getApplicationContext(), "You have successfully logged in as: " +"\n" +regNameSplit[0], duration).show(); Log.i(TAG, "Printing value of id which will be inserted only to remove warnings "+id); userAdapter.closeDatabase(); } catch(SQLiteException e){ e.printStackTrace(); } } }); } } This is the class to which I am sending the JSON object to be parsed public class HandleJSON{ UserHelper userAdapter; private static final String TAG = "&&----HTTPClient-----**"; public static String SendHttpPost (String URL, JSONObject jsonobj) { String regName = ""; try{ Log.v("Json object request is ",jsonobj.toString()); DefaultHttpClient httpClientInstance = GetHttpClient.getHttpClientInstance(); HttpPost httpPostRequest = new HttpPost(URL); Log.v(TAG,"The url is "+URL); StringEntity se; se = new StringEntity(jsonobj.toString()); httpPostRequest.setEntity(se); httpPostRequest.setHeader("Accept", "application/json"); httpPostRequest.setHeader("Content-type", "application/json"); long t = System.currentTimeMillis(); HttpResponse response = (HttpResponse) httpClientInstance.execute(httpPostRequest); Log.i(TAG, "HTTPRESPONSE RECIEVED" +(System.currentTimeMillis()-t) + "ms"); String resultString = convertStreamToString(response.getEntity().getContent()); Log.v(TAG , "The response is " +resultString); JSONObject jsonObj = new JSONObject(resultString); JSONObject sessionJson = jsonObj.getJSONObject("session"); String sessionId = sessionJson.getString("sessionid"); String name = sessionJson.getString("name"); Log.v(TAG,"The session ID is "+sessionId); Log.v(TAG,"The name is "+name); regName = name+"-"+sessionId+"-"+URL; } catch (Exception e){ e.printStackTrace(); } return regName; } private static String convertStreamToString(InputStream is) { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line = null; try{ while((line = reader.readLine()) !=null ){ sb.append(line + "\n"); } } catch (IOException e){ e.printStackTrace(); } finally{ try { is.close(); } catch (IOException e){ e.printStackTrace(); } } return sb.toString(); } } I've just added some of the code that was missing at the MainActivity, String regNameSplit[] = regName.split("-"); keeps showing up as null A: * *Instead of your convertStreamToString() method try using system provided EntityUtils.toString(entity). *IMPORTANT: do not catch generic Exception, this hides unchecked (runtime) exceptions. You might be hiding the JSONException that happens in JSONObject constructor. Update: You are calling SendHttpPost and not assigning result to variable: HandleJSON.SendHttpPost(URL, jsonobj); should be: regName = HandleJSON.SendHttpPost(URL, jsonobj); A: I don't see anything wrong with this, could you tell me what is the use of regname ? at your mainactivity just change the following: regname = HandleJSON.SendHttpPost(URL, jsonobj); Your not calling back regname to be assigned to name and sessionid that you are returning at the sendhttppost.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583419", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: plot stacked bar plot in R I would like to create histogram [stacked bar plot] in R with data like this: Period = c(1,1,2,2,3,3,4,4) Sample = c("A","B","A","B","A","B","A","B") Value1 = c(3,2,6,7,3,2,1,2) Value2 = c(1,0,5,2,2,0,2,5) x <- data.frame(Period,Sample,Value1,Value2) Is it possible to have "Period" and "Sample" on the X axes and The values ("Value1" and "Value2") in "Stacked Bar Plot". So the hight of first histogram would be 4 (separate for Value1 and Value2) Thank you for your help in advance! Best regards. A: It's not as pretty as the ggplot solution but v <- rbind(Value1,Value2) barplot(v,beside=FALSE,names=levels(interaction(Period,Sample)),legend=TRUE) seems to work. A: You are describing a stacked bar chart, not a histogram. With ggplot you can do it as follows: library(ggplot2) library(reshape2) x <- data.frame( Period = c(1,1,2,2,3,3,4,4), Sample = c("A","B","A","B","A","B","A","B"), Value1 = c(3,2,6,7,3,2,1,2), Value2 = c(1,0,5,2,2,0,2,5) ) mx <- melt(x, id.vars=1:2) ggplot(mx, aes(x=Period, y=value, fill=variable)) + geom_bar(stat="identity") + facet_grid(~Sample)
{ "language": "en", "url": "https://stackoverflow.com/questions/7583432", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: What does this expression mean on the ipfiltering project? I have seen the expression: configuration.Filters.Select(f=> Create(f)).ToArray()); Im wondering what the f => Create(f) means? Is this a Lambda? And why is it in a Select clause? A: Yes, this is a lambda expression. It's in a select clause as a projection. The lambda expression is executed for each item from configuration.Filters, and the result is then passed on to the next stage. It's hard to know exactly what that means in this case without knowing what Create does, but as an example, you might have: int[] values = { 1, 2, 3 }; int[] squares = values.Select(x => x * x); .ToArray(); // Now squares is { 1, 4, 9 } This is part of LINQ (at least, I assume it is - it's just possible that you're calling a completely different Select method). LINQ is a big topic, but well worth exploring - fortunately there are plenty of tutorials and books around. A: That's a lambda expression. The Select extension method takes a delegate as a parameter.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583434", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to handle multiple asynch downloads I recently moved my background synch downloads to a view controller and need some advice on how to best handle them asynch. I have written all the code to show a progressview as the download occurs but as you might have guessed it's not that simple. Here's how it works. user sees a tableview with two entires one for each database. they can press a button to download the database and when the download starts that fires off the asynch URL connection,etc. This works to a certain extent however it's not that simple. here's what i want it to do. * *download the main update URL (works ok) *then download a secondary URL. *then apply the first URL content to the sqlite store (code written for that) *then apply the 2nd URL content to the sqlite store (code written for that) (All the while showing progress to the user) when the downloads were synch it was easy as i just waited for them to finish in order to fire the next activity off but when using the asynch method i'm struggling with how to get them to wait. Step 3 depends upon step 1 finishing and step 4 depends on step 2 finishing and overall success relies on all finishing. step 4 needs to wait for step 3 to finish otherwise the database locks will cause a clash. the second complication is that if the user presses the second button while the first is downloading then steps 3, 4 will clash if they execute at the same time as the first row is accessing the database. Has anyone done anything similar and if so what was the strategy you used to manage the flow of events. Also i wanted to wrap this all up in a backgroundTask with ExpirationHandler so it would survive the user pressing the home button... but the delegate methods don't get called when i do that. A: Ok Here is what i did to fix the problem. * *Created an NSOperationQueue *Added the URL operations as NSURLInnvocationOperations 3.waited until the URL operations were complete (waituntilalloperationsarefinished). Then set the max concurrent count to 1 which forced the subsequent database operations to execute in series one after the other and thus prevented SQLite from locking it's self out.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583438", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Rails 3.1 thread safety broken Or something like that. I've upgraded several apps from Rails 3.0 to Rails 3.1. They are are running on Thin with the multithreaded option enabled, they are all configured with threadsafe!. Worked great in Rails 3.0. But in 3.1, after a few requests, things start slowing down. After a few more requests, the pages hangs for N seconds (where N is my db timeout) and I get this error: ActiveRecord::ConnectionTimeoutError (could not obtain a database connection within 5 seconds. The max pool size is currently 5; consider increasing it.): Those default values of 5 and 5 have been find in the past and should still be fine. Also increasing them does not fix the problem, though it takes a little longer to manifest. I should stress that during these times I have been the only one accessing the apps. When I drop Thin down to single-threaded mode, everything works as expected. This occurs with MySQL, SQLite, Ruby 1.8.7 and Ruby 1.9.2. Thin is unchanged. The only variable I can find is the upgrade to Rails 3.1. Is there anything I can do, or is this a regression in Rails? A: Looks like this is a bug. There's a patch and pull request for it. Hopefully Rails will merge it in. Until then, multi-threaded Rails apps won't work on Thin. https://github.com/rails/rails/pull/1670
{ "language": "en", "url": "https://stackoverflow.com/questions/7583439", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Is there any way to disable media queries under certain conditions? I am using the same stylesheet for the main site as well as a 'preview' of the site (NOT in an iframe because I need it to be interactive). The issues is, the preview does not take up 100% of the screen width, so when media queries are based on screen size, the page behaves oddly. I am ok with making the editor/preview mode fixed width, though, so I thought perhaps there is some way I can disable the media-queries under certain conditions? I have no idea how to approach that, though. Either through javascript, or potentially loading an additional, generic stylesheet after the mediaqueries that would somehow reset things. Otherwise I may have to make alternate stylesheets, which would be a pain to maintain, or redesign the page so that the preview area is 100% of the width. A: You've got a number of options. * *First off, you can disable the "offending" stylesheet: with <link id="mediaSheet" rel="stylesheet" href="....">, you may run this in your onload handler: document.getElementById("mediaSheet").sheet.disabled = true;. *If you feel like coding, you may add this link to your final HTML conditionally. E.g. if the page is requested with a GET parameter ?preview=true, the stylesheet element will not be generated. A: Set the viewport meta to be a certain width that complies with the media query. Ensure you have the scale set correctly though. I tend to remove it if you want a mobile to be able to see the desktop version. A: Just like to add to A.Pavlov's answer (I can't add comments yet): If you want to use JQuery $('#mediaSheet')[0].sheet.disabled = true Or if you want to disable all media queries, use class="mediaSheet" instead of ID: $('.mediaSheet').each(function(){ $(this)[0].sheet.disabled = true; });
{ "language": "en", "url": "https://stackoverflow.com/questions/7583441", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Image Flow and Iframe I am using ImageFlow 9. I have an ImageFlow scroller script added in the Iframe. I want to have the images opened outside the iframe that is on the Parent page. Right now it is opening the images in the Iframe itself. What changes should I do and in which file? There is a .js file that has a function as below - image.onclick = function() { document.location = this.url; } Do I need to make the changes here or in the actual script that uses this code- <img src="reflect.php?img=img/large1.jpg" longdesc="javascript:myLightbox.start('img/large1.jpg|Image 1');" alt="Image 1" /> A: Create a JavaScript function on the parent page, and call that from the iFrame. Something like function openImage(url){ // do your image handling stuff here } From the iFrame call the function: parent.openImage(url); ps: I recommend not using iFrames at all unless there is no other way (which most of the time is not the case)
{ "language": "en", "url": "https://stackoverflow.com/questions/7583445", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is this correct C++0x code? Tried this in GCC 4.6 and it compiles and links, but gives a "bus error" message on runtime on MacOS. VS2010 doesn't even compile it. But the question is, should this actually work in standard C++0x? #include <cstdio> int (*main)()=[]()->int{printf("HEY!\n");return 0;}; Yes, what it's trying to do is to define "main" as a lambda function. A: No, this is not correct. Main is a special function and there are strict requirements for it (even more strict than a regular function), but you are also making some confusion between what is a function and what is a pointer to a function. The logical problem is that there is a difference between a function and a variable holding a pointer to a function (what you want main to be). A function has a fixed address in memory, so to call a function that address is simply called. A pointer to a function points to an address in memory, so to call the function you need first to read what the pointer is pointing to and then call that address. A pointer to function has a different level of indirection from a function. The syntax is the same... i.e. if x is a pointer to a function you can write x(42), but still the generated machine code is different if x is instead a function (in the case of a pointer a value must be looked up and the call address is determined at run time, with a function the address is fixed - up to relocation - and is determined at link time). A: This is not a valid C++ program, because the symbol main is not defined to be a function, but rather a pointer to function. That's why you get segmentation fault -- the runtime is attempting to execute a pointer. A: For portability among compilers and standard library implementations, printf() must be std::printf() when #including <cstdio>. And the other stuff about the invalid main(). A: Now, it should not even compile. The lambda expression yields a type (a functor). There is no implicit conversion from type to function pointer. Depending on compiler, main function can have C++ or C linkage (it is implementation defined). Lambda expression returns C++ type with function call operator, thus C++ linkage.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583447", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: How to shutdown supervisor process correctly/completely? I am using supervisor to launch and manage a nginx process. So far this works perfectly. The problem I am having is shutting down the instance. I have tried using "supervisorctl -c shutdown [all]" and this shuts down the daemon and in the supervisorctl interactive console it says nginx is stopped. However, if I do a ps -A | grep nginx command it still appears in the list. My config for the nginx instance is as follows: [program:nginx] command=./bin/nginx -p /home/me/sites/project.domain.com/ -c project/etc/nginx.conf directory=/home/me/sites/project.domain.com autostart=true autorestart=true redirect_stderr=true exitcodes=0 stopsignal=TERM Any suggestion why nginx could not be shutting down? A: Have you made sure you are not starting up nginx in daemonized mode? It is important you start all your child-processes of supervisor in non-daemonized mode. I currently don't have nginx boot options at hand, but this might give you a start in the right direction.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583449", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: System.web.mvc.modelstatedictionary does not contain a definition for addruleviolations I am getting two errors when trying to build NerdDinner in DinnerController.cs. Here is what I currently have in DinnerController.cs. I am getting errors on the two lines with '**' using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using NerdDinner.Models; namespace NerdDinner.Controllers { public class DinnersController : Controller { DinnerRepository dinnerRepository = new DinnerRepository(); // // GET: /Dinners/ public ActionResult Index() { var dinners = dinnerRepository.FindUpcomingDinners().ToList(); return View(dinners); } // // GET: /Dinners/Details/2 public ActionResult Details(int id) { Dinner dinner = dinnerRepository.GetDinner(id); if (dinner == null) return View("NotFound"); else return View(dinner); } // // GET: /Dinners/Edit/2 public ActionResult Edit(int id) { Dinner dinner = dinnerRepository.GetDinner(id); return View(dinner); } // // POST: /Dinners/Edit/2 [AcceptVerbs(HttpVerbs.Post)] public ActionResult Edit(int id, FormCollection formValues) { Dinner dinner = dinnerRepository.GetDinner(id); try { UpdateModel(dinner); dinnerRepository.Save(); return RedirectToAction("Details", new { id = dinner.DinnerID }); } catch { **ModelState.AddRuleViolations(dinner.GetRuleViolations()); return View(dinner); } } // // GET: /Dinners/Create public ActionResult Create() { Dinner dinner = new Dinner() { EventDate = DateTime.Now.AddDays(7) }; return View(dinner); } // // POST: /Dinners/Create [AcceptVerbs(HttpVerbs.Post)] public ActionResult Create(Dinner dinner) { if (ModelState.IsValid) { try { dinner.HostedBy = "SomeUser"; dinnerRepository.Add(dinner); dinnerRepository.Save(); return RedirectToAction("Details", new { id = dinner.DinnerID }); } catch { ** ModelState.AddRuleViolations(dinner.GetRuleViolations()); } } return View(dinner); } // // HTTP GET: /Dinners/Delete/1 public ActionResult Delete(int id) { Dinner dinner = dinnerRepository.GetDinner(id); if (dinner == null) return View("NotFound"); else return View(dinner); } // // HTTP POST: /Dinners/Delete/1 [AcceptVerbs(HttpVerbs.Post)] public ActionResult Delete(int id, string confirmButton) { Dinner dinner = dinnerRepository.GetDinner(id); if (dinner == null) return View("NotFound"); dinnerRepository.Delete(dinner); dinnerRepository.Save(); return View("Deleted"); } } } Any help is greatly appreciated. A: Have you created the Nerd Dinner Helper Class in the Helper Directory as below? I Think I had this issue when I was at that stage... using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using NerdDinner.Models; namespace NerdDinner.Helpers { public static class ModelStateHelpers { public static void AddModelErrors(this ModelStateDictionary modelState, IEnumerable<RuleViolation> errors) { foreach (RuleViolation issue in errors) { modelState.AddModelError(issue.PropertyName, issue.ErrorMessage); } } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7583450", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to sort Excel data by Date in VB6 i wanna sort it by date which is the mid column of my worksheet. im getting my data from a db system but i cannot sort it in that system i need to sort the data which comes to me as this: | A FIELD | B FIELD | C FIELD | DATE FIELD | E FIELD | F FIELD | | Adata1 | Bdata | Cdata | 09.05.2011 | Edata | Fdata | | Adata2 | Bdata | Cdata | 03.05.2011 | Edata | Fdata | | Adata3 | Bdata | Cdata | 21.05.2011 | Edata | Fdata | | Adata4 | Bdata | Cdata | 01.05.2011 | Edata | Fdata | | Adata5 | Bdata | Cdata | 11.05.2011 | Edata | Fdata | And i should find a way to make it like this than paste to excel: | A FIELD | B FIELD | C FIELD | DATE FIELD | E FIELD | F FIELD | | Adata4 | Bdata | Cdata | 01.05.2011 | Edata | Fdata | | Adata2 | Bdata | Cdata | 03.05.2011 | Edata | Fdata | | Adata1 | Bdata | Cdata | 09.05.2011 | Edata | Fdata | | Adata5 | Bdata | Cdata | 11.05.2011 | Edata | Fdata | | Adata3 | Bdata | Cdata | 21.05.2011 | Edata | Fdata | so how can i do this in VB6 to Excel? I can use a helper for it and read data from it order/sort than paste back to excel but which helper OLE? Dim strcnn As String Dim cnn As New ADODB.Connection Dim Cmd As New ADODB.Command Dim rs As New ADODB.Recordset Private Sub Form_Load() 'Create database connection strcnn = "MyConnectionToDb" cnn.Open strcnn Cmd.ActiveConnection = cnn End Sub Private Sub Command1_Click() Dim i As Integer Dim cek As String Dim tarih As String 'Set excel Set kitap = CreateObject("Excel.Application") kitap.Workbooks.Add 'Data Query cek = "SELECT * FROM DATATEST.trolololollololollololoo" rs.Open cek, cnn 'If result is empty If rs.EOF = True Then 'Report situation Situation.Caption = "Situation : is under control!" Else 'Start counter i = i + 1 'Add headers kitap.Cells(i, 1).Value = "SN" kitap.Cells(i, 2).Value = "OP" kitap.Cells(i, 3).Value = "HF" kitap.Cells(i, 4).Value = "UC" kitap.Cells(i, 5).Value = "HA" kitap.Cells(i, 6).Value = "UA" kitap.Cells(i, 7).Value = "IN" 'While not end of file Do While Not rs.EOF 'Increase the Counter i = i + 1 'Add the data kitap.Cells(i, 1).Value = rs.Fields("SN") kitap.Cells(i, 2).Value = rs.Fields("OP") kitap.Cells(i, 3).Value = rs.Fields("HF") kitap.Cells(i, 4).Value = rs.Fields("UC") kitap.Cells(i, 5).Value = rs.Fields("HA") kitap.Cells(i, 6).Value = dotdate(rs.Fields("UA")) 'UA is date field, this will be the key column kitap.Cells(i, 7).Value = rs.Fields("IN") 'to sort all data is being saved to excel. 'Next record rs.MoveNext Loop 'Close data connection rs.Close End If 'Save data to excel kitap.ActiveWorkbook.SaveAs(App.Path & "\troll.xls") kitap.Application.Quit 'Report situation Situation.Caption = "Situation : Excel Formatted Troll is Ready" Exit Sub Error: 'On error close connection rs.Close 'Report situation Situation.Caption = "Critical ERROR! : Connection has been trolled! Reset ur computer." End Sub A: The easiest way to do what you want would appear to be to order the data returned from your database. Instead of: "Select * From DATATEST.trolololollololollololoo" Try "Select * From DATATEST.trolololollololollololoo ORDER BY [Date Field Name]" A: To be honest - I don't understand your problem. In fact I think you created the problem yourself. Why don't you just copy the data as it is, and later run something like below? 'set autofilter Me.Range(Cells(1,1), Cells(lastRow, lastColumn)).AutoFilter 'sort Me.AutoFilter.Range.Sort Key1:=Cells(rowDateField, 1), Order1:=xlAscending, Header:=xlYes Sorting done. A: I found the solution. Here is a badly shaped code but solves the problem. OptionExplit Dim strcnn As String Dim cnn As New ADODB.Connection Dim Cmd As New ADODB.Command Dim rs As New ADODB.Recordset Private Sub Form_Load() 'Create database connection strcnn = "MyConnectionToDb" cnn.Open strcnn Cmd.ActiveConnection = cnn End Sub 'Sorting function here! Public Function OrderByDate() Dim i, j, k As Integer Dim temp(100, 50) As Variant 'for my work here 100 was enough.. change it if u got more items in ur excel data. Dim xlApp As Excel.Application Dim xlWorkBook As Excel.Workbook Dim xlWorkSheet As Excel.Worksheet 'Set excel Set xlApp = New Excel.Application Set xlWorkBook = xlApp.Workbooks.Open(App.Path & "\my.xls") Set xlWorkSheet = xlWorkBook.Worksheets(1) 'Start working on worksheet With xlWorkSheet 'Start counters i = 2 j = 3 k = 1 'Report situation Situation.Caption = "Situation : Ordering by Date." 'Till Excell Book finishes Do While Not k = .Rows.Count - 1 'When you reach empty cells in ur sheet it means you're at the end of ur data. 'So finish there. If UnDotAndTurn(Replace(Trim(.Cells(j, 6)), ".", "")) = "" Then 'Exit Exit Do Else 'ReOrder the data If UnDotAndTurn(Replace(Trim(.Cells(i, 6)), ".", "")) > UnDotAndTurn(Replace(Trim(.Cells(j, 6)), ".", "")) Then 'First get the values to a template temp(i, 1) = .Cells(j, 1) temp(i, 2) = .Cells(j, 2) temp(i, 3) = .Cells(j, 3) temp(i, 4) = .Cells(j, 4) temp(i, 5) = .Cells(j, 5) temp(i, 6) = .Cells(j, 6) temp(i, 7) = .Cells(j, 7) 'Then get the next value into current .Cells(j, 1).Value = .Cells(i, 1) .Cells(j, 2).Value = .Cells(i, 2) .Cells(j, 3).Value = .Cells(i, 3) .Cells(j, 4).Value = .Cells(i, 4) .Cells(j, 5).Value = .Cells(i, 5) .Cells(j, 6).Value = .Cells(i, 6) .Cells(j, 7).Value = .Cells(i, 7) 'At last write the values in temp to next value set .Cells(i, 1).Value = temp(i, 1) .Cells(i, 2).Value = temp(i, 2) .Cells(i, 3).Value = temp(i, 3) .Cells(i, 4).Value = temp(i, 4) .Cells(i, 5).Value = temp(i, 5) .Cells(i, 6).Value = temp(i, 6) .Cells(i, 7).Value = temp(i, 7) 'return previous data to see if its still-> '->higher than what data comes before it. If i <= 3 Then i = i - 1 ElseIf i > 3 Then i = i - 2 j = j - 2 End If ElseIf UnDotAndTurn(Replace(Trim(.Cells(i, 6).Value), ".", "")) = UnDotAndTurn(Replace(Trim(.Cells(j, 6).Value), ".", "")) Then 'do smt here if u need to do! when they are equals to each other ElseIf UnDotAndTurn(Replace(Trim(.Cells(i, 6).Value), ".", "")) < UnDotAndTurn(Replace(Trim(.Cells(j, 6).Value), ".", "")) Then 'do smt here if u need to do! when i lower than j End If '+1 to go next data i = i + 1 j = j + 1 k = k + 1 End If Loop 'Report situation Situation.Caption = "Situation : Order Finished! Saving." 'Save worksheet .SaveAs (App.Path & "\my.xls") End With 'Save workbook xlWorkBook.Save xlWorkBook.Close xlApp.Quit 'Report situation Situation.Caption = "Situation : Changes Saved!" End Function 'Take date data as string and clear "." and turn it to yyyymmdd together. Public Function UnDotAndTurn(ByRef elem) As String Dim Day, Month, Year As String 'Clear dots and spaces elem = Trim(elem) elem = Replace(elem, ".", "") 'If result is empty If elem = "" Then 'Return empty elem = 0 UnDotAndTurn = "" ElseIf elem <> "" Then 'Get date values Year = Right(elem, 4) Month = Mid(elem, Len(elem) - 5, 2) Day = Mid(elem, 1, Len(elem) - 6) 'If "Day" is 1 charachter long than add 0 to head to get this: 09 If Len(Day) = 1 Then Day = "0" & Day End If 'Return result UnDotAndTurn = Year & Month & Day End If End Function 'i use this while i read data from my db it takes date field as numeric like 9082011 'and i turn it into 09.08.2011 date format, putting dots to make it more understandable Public Function dotdate(ByRef elem) As String Dim Day, Month, Year As String 'Get date values Year = Right(elem, 4) Month = Mid(elem, Len(elem) - 5, 2) Day = Mid(elem, 1, Len(elem) - 6) 'If "Day" is 1 charachter long than add 0 to head to get this: 09 If Len(Day) = 1 Then Day = "0" & Day End If 'Return result dotdate = Day & "." & Month & "." & Year End Function Private Sub Command1_Click() Dim i, j As Integer Dim cek As String Dim xlApp As Excel.Application Dim xlWorkBook As Excel.Workbook Dim xlWorkSheet As Excel.Worksheet 'Set excel Set xlApp = New Excel.Application Set xlWorkBook = xlApp.Workbooks.Add Set xlWorkSheet = xlWorkBook.Worksheets(1) 'With worksheet With xlWorkSheet 'Data Query cek = "Select * From DATATEST.trolololollololollololoo" rs.Open cek, cnn 'Start counter j = 1 'If result is empty If rs.EOF = True Then 'Report situation Situation.Caption = "Situation : End Of File! END OF LIFE! RUN AWAY!" Else 'Add headers .Cells(j, 1).Value = "SN" .Cells(j, 2).Value = "OP" .Cells(j, 3).Value = "HF" .Cells(j, 4).Value = "UC" .Cells(j, 5).Value = "HA" .Cells(j, 6).Value = "UA" .Cells(j, 7).Value = "IN" 'Increase the Counter j = j + 1 'While not end of file Do While Not rs.EOF 'Add the data .Cells(j, 1).Value = rs.Fields("SN") .Cells(j, 2).Value = rs.Fields("OP") .Cells(j, 3).Value = rs.Fields("HF") .Cells(j, 4).Value = rs.Fields("UC") .Cells(j, 5).Value = rs.Fields("HA") .Cells(j, 6).Value = dotdate(rs.Fields("UA")) .Cells(j, 7).Value = rs.Fields("IN") 'Increase the Counter j = j + 1 'Next record rs.MoveNext Loop 'Close data connection rs.Close End If 'Save worksheet .SaveAs (App.Path & "\my.xls") End With 'Save workbook xlWorkBook.Save xlWorkBook.Close xlApp.Quit 'Order excel file DoEvents OrderByDate 'Report situation Situation.Caption = "Situation : Excel Formatted Troll is Ready" Exit Sub Error: 'On error close connection rs.Close 'Report situation Situation.Caption = "Critical ERROR! : Connection has been trolled! Reset ur computer." End Sub
{ "language": "en", "url": "https://stackoverflow.com/questions/7583459", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to open a .doc file stored in SD card in browser? I have a .doc file stored in the SD card. I have to open it using the browser. I used Intent intent = new Intent(); File file = new File("/sdcard/ValidateLibrary.doc"); intent.setDataAndType( Uri.fromFile(file),"text/html"); in the manifest file i wrote: <activity android:name=".TextFileShow"> <intent-filter> <action android:name="myaction"/> </intent-filter> </activity> But it opens the "message compose". I have to open the ValidateLibrary.doc file inside a browser. How do i do that? A: I have to open it using the browser. I am not aware of any Web browser on the face of the planet, other than perhaps Internet Explorer, that is capable of natively displaying Microsoft Word documents. I am not aware of any Web browser for Android that is capable of natively displaying Microsoft Word documents. With regards to your Java source code snippet: * *text/html is not the MIME type for Microsoft Word. *Never hardcode paths like /sdcard, particularly since it is wrong for many devices. Use Environment.getExternalStorageDirectory() to get at the root of external storage. *Just creating an Intent will do you little good. If you want to display a Word document using some document viewer that the user might have installed, you would need to use ACTION_VIEW in the Intent constructor, then set the path/type as you are doing, then call startActivity(). in the manifest file i wrote: I have no idea why this is here. It certainly has nothing obvious to do with your Java code snippet, and it has nothing obvious to do with this question. I have to open the ValidateLibrary.doc file inside a browser. How do i do that? Step #1: Write a Web browser. Step #2: Augment your Web browser to be able to display Microsoft Word documents. This may involve you having to license some patents and will probably take a few developer-decades to write. Step #3: Convince users to install your Web/Word browser. It would be simpler for you to simply start up an ACTION_VIEW Intent on the Word document, then direct users to the Market to install some third-party application that handles Word documents if the user does not have one installed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583460", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Redirect to page and send custom HTTP headers I use the following code to redirect to a page in PHP. I need to set a custom HTTP headers to pass along with the redirect. header("Location: http://..."); How can I archive this? A: I'm afraid, all the answers are wrong and misleading! It's impossible to redirect to a page with custom headers set, no matter what language or framework you use. In other words, there's no way to trigger an HTTP redirect and cause the client (browser) to add a custom header. You might be thinking that using multiple header() calls should work just fine. But it won't. You're setting the custom headers for the response which is instructing the browser to redirect, not for the redirect itself. The only way for a site to instruct a browser to issue an HTTP request with a custom header is to use Javascript and the XMLHttpRequest object. And it needs CORS implemented on the target server to allow such ajax requests. Please note that a page can not set HTTP request headers unless it's making an async request using XMLHttpRequest. Meaning that you can't do such redirection with the custom header on the client-side as well. A: Just add additional header() calls after or before this one. header("Location: http://..."); header("Content-Type: text/plain"); A: This question needs to be answered differently as depending from where you're looking the answer is different: Redirect Response (PHP) As far as you're concerned about the redirect response (and not the request that may be triggered by a redirect response) Multiple headerDocs calls: header("Location: ...."); header("Header2: ...."); header("Header3: ...."); ... New Request triggered by a Redirect Response (Browser, HTTP client) If you're looking for the new request that has been triggered by a redirect response, please consult your HTTP clients technical documentation for your options. Commonly, HTTP clients do not offer any such options, that is most HTTP clients do not turn response headers into request headers in case one of the response headers is a Location: header and a status code in the 3xx range. This would not make any sense anyway as such practice would be unsafe. Especially on the level of interactive HTTP clients (like a browser) that automatically perform redirects without approval of the user. See HTTP, compare Fetch API. Further reading: https://ec.haxx.se/http/http-redirects
{ "language": "en", "url": "https://stackoverflow.com/questions/7583461", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "34" }
Q: Visual Basic 6: reset ImageList-Control following issue ... In my project I have to reset (delete all saved images and format) an ImageList that's bound to a ListView-control. At first I unbind the ImageList from the ListView with "ListView1.Icons = Nothing". Then I clear my ImageList with "ImageList1.ListImages.Clear" ... no problem up to now. But if I wanna "rebind" (make new binding between both controls) both controls with "ListView1.Icons = ImageList1" I receive an message like "ImageList must be initialized befor use" ... and I don't know how to initialize an ImageList. Does somebody can help me? Greetings, Chris A: You need to add at least 1 image with ImageList.ListImages.Add(..) before you set ListView1.Icons = ImageList1
{ "language": "en", "url": "https://stackoverflow.com/questions/7583471", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Entity Framework and DDD Here's my problem: I use EntityFramework 4.1 Model first, and I have two assembly (Domain and Store) The domain contains all my business logic Store manages all persistence logic to the database So I do not want any entity framework query in my Domain. I use a repository to expose the Store. The Hic! My edmx is in the Store, so the TT that generates my business classes too. As I want my business classes in the assembly's Domain , I moved the TT into the Domain and change the namespace of code generator. I must refer my Store to know my Domain classes (logic !). But how to call my repository from my Domain without creating a circular reference ...? Summary: * *My Store reference Domain to know the business classes. *My Domain reference Store to know the repository A: You need a repository interface in your domain layer. Then the repository implementation is in your infrastructure layer, and uses EF. This way your infrastructure layer depends on your domain layer (via the implementation of the repository interface, and the creation/retrieval of domain entities), but the domain does not depend on the infrastructure layer. A good explanation of this general architectural pattern is given in Jeffrey Palermo's articles on the "onion architecture".
{ "language": "en", "url": "https://stackoverflow.com/questions/7583474", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: AuthorizeAttribute and output caching in asp.net mvc 3 I'm thinking to write custom authorize attribute and I'm not sure about output caching. Attribute would look like this: public class AuthorizeWithAreasAttribute : AuthorizeAttribute { public override void OnAuthorization(AuthorizationContext filterContext) { if (!filterContext.HttpContext.User.IsInRole(Roles)) { var urlHelper = new UrlHelper(filterContext.RequestContext); filterContext.HttpContext.Response.Redirect(urlHelper.Action(ControllerName, ActionName, new { area = AreaName })); } base.OnAuthorization(filterContext); } public string ControllerName { get; set; } public string ActionName { get; set; } public string AreaName { get; set; } } I have following quote from book professional asp.net mvc: So, what happens if you combine an authorization filter with [OutputCache]? In the worst case, you run the risk of an authorized user first visiting your action, causing it to run and be cached, shortly followed by an unauthorized user, who gets the cached output even though they aren’t authorized. Fortunately, the ASP.NET MVC team has anticipated this problem, and has added special logic to AuthorizeAttribute to make it play well with ASP.NET output caching. It uses a little-known outputcaching API to register itself to run when the output-caching module is about to serve a response from the cache. This prevents unauthorized users from getting cached content. After reading this, it remains unclear to me - should I do something regarding caching or not. A: No you'll be fine. The AuthorizeAttribute will always be used. The output cache may cache the authorized user's content, but it will never display that to an unauthorized user, and vice versa.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583475", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: addEventListener doesn't work in an event listener I have an event listener, which listen to document load (this is "myExtension" and it's work correctly). And I want to put another listener into this listener, but it doesn't work. This is that listener: myExtension.$("#quicklink img").addEventListener("click", function(){ alert("It's works!"); }, false, true); but if I change that listener to this listener: document.addEventListener("click", function(){ alert("It's works!"); }, false, true); it works correctly. $("#quicklink img") - it's an array with images, there are some of them in the page (0-20 ea). I want to use this, only some pages, so I need myExtension, because I don't want to work all sites, where there are img in an element with quicklink id. Why it doesn't work? What is the problem? A: $("#quicklink img") - it's an array with images, there are some of them in the page (0-20 ea). Arrays don't have an addEventListener method. You would have to loop over it and call addEventListener on each HTMLElementNode. A: you need to add the listener on each image $("#quicklink img").each( function(){ $(this).click(function(){ alert("It's work"); }); }); A: I find my answer window.addEventListener("load", function() { myExtension.init(); }, false); var myExtension = { $: jQuery.noConflict(true), init: function() { gBrowser.addEventListener("DOMContentLoaded", myExtension.onPageLoad, true); }, onPageLoad: function(aEvent) { [...] var wnd = aEvent.target.defaultView; wnd.document.getElementById('a1').addEventListener("click", function(){ alert("It's works!"); }, false, true); [...] } where "a1" is one image id
{ "language": "en", "url": "https://stackoverflow.com/questions/7583476", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-4" }
Q: onClickListener on TableLayout I faced with trivial problem but i don't know how to solve it. I have several ImageViews on my TableLayout how can i create one onClickListner for all of them. It should looks like this : public void onClick(View v) { switch(v.getId()) { case(R.id.imageStart): { this.startActivity(new Intent(MainActivity.this,GameActivity.class)); break; } case(R.id.imageExit): { finish(); break; } } } If it's possible or course, i am new in Android Dev. I saw sample where for each ImageView have his own onClickListner but its not a good practice i suppose. Thanks. A: Yes you can do that. Just implement the OnClickListener in your class: public class MainActivity extends Activity implements OnClickListener { } Add your onClick method to that class and then all you have to do for each button is this: button.setOnClickListener(this); A: follow this Steps : public class MyActivity extends Activity implement OnClickListener{ @override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); //get the View by Id ImageView img1 = (ImageView) findViewById(R.id.img1); ImageView img2 = (ImageView) findViewById(R.id.img2); ImageView img3 = (ImageView) findViewById(R.id.img3); //set the OnClickListener on your ImageViews img1.setOnClickListener(this); img2.setOnClickListener(this); img3.setOnClickListener(this); } @override public void onClick(View v){ switch(v.getId()){ case(R.id.img1): Toast.makeText(this,"image 1 clicked ...",3000).show(); break; case(R.id.img2): Toast.makeText(this,"image 2 clicked ...",3000).show(); break; case(R.id.img3): Toast.makeText(this,"image 3 clicked ...",3000).show(); break; } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7583478", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to create mouseover highlight box in html 5? If I have a 600 by 400 grid, with 10 by 10 pixel squares like this: /** * draws grid to screen */ function drawgrid(context) { for(var x = 0.5; x < 600; x += 10) { context.moveTo(x, 0); context.lineTo(x, 400); } for(var y = 0.5; y < 400; y += 10) { context.moveTo(0, y); context.lineTo(600, y); } context.strokeStyle = "#eee"; context.stroke(); } /** * Creates a canvas element, loads images, adds events, and draws the canvas for the first time. */ function prepareCanvas() { var context = document.getElementById('canvas').getContext("2d"); drawgrid(context); } How would I mouseover the individual squares and highlight the square that the mouse is hovering over. Like make a red box highlighting the grid square the mouse is over. A: See code below. Adjust coordinates for event <body> <canvas id=canvas height=400 width=600 onmousemove="over()" style="cursor:crosshair"> </canvas> </body> <script type="text/javascript"> <!-- var grid; function prepareCanvasGrid() { var cnv = document.getElementById('canvas'); grid = new CanvasGrid(cnv.getContext("2d"),cnv.offsetLeft, cnv.offsetTop); } function CanvasGrid(context,x,y) { this.sq = []; this.dirty = []; this.ctx = context; this.x = x; this.y = y; this.init = function(){ for(var x = 0.5; x < 600; x += 50) { for(var y = 0.5; y < 400; y += 50) { var s = new square(x,y, context); this.sq.push(s); } } } this.draw = function(){ this.ctx.clearRect(0,0,600,400); for(var i=0; i < this.sq.length; i++) this.sq[i].draw(); } this.clean = function(){ for(var i=0; i < this.dirty.length; i++) this.dirty[i].draw(); this.dirty = []; } this.over = function(ex,ey){ ex = ex - this.x; ey = ey - this.y; for(var i=0; i < this.sq.length; i++) { if(this.sq[i].eleAtPoint(ex,ey)){ this.clean(); // clean up this.dirty.push(this.sq[i]); this.sq[i].over(); break; } } } this.init(); this.draw(); } function square(x,y, ctx){ this.ctx = ctx; this.x = x; this.y = y; this.h = 50; this.w = 50; this.draw = function(){ this.ctx.strokeStyle = "#eee"; this.ctx.strokeRect(this.x, this.y, this.w, this.w); this.ctx.fillStyle = "#fff"; this.ctx.fillRect(this.x, this.y, this.w, this.w); } this.over = function() { this.ctx.fillStyle = "red"; this.ctx.fillRect(this.x, this.y, this.w, this.w); } this.eleAtPoint = function(ex,ey){ if(ex < this.x + this.w && ex > this.x && ey > this.y && ey < this.y + this.h) return true; return false; } } function over(){ var e = window.event; grid.over(e.clientX ,e.clientY); } prepareCanvasGrid(); //--> </script> Updated code for better performance A: Just to add to hungryMind's answer, if you don't want any boxes to remain highlighted when the mouse is no longer over the canvas, add these two things: 1) An else if this.over = function(ex,ey){ ex = ex - this.x; ey = ey - this.y; for(var i=0; i < this.sq.length; i++) { if(this.sq[i].eleAtPoint(ex,ey)){ this.clean(); // clean up this.dirty.push(this.sq[i]); this.sq[i].over(); break; } else if (!this.sq[i].eleAtPoint(ex,ey)) { this.sq[i].off(); } } } 2) A square off() method: this.off = function() { this.draw(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7583482", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: sqlite prepopulation How to prepopulate an sqlite database at development time? I found a tutorial how to use a prepopulated sqlite with android but I want to populate the database with data from a text file. Is it possible to write a java program that will read the data from a text file insert into sqlite database and save the database? A: Yes, what you described is what you need to do: * *Read data from a text file *Generate "insert" sentences from it *Run them against your SQLite database Done. Your DB is now pre-populated. Make sure you flag this "pre population:" command so you don't run it twice.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583491", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: run picoC non-recursively as an iterated function I've been playing around with a few C interpreters and have found picoC to look like it meets all my needs. to kick off a script you call void PicocCallMain(int argc, char **argv); which recursively calls the internal parser etc.. Is it possible to recode picoC so that I could run scripts iteratively. for example. while(1) { picoCyield(&script1); picoCyield(&script2); } each call to picoCyield would call the token reader no more than required to execute the smallest possible block of script. I could run picoC as is with threads, but I the enviorment I am working in prohibits it.. Any help, or pointers to a similair interpreter that can do this, would be greatly appreciated. A: I would look at the top-level code for interactive mode. Where it currently prints the prompt and waits for input, I would replace with a callback to your program which you would use to provide the next statement. Then all the line-by-line execution is already done for you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583494", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to stroke and reveal a path slowly? For a scientific simulation, I need to stroke and reveal a path slowly over time, starting at the first point and traveling through all other points until reaching the last point. Like if you take a pencil and start slowly drawing a circle, spiral or triangle. How could I do this with Core Animation or maybe OpenGL ES? Core Graphics would possibly be too slow to refresh at 60 fps. There is CAKeyframeAnimation which can travel along a path, but I need a way of actually stroking that path while traveling along it. Edit: Should run on iOS 3.2 as well! A: * *Create a CAShapeLayer to display your path. *Animate the layer's strokeEnd property from 0.0 to 1.0. See this blog post of mine for details.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583501", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SSH client and server in java Which are the popular libraries to use to implement both custom SSH client and server in java? I'm aware that Jsch (http://www.jcraft.com/jsch/) is a popular java ssh client, are there good and secure java ssh servers that have an open source license? A: Apache Mina server I haven't checked it out but apparently it has support for: * *Port forwarding *SFTP *X11 Forwarding *Agent forwarding NSsh I know this is the wrong language but this C# server is partly based off the Ganymed client code and might be a good reference if Apache Mina doesn't work out.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583507", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: jQuery need help to navigate/highligt elements on a complex list this is my hmtl list. <div class="bradius3 taggy-beans"> <div class="taggy-beans-search"><input type="text" id="search-tags" class="bradiusMax" style=""></div> <div class="pajinate-content"> <ul class="pajinate"> <li class="page1" style="display: inline;"> <ul class="filtered-tags"> <li><a id="4e72858ccaa47ca608510000" class="bradiusMax bean" href="javascript:void(0)">hey</a> </li> </ul> </li> <li class="page1" style="display: inline;"> <ul class="filtered-tags"> <li> <a id="4e72858ccaa47ca6082d0000" class="bradiusMax bean" href="javascript:void(0)">hi</a> </li> </ul> </li> <li class="page1" style="display: inline;"> <ul class="filtered-tags"> <li> <a id="4e72858ccaa47ca6082d0000" class="bradiusMax bean" href="javascript:void(0)">jhon</a> </li> </ul> </li> </ul> </div> </div> my js script. $('#search-tags').live('keydown',function(e){ var $prev, $next, $current = $(".pajinate a.highlight"); if (e.which === 40 && !$current.length) { $(".pajinate a:first").addClass("highlight"); } else if (e.which === 39) { console.log($next); $next = $current.next(".pajinate a"); if ($next.length) { $current.removeClass("highlight"); $next.addClass("highlight"); } } else if (e.which === 37) { console.log($prev); $prev = $current.prev(".pajinate a"); if ($prev.length) { $current.removeClass("highlight"); $prev.addClass("highlight"); } } else if (e.which === 38) { $(".pajinate a").removeClass("highlight"); } }); what i'm trying to do is to navigate by e.keyCode in the html list above, trying highlighting a.bean elements but the script highlights only the first a.bean, then key left or right doesn't highlights a elements any suggest? here is an example of the script logic: http://jsfiddle.net/WeNdW/ A: if you're trying to highlight a elements, you would be too deep in the DOM tree for next to work properly. next gets the next sibling, and a doesn't have any. a is highlighted and is set to be $current so $next and $prev need to go a few levels up the DOM tree in order to get to the true next a Thus, the part that says parent().parent().parent() to go the appropriate amount up the DOM structure. Similarly, children().children().children() to go back down and highlight the a. $("#search-tags").live("keydown", function(e) { var $prev, $next, $current = $(".pajinate a.highlight"); if (e.which === 40 && !$current.length) { $(".pajinate li:first a").addClass("highlight"); } else if (e.which === 39) { $next = $current.parent().parent().parent().next("li"); if ($next.length) { $current.removeClass("highlight"); $next.children('ul').children('li').children('a').addClass("highlight"); } } else if (e.which === 37) { $prev = $current.parent().parent().parent().prev("li"); if ($prev.length) { $current.removeClass("highlight"); $prev.children('ul').children('li').children('a').addClass("highlight"); } } else if (e.which === 38) { $(".pajinate a.highlight").removeClass("highlight"); } }); fiddle here
{ "language": "en", "url": "https://stackoverflow.com/questions/7583508", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C library for email composition with UTF-8 characters I'm building a C app that must send email containing UTF-8 (accented) characters in the body. I found 285 related postings on stackoverflow but they don't address my specific questions: * *Is there a C library (not windows/platform specific) to help compose an email, then send by SMTP? (I don't want to just call a shell command from C). I found chilkat libraries but they look overwhelming. *Is it possible to put UTF-8 characters into a plaintext email? If not, how would I send UTF-8 characters in the body? *If I send an HTML based email body, does a plaintext version automatically get created (or is this a function of the mail client presenting the email to the recipient). Thanks@ A: You didn't mention an operating system. the c-client library from ftp://ftp.cac.washington.edu/imap/ (called "imap" there) has function to encode mails and should work on different Unix flavors and Windows. Even though the version number says 2007 it's updated this year. The tarball contains some documentation. ftp://ftp.cac.washington.edu/imap/imap-2007f.tar.gz A: Simply put Content-type: text/plain; charset=utf-8 and Content-transfer-encoding: quoted-printable in the header (for the message or MIME part, depending on if you're using multiple MIME parts), and encode the byte stream of UTF-8 as quoted-printable (the ugly =XX stuff). There's nothing UTF-8-specific to be done.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583510", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android OnTouch events numerous Objects ok I'm playing w/ ontouch events extending a view. what I've done is made a circle on touch.. the cirlce will follow as you move. As you move another circle is made and will sit in the postion decrementing the radius until it disappears.. (right now up to like 10 circles). I can also handle multiple fingers touching at one point in time. Here's the problem.. THE CODE IS NASTY! To create multiple circle This is my paint method: public void onDraw(Canvas canvas) { paint.setColor(Color.RED); paint.setStyle(Style.STROKE); paint.setStrokeWidth(stroke); canvas.drawCircle(x,y,radius,paint); canvas.drawCircle(x1,y1,radius1,paint); canvas.drawCircle(x2,y2,radius2,paint); canvas.drawCircle(x3,y3,radius3,paint); canvas.drawCircle(x4,y4,radius4,paint); canvas.drawCircle(x5,y5,radius5,paint); canvas.drawCircle(x6,y6,radius6,paint); paint.setColor(Color.BLUE); canvas.drawCircle(x7,y7,radius7,paint); canvas.drawCircle(x8,y8,radius8,paint); paint.setColor(Color.YELLOW); canvas.drawCircle(x9,y9,radius9,paint); canvas.drawCircle(x10,y10,radius10,paint); } so as you can see this by far inefficient and makes for some long nasty code.. Part of the issue is the fact I'm bound to only being able to change coordinates in Ontouch.. and invalidate. Anyoone know a way I can do this more efficently (in a more object orriented type approach). A: First things first, start with this: public class Circle { public int x; public int y; public double radius; public Paint paint; /* constructors, getters & setters if you feel like ...*/ } And put all your circles in a ArrayList<Circle> circles = new ArrayList(); public void onDraw(Canvas canvas) { /*...*/ Iterator iterator = circles.iterator(); while(iterator.hasNext()) { drawCircle(iterator.next()); } } public void drawCircle(Canvas canvas, Circle circle) { canvas.drawCircle(circle.x, circle.y, circle.raidus, circle.paint); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7583514", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Convert Character to Number in Oracle I have ColumnA in table. The data of each row is single character between A & H. I want my select query to return 1 for 'A', 2 for B .... 8 for H. My query always returns only one row. I can make a lookup table. Anyone has better ideas to achieve the same ? A: SELECT 1 + ASCII(columnA) - ASCII('A') FROM table
{ "language": "en", "url": "https://stackoverflow.com/questions/7583515", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: access java synchronized method from native code I have a java class that has some (private static) synchronized methods which I want to call from native code as well. with some example code it becomes more clear what I mean public class SomeClass { private static synchronized void method() { //do something that needs synchronization } } and the associated native code (C++) void someFunction(JNIEnv * env) { jclass someClass = env->findClass("SomeClass"); jmethodID methodId = env->GetStaticMethodID(jclass, "method", "()V"); env->MonitorEnter(jclass); // <--- IS THIS NEEDED/ALLOWED env->CallStaticVoidMethod(jclass, methodId); env->MonitorExit(jclass); // <--- IS THIS NEEDED/ALLOWED } So what I am wondering is if I need to call MonitorEnter/MonitorExit, or if the method synchronization is enforced already by the synchronized attribute on SomeClass.method(). I am not so much interested in rewriting the code. I can think of a few solutions to work around this, but I am interested in what the behaviour is, given a synchronized method that is called from native code. A: Section 8.4.3.6 synchronized Methods of the Java Language Specification says that declaring the method synchronized has the same effect as adding a synchronized block within the method. A: No, explicit MonitorEnter / MonitorExit are not needed. According to The JNI guide, ...it is preferable to express synchronization constructs in the Java programming language. If, for example, a static native method needs to enter the monitor associated with its defining class, you should define a static synchronized native method as opposed to performing JNI-level monitor synchronization in native code. Even though your case of calling a Java method from the native code (and not vice versa) isn't directly discussed in the spec, the opposite is not stated either, so I would assume that it works similarly. A: If you own SomeClass you can just do public class SomeClass { private static synchronized void method() { //do something that needs synchronization } private static void synchronizedMethod() { method(); } } and just call synchronizedMethod() from C++.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583531", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Django BooleanField value I have a form field like so IS_EMPLOYED_CHOICES = ( ('1', 'yes'), ('0', 'no') ) class AddEmployee(forms.Form): is_employed = forms.ChoiceField(choices=IS_EMPLOYED_CHOICES) and the field in the model is a BooleanField is_employed = models.BooleanField() I am aware that a BooleanField is a varchar with either a '1' or '0' for True or False However I want to pass this value from the model to the form field above so it would show no when it is False and yes when it is true. emp_profile = Employees.objects.get(pk=1) emp_form = AddEmployee(initial={ 'is_employed' = emp_profile.is_employed }) does not work A: When the value actually comes out, it's True and False instead of '1' and '0'. So you would do something like IS_EMPLOYED_CHOICES = ( (True, 'yes'), (False, 'no') ) and it should work A: I think it will work if you remove the quotes : IS_EMPLOYED_CHOICES = ( (1, 'yes'), (0, 'no') ) (nod) Good luck
{ "language": "en", "url": "https://stackoverflow.com/questions/7583532", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using Node.js to connect to Microsoft SQL Server 2008 (MSSQL) database Possible Duplicate: Connecting to a remote Microsoft SQL server from Node.js I'm looking for an up-to-date explanation of how to connect to a MS SQL Sever 2008 using Node.js (v0.5.7) I have tried both Node.js projects on GitHub here: https://github.com/vivina/node-mssql https://github.com/orenmazor/node-tds node-tds is an abandoned project and node-mssql appears to be incomplete or at least the code-base seems to be out-of-date with the most recent version of Node.js Has anyone actually got Node.js to connect to and query a Microsoft SQL Server 2008? I would love to see some configuration details (versions, addons etc.) and code samples. Thanks, P. Out of date answers on SO: Node.js and Microsoft SQL Server, Connecting to a remote Microsoft SQL server from Node.js A: Just today I released a new module, for windows only, allowing native and asynchronous use of MSSQL. It's called TSQLFTW, and currently supports connecting and querying the database. It returns results in JSON. Check out the Github here: https://github.com/gfosco/tsqlftw Hacker News submission/comments: http://news.ycombinator.com/item?id=3353389 A: I am working on a solution (https://github.com/pekim/tedious), but it's not quite usable yet. Currently it can connect, authenticate, send SQL statements. The parsing of the response to the statement is in progress; some column metadata is processed, and the rows data itself is next. In the next few weeks (it's a spare time project), I hope to have it in a useable, but far from complete state. The API, and the guts of it, will still be subject to significant changes though, as there's lots that I'm still unhappy about. There's quite a bit of additional error checking and state handling that need to be addressed, as well as stored procedures and parameterised statements. I'll try to update the status in the README a bit more frequently, so that's it's easier to see how close (or far) from useable it is.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583536", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to split youtube video ID? src="http://www.youtube.com/v/R5zKIOTvfwQ?version=3" and src="http://www.youtube.com/v/R5zKIOTvfwQ" How can I get the video ID alone from this src? Is there any predefined option available for that? A: The video ID is the string which is after the v/ and before the ? In your case R5zKIOTvfwQ. If you are looking for an automatic way to retrieve it, try this regex: /v\/(.*)[\?$]/
{ "language": "en", "url": "https://stackoverflow.com/questions/7583537", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Updating a Place's lat/lon co-ordinates? I have a Facebook Page which originally had one street address, but now has a new one. I can change the street address within Facebook itself, but when I come to query the Graph API for the Page, the latitude & longitude are & have been for some time stuck on the old co-ordinates. Is there a way to get Facebook to refresh the latitude & longitude to the new co-ordinates at all, either by using the Graph API or some other means? A: Updating places or refreshing places cache is not available via the Facebook API. I would log a bug about the coordinates not getting updated via the graph api. You can ask Facebook directly in their community forum.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583540", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do I avoid getting "No peer certificate" error when connecting to this HTTPS site on Android? I am developing an Android application which needs to access QuickPay's service ("https://secure.quickpay.dk/form") through an Http-client. But I keep getting errors when accessing the page. More specifically I get a "No Peer Certificate" error message. I tried several different things already: I tried adding the root certificate to my keystore, and to use this keystore when connecting, following this procedure: adding certificate to keystore. I also tried accepting all certificates, following the proposed method from here: accepting certificate for android. I have successfully connected to other https sites, but can not seem to connect to this one. I have tried on different Android devices (1.6, 2.2, and 2.3.3). Can anyone succeed in connecting to quickpay's site, or can anyone come up with a possible solution/fix? //Update: If I access this site with my WebView: payment window examples, and press one of the buttons (which basically just launches a http post with some pre-defined variables) I am able to connect to the site in the webview on Android 2.3.3. Furthermore, I found out that I get a reply from the site if I try to launch the above application on Android 3.1! Any suggestions? public class MyHttpClient extends DefaultHttpClient { final Context context; public MyHttpClient(Context context) { this.context = context; loadHttps(); } private void loadHttps() { String url = "https://secure.quickpay.dk/form"; HttpPost httpPost = new HttpPost(url); try { System.out.println("Executing"); this.execute(httpPost); } catch (UnsupportedEncodingException e) { System.out.println(e.getMessage()); } catch (ClientProtocolException e) { System.out.println(e.getMessage()); } catch (IOException e) { System.out.println(e); } } @Override protected ClientConnectionManager createClientConnectionManager() { SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); registry.register(new Scheme("https", newSslSocketFactory(), 443)); return new SingleClientConnManager(getParams(), registry); } private SSLSocketFactory newSslSocketFactory() { try { KeyStore trusted = KeyStore.getInstance("BKS"); InputStream in = context.getResources().openRawResource(R.raw.test); try { trusted.load(in, "mysecret".toCharArray()); } finally { in.close(); } SSLSocketFactory sf = new SSLSocketFactory(trusted); return sf; } catch (Exception e) { throw new AssertionError(e); } } } StackTrace: WARN/System.err(8459) at org.apache.harmony.xnet.provider.jsse.SSLSessionImpl.getPeerCertificates(SSLSessionImpl.java 258) WARN/System.err(8459) at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java 93) WARN/System.err(8459) at org.apache.http.conn.ssl.SSLSocketFactory.createSocket(SSLSocketFactory.java 381) WARN/System.err(8459) at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java 177) WARN/System.err(8459) at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java 164) WARN/System.err(8459) at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java 119) WARN/System.err(8459) at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java 359) WARN/System.err(8459) at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java 555) WARN/System.err(8459) at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java 487) WARN/System.err(8459) at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java 465) WARN/System.err(8459) at test.https.MyHttpClient.loadHttps(MyHttpClient.java 34) WARN/System.err(8459) at test.https.MyHttpClient.<init>(MyHttpClient.java 26) WARN/System.err(8459) at test.https.HttpsTesterActivity.onCreate(HttpsTesterActivity.java 60) WARN/System.err(8459) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java 1047) WARN/System.err(8459) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java 1615) WARN/System.err(8459) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java 1667) WARN/System.err(8459) at android.app.ActivityThread.access$1500(ActivityThread.java 117) WARN/System.err(8459) at android.app.ActivityThread$H.handleMessage(ActivityThread.java 935) WARN/System.err(8459) at android.os.Handler.dispatchMessage(Handler.java 99) WARN/System.err(8459) at android.os.Looper.loop(Looper.java 123) WARN/System.err(8459) at android.app.ActivityThread.main(ActivityThread.java 3687) WARN/System.err(8459) at java.lang.reflect.Method.invokeNative(Native Method) WARN/System.err(8459) at java.lang.reflect.Method.invoke(Method.java 507) WARN/System.err(8459) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java 842) WARN/System.err(8459) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java 600) A: Just to sum up, I fixed this issue by sticking to the WebView approach. The interaction with the API was moved to a server, creating an intermediate communication point which handles the certificate issues. Not the most elegant solution but it works :) A: This is very mysterious. The only way an HTTPS/SSL server can avoid sending a certificate is if both sides agree to operate the SSL connection in reverse, where the server is the SSL client and the client is the SSL server, so the certificate travels in the other direction. But I can't see anything in your code that enables that mode, and it would have to be enabled at the other end too. And you would have to be providing a certificate yourself from your keystore ... Very strange. A: Try using UrlConnection class to make connections, and see whether you can avoid this "no peer certificate" error.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583548", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: string as object reference to object variable var string = 'object.data.path'; That's a string that resembles a path to variable. How can I return the corresponding variable from that string? Something like transforming the string into return object.data.path; The thing behind this is that the string could be much longer (deeper), like: var string = 'object.data.path.original.result'; A: function GetPropertyByString(stringRepresentation) { var properties = stringRepresentation.split("."), myTempObject = window[properties[0]]; for (var i = 1, length = properties.length; i<length; i++) { myTempObject = myTempObject[properties[i]]; } return myTempObject; } alert(GetPropertyByString("object.data.path")); this assumes that your first level object (in this case called object is global though. Alternatively, although not recommended, you could use the eval function. A: Assuming you don't want to just use eval you could try something like this: function stringToObjRef(str) { var keys = str.split('.'), obj = window; for (var i=0; i < keys.length; i++) { if (keys[i] in obj) obj = obj[keys[i]]; else return; } return obj; } console.log(stringToObjRef('object.data.path.original.result')); Uses a for loop to go one level down at a time, returning undefined if a particular key in the chain is undefined.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583549", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Naming Objects in JS How do I create dynamic names for objects in JS? I am pulling elements from a form (ex: First Name). I would either like to assign a number as the object name or just use the first name. A: I'm not sure about variable names, but you can do so with property names var string = "propertyName"; var obj = {}; obj[string] = "some value"; document.write(obj.propertyName); // some value As to your specific use case It might be better to use an array to maintain a list of users... var users = []; var newUser = { foo: "foo" , bar: "bar" }; users.push(newUser); var anotherUser = { foo: "foo" , bar: "bar" }; users.push(anotherUser); This gives you an array of users.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583550", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is StoreView1 and why is it being requested Hi all i am using c# and i'm being prompted to enter an out int storeview1 as a property of catalogProductCurrentStore(out int storeview1, string sessionID, string storeview). Can anyone tell me what this is? Thanks A: You can look this up yourself. The catalogProductCurrentStore looks like a generated c# method for the catalog_product.currentstore API method. The PHP entry point for this method (in Magento 1.6) is here #File: app/code/core/Mage/Catalog/Model/Api/Resource.php public function currentStore($store=null) { if (!is_null($store)) { try { $storeId = Mage::app()->getStore($store)->getId(); } catch (Mage_Core_Model_Store_Exception $e) { $this->_fault('store_not_exists'); } $this->_getSession()->setData($this->_storeIdSessionField, $storeId); } return $this->_getStoreId(); } So, calling this API method persists the passed in store ID into a PHP session variable. This doesn't make sense until you look at other API methods, and see that they're reading this ID back out of the session whenever they need to make a call that requires a specific Store ID. The Magento system, and Magento objects, have a base configuration for an online store. But, you can also setup a single Magento system to serve out multiple stores, each with different products, pricing, etc. Internally, Magento keeps track of a base configuration, and then the differences each store has. Oversimplified mostly true example: Say you had a system with two stores Store A Store B which had 10,000 shoe products, and the only different was one pair of shoes cost $100 in Store A, but $200 is Store B, rather than store 20,000 show object, Magento stores 10,001. The base configuration of all those shoes, and the way that Store B is different. To keep track of all this, Magento provides a store object. These store objects have IDs. This is relevant to you because you may make an API request for product information, but that information is going to vary from store to store. The catalog_product.currentstore method (which you API tools have generated as catalogProductCurrentStore?) lets you set a default store ID to use for requests that require an optional store id paramater.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583551", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to disable Home button without using the TYPE_KEYGUARD? i create a lockscreen application and i need to disable a home button, so if that phone is stolen, that phone can't be accessed.. my lockscreen is a fullscreen activity.. im use this code to disable a home button, but it gave me some bug. here's the code: @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } @Override public void onAttachedToWindow() { this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD); super.onAttachedToWindow(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { return false; } that code gave me some bug like a notification/status area still can be accessed even my activity on the full screen mode, if i turn off my display and turn on it again.. the bug is like this : first time application started: (still no problem) after i turn off my screen from power button and turn it on again: the main problem is on the lockscreen.. when the notification area still can be accessed, then the lockscreen is not useful.. any idea how to solve this?? please help.. I am also facing the same problem when i press the end key button. A: For my phone TYPE_KEYGUARD seems to override the fullscreen, no titlebar theme. The notification bar is always present. Try this: @Override public void onAttachedToWindow() { this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG); super.onAttachedToWindow(); } Make your view stretch the entire screen and it will cover up the notification area. Your notification area may still be clickable (invisibly) but I believe if you catch all the key events on your view it should not propagate down to the bar. A: This is the working for the above issue.. @Override public void onAttachedToWindow() { this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG); KeyguardManager keyguardManager = (KeyguardManager) getSystemService(KEYGUARD_SERVICE); KeyguardLock lock = keyguardManager.newKeyguardLock(KEYGUARD_SERVICE); lock.disableKeyguard(); } Add android.permission.DISABLE_KEYGUARD permission and give android:theme="@android:style/Theme.NoTitleBar.Fullscreen" to Application A: In my Samusung Pocket, nothing above worked fine. I could make it finally after further search. I put full screen them in your AndroidMainfest.xml like following (not in Acitivity code): <activity android:name=".geo.activity.LockActivity" android:theme = "@android:style/Theme.Black.NoTitleBar.Fullscreen" /> And use keygurad onAttachedToWindow() method in your activity: @Override public void onAttachedToWindow() { this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG); KeyguardManager keyguardManager = (KeyguardManager) getSystemService(KEYGUARD_SERVICE); KeyguardLock lock = keyguardManager.newKeyguardLock(KEYGUARD_SERVICE); lock.disableKeyguard(); } Exactly what I have wanted. Blocking HOME button and same after turning off/on. A: It's very simple, you should disable keyguard in the onAttachedToWindow() method: KeyguardManager keyguardManager = (KeyguardManager) getSystemService(KEYGUARD_SERVICE); KeyguardLock lock = keyguardManager.newKeyguardLock(KEYGUARD_SERVICE); lock.disableKeyguard(); A: Try this code : @Override public void onAttachedToWindow() { // TODO Auto-generated method stub super.onAttachedToWindow(); handler.postDelayed(mUpdateUiMsg, 100); } public boolean onKeyDown(int keyCode, KeyEvent event) { // TODO Auto-generated method stub if(keyCode==KeyEvent.KEYCODE_BACK){ return true; } if(keyCode==KeyEvent.KEYCODE_HOME){ return true; } return super.onKeyDown(keyCode, event); } private Runnable mUpdateUiMsg = new Runnable() { public void run() { getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD); } }; A: For a lockscreen Why don't you just use the following: @Override public void onAttachedToWindow() { getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED); getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD); } If the user doesn't have a secure lock screen set, the app will just go to the home screen when your app closes. If the user does have a secure lockscreen set then the standard secure lockscreen will come up next no matter how your app closes. I guess I wouldn't worry about disabling the buttons. The user should be allowed to use the standard security features anyways, because they provide more security then you can guarantee from your app. Plus you don't have to spend the time coding secure unlock features. A: You can not control the behaviour of Home Button. It will do it's task and you need to adjust your app requirements. For full screen add this in your activity tag in your manifest file: android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
{ "language": "en", "url": "https://stackoverflow.com/questions/7583553", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How do I deinterlace an image in Python? Let's assume the image is stored as a png file and I need to drop every odd line and resize the result horizontally to 50% in order to keep the aspect ratio. The result must have 50% of the resolution of the original image. It will not be enough to recommend an existing image library, like PIL, I would like to see some working code. UPDATE - Even if the question received a correct answer, I want to warn others that PIL is not in a great shape, the project website was not updated in months, there is no link to a bug traker and the list activity is quite low. I was surprised to discover that a simple BMP file saved with Paint was not loaded by PIL. A: Is it essential to keep every even line (in fact, define "even" - are you counting from 1 or 0 as the first row of the image?) If you don't mind which rows are dropped, use PIL: from PIL import Image img=Image.open("file.png") size=list(img.size) size[0] /= 2 size[1] /= 2 downsized=img.resize(size, Image.NEAREST) # NEAREST drops the lines downsized.save("file_small.png") A: I recently wanted to deinterlace some stereo images, extracting the images for the left and right eye. For that I wrote: from PIL import Image def deinterlace_file(input_file, output_format_str, row_names=('Left', 'Right')): print("Deinterlacing {}".format(input_file)) source = Image.open(input_file) source.load() dim = source.size scaled_size1 = (math.floor(dim[0]), math.floor(dim[1]/2) + 1) scaled_size2 = (math.floor(dim[0]/2), math.floor(dim[1]/2) + 1) top = Image.new(source.mode, scaled_size1) top_pixels = top.load() other = Image.new(source.mode, scaled_size1) other_pixels = other.load() for row in range(dim[1]): for col in range(dim[0]): pixel = source.getpixel((col, row)) row_int = math.floor(row / 2) if row % 2: top_pixels[col, row_int] = pixel else: other_pixels[col, row_int] = pixel top_final = top.resize(scaled_size2, Image.NEAREST) # Downsize to maintain aspect ratio other_final = other.resize(scaled_size2, Image.NEAREST) # Downsize to maintain aspect ratio top_final.save(output_format_str.format(row_names[0])) other_final.save(output_format_str.format(row_names[1])) output_format_str should be something like: "filename-{}.png" where the {} will be replaced with the row name. Note that it ends up with the image being half of it's original size. If you don't want this you can twiddle the last scaling step It's not the fastest operation as it goes through pixel by pixel, but I could not see an easy way to extract rows from an image.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583564", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Searching for a concept like 'verbosity' in Modelica I'm struggling with the size of output files for large Modelica models. Off course, I can protect some objects in order to remove them completely from the result file. However, that gives rise to two problems: * *it's not possible to redeclare protected objects *if i want to test my model in detail (eg for a short time period), i need to declare those objects publicly again in order to see their variables I wonder if there's a trick to set the 'verbosity' of a Modelica model. Maybe what I would like is a third keyword next to public, protected, eg. transparent. Then, when setting up a simulation, I want be able to set the verbosity level to 1, or 2 with the following effect: 1--> consider all transparentelements as protected 2--> consider all transparentelements as public This effect would propagate to all models and submodels. I don't think this already exists. But is there an easy workaround? Thanks, Roel A: As Michael Tiller wrote above, this is not handled the same way in all Modelica tools and there is no definite answer. To give an OpenModelica-specific answer, it's possible to use simulate(ModelName,outputFilter="regex"), to store only the variables that fully match the given regex (default is .*, matching any variable). A: Roel, I know several people wrestling with this issue. At the moment, all of this depends on the tool being used. I don't know how other tools handle filtering of results, but in Dymola you control it (as you point out) by giving the signals special qualifiers (e.g. protected). One thing I've done in the past is to extend from a model and then add a bunch of output signals for things I'm interested in. Then you can select "Outputs" in Dymola to make sure those get in the results file. This is far from perfect because a) listing everything you want can get tedious and b) referencing protected variables is not strictly allowed (although Dymola lets you get away with it but issues a warning). At Dassault, we are actively discussing this idea and hope to provide some better functionality along these lines. It isn't clear whether such functionality will be strictly tool specific or whether it will involve the language somehow. But if it is language related, we will (of course) work with the design group to formulate a specification that other tool vendors can support as well. A: In SystemModeler, you go to the Settings tab in the Experiment Browswer in Simulation Center. Click on Output on the bottom and select which variables to store. (The options are state variables, derivatives, algebraic variables, parameters, protected variables and if you mark the Store simulation log-option, you'll get some interesting statistics on events over time and function evaluations, opening another possibility to track down parts of the simulation and model that creates more evaluations) A: I am not sure if this helps you, but in Dymola you can go to Simulation->Setup->Output and mark a checkbox saying "Store Protected variables". That way it is possible to declare most variables as protected: during normal simulation they are not stored, but when debugging your model, you just mark that checkbox and they are stored. Of course that is not the same as your suggested keyword transparent, but maybe it helps a little... A: A bit late, but in Dymola 2013 FD01 and later you can select which variables to store based on names (and model names) using the annotation __Dymola_selections, and even filter on user-defined tags - so you could create a tag name "transparent" in the model. See "Matching and variable selections" in the manual.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583567", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Get other property in class of bound property If I got a nested class that I am binding to, how could I retrieve that parent class. For example, I have bound to SecondClass.ImageSource. I now want to get the information of the SecondClass when I click on the Image, how can I achieve this? I would like to change the SecondClass property, but the problem is that I have a grid of the same image items. The binding of the image works already. Xaml: <Image Source="{Binding Path=SecondClass.ImageSource}" Width="48" Height="48" MouseUp="Image_MouseUp_1" /> Code: public class FirstClass { public int number { get; set; } public SecondClass SecondClass } public class SecondClass { public ImageSource ImageSource { get; set; } } private void Image_MouseUp_1(object sender, MouseButtonEventArgs e) { FirstClass item = ???? } A: You can only bind to SecondClass.ImageSource because the DataContext of the Image is an instance of FirstClass. So in the handler you only need to cast it: private void Image_MouseUp_1(object sender, MouseButtonEventArgs e) { FirstClass item = (sender as Image).DataContext as FirstClass; //<Change item.SecondClass or do whatever you want> } A: Your Data Object either needs to know it's parent object, or you can use a RelativeSource or ElementName binding to reference a parent object. For example <Window x:Name="RootWindow" DataContext="{Binding FirstClass}"> <Grid DataContext="{Binding SecondClass.SomeProperty}"> <!-- Binding using ElementName --> <Button Context="{Binding ElementName=RootWindow, Path=DataContext.SecondClass}" /> <!-- Binding using RelativeSource --> <Button Context="{Binding RelativeSource= {RelativeSource AncestorType={x:Type Window}}, Path=DataContext.SecondClass}" /> </Grid> </Window>
{ "language": "en", "url": "https://stackoverflow.com/questions/7583568", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Position absolute or something else? Hi I want to achieve the following: The following code works but I'm not sure if position: absolute for left upper "Name" is the wise way to do it or should I use float ? Here is the html <div class="bodyframe"> <div class="upperbodyframe"> <div id="leftupperbodyframe">Name</div> <div id="rightupperbodyframe">Name 2 Name 3</div> </div> And the css ![.bodyframe { } .upperbodyframe{ } #leftupperbodyframe{ text-align:left; border: 1px solid ; position: absolute; } #rightupperbodyframe{ text-align: right; }] A: You can do this with two method. First Method .upperbodyframe{ width:100%; position:absolute; } #leftupperbodyframe{ position: absolute; left:0px; } #rightupperbodyframe{ position: absolute; right:0px; } .clear{ clear:both; } <div class="upperbodyframe"> <div id="leftupperbodyframe">Name</div> <div id="rightupperbodyframe">Name 2 Name 3</div> </div> Second Method .upperbodyframe{ width:100%; } #leftupperbodyframe{ float:left; } #rightupperbodyframe{ float:right; } .clear{ clear:both; } <div class="upperbodyframe"> <div id="leftupperbodyframe">Name</div> <div id="rightupperbodyframe">Name 2 Name 3</div> </div> Thanks,Arun Krishnan A: i would use floats here. there's really no reason for the position:absolute here as well. .upperbodyframe {overflow:hidden} /* or div will collapse with only floated elements inside */ #leftupperbodyframe {float:left; border: 1px solid ;} #rightupperbodyframe {float:right;}
{ "language": "en", "url": "https://stackoverflow.com/questions/7583569", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Export to Excel, PDF, CSV file doesn't support Arabic Language I have tomcat6 and use open report application in it. when i export any report as excel or pdf, it doesn't support arabic language. Please can anyone help me? you can find below jsp page code. <%@ taglib prefix="s" uri="/struts-tags" %> <%@ taglib uri="http://displaytag.sf.net" prefix="display" %> <%@page import="org.efs.openreports.util.DisplayProperty"%> <%@page import="org.efs.openreports.objects.Report"%> <%@page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <s:include value="Banner.jsp" /> <s:if test="report == null || !report.isDisplayInline()"> <a class="back-link img-report-small" href="reportList.action"><s:text name="link.back.reports"/></a> <a class="back-link img-group-small" href="reportGroup.action"><s:text name="link.back.groups"/></a> <br/> <s:actionerror/> <div align="center"> <div class="important img-queryreport" id="instructions"><s:property value="report.name"/></div> </div> </s:if> <div align="center"> <s:set name="results" value="results" scope="request" /> <s:set name="properties" value="properties" scope="request" /> <s:set name="report" value="report" scope="request" /> <% DisplayProperty[] displayProperties = (DisplayProperty[]) request.getAttribute("properties"); request.setCharacterEncoding("UTF-8"); Report report = (Report) request.getAttribute("report");%> <display:table name="results" class="displayTag" sort="list" export="true" pagesize="20" requestURI="queryReportResult.action?tab=PRODUCTIVITY" excludedParams="org.apache.struts.taglib.html.TOKEN"> <% for (int i=0; i < displayProperties.length; i++) { %> <display:column property="<%=displayProperties[i].getName()%>" title="<%=displayProperties[i].getDisplayName()%>" sortable="true" headerClass="sortable" /> <% } %> <display:setProperty name="export.pdf" value="true"/> <display:setProperty name="export.xml.filename" value="<%=report.getName() + ".xml"%>"/> <display:setProperty name="export.pdf.filename" value="<%=report.getName() + ".pdf"%>"/> <display:setProperty name="export.csv.filename" value="<%=report.getName() + ".csv"%>"/> <display:setProperty name="export.excel.filename" value="<%=report.getName() + ".xls"%>"/> </display:table> <s:if test="#session.user.scheduler"> <s:text name="queryReport.scheduleReport"/> <a href="reportOptions.action?reportId=<%=report.getId()%>&submitSchedule=true&exportType=3">CSV</a> | <a href="reportOptions.action?reportId=<%=report.getId()%>&submitSchedule=true&exportType=1">Excel</a> | <a href="reportOptions.action?reportId=<%=report.getId()%>&submitSchedule=true&exportType=0">PDF</a> </s:if> </div> <s:if test="report == null || !report.isDisplayInline()"> <s:include value="Footer.jsp" /> </s:if> help me quickly please... A: I got a similar issue under JBoss using Displaytag 1.2 picked from a Stripes MVC application. When the database (MySQL) was giving strings containing Scandinavian language characters encoded in UTF-8, then the CSV and Excel exporting of those tables was corrupted i.e. the downloaded file contained no data or a small amount of useless corrupted data. I think the main issue, data related, was regarding Finnish characters' encodings which are in ISO-8859-1 but not in UTF-8 (cfr. http://en.wikipedia.org/wiki/ISO/IEC_8859-1). The fix that is working for me was to: * *adding this to the Stripes Action Bean: getContext().getResponse().setCharacterEncoding("UTF-8"); getContext().getResponse().setContentType("application/vnd.ms-excel;charset=UTF-8"); *adding this to the corresponding JSP: <%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> After this I am succesfully able to download CSV and Excel files from a Displaytag table containing data encoded with UTF-8 characters from Scandinavian languages. A: After searching i found solution for this case: You should Add response.setContentType("application/vnd.ms-excel;charset=Cp1256"); instead of: request.setCharacterEncoding("UTF-8"); in <% DisplayProperty .....> line for benefit A: We are using DisplayTag 1.1.1 and we had a problem with special character encoding (UTF-8) in Excel/CSV export. After some search's we were able to fix the issue by adding BOM before export string to writeExport() in TableTag.java class. Ex: JspWriter lOut = pageContext.getOut(); ... lOut.write('\ufeff'); lOut.write(pExportString); This works well (display special characters correctly) except in xls output, all data displayed in one cell in Excel 2010 although CSV output displayed correctly. \t - TAB separator didn't work after adding BOM. But if we replace \t with Comma(,), it works as expected in Excel 2010.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583570", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Upload Video to Vimeo in Objective C on iPhone I am developing an app from which I want to upload Videos to Vimeo, Facebook and Youtube. Facebook and Youtube have pretty straightforward apis, Vimeo has a good developer documentation, but no Objective C framework. I have seen a couple of Apps which use Vimeo, so I was wondering if there is some kind of Framework out there I'm not aware of. A: #import <Foundation/Foundation.h> @protocol vimeodelagate; @interface Vimeo_uploader : NSObject<NSURLSessionDelegate, NSURLSessionTaskDelegate> @property(weak) id<vimeodelagate> delegate; +(id)SharedManger; -(void)pass_data_header:(NSData *)videoData; - (void)Give_title_to_video:(NSString *)VIdeo_id With_name:(NSString *)name ; @end @protocol vimeodelagate <NSObject> -(void)vimeouploader_succes:(NSString *)link methodName:(NSString *)methodName; -(void)vimeouploader_progress:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalByte; -(void)vimeouploader_error:(NSError *)error methodName:(NSString *)methodName; @end #define Aurtorizartion @"bearer 123456789" // replace 123456789 with your token, bearer text will be there #define accept @"application/vnd.vimeo.*+json; version=3.2" #import "Vimeo_uploader.h" @implementation Vimeo_uploader +(id)SharedManger{ static Vimeo_uploader *Vimeouploader = nil; @synchronized (self) { static dispatch_once_t oncetoken; dispatch_once(&oncetoken, ^{ Vimeouploader = [[self alloc] init]; }); } return Vimeouploader; } -(id)init{ if (self = [super init]) { } return self; } - (void)pass_data_header:(NSData *)videoData{ NSString *tmpUrl=[[NSString alloc]initWithFormat:@"https://api.vimeo.com/me/videos?type=streaming&redirect_url=&upgrade_to_1080=false"]; NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:tmpUrl] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:0]; [request setHTTPMethod:@"POST"]; [request setValue:Aurtorizartion forHTTPHeaderField:@"Authorization"]; [request setValue:accept forHTTPHeaderField:@"Accept"];//change this according to your need. NSError *error; NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: &error]; NSDictionary * json = [NSJSONSerialization JSONObjectWithData:returnData options:kNilOptions error:&error]; if (!error) { [self call_for_ticket:[json valueForKey:@"upload_link_secure"] complet_url:[json valueForKey:@"complete_uri"] videoData:videoData]; }else{ NSLog(@"RESPONSE--->%@",json); } } - (void)call_for_ticket:(NSString *)upload_url complet_url:(NSString *)complet_uri videoData:(NSData *)videoData{ NSURLSessionConfiguration *configuration; //configuration.timeoutIntervalForRequest = 5; //configuration.timeoutIntervalForResource = 5; configuration.HTTPMaximumConnectionsPerHost = 1; configuration.allowsCellularAccess = YES; // configuration.networkServiceType = NSURLNetworkServiceTypeBackground; configuration.discretionary = NO; NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:[NSOperationQueue mainQueue]]; NSURL *url = [NSURL URLWithString:upload_url]; NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url]; [urlRequest setHTTPMethod:@"PUT"]; [urlRequest setTimeoutInterval:0]; [urlRequest setValue:Aurtorizartion forHTTPHeaderField:@"Authorization"]; [urlRequest setValue:accept forHTTPHeaderField:@"Accept"]; NSError *error; NSString *str_lenth = [NSString stringWithFormat:@"%lu",(unsigned long)videoData.length]; NSDictionary *dict = @{@"str_lenth":str_lenth, @"Content-Type":@"video/mp4"}; NSData *postData12 = [NSJSONSerialization dataWithJSONObject:dict options:0 error:&error]; [urlRequest setHTTPBody:postData12]; // [urlRequest setHTTPBody:videoData]; // You could try use uploadTaskWithRequest fromData NSURLSessionUploadTask *taskUpload = [session uploadTaskWithRequest:urlRequest fromData:videoData completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { NSHTTPURLResponse *httpResp = (NSHTTPURLResponse*) response; if (!error && httpResp.statusCode == 200) { [self call_complete_uri:complet_uri]; } else { if([self.delegate respondsToSelector:@selector(vimeouploader_error:methodName:)]){ [self.delegate vimeouploader_error:error methodName:@"vimeo"];} NSLog(@"ERROR: %@ AND HTTPREST ERROR : %ld", error, (long)httpResp.statusCode); } }]; [taskUpload resume]; } -(void)call_complete_uri:(NSString *)complettion_url{ NSString *str_url =[NSString stringWithFormat:@"https://api.vimeo.com%@",complettion_url]; NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:str_url] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:0]; [request setHTTPMethod:@"DELETE"]; [request setValue:Aurtorizartion forHTTPHeaderField:@"Authorization"]; [request setValue:accept forHTTPHeaderField:@"Accept"]; //change this according to your need. [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response; if ([httpResponse statusCode] == 201) { NSDictionary *dict = [[NSDictionary alloc]initWithDictionary:[httpResponse allHeaderFields]]; if (dict) { if([self.delegate respondsToSelector:@selector(vimeouploader_succes:methodName:)]){ // [self.delegate vimeouploader_succes:[dict valueForKey:@"Location"] methodName:@"vimeo"]; NSLog(@"sucesses"); NSString *str = [NSString stringWithFormat:@"title"]; [self Give_title_to_video:[dict valueForKey:@"Location"] With_name:str]; }else{ if([self.delegate respondsToSelector:@selector(vimeouploader_error:methodName:)]){ [self.delegate vimeouploader_error:error methodName:@"vimeo"];} } } }else{ //9 if([self.delegate respondsToSelector:@selector(vimeouploader_error:methodName:)]){ [self.delegate vimeouploader_error:error methodName:@"vimeo"];} NSLog(@"%@",error.localizedDescription); } }]; } - (void)Give_title_to_video:(NSString *)VIdeo_id With_name:(NSString *)name { NSString *tmpUrl=[[NSString alloc]initWithFormat:@"https://api.vimeo.com%@",VIdeo_id]; NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:tmpUrl] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:0]; [request setHTTPMethod:@"PATCH"]; [request setValue:Aurtorizartion forHTTPHeaderField:@"Authorization"]; [request setValue:accept forHTTPHeaderField:@"Accept"];//change this according to your need. NSError *error; NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: &error]; NSDictionary * json = [NSJSONSerialization JSONObjectWithData:returnData options:kNilOptions error:&error]; NSString *str_description = @"description"; NSDictionary *dict = @{@"name":name, @"description":str_description, @"review_link":@"false" }; NSData *postData12 = [NSJSONSerialization dataWithJSONObject:dict options:0 error:&error]; [request setHTTPBody:postData12]; if (!error) { NSLog(@"RESPONSE--->%@",json); [self.delegate vimeouploader_succes:[json valueForKey:@"link"] methodName:@"vimeo"]; }else{ if([self.delegate respondsToSelector:@selector(vimeouploader_error:methodName:)]){ [self.delegate vimeouploader_error:error methodName:@"vimeo"];} //NSLog(@"%@",error.localizedDescription); NSLog(@"Give_title_to_video_error--->%@",error); } } - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend { NSLog(@"didSendBodyData: %lld, totalBytesSent: %lld, totalBytesExpectedToSend: %lld", bytesSent, totalBytesSent, totalBytesExpectedToSend); if([self.delegate respondsToSelector:@selector(vimeouploader_progress:totalBytesExpectedToSend:)]){ [self.delegate vimeouploader_progress:totalBytesSent totalBytesExpectedToSend:totalBytesExpectedToSend];} } - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error { if (error == nil) { NSLog(@"Task: %@ upload complete", task); } else { NSLog(@"Task: %@ upload with error: %@", task, [error localizedDescription]); } } @end A: The vimeo-Api is enough. Take a closer look to the vimeo-upload-api The interface can be used in any language which is able to send network-data. You have to create some NSURLConnections and you have to set the HTTP-Body like in their examples. A: I wrote AFNetworking Client for Vimeo API - https://github.com/m1entus/RWMViemoClient A: OK everybody. If you're still interested in how to upload a video to vimeo, here's the code. First you need to register an App with vimeo and obtain your secret and consumer key. Then you need to get the GTMOAuth framework from Google and possibly the SBJson framework. At the moment I unfortunately don't have the time to clean up the below code, but I thought this may be better than nothing for those, who need some help with vimeo. Essentially you authenticate with vimeo, get an upload ticket, upload the video with this ticket and then ad a title and some text. The code below won't work out of the box, because there are a couple of view elements connected, but it should give you an understanding of what is happening. #define VIMEO_SECRET @"1234567890" #define VIMEO_CONSUMER_KEY @"1234567890" #define VIMEO_BASE_URL @"http://vimeo.com/services/auth/" #define VIMEO_REQUEST_TOKEN_URL @"http://vimeo.com/oauth/request_token" #define VIMEO_AUTHORIZATION_URL @"http://vimeo.com/oauth/authorize?permission=write" #define VIMEO_ACCESS_TOKEN_URL @"http://vimeo.com/oauth/access_token" #import "MMVimeoUploaderVC.h" #import "GTMOAuthAuthentication.h" #import "GTMOAuthSignIn.h" #import "GTMOAuthViewControllerTouch.h" #import "JSON.h" @interface MMVimeoUploaderVC () @property (retain) GTMOAuthAuthentication *signedAuth; @property (retain) NSString *currentTicketID; @property (retain) NSString *currentVideoID; @property (assign) BOOL isUploading; @property (retain) GTMHTTPFetcher *currentFetcher; @end @implementation MMVimeoUploaderVC - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization first = YES; [GTMOAuthViewControllerTouch removeParamsFromKeychainForName:@"Vimeo"]; } return self; } - (void)stopUpload { if ( self.isUploading || self.currentFetcher ) { [self.currentFetcher stopFetching]; } } - (void) setProgress:(float) progress { // Connect to your views here } #pragma mark - handle error - (void) handleErrorWithText:(NSString *) text { //notify your views here self.currentFetcher = nil; self.isUploading = NO; self.progressBar.alpha = 0; self.uploadButton.alpha = 1; } #pragma mark - interface callbacks //step one, authorize - (void)startUpload { if ( self.signedAuth ) { //authentication present, start upload } else { //get vimeo authentication NSURL *requestURL = [NSURL URLWithString:VIMEO_REQUEST_TOKEN_URL]; NSURL *accessURL = [NSURL URLWithString:VIMEO_ACCESS_TOKEN_URL]; NSURL *authorizeURL = [NSURL URLWithString:VIMEO_AUTHORIZATION_URL]; NSString *scope = @""; GTMOAuthAuthentication *auth = [self vimeoAuth]; // set the callback URL to which the site should redirect, and for which // the OAuth controller should look to determine when sign-in has // finished or been canceled // // This URL does not need to be for an actual web page [auth setCallback:@"http://www.....com/OAuthCallback"]; // Display the autentication view GTMOAuthViewControllerTouch *viewController; viewController = [[[GTMOAuthViewControllerTouch alloc] initWithScope:scope language:nil requestTokenURL:requestURL authorizeTokenURL:authorizeURL accessTokenURL:accessURL authentication:auth appServiceName:@"Vimeo" delegate:self finishedSelector:@selector(viewController:finishedWithAuth:error:)] autorelease]; [[self navigationController] pushViewController:viewController animated:YES]; } } //step two get upload ticket - (void)viewController:(GTMOAuthViewControllerTouch *)viewController finishedWithAuth:(GTMOAuthAuthentication *)auth error:(NSError *)error { if (error != nil) { [self handleErrorWithText:nil]; } else { self.signedAuth = auth; [self startUpload]; } } - (void) startUpload { self.isUploading = YES; NSURL *url = [NSURL URLWithString:@"http://vimeo.com/api/rest/v2?format=json&method=vimeo.videos.upload.getQuota"]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; [self.signedAuth authorizeRequest:request]; GTMHTTPFetcher* myFetcher = [GTMHTTPFetcher fetcherWithRequest:request]; [myFetcher beginFetchWithDelegate:self didFinishSelector:@selector(myFetcher:finishedWithData:error:)]; self.currentFetcher = myFetcher; } - (void) myFetcher:(GTMHTTPFetcher *)fetcher finishedWithData:(NSData *)data error:(NSError *) error { if (error != nil) { [self handleErrorWithText:nil]; NSLog(@"error %@", error); } else { NSString *info = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]; NSDictionary *result = [info JSONValue]; //quota int quota = [[result valueForKeyPath:@"user.upload_space.max"] intValue]; //get video file size NSString *path; path = @"local video path"; NSFileManager *manager = [NSFileManager defaultManager]; NSDictionary *attrs = [manager attributesOfItemAtPath:path error: NULL]; UInt32 size = [attrs fileSize]; if ( size > quota ) { [self handleErrorWithText:@"Your Vimeo account quota is exceeded."]; return; } //lets assume we have enough quota NSURL *url = [NSURL URLWithString:@"http://vimeo.com/api/rest/v2?format=json&method=vimeo.videos.upload.getTicket&upload_method=streaming"]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; [self.signedAuth authorizeRequest:request]; GTMHTTPFetcher* myFetcher = [GTMHTTPFetcher fetcherWithRequest:request]; [myFetcher beginFetchWithDelegate:self didFinishSelector:@selector(myFetcher2:finishedWithData:error:)]; self.currentFetcher = myFetcher; } } - (void) myFetcher2:(GTMHTTPFetcher *)fetcher finishedWithData:(NSData *)data error:(NSError *) error { if (error != nil) { [self handleErrorWithText:nil]; NSLog(@"error %@", error); } else { NSString *info = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]; NSDictionary *result = [info JSONValue]; //fail here if neccessary TODO NSString *urlString = [result valueForKeyPath:@"ticket.endpoint"]; self.currentTicketID = [result valueForKeyPath:@"ticket.id"]; if ( [self.currentTicketID length] == 0 || [urlString length] == 0) { [self handleErrorWithText:nil]; return; } //get video file // load the file data NSString *path; path = [MMMovieRenderer sharedRenderer].localVideoURL; //get video file size NSFileManager *manager = [NSFileManager defaultManager]; NSDictionary *attrs = [manager attributesOfItemAtPath:path error: NULL]; UInt32 size = [attrs fileSize]; //insert endpoint here NSURL *url = [NSURL URLWithString:urlString]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; [request setHTTPMethod:@"PUT"]; [request setValue:[NSString stringWithFormat:@"%i", size] forHTTPHeaderField:@"Content-Length"]; [request setValue:@"video/mp4" forHTTPHeaderField:@"Content-Type"]; [request setHTTPBody:[NSData dataWithContentsOfFile:path]]; [self.signedAuth authorizeRequest:request]; GTMHTTPFetcher* myFetcher = [GTMHTTPFetcher fetcherWithRequest:request]; myFetcher.sentDataSelector = @selector(myFetcher:didSendBytes:totalBytesSent:totalBytesExpectedToSend:); [myFetcher beginFetchWithDelegate:self didFinishSelector:@selector(myFetcher3:finishedWithData:error:)]; self.currentFetcher = myFetcher; } } - (void)myFetcher:(GTMHTTPFetcher *)fetcher didSendBytes:(NSInteger)bytesSent totalBytesSent:(NSInteger)totalBytesSent totalBytesExpectedToSend:(NSInteger)totalBytesExpectedToSend { NSLog(@"%i / %i", totalBytesSent, totalBytesExpectedToSend); [self setProgress:(float)totalBytesSent / (float) totalBytesExpectedToSend]; self.uploadLabel.text = @"Uploading to Vimeo..."; } - (void) myFetcher3:(GTMHTTPFetcher *)fetcher finishedWithData:(NSData *)data error:(NSError *) error { if (error != nil) { [self handleErrorWithText:nil]; } else { NSString *info = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]; //finalize upload NSString *requestString = [NSString stringWithFormat:@"http://vimeo.com/api/rest/v2?format=json&method=vimeo.videos.upload.complete&ticket_id=%@&filename=%@", self.currentTicketID, @"movie.mov"]; NSURL *url = [NSURL URLWithString:requestString]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; [self.signedAuth authorizeRequest:request]; GTMHTTPFetcher* myFetcher = [GTMHTTPFetcher fetcherWithRequest:request]; [myFetcher beginFetchWithDelegate:self didFinishSelector:@selector(myFetcher4:finishedWithData:error:)]; self.currentFetcher = myFetcher; } } - (void) myFetcher4:(GTMHTTPFetcher *)fetcher finishedWithData:(NSData *)data error:(NSError *) error { if (error != nil) { [self handleErrorWithText:nil]; } else { //finish upload NSString *info = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]; NSDictionary *result = [info JSONValue]; self.currentVideoID = [result valueForKeyPath:@"ticket.video_id"]; if ( [self.currentVideoID length] == 0 ) { [self handleErrorWithText:nil]; return; } //set title NSString *title = [MMMovieSettingsManager sharedManager].movieTitle; title = [title stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]; NSString *requestString = [NSString stringWithFormat:@"http://vimeo.com/api/rest/v2?format=json&method=vimeo.videos.setTitle&video_id=%@&title=%@", self.currentVideoID, title]; NSLog(@"%@", requestString); NSURL *url = [NSURL URLWithString:requestString]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; [self.signedAuth authorizeRequest:request]; GTMHTTPFetcher* myFetcher = [GTMHTTPFetcher fetcherWithRequest:request]; [myFetcher beginFetchWithDelegate:self didFinishSelector:@selector(myFetcher5:finishedWithData:error:)]; } } - (void) myFetcher5:(GTMHTTPFetcher *)fetcher finishedWithData:(NSData *)data error:(NSError *) error { if (error != nil) { [self handleErrorWithText:nil]; NSLog(@"error %@", error); } else { //set description NSString *desc = @"Video created with ... iPhone App."; desc = [desc stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]; NSString *requestString = [NSString stringWithFormat:@"http://vimeo.com/api/rest/v2?format=json&method=vimeo.videos.setDescription&video_id=%@&description=%@", self.currentVideoID, desc]; NSURL *url = [NSURL URLWithString:requestString]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; [self.signedAuth authorizeRequest:request]; GTMHTTPFetcher* myFetcher = [GTMHTTPFetcher fetcherWithRequest:request]; [myFetcher beginFetchWithDelegate:self didFinishSelector:@selector(myFetcher6:finishedWithData:error:)]; } } - (void) myFetcher6:(GTMHTTPFetcher *)fetcher finishedWithData:(NSData *)data error:(NSError *) error { if (error != nil) { [self handleErrorWithText:nil]; NSLog(@"error %@", error); } else { //done //alert your views that the upload has been completed } } - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view from its nib. [self setProgress:0]; } - (void) viewDidDisappear:(BOOL)animated { [super viewDidDisappear:animated]; [GTMOAuthViewControllerTouch removeParamsFromKeychainForName:@"Vimeo"]; } #pragma mark - oauth stuff - (GTMOAuthAuthentication *)vimeoAuth { NSString *myConsumerKey = VIMEO_CONSUMER_KEY; // pre-registered with service NSString *myConsumerSecret = VIMEO_SECRET; // pre-assigned by service GTMOAuthAuthentication *auth; auth = [[[GTMOAuthAuthentication alloc] initWithSignatureMethod:kGTMOAuthSignatureMethodHMAC_SHA1 consumerKey:myConsumerKey privateKey:myConsumerSecret] autorelease]; // setting the service name lets us inspect the auth object later to know // what service it is for auth.serviceProvider = @"Vimeo"; return auth; } @end
{ "language": "en", "url": "https://stackoverflow.com/questions/7583573", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: what is the command object in spring framework Could you please explain about command object in spring frame work with an example? A: from Spring Documentation: * *Command Object - a JavaBean which will be populated with the data from your forms Think of Command Object as a POJO/JavaBean/etc.. that backs the form in your presentation layer. Once the form is submitted, all the individual attributes are mapped/bound to this object. On the way up to presentation, Command Object properties may be used to pre/populate the form. check an example here
{ "language": "en", "url": "https://stackoverflow.com/questions/7583577", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "44" }
Q: strtotime() converts a non existing date to another date I am building a timestamp from the date, month and year values entered by users. Suppose that the user inputs some wrong values and the date is "31-02-2012" which does not exist, then I have to get a false return. But here its converting it to another date nearby. Precisely to: "02-03-2012".. I dont want this to happen.. $str = "31-02-2012"; echo date("d-m-Y",strtotime($str)); // Outputs 02-03-2012 Can anyone help? I dont want a timestamp to be returned if the date is not original. A: You might look into checkdate. A: That's because strtotime() has troubles with - since they are used to denote phrase like -1 week, etc... Try $str = '31-02-2012'; echo date('d-m-Y', strtotime(str_replace('-', '/', $str))); However 31-02-2012 is not a valid English format, it should be 02-31-2012. If you have PHP >= 5.3, you can use createFromFormat: $str = '31-02-2012'; $d = DateTime::createFromFormat('d-m-Y', $str); echo $d->format('d-m-Y'); A: You'll have to check if the date is possible before using strtotime. Strtotime will convert it to unix date meaning it will use seconds since... This means it will always be a date. A: You can workaround this behavior <?php $str = "31-02-2012"; $unix = strtotime($str); echo date('d-m-Y', $unix); if (date('d-m-Y', $unix) != $str){ echo "wrong"; } else{ echo date("d-m-Y", $unx); } or just use checkdate() A: Use the checkdate function. $str = "31-02-2012"; $years = explode("-", $str); $valid_date = checkdate($years[1], $years[0], $years[2]); Checkdate Function - PHP Manual & Explode Function - PHP Manual A: Combine date_parse and checkdate to check if it's a valid time. <?php date_default_timezone_set('America/Chicago'); function is_valid_date($str) { $date = date_parse($str); return checkdate($date['month'], $date['day'], $date['year']); } print is_valid_date('31-02-2012') ? 'Yes' : 'No'; print "\n"; print is_valid_date('28-02-2012') ? 'Yes' : 'No'; print "\n"; Even though that date format is acceptable according to PHP date formats, it may still cause issues for date parsers because it's easy to confuse the month and day. For example, 02-03-2012, it's hard to tell if 02 is the month or the day. It's better to use the other more specific date parser examples here to first parse the date then check it with checkdate.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583579", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Convert DateString in a particular format I have a problem that I have Date String in the format "2011-09-28T10:33:53.694+0000". I want to change this Date format in MM/DD/YYYY, don't know How? Please suggest me for right result. A: Something like this. Check the details for your "from" format. DateFormat from = new SimpleDateFormat("yyyy-MM-ddThh:mm:ss"); // not sure about the details from.setLenient(false); DateFormat to = new SimpleDateFormat("MM/dd/yyyy"); to.setLenient(false); Date d = from.parse(dateStr); System.out.println(to.format(d)); A: Do it this way ----> * *Create object Date class Date date = new Date(); *Create object of Simple Date Format class SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy"); Note -> MM - will give month in character and dd and yyyy will give date and year in numeric *Convert date into string String s = sdf.format(date); and you are done with it... A: String string = "2011-09-28T10:33:53.694+0000"; SimpleDateFormat inFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.ENGLISH); SimpleDateFormat outFormat = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH); Date date; String output; try { date = inFormat.parse(string); output = outFormat.format(date); // 28/09/2011 } catch (ParseException e) { e.printStackTrace(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7583588", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I associate file types in VS Setup project with a condition? I need to ask for user's permission to change video and audio file associations on their computer, so I added a checkbox UI to the setup project in VS2010. My problem is that I don't see a condition for file type associations in the relevant editor to link to the checkbox property. Doesn't VS setup and deployment project provide this functionality? Any ideas? EDIT: It was pointed out that Visual Studio setup projects don't have an option for conditional file associations. I am now using Orca to edit the .msi tables directly. Has anyone been able to introduce conditions for file type associations by modifying the Condition table of the .msi package, or something like that? How am I supposed to do this? A: Windows Installer doesn't support conditional file associations. So a solution would be to use a custom action to create them instead of the native support. You can then condition this custom action with your checkbox property.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583590", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I determine a new Reply/Forward message's parent MailItem in an Outlook 2010 C#.NET Add-in I am trying to develop an Add-in for Outlook 2010 that allows me to tag an email using an Outlook.MailItem's UserProperties collection. The fields are loaded from a database configuration and displayed in a task pane for population by the user when composing the email. When someone with the Add-in receives the email they can open it up and view/edit the tagged values in the same task pane. I also want to populate a reply or forward message spawned from the tagged email with the current values. Unfortunately, I have found no way to determine what Outlook.MailItem the new email originated from. I tried using the newly created email passed to Reply event to find the parent, using the Parent property or GetConversation() method, both of which return null for the newly created item. So, to summarize: is there a way to determine the spawning MailItem from which a new Reply or Forward MailItem is generated? If you need any clarification on this issue, let me know. Thanks, Andrew A: I'm currently developing an add-in for Outlook 2007/2010 which makes use of one user-property. I've made the experience that a MailItem with the user property set inherits it when it is forwarded. Have you already looked for the user property/properties in the new e-mail? You can use Outlook Spy from Dmitry Streblechenko to explore them better.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583592", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Writing an encrypted mail via Exchange Web Services I would like to send an encrypted EMail Message with Exchange WEb Services using C#. Is there any possibillity? Thanks Edit: My Mail body encrypter: public static byte[] encry(string body, ContentTyp typ, string to ) { X509Certificate2 cert = GetMailCertificate(to); StringBuilder msg = new StringBuilder(); msg.AppendLine(string.Format("Content-Type: text/{0}; charset=\"iso-8859-1\"", typ.ToString())); msg.AppendLine("Content-Transfer-Encoding: 7bit"); msg.AppendLine(); msg.AppendLine(body); EnvelopedCms envelope = new EnvelopedCms(new ContentInfo(Encoding.UTF8.GetBytes(msg.ToString()))); CmsRecipient recipient = new CmsRecipient(SubjectIdentifierType.IssuerAndSerialNumber, cert); envelope.Encrypt(recipient); //System.IO.MemoryStream ms = new System.IO.MemoryStream(envelope.Encode()); return envelope.Encode(); } Main byte [] con = encrypted.encry("test", encrypted.ContentTyp.plain, "test@server.com"); EmailMessage msg1 = new EmailMessage(_server); msg1.MimeContent = new MimeContent("UTF-8", con); msg1.ToRecipients.Add("user@server.com"); msg1.InternetMessageHeaders = ?? msg1.Send(); A: If you are referring to S/Mime encryption, then you'll have to create the encrypted message according to RFC 3852 and RFC 4134. After you've done that, you can send the message. Using the EWS Managed API, this can be done as follows: var item = new EmailMessage(service); item.MimeContent = new MimeContent(Encoding.ASCII.HeaderName, content); // Set recipient infos, etc. item.Send(); EDIT: You should add the standard headers like From, To, Date, Subject, etc. And the content-type. Subject: Test From: "sender" <sender@yourcompany.com> To: "recipient" <recipient@othercompany.com> Content-Type: application/pkcs7-mime; smime-type=signed-data; name=smime.p7m Content-Transfer-Encoding: base64 Content-Disposition: attachment; filename=smime.p7m Your encrypted body goes here Just use a StringWriter put all that together. The result is your MIME body.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583596", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Start Different Keyboard for different activities My application has two requirements where one screen is an numeric entry and other has an search option. Since user has to use the numeric keyboard most of the time he has to change the input type of edit text and select the keyboard. Is there any way i could start a numeric keyboard for one activity and charater keyboard when other activty starts Sebs A: hiii,,, Use for the edit text that should open a numeric keypad with following property: android:inputType="phone" And android:imeOptions="actionSearch" for other activity Edit Text xml layout Hope you would be able to get what I mean to convey With Regards, Arpit Garg A: To just get a numeric keyboard the user should not have to longpress and choose input type. That would be only if they are trying to change which actual keyboard application they are using, for instance switching from Android Keyboard to Swype keyboard. All of the different configurations of keys are all part of each keyboard separately. So the Android keyboard contains a qwerty keyboard, a number keyboard (which has numbers across the top row and symbols on all the other keys) and a Number pad keyboard (9x9 block of numbers like the numpad on your PC, or an old telephone). To tell the system which you'd like to use you just have to specify the inputType for your EditText. this page will show you possible types this question will show you how to set it from xml
{ "language": "en", "url": "https://stackoverflow.com/questions/7583599", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Header-only linking Many C++ projects (e.g. many Boost libraries) are "header-only linked". Is this possible also in plain C? How to put the source code into headers? Are there any sites about it? A: You do not link headers. In C++ it's slightly easier to write code that's already better-off in headers than in separately-compiled modules because templates require it. 1 But you can also use the inline keyword for functions, which exists in C as well as C++. 2 // Won't cause redefinition link errors, because of 6.7.4/5 inline void foo(void) { // ... } [c99: 6.7.4/5:] A function declared with an inline function specifier is an inline function. The function specifier may appear more than once; the behavior is the same as if it appeared only once. Making a function an inline function suggests that calls to the function be as fast as possible. The extent to which such suggestions are effective is implementation-defined. You're a bit stuck when it comes to data objects, though. 1 - Sort of. 2 - C99 for sure. C89/C90 I'd have to check. A: Boost makes heavy use templates and template meta-programming which you cannot emulate (all that easily) in C. But you can of course cheat by having declarations and code in C headers which you #include but that is not the same thing. I'd say "When in Rome..." and program C as per C conventions with libraries. A: Yes, it is quite possible. Declare all functions in headers and either all as static or just use a single compilation unit (i.e. only a single c file) in your projects. As a personal anecdote, I know quite a number of physicists who insist that this technique is the only true way to program C. It is beneficial because it's the poor man's version of -fwhole-program, i.e. makes optimizations based on the knowledge of function behaviour possible. It is practical because you don't need to learn about using the linker flags. It is a bad idea because your whole program must be compiled as a whole and recompiled with each minor change. Personally, I'd recommend to let it be or at least go with static for only a few functions. A: Executive summary: You can, but you shouldn't. C and C++ code is preprocessed before it's compiled: all headers are "pasted" into the source files that include them, recursively. If you define a function in a header and it is included by two C files, you will end up with two copies in each object file (One Definition Rule violation). You can create "header-only" C libraries if all your functions are marked as static, that is, not visible outside the translation unit. But it also means you will get a copy of all the static functions in each translation unit that includes the header file. It is a bit different in C++: inline functions are not static, symbols emitted by the compiler are still visible by the linker, but the linker can discard duplicates, rather than giving up ("weak" symbols). It's not idiomatic to write C code in the headers, unless it's based on macros (e.g. queue(3)). In C++, the main reason to keep code in the headers are templates, which may result in code instantiation for different template parameters, which is not applicable to C.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583602", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Sub Process in its own Thread I'm wondering if the following class is sound. I'm using it to launch a bunch of simulators for each test in my test environment. class SubProcessInOwnThread(threading.Thread): def __init__(self, arguments, currentWorkingDirectory): self.arguments = arguments self.currentWorkingDirectory = currentWorkingDirectory threading.Thread.__init__(self) self.isTerminated = False def run(self): try: self.subProcess = subprocess.Popen(self.arguments, cwd=self.currentWorkingDirectory) self.subProcess.wait() finally: self.isTerminated = True def kill(self): while not self.isTerminated: try: self.subProcess.kill() except: time.sleep(0.1) Some senarios: # Normal subProcessThreadArguments = ["cmd.exe"] subProcessThread = SubProcessInOwnThread(subProcessThreadArguments,r"C:\\") subProcessThread.start() time.sleep(5) subProcessThread.kill() # Process killed very quickly subProcessThreadArguments = ["cmd.exe"] subProcessThread = SubProcessInOwnThread(subProcessThreadArguments,r"C:\\") subProcessThread.start() subProcessThread.kill() # Incorrect configuration subProcessThreadArguments = ["cmdsfgfg.exe"] subProcessThread = SubProcessInOwnThread(subProcessThreadArguments,r"C:\\") subProcessThread.start() time.sleep(5) subProcessThread.kill() So I can create simulators like this: subProcessThreadArguments1 = ["sim1.exe"] subProcessThread1 = SubProcessInOwnThread(subProcessThreadArguments1,r"C:\\") subProcessThread1.start() subProcessThreadArguments2 = ["sim2.exe"] subProcessThread2 = SubProcessInOwnThread(subProcessThreadArguments2,r"C:\\") subProcessThread2.start() # do test... subProcessThread1.kill() subProcessThread2.kill() I'd be interested in any improvents. Should I consider the use of the with keyword? If so, what would the benifits be? Thanks! A: I don't see the point of having a separate thread being stuck in wait() here. Working directly on the subprocess would work like class SubProcessWithoutThread(object): def __init__(self, arguments, currentWorkingDirectory): self.arguments = arguments self.currentWorkingDirectory = currentWorkingDirectory self.isTerminated = False def start(self): self.subProcess = subprocess.Popen(self.arguments, cwd=self.currentWorkingDirectory) def kill(self): while self.subProcess.poll() is None: try: self.subProcess.kill() except: time.sleep(0.1) __enter__ = start def __exit__(self, *x): self.kill() (untested) I have added the methods for a context manager, but I cannot see how that would help you as it would be quite a bunch of with statements which you would have to create, including the necessary indentation. But maybe I have got your intention wrong...
{ "language": "en", "url": "https://stackoverflow.com/questions/7583603", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: making the checkbox to display div here am trying to display divs ClinicFieldSet and HospitalFieldset by selecting the given text boxes. If both are selected, both ClinicFieldset and HospitalFieldset should display and if one of the check box is selected it should show which div is selected. The problem with my script is, when one of the checkboxes are clicked, both checkboxes are getting selected and it is not posible to uncheck them also. So please suggest me an idea to fix this problem :( I used Javascript onClick in both checkboxes to apply on both of them. <script type="text/javascript> var clinic = document.getElementById('clinic'); var visit = document.getElementById('visit'); if((clinic.checked = true) && (visit.checked = true) ) { document.getElementById('ClinicFieldSet').style.display='block'; document.getElementById('HospitalFieldSet').style.display='block'; } else if((clinic.checked = true) && (visit.checked = false)) { document.getElementById('ClinicFieldSet').style.display='block'; document.getElementById('HospitalFieldSet').style.display='none'; } else if((clinic.checked = false) && (visit.checked = true)) { document.getElementById('ClinicFieldSet').style.display='none'; document.getElementById('HospitalFieldSet').style.display='block'; } else { document.getElementById('ClinicFieldSet').style.display='none'; document.getElementById('HospitalFieldSet').style.display='none'; } HTML <input type="checkbox" name="type" id="clinic" onClick="dispp();" >Clinic Practice <input type="checkbox" name="type" id="visit" onClick="dispp();" >Visiting Hospital A: In your if statement use the == equality operator. The single = is used to assign a value, not test its equality. A: May I suggest a revised approach (not using in-line click-handlers) with a slightly amended html, just to make the JavaScript somewhat more simple: HTML: <input type="checkbox" name="type" id="clinic" /><label for="clinic">Clinic Practice</label> <input type="checkbox" name="type" id="hospital" /><label for="hospital">Visiting Hospital</label> <div id="clinicInfo"> <h2>Clinic information</h2> </div> <div id="hospitalInfo"> <h2>Hospital information</h2> </div> JavaScript: document.getElementById('hospitalInfo').style.display = 'none'; document.getElementById('clinicInfo').style.display = 'none'; var inputs = document.getElementsByTagName('input'); function dispp() { if (this.checked) { document.getElementById(this.id + 'Info').style.display = 'block'; } else { document.getElementById(this.id + 'Info').style.display = 'none'; } } for (i = 0; i < inputs.length; i++) { if (inputs[i].type.toLowerCase() == 'checkbox') { inputs[i].onchange = dispp; } } JS Fiddle demo. A: Try this if(clinic.checked == true) { document.getElementById('ClinicFieldSet').style.display='block'; } else { document.getElementById('ClinicFieldSet').style.display='none'; } if(visit.checked == true) { document.getElementById('HospitalFieldSet').style.display='block'; } else { document.getElementById('HospitalFieldSet').style.display='none'; } A: var form=document.forms.add form.elements.check.addEventListener('change',function(e) { e.preventDefault() var check=document.querySelector('.check') if(check.checked=true) { document.querySelector('.inside').style.display='block' } else{ document.querySelector('.inside').style.display='none' } })
{ "language": "en", "url": "https://stackoverflow.com/questions/7583609", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Move data from one table to another every night SQL server I have this scenario i have a staging table that contains all the record imported from a XML file .Now i want to move this data based on verification like if the record is already in the other table update the record other wise insert the new record. i want to create a job or scheduler in SQL Server that do this for me every night without using any SSIS packages. A: SSIS really is an easy way to go with something like this, but if necessary, you can set up a a SQL server agent job. Take a look at this MSDN Article. Basically, write your validation code in a stored procedure, then create a job with a TSQL job step which calls that stored procedure. A: Have you tried using the MERGE statement?
{ "language": "en", "url": "https://stackoverflow.com/questions/7583610", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Start process on Mac I want to write command in Mac equivalent to "ffmpeg -i input.avi output.avi" in Windows. My code is: Process proc = new Process { StartInfo = new ProcessStartInfo { FileName = "ffmpeg.exe", Arguments = "-i /Users/John/Desktop/input.avi /Users/John/Desktop/hhh.avi", UseShellExecute = false, RedirectStandardOutput = true, CreateNoWindow = true } }; proc.Start(); After I write "mono previousCode.exe" in the terminal in Mac, I get "filename unknown" error. Where is my mistake? A: Executables in MacOS generally don't end with a .exe suffix, so just leave off the ".exe" and see if that works. If not, you'll need to provide the full path to ffmpeg
{ "language": "en", "url": "https://stackoverflow.com/questions/7583623", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Are asynchronous RESTful web services possible? Reading RESTful documentation, it does not seem like it is possible to implement an asynchronous instance, but someone may know better on SO. What I mean here is I would like to execute service requests asynchronously: @Path("/helloworld", asyncSupported=true) public class MyHelloWorldService { ... } I know asyncSupported is not defined in @Path, but I am looking for something similar to @WebServlet. Then, I would like to use AsyncContext instances (or anything equivalent). Is this possible? A: RestEasy has some support1 for it - using a custom annotation called @Suspend. See here: http://docs.jboss.org/resteasy/docs/2.2.1.GA/userguide/html/Asynchronous_HTTP_Request_Processing.html There is also a framework/library on top of Jersey called Atmosphere however that might be overkill for your usecase as its focus appears to be on long-polling client/server web applications ( e.g. chats - https://github.com/Atmosphere/atmosphere ) [1] The CDI scope for your request will be lost in in the thread that actually executes the logic. See the RESTEasy-682 issue for more information. This is a problem that hasn't been solved by any REST frameworks that I know of at this moment[March 2014]. A: It's apparently possible with CXF and Jetty Continuations but that only appears to be possible with Jetty 6; they've been changed in Jetty 7 to something that's in the Servlet 3.0 spec and I don't know if that's supported by CXF. Moreover, Jetty Continuations seem to be a bit of a messy API, with a lot of manual stuff so I don't know how easy it is to convert the code. Still, somewhat possible it seems. With a following breeze and when God wills it. A: Restful spesification is still at early ages of its life. But this problem should be considered as 2 part. Client and Server. Client: For the client side recent changes at last year became mature enough. And recently a non blocking client from based on Jeanfrancois Arcand was implemented and pushed to repository. There is an explanation here. Server: For the server side, it is still immature. The adoption of the new servlet specification is quite slow and as a developer I am expecting JSR 339 to address these issues as well. And this is also addressed at the JSR spec clearly with these sentences. JAX-RS 1.1 defines a synchronous request response model on the server side. This JSR will specify a simple asynchronous request processing model such that a response can be returned asynchronous to the request. Servlet 3.0 can be leveraged to enable such support but implementations may choose to use other container-specific APIs instead. However there are other alternatives too. Projects such as Jetty are addressing such kind of problems elegant as in this example. I can only suggest you to consider other alternatives as the community is growing. A: Now you can make Asynchoronous RESTful calls using JAX-RS 2.0 API which is part of the recently released Java EE 7.0 http://www.slideshare.net/reza_rahman/jaxrs2?ref= A: Check out Pubsubhubbub found here for an example of a REST-based asynchronous protocol. It is based on the Atom Syndication format and is a lot simplier than WS-* pub/sub mechanisms. A: You may also want to try Spring Webflux which is async and reactive at the same time. However, this is not a JAX-RS implementation from Java EE.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583624", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: CSS animations in Opera and IE Recently I have launched CSSload.net - CSS spinners and bars generator. The animations work perfectly in Firefox and Webkit browsers. Does anyone know if there is anyway to animate elements like this in Opera and IE? A: IE10 will support CSS3 animations without prefixes so the vendor prefix for IE is not needed for any code, even for backwards compatibility, since IE9 never supported it. A: for progressive enhancement, add the real style property, example, you have -moz-transition,-webkit-transition...add transition too. for opera, add their prefix, -o- to everything that is -moz and -webkit. for ie, you can use css sandpaper, but its relying on a javascript fix http://www.useragentman.com/blog/2010/04/05/cross-browser-animated-css-transforms-even-in-ie/ if you want pure css, you could always add filters for IE http://msdn.microsoft.com/en-us/library/ms532847(v=vs.85).aspx here's a great example of adding filters for IE http://robertnyman.com/css3/css-transitions/css-transitions-mac-os-x-stacks.html i'm not sure if there is an -ms-transition. i want to say there is, but not finding anything atm
{ "language": "en", "url": "https://stackoverflow.com/questions/7583625", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is this a case for dynamic classes or ...? I'm not really sure even what to search for regarding this issue, so I figured I'd post it here. Let's say I have a bunch of interfaces like... /// <summary> /// All interesting classes will implement this interface /// </summary> interface IMasterInterface {} /// <summary> /// Interface to represent someone that creates / produces goods /// </summary> interface IProduceGoods : IMasterInterface { int Prop1 {get;} } /// <summary> /// Interface to represent someone that buys / consumes goods /// </summary> interface IConsumeGoods : IMasterInterface { int Prop2 {get;} } /// <summary> /// Interface to represent someone that stores goods /// </summary> interface IStoreGoods : IMasterInterface { double Prop3 {get;} string name {get;}} /// <summary> /// Interface to represent someone that enjoys looking at goods /// </summary> interface IEnjoyLookingAtGoods : IMasterInterface { int Prop4 {get;} DateTime Prop5 {get;} } Now, I have some combination that I know I want today, something like: /// <summary> /// Class to represent a farm which grows and stores crops /// </summary> class Farm : IProduceGoods, IStoreGoods {/*...*/} /// <summary> /// Class to represent a merchant who buys goods and stores them /// </summary> class Merchant : IConsumeGoods, IStoreGoods {/*...*/} /// <summary> /// Window Shopper represents someone who doesn't buy anything and only looks /// </summary> class WindowShopper : IEnjoyLookingAtGoods{ /*...*/ } Now I'm happy that I've got my few classes, but tomorrow, I think, wouldn't it be nice to also have a class where someone actually buys from the Merchant so I'd go to my code and add /// <summary> /// Princesses have lots of money to buy stuff and lots of time to look at stuff /// </summary> class Princess : IEnjoyLookingAtGoods, IConsumeGoods {/*...*/} Now, I don't think I should have to do that... What I would like to do is have a factory (or similar) thing and say: IMasterInterface princess = MyFactory.Create(IEnjoyLookingAtGoods, IEnjoyLookingAtGoodsParameters, IConsumeGoods, IConsumeGoodsParameters) /// This should be true ((princess is IEnjoyLookingAtGoods) && (princess is IConsumeGoods)) Essentially, I'd like to tell the factory which interfaces to use to construct the object. I have containers that have lists of IMasterInterface /// <summary> /// My container class for interesting objects /// </summary> class InterestingObjectContainer { public ReadOnlyCollection<IMasterInterface> InterestingObjects {get;} } Now, here is where the meat of the question lies. The reason for having all the interesting classes implement the IMasterInterface was to be able to have a List and use the more specific interfaces as filters. Perhaps the following will make it more clear: /// <summary> /// I want to see the net population of producers and get there total production /// </summary> class ProducerProductionCalculator { // THIS IS WHERE THE MEAT OF THE QUESTION RESIDES! ProductionResults Calculate(InterestingObjectContainer interestingObject) { List<IProduceGoods> producers = interestingObject.InterestingObjects.OfType<IProduceGoods>(); // Perhaps more interest LINQ return DoSomethingWithListToAggregate(producers); } } By filtering out to the more specific interface, I can now count on all the objects passed to DoSomethingWithListToAggregate(ICollection producers) having the methods / properties of the IProduceGoods class. I thought about implementing this with dictionaries and string property look ups, but it feels like I can write more strongly typed code this way and ensure that a simple spelling mistake somewhere is not going to mess everything up. Anyway, I guess the summary is: Is this a poor way of implementing variable properties on a object and if so what would be a better. If not, is there a way to create the objects in a factory as I have tried to explain above? EDIT: I see some oks to the idea of doing this, and that's cool. I was wondering how to create a factory that takes arguments of an interface which only has properties and the properties only have getters (I think that's an important point) along with property values for the properties and returns a object that implements the interface and has all the properties defined. For instance, /// <summary> /// Factory to create any combination of properties /// </summary> class FactoryForInterestingObjects { public static IMasterInterface Create( List<KeyValuePair</*what goes here is the interface that I want to use, what goes here are the parameter values that should be returned by the getter */>> ); } I'd pass the factory all the interfaces and their parameter values and it would create some class that implements those interfaces and has those values. Hopefully this is a little more clear? EDIT 2: How to use Decorator? From what I see about the decorator, you can extend the functionality of an object. That's cool. However, you have to know ahead of time how you are extending that functionality. You cannot do this arbitrarily. Consider that my code base is as above and I want to use decorator. I'd say: // Edited to be correct class EnjoyLookingDecorator : IEnjoyLookingAtGoods { private IMasterInterface instance; public EnjoyLookingDecorator(IMasterInterface wrappedObject) { this.instance = wrapped Object;} #region Implementation of IEnjoyLookingAtGoods /*...*/ #endregion } EDIT 4: I still don't think that'll work. In your example, I lose the contained classes interface, I have to redirect it down. For instance, class EnjoyLookingDecorator : IEnjoyLookingAtGoods { private IMasterInterface instance; public EnjoyLookingDecorator(IMasterInterface concrete) { this.instance = concrete;} #region Implementation of IEnjoyLookingAtGoods here /*...*/ #endregion bool Is<T>() //this should be in the IMasterInterface { return this is T or instance is T; } } class ConsumesGoodsDecorator : IConsumeGoods { private IMasterInterface instance; public ConsumesGoodsDecorator (IMasterInterface concrete) { this.instance = concrete;} #region Implementation of IConsumeGoods here /*...*/ #endregion bool Is<T>() { return this is T or instance is T; } } so when you d IMasterInterface princess = new MasterClass() //whatever your concrete type is named princess = new ConsumesGoodsDecorator(new EnjoyLookingDecorator(princess)) you no longer can do princess.PropertyOnIEnjoyLookingDecoratorInterface you lose all those properties. This is not what I want. The only way to preserve the properties is to redirect class ConsumesGoodsDecorator : IConsumeGoods, IEnjoyLookingAtGoods { private IMasterInterface instance; public ConsumesGoodsDecorator (IMasterInterface concrete) { this.instance = concrete;} #region Implementation of IConsumeGoods here /*...*/ #endregion #region Redirect all the IEnjoyLookingAtGoods Property Getters to instance /* ... */ #endregion bool Is<T>() { return this is T or instance is T; } } By doing the redirect, we have to implement the interface. Then the combinations have to all have code, which is what I'm trying to avoid. I don't to have constraints on the combinations of interfaces. EDIT 5: Perhaps I'm still not clear in my question. Imagine the interfaces as they are above with their properties filled in. If the factory could do something like this: /// <summary> /// Factory to create any combination of properties /// </summary> class FactoryForInterestingObjects { public static IMasterInterface Create( List<KeyValuePair<Type t, ArgSet customArguments>> interfaces)) { object baseObject; foreach(KeyValuePair<Type, ArgSet> interface in interfaces) { AddInterface(interface, object); } } private static void AddInterface(KeyValuePair<Type, ArgSet> interface, ArgSet arguments) { // Delegate this to someone else if(interface.Key is typeof(IProduceGoods)) { IProduceGoodsExtensions.AddInterface(o, interface.value); } } } public static class IProduceGoodsExtensions { public static void AddInterface(object o, ArgSet arguments) { // do something to object to make it implement IProductGoods // and make all the getters return the arguments passed in ArgSet } } I realize this is not how it will actually work, but illustrates the point I'm trying to make. I want the object to implement a dynamic combination of interfaces and have default values for the setters. Even if I could do something like have the factory write a text file containing the code: /// <summary> /// Auto Generated by Factory to create a new type on the fly /// </summary> class ClassImplementingIProduceGoodsAndIEnjoyLookingAtGoods : IProduceGoods, IEnjoyLookingAtGoods { // From IProduceGoods public int Prop1 {get; private set;} // From IEnjoyLookingAtGoods public int Prop4 {get; private set;} public DateTime Prop5 {get; private set;} public ClassImplementingIProduceGoodsAndIEnjoyLookingAtGoods(int prop1, int Prop4 , DateTime Prop5) { this.Prop1 = prop1; this.Prop4 = Prop4; this.Prop5 = Prop5; } } Then compile the class and somehow allow me to create instances of it. That's what I'm looking for. Hopefully that makes more sense. EDIT 6: This is the solution I'll probably go with since I'm not seeing an alternative at this point. //Update Master Interface interface IMasterInterface { bool Is(Type t); IMasterInterface As(Type t); } /// <summary> /// Class to build up a final object /// </summary> class CompositionObject : IMasterInterface { ICollection<IMasterInterface> parts; CompositionObject(IMasterInterface object){ parts = new List<IMasterInterface(object);} bool Is(Type t) { foreach(IMasterInterface part in parts) { if (part is t) return true; // not sure on this off top of head } return false; } IMasterInterface As(Type t) { foreach(IMasterInterface part in parts) { if(part is t) return part; } } bool Add(IMasterInterface interface) { this.Is(typeof(interface)) return false; // don't add again this.parts.Add(interface) } } Now my factory can just return these composition objects and as long as As is called, I can then downcast safely. I feel like there's probably a way to use generics to avoid the casting. Any concrete classes implementing IMasterInterface can simply return themselves when As is called. EDIT 3: Thanks to everyone for comments. I'm glad I posted my ignorance of the pattern ;D Thanks for the clarification! I love this site and all you lovely people out there!! A: Try looking into the Decorator Design Pattern. As far as I can see it is intended for the sort of case you have in mind, i.e. objects which can contain a mixed set of properties drawn from a set of properties. In the Decorator model, each property is a class of its own, and you effectively concatenate these classes dynamically to create objects with the properties you want. To implement the filtering, you'd need to have some sort of iterator to walk the chain of Decorators to see if the one you are after is included for the object you are testing. I haven't used Decorator in C#, only C++, but I have found it a very useful and flexible way forwards. If you find yourself creating more & more specialised classes which represent intersections of 'property' classes then I think Decorator may well help. See Decorator Design Pattern in C# for info on this pattern. (And buy and read the GoF Design Patterns book!) A: based on your update I see that you don't seem to understand the decorator pattern. I don't know if this is the best way to go yet, as if you don't have any difference in behaviour and your interfaces are static (IenjoyLookingAtGoods, IConsumeGoods, etc) you can go ahead and implement these with properties on your abstract type, and just create new instances by setting them. The decorators should be something like this class EnjoyLookingDecorator : IEnjoyLookingAtGoods { private IMasterInterface instance; public EnjoyLookingDecorator(IMasterInterface concrete) { this.instance = concrete;} #region Implementation of IEnjoyLookingAtGoods here /*...*/ #endregion bool Is<T>() //this should be in the IMasterInterface { return this is T || instance.Is<T>(); } } class ConsumesGoodsDecorator : IConsumeGoods { private IMasterInterface instance; public ConsumesGoodsDecorator (IMasterInterface concrete) { this.instance = concrete;} #region Implementation of IConsumeGoods here /*...*/ #endregion bool Is<T>() { return this is T || instance.Is<T>(); } } and if you want to get something that implements both you need to do something like this: IMasterInterface princess = new MasterClass() //whatever your concrete type is named princess = new ConsumesGoodsDecorator(new EnjoyLookingDecorator(princess)) var b = princess.Is<IEnjoysLookingAtGoods>() EDIT- you could hack it like this: T As<T>() { return this is T ? this : instance.As<T>(); /*be careful here, the implementation in the concrete class should return null if he is not a T*/ } /*continuing the example above*/ var consumer = princess.As<IConsumesGoods>(); //this is good var producer = princess.As<IProducesGoods>(); //this will return null but this is nasty, the most I read your question, the most seems that those interfaces make no sense. You are not adding behaviour at all. Why not have a class that implements IMasterInterface, and has 4 properties with the different interfaces (composition), if you don't want a princess to have IProduceGoods then set that as null. Still is hard to figure out without context HTH A: I don't like the IMasterInterface concept, but assuming that you're just using an abstract term for the question - I can see past that. I also have a niggling doubt about the usage in your example: IMasterInterface princess = MyFactory.Create(IEnjoyLookingAtGoods, IEnjoyLookingAtGoodsParameters, IConsumeGoods, IConsumeGoodsParameters) /// This should be true ((princess is IEnjoyLookingAtGoods) && (princess is IConsumeGoods)) Shouldn't "princess" should be "somethingthatlikestolooksandconsumegoods"? Other than that, I think the approach of filtering on the types of interface implemented is fine. A: This is a good way. And, frankly, I do not see any problems with it. Interfaces are just interfaces - they only provide a way to describe a set of common members. The problem is that your question is quite generic and it is hard to understand what you are trying to achieve. The factory method accepting interfaces is quite weird. For example we have the following code: public class A : IFoo { } public class B : IFoo { } var x = MyFactory.Create(IFoo); What would the factory create? Instance of A or B? Anyway, I think that the best advise I can come up with is: Don't overthink it. A: Answering the question abouth the factory, you could use reflection and/or the prototype pattern to accomplish, but only if the combination of interfaces is unique. If you have more than one concrete class that can satisfy the list of requested interfaces (say, classes Pricess and Prince) then the factory would have no way to know which to create. If there are no concrete classes, and you are truely trying to create/compose/etc an object at runtime then that is a horse of a different color. You would likely need a common base class (or perhaps support in your master interface) to assist with this using (as another poster suggested) a decorator approach, or perhaps using a facet-type pattern.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583632", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: prevent the execution of function from double click when on button click this function is called save_edit: function() { this.do_save(); }, I am trying to disable a button once it is clicked to prevent double clicks. How can I do it within this function? A: $("#element").dblclick(function(){ return false; }); $("#element").click(function(){ //do stuff }); A: $("#el").click(function() { $(this).prop('disabled',true); // do more stuff $(this).prop('disabled',false); // if desired }); Or, if you have several buttons: $(":button").click(function() { $(this).prop('disabled',true); // $(this) is a jQuery object of the button that was just clicked str_id = $(this).attr('id'); // if you really need the ID itself // do more stuff }); A: If you do not want to disable the button, you can stop the method from calling the function for a set peroid of time. save_edit: function() { if(this.timer)return; this.do_save(); this.timer = window.setTimeout( function(){}, 300 ); //number of ms before you want another submit to happen }, A: $("#btn").one(function(){ //do stuff once and remove handler }); $("#btn").dblclick(function(){ return false; });
{ "language": "en", "url": "https://stackoverflow.com/questions/7583635", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: need help to read file with specific formatted contents i'm using F#. I want to solve some problem that require me to read the input from a file, i don't know what to do. The first line in the file consist of three numbers, the first two numbers is the x and y for an map for the next line. The example file: 5 5 10 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 the meaning of 5 5 10 is the next line have 5x5 map and 10 is just some numbers that i need to solve the problem, the next until the end of the line is contents of the map that i have to solve using the 10 and i want to save this map numbers in 2 dimensional array. Someone can help me to write a code to save the all the numbers from the file so i can process it? * Sorry my english is bad, hope my question can be understood :) The answer for my own question : Thanks for the answer from Daniel and Ankur. For my own purpose i mix code from both of you: let readMap2 (path:string) = let lines = File.ReadAllLines path let [|x; y; n|] = lines.[0].Split() |> Array.map int let data = [| for l in (lines |> Array.toSeq |> Seq.skip 1) do yield l.Split() |> Array.map int |] x,y,n,data Many Thanks :D A: Here's some quick and dirty code. It returns a tuple of the last number in the header (10 in this case) and a two-dimensional array of the values. open System.IO let readMap (path:string) = use reader = new StreamReader(path) match reader.ReadLine() with | null -> failwith "empty file" | line -> match line.Split() with | [|_; _; _|] as hdr -> let [|x; y; n|] = hdr |> Array.map int let vals = Array2D.zeroCreate y x for i in 0..(y-1) do match reader.ReadLine() with | null -> failwith "unexpected end of file" | line -> let arr = line.Split() |> Array.map int if arr.Length <> x then failwith "wrong number of fields" else for j in 0..(x-1) do vals.[i, j] <- arr.[j] n, vals | _ -> failwith "bad header" A: In case the file is this much only (no further data to process) and always in correct format (no need to handle missing data etc) then it would be as simple as: let readMap (path:string) = let lines = File.ReadAllLines path let [|_; _; n|] = lines.[0].Split() |> Array.map int [| for l in (lines |> Array.toSeq |> Seq.skip 1) do yield l.Split() |> Array.map int |]
{ "language": "en", "url": "https://stackoverflow.com/questions/7583636", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Set lower limit of number of stars shown in RatingBar Android With the RatingBar widget in android you can set the number of stars to be show, but is there a way of setting a lower limit on the number of stars that are always active. As an example rating a film or something where you cannot submit a rating of 1? A: If this is not possible in the framework strictyl speaking, you could put a default value of 1 with android:rating set to 1, and the add a listener on the RatingBar to go back to 1 when the user tries to go lower no? A: is there a way of setting a lower limit on the number of stars that are always active. Yes you can set the Rating using setRating() method. For example: ratingBar.setRating(rat); As an example rating a film or something where you cannot submit a rating of 1? For this, you have to implement a condition inside the onRatingChanged() method. for example: ratingBar.setOnRatingBarChangeListener(new OnRatingBarChangeListener() { @Override public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) { // implement your condition here } }); A: <RatingBar android:id="@+id/ratingbar" android:layout_width="wrap_content" android:layout_height="wrap_content" android:numStars="5" android:stepSize="1.0" android:rating="1"/> By setting rating =1 it is shows rating 1. A: As mentioned by @sephy supporting his answer. I am adding a sample code which I have used in my app. mRatingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() { @Override public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) { if(selectedRating<=0) { mRatingBar.setRating(1); } } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7583637", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }