text
stringlengths
8
267k
meta
dict
Q: Fql request error? String fqlurl="https://api.facebook.com/method/fql.query?SELECT flid, owner, name friendlist WHERE owner=me()&format=json"; I made request but I don't see the result I have an error java.lang.IllegalArgumentException: Illegal character in query What's wrong here. A: you need to specify FROM ex: SELECT flid, owner, name FROM friendlist WHERE owner=me()
{ "language": "en", "url": "https://stackoverflow.com/questions/7606855", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: EJB deployment error when migrating to jboss 6.1 I am migrating from jboss 5.1 to 6.1. I have an ear which having some EJBs and a war. I am getting following error after deploying it in 6.1. 12:00:23,184 INFO [PersistenceUnitDeployment] Starting persistence unit persistence.unit:unitName=ZServer.ear/#ZPersistCtx 12:00:23,204 ERROR [AbstractKernelController] Error installing to Start: name=persistence.unit:unitName=ZServer.ear/#ZPersistCtx state=Create: java.lang.ClassCastException: org.hibernate.ejb.HibernatePersistence cannot be cast to javax.persistence.spi.PersistenceProvider at org.jboss.jpa.builder.DefaultCEMFBuilder.build(DefaultCEMFBuilder.java:46) [:1.0.2-alpha-4] at org.jboss.as.jpa.scanner.HackCEMFBuilder.build(HackCEMFBuilder.java:49) [:6.1.0.Final] at org.jboss.jpa.deployment.PersistenceUnitDeployment.start(PersistenceUnitDeployment.java:275) [:1.0.2-alpha-4] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [:1.6.0_26] . . . at org.jboss.profileservice.bootstrap.AbstractProfileServiceBootstrap.start(AbstractProfileServiceBootstrap.java:91) [:0.2.2] at org.jboss.system.server.profileservice.bootstrap.BasicProfileServiceBootstrap.start(BasicProfileServiceBootstrap.java:132) [:6.1.0.Final] at org.jboss.system.server.profileservice.bootstrap.BasicProfileServiceBootstrap.start(BasicProfileServiceBootstrap.java:56) [:6.1.0.Final] at org.jboss.bootstrap.impl.base.server.AbstractServer.startBootstraps(AbstractServer.java:827) [jboss-bootstrap-impl-base.jar:2.1.0-alpha-6] at org.jboss.bootstrap.impl.base.server.AbstractServer$StartServerTask.run(AbstractServer.java:417) [jboss-bootstrap-impl-base.jar:2.1.0-alpha-6] at java.lang.Thread.run(Thread.java:662) [:1.6.0_26] 12:00:23,442 INFO [EJBContainer] STARTED EJB: com.al.sqlgen.ejb.ResponseListnerMDBBean ejbName: ResponseListnerMDBBean 12:00:23,751 WARN [TimerServiceContainer] EJBTHREE-2193: using deprecated TimerServiceFactory for restoring timers I have following libs in ear. dohan@mypc:~/usr/local/jboss-6.1.0.Final/server/all/deploy/ZServer.ear/lib> ls antlr-2.7.6.jar flex-messaging-remoting.jar asm-attrs.jar hibernate3.jar asm.jar hibernate-annotations.jar cglib-2.1.3.jar hibernate-commons-annotations.jar commons-collections-2.1.1.jar hibernate-entitymanager.jar commons-io-1.4.jar hibernate-tools.jar commons-logging-1.1.jar HsmSEE.jar dom4j-1.6.1.jar javassist.jar ehcache-1.2.3.jar jdbc2_0-stdext.jar ejb3-persistence.2.jar jta.jar I tried changing class loading procedure as mentioned here but still getting same error. Appreciate if anyone can help me to solve this. A: I removed the jars and did the changes proposed at mastertheboss.com/hibernate/…. It is working now. Thanks!
{ "language": "en", "url": "https://stackoverflow.com/questions/7606856", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Not allowing user exit the app using Home Button In my app i do not want the user be able to exit my app on pressing the Home press key. There's a specific reason for not allowing the user to do this. Can anyone suggest what can be the correct way to achieve this? At present what i am doing is Overriding the onKeyDown()-Method. The Code for it is as follows: @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_HOME) { Intent intent = new Intent(this, LockScreen.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } return true; } In the Manifest file i am making changes as below: <activity android:name=".LockScreen" android:screenOrientation="portrait" android:theme="@android:style/Theme.NoTitleBar.Fullscreen"> <intent-filter> <category android:name="android.intent.category.HOME"/> </intent-filter> </activity> A: I agree with inazaruk but if you still want to do that then you need to override: @Override public void onAttachedToWindow() { this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD); super.onAttachedToWindow(); } A: Android doesn't support this scenario for simple apps, so you can't do this. Read this article by CommonsWare: Please ignore the Home Button. It will explain why handling Home button the way you want is not really a good idea. A: Look at this app: Kid mode. It does what you try to do, in order to prevent child to exit the app. And it does it so that, when enabled, this app becomes Home Screen application, thus controlling what happens when pressing Home screen. However, user must click to make this app be default Home screen app in order for this to work. A: Since android uses stack structure, apps are closed by clearing the stack. Each back button click clears top of stack and thats how app exits. Clicking Home abruptly closes the app but the activity still remains on top of stack. You can hit HOME button in the middle of the app and again enter your app, you can see you are still in the same activity where you were before you hit HOME.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606858", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Display image hover div at vertically middle prob all I want to display a horizontal stripe on image to vertical align. this is my code Html <div class="demobox" id="demo-5"> <img src="Untitled-1000x288.jpg" /> <div class="details"> <h3>Play Trialer</h3> </div> </div> css #demo-5 { position: relative; } .demobox { float: left; height: 288px; overflow: hidden; width: 1000px; } #demo-5:hover .details { margin-left: 0; } #demo-5 .details { left: 0; margin-left: -1200px; opacity: 0.7; filter:alpha(opacity=70); position: absolute; top: 0; } .details { background: none repeat scroll 0 0 #000000; color: #FF0000; height: 50px; margin-top: 119px; text-align: center; width: 735px; } Now problem is images are not with fixed height & width.And i want to display horizontal stripe in middle, how can i ? will greatly appreciate your help !! A: You need to set container's css position to relative and absolutelly position the title of the image inside the container. The trick is in usage of percentage vertical positioning and subtracting half of stripes height via margin-top. Quick example on jsfiddle. Edit: I badly read the question... here is the corrected answer :-)
{ "language": "en", "url": "https://stackoverflow.com/questions/7606859", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how can block sending message in an ios through programmatically? through iphone application how to blocking sms using background service running in iphone . want to listen and trigger when Message send through default message in an iphone. need to block message when we are in travel . A: You can't do this in a non-jailbroken phone. If it is possible in a jailbroken phone, I don't know how to do it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606860", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: CommunicationObjectAbortedException in WCF service channel while multiple data load I am using WCF service in my client-server application and I am facing following error while communication between server and client. Error Message =>> System.ServiceModel.CommunicationObjectAbortedException: The communication object, System.ServiceModel.Channels.ServiceChannel, cannot be used for communication because it has been Aborted. Server stack trace: at System.ServiceModel.Channels.CommunicationObject.ThrowIfDisposedOrNotOpen() at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout) at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation) at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message) Exception rethrown at [0]: at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type) at ServiceLib.ServiceCallbackInterfaces.IHostServiceCallback.SendEventAndStatus(String message, Boolean isBackupGenerated) at ServiceLib.Services.DriversService.objDriver_EventReceived(Object sender, EventReceivedEventArgs e) Application Scenario : Client is getting data from server through WCF service and using nettcp binding. Server is connected with real device and generating 20-30 events every seconds. Generated events are pushed as string message to all connected clients using callback interface of WCF. It's working fine if client have no any process load (just receive event and display). But it gives error when we do some loading process at client side and busy for some time. Note: I had already set maximum all timeouts in nettcp binding as below, but still problem not solved. NetTcpBinding tcpBinding = new NetTcpBinding(SecurityMode.None); tcpBinding.MaxBufferPoolSize = 2147483647; tcpBinding.MaxReceivedMessageSize = 2147483647; tcpBinding.MaxBufferSize = 2147483647; tcpBinding.ReaderQuotas.MaxStringContentLength = 2147483647; tcpBinding.ReaderQuotas.MaxDepth = 2147483647; tcpBinding.ReaderQuotas.MaxBytesPerRead = 2147483647; tcpBinding.ReaderQuotas.MaxNameTableCharCount = 2147483647; tcpBinding.ReaderQuotas.MaxArrayLength = 2147483647; tcpBinding.SendTimeout = TimeSpan.MaxValue; tcpBinding.ReceiveTimeout = TimeSpan.MaxValue; tcpBinding.ReliableSession.InactivityTimeout = TimeSpan.MaxValue; Please guide me is there any other settings required related to communication channel or binding ? UPDATE : Error thrown by svc tracer : <E2ETraceEvent xmlns="http://schemas.microsoft.com/2004/06/E2ETraceEvent"> <System xmlns="http://schemas.microsoft.com/2004/06/windows/eventlog/system"> <EventID>131075</EventID> <Type>3</Type> <SubType Name="Error">0</SubType> <Level>2</Level> <TimeCreated SystemTime="2011-09-30T08:37:01.5691715Z" /> <Source Name="System.ServiceModel" /> <Correlation ActivityID="{00000000-0000-0000-0000-000000000000}" /> <Execution ProcessName="ServerUtility" ProcessID="2396" ThreadID="5" /> <Channel /> <Computer>TEST</Computer> </System> <ApplicationData> <TraceData> <DataItem> <TraceRecord xmlns="http://schemas.microsoft.com/2004/10/E2ETraceEvent/TraceRecord" Severity="Error"> <TraceIdentifier>http://msdn.microsoft.com/it-IT/library/System.ServiceModel.Diagnostics.ThrowingException.aspx</TraceIdentifier> <Description>Throwing an exception.</Description> <AppDomain>ServerUtility.exe</AppDomain> <Exception> <ExceptionType>System.ServiceModel.CommunicationException, System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</ExceptionType> <Message>The socket connection was aborted. This could be caused by an error processing your message or a receive timeout being exceeded by the remote host, or an underlying network resource issue. Local socket timeout was '10675199.02:48:05.4775807'.</Message> <StackTrace> at System.ServiceModel.Channels.SocketConnection.EndRead() at System.ServiceModel.Channels.DelegatingConnection.EndRead() at System.ServiceModel.Channels.SessionConnectionReader.OnAsyncReadComplete(Object state) at System.ServiceModel.Channels.SocketConnection.FinishRead() at System.ServiceModel.Channels.SocketConnection.AsyncReadCallback(Boolean haveResult, Int32 error, Int32 bytesRead) at System.ServiceModel.Channels.OverlappedContext.CompleteCallback(UInt32 error, UInt32 numBytes, NativeOverlapped* nativeOverlapped) at System.Runtime.Fx.IOCompletionThunk.UnhandledExceptionFrame(UInt32 error, UInt32 bytesRead, NativeOverlapped* nativeOverlapped) at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP) </StackTrace> <ExceptionString>System.ServiceModel.CommunicationException: The socket connection was aborted. This could be caused by an error processing your message or a receive timeout being exceeded by the remote host, or an underlying network resource issue. Local socket timeout was '10675199.02:48:05.4775807'. ---&gt; System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host --- End of inner exception stack trace ---</ExceptionString> <InnerException> <ExceptionType>System.Net.Sockets.SocketException, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</ExceptionType> <Message>An existing connection was forcibly closed by the remote host</Message> <StackTrace> at System.ServiceModel.Channels.SocketConnection.EndRead() at System.ServiceModel.Channels.DelegatingConnection.EndRead() at System.ServiceModel.Channels.SessionConnectionReader.OnAsyncReadComplete(Object state) at System.ServiceModel.Channels.SocketConnection.FinishRead() at System.ServiceModel.Channels.SocketConnection.AsyncReadCallback(Boolean haveResult, Int32 error, Int32 bytesRead) at System.ServiceModel.Channels.OverlappedContext.CompleteCallback(UInt32 error, UInt32 numBytes, NativeOverlapped* nativeOverlapped) at System.Runtime.Fx.IOCompletionThunk.UnhandledExceptionFrame(UInt32 error, UInt32 bytesRead, NativeOverlapped* nativeOverlapped) at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP) </StackTrace> <ExceptionString>System.Net.Sockets.SocketException (0x80004005): An existing connection was forcibly closed by the remote host</ExceptionString> <NativeErrorCode>2746</NativeErrorCode> </InnerException> </Exception> </TraceRecord> </DataItem> </TraceData> <System.Diagnostics xmlns="http://schemas.microsoft.com/2004/08/System.Diagnostics"> <LogicalOperationStack></LogicalOperationStack> <Timestamp>4730654290080</Timestamp> </System.Diagnostics> </ApplicationData> </E2ETraceEvent> A: As you mentioned in your question, you have set all timeouts to maximum. So as per my opinion, there should be problem in InstanceContextMode you defined. Which mode you defined in your service ? PerSession, PerCall or Single. There might be PerCall you defined and calling service by same object (globally declared object of service) then it's possible to channel come in fault state or connection disconnected. So If you defined PerSession mode then use single object (Globally declared) from client side to get data from service. If you defined PerCall option then create new object every time. Hope this help to you. Please feel free to ask any doubt...
{ "language": "en", "url": "https://stackoverflow.com/questions/7606868", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: how to show or display the newly changed text field value instead of default value using jquery ajax method? Here is my code, This is my form part, this is basically divided into two main actions using jquery, 1) First action :, Based on Selection from :'Academic Year' selection, 'Course' selection & 'Class' selection , i used jquery ajax post method to load data from DB to All 5 set of IDs. .... Hey this part work Fine.. 2) [my probs comes here -->], Second Action :, when i select anyone of IDs, it shud show or display new value of text box instead of default value, based on data from DB by using similar ajax post method ======================================================================== <form name="aone" id="aone" action="mattendance.php" method="POST" enctype="multipart/form-data"> <div> <div style='padding-top:20px;'> Academic Year :&nbsp;&nbsp; <select name="academic" id="academic"> <option value="0"> --- Select ---- </option> <option value="1990-91">1990-91 </option> <option value="1991-92">1991-92 </option> <option value="1992-93">1992-93 </option> <option value="1993-94">1993-94 </option> <option value="1994-95">1994-95 </option> <option value="1995-96">1995-96 </option> <option value="1996-97">1996-97 </option> <option value="1997-98">1997-98 </option> <option value="1998-99">1998-99 </option> <option value="1999-00">1999-00 </option> <option value="2000-01">2000-01 </option> <option value="2001-02">2001-02 </option> <option value="2002-03">2002-03 </option> <option value="2003-04">2003-04 </option> <option value="2004-05">2004-05 </option> <option value="2005-06">2005-06 </option> <option value="2006-07">2006-07 </option> <option value="2007-08">2007-08 </option> <option value="2008-09">2008-09 </option> <option value="2009-10">2009-10 </option> <option value="2010-11">2010-11 </option> <option value="2011-12">2011-12 </option> <option value="2012-13">2012-13 </option> <option value="2013-14">2013-14 </option> <option value="2014-15">2014-15 </option> <option value="2015-16">2015-16 </option> <option value="2016-17">2016-17 </option> <option value="2017-18">2017-18 </option> <option value="2018-19">2018-19 </option> <option value="2019-20">2019-20 </option> </select> </div> <div style='padding-top:15px;'> <label>Select Course : </label> &nbsp;&nbsp;&nbsp;<input type="radio" name="course" class="course" value="SDC">SDC &nbsp;&nbsp; <input type="radio" name="course" class="course" value="GDC" checked="defaultChecked" />GDC </div> <div style='padding-top:15px;'> <label>Select Class : </label> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="checkbox" name="first" id="first" value="I Year" >I Year&nbsp;&nbsp; <input type="checkbox" name="second" id="second" value="II Year">II Year&nbsp;&nbsp; <input type="checkbox" name="third" id="third" value="III Year">III Year </div> <div style='padding-top:25px;'> <label> Date : </label>&nbsp;&nbsp;&nbsp;&nbsp; <span class="demo"> <input type="text" name="date" class="datepicker"> </span>&nbsp;&nbsp; <span> FN :&nbsp;<input type='checkbox' name='actfnone' value='0'> </span> <span > AN :&nbsp;<input type='checkbox' name='actanone' value='0'> </span> </div> <div style='padding-top:10px;'> <div style='padding-top:5px;'> ID No: 1 <span style="padding-left:10px;"> <select name="sId1" class="sId" onchange="Javascript: callone(this.options[this.selectedIndex].value);"> </select> </span><span> <input type="text" id="nameone" value=""> </span> </div> <div style='padding-top:5px;'> ID No: 2 <span style="padding-left:10px;"> <select name="sId2" class="sId" onchange="Javascript: calltwo(this.options[this.selectedIndex].value);"> </select> </span><span > <input type="text" id="nametwo" value=""> </span> </div> <div style='padding-top:5px;'> ID No: 3 <span style="padding-left:10px;"> <select name="sId3" class="sId" onchange="Javascript: callthree(this.options[this.selectedIndex].value);"> </select></span><span > <input type="text" id="namethree" value=""> </span> </div> <div style='padding-top:5px;'> ID No: 4 <span style="padding-left:10px;"> <select name="sId4" class="sId" onchange="Javascript: callfour(this.options[this.selectedIndex].value);"> </select> </span><span > <input type="text" id="namefour" value=""> </span> </div> <div style='padding-top:5px;'> ID No: 5 <span style="padding-left:10px;"> <select name="sId5" class="sId" onchange="Javascript: callfive(this.options[this.selectedIndex].value);"> </select> </span> <span > <input type="text" id="namefive" value=""> </span> </div> </div> </div> <p align="center"> <input type="submit" value="SUBMIT" onclick="javascript: return ATcheck()" > <input type="hidden" name="add" value="add" /> </p> </form> Jquery Area [Works fine] : Action Part one : <script> function popfield(acyr,crs,cls) { $.ajax({ type : "POST", url : "mattendance.php", cache: false, data : "academic="+ acyr +"&course="+ crs +"&class="+ cls, success: function(data) { $(".sId").html(data).show(); } }); } $("#aone").ready(function() { $("#academic").change(function () { var acval = $(this).find("option:selected").text(); }); $("input:radio[name=course]").click(function() { var csval = $('input[name=course]:checked', '#aone').val(); }); $("#first").click(function () { if ($("#first").is(":checked")) { var sclass = $('input[name=first]:checked').val(); $(":checkbox").click(popfield($("#academic").find("option:selected").text(),$('input[name=course]:checked', '#aone').val(),$('input[name=first]:checked').val())); } }); $("#second").click(function () { if ($("#second").is(":checked")) { var sclass = $('input[name=second]:checked').val(); $(":checkbox").click(popfield($("#academic").find("option:selected").text(),$('input[name=course]:checked', '#aone').val(),$('input[name=second]:checked').val())); } }); $("#third").click(function () { if ($("#third").is(":checked")) { var sclass = $('input[name=third]:checked').val(); $(":checkbox").click(popfield($("#academic").find("option:selected").text(),$('input[name=course]:checked', '#aone').val(),$('input[name=third]:checked').val())); } }); }); Action Part two [Problem is here] : function callone(sid) { alert('alert one :'+ sid); var dataString = "Id="+ sid ; $.ajax({ type : "POST", url : "mattendance.php", data : dataString, success: function(data) { $("#nameone").html(data); } }); } } [PHP part for Action Two :] <? // Call to Names from Ajax if($_POST["Id"]!="") { $dbselect=mysql_query("SELECT * FROM `tblNewStudent` WHERE `IdNo`='".$_POST["Id"]."' ORDER BY `SNo` ASC "); $row = mysql_fetch_object($dbselect); print $row->Name; } ?> I tried alot by seeing examples but cant able to display new value in text field n got wierd , seriously looking forward to ur best answers.. Thanks in Advance , {Raymond Herbert} A: Try using following $('#nameone').val(data); instaed of $("#nameone").html(data);
{ "language": "en", "url": "https://stackoverflow.com/questions/7606874", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Merging Solr 3.4.0 indexes using lucene Merge Tool I have three solr 3.4.0 indexes that I want to merge, after searching I've found that there are two ways to do it: * *Using Lucene Merge tool. *Merging through core admin I am using lucene 3.4.0 and running following command: java -cp d:/lucene/lucene-core-3.4.0.jar:./contrib/misc/lucene-misc-3.4.0.jarorg/apache/lucene/misc/IndexMergeTool ./newindex ./app1/solr/data/index ./app2/solr/data/index but unfortunately it gives me following exception: Exception in thread "Main Thread" java.lang.NoClassDefFoundError: org/apache/lucene/misc/IndexMergeTool Can anybody help me with this? A: Couple of things :- ./contrib/misc/lucene-misc-3.4.0.jar Are you running it from the correct directory for it to find the jar. Why not use full path ? You are using :(colon) as jar classpath separator, and using windows it should be ; (semi-colon) Also - If you already have Solr running with the Solr indexes ready, I would recommend you to use the second option - merging through Solr Admin. This is more easy to use with direct http interface without any additional overheads and would work out of the box. A: I solved this particular problem by creating a new java application in net beans 7.1 and adding both the jar files as library. and inside my new application's main method i have called IndexMergeTool.main and pass all command line arguments to above mentioned method. Regards Ahsan
{ "language": "en", "url": "https://stackoverflow.com/questions/7606883", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: window.open(URL,name,specs,replace) ?? name Vs replace If current window iswww.myparent.com by clicking a button-a, it invokes this function window.open('children','same','',??). The new page opens as www.myparent.com/children Clicking button-b, it invokes this function window.open('sub','same','',??). www.myparent.com/children is replaced by www.myparent.com/sub Now I want to know, what is the use of replace (true/false). Please take a look the syntax definition A: Actually this is the syntax window.open(URL,name,specs,replace) and this is the documentation: As you can see from the docs, replace Optional.Specifies whether the URL creates a new entry or replaces the current entry in the history list. The following values are supported: - true - URL replaces the current document in the history list - false - URL creates a new entry in the history list If you set it to true, in your history list the page that is opened in the new window replace the page you are currently browsing (I.E you will not have the page in history)
{ "language": "en", "url": "https://stackoverflow.com/questions/7606887", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Access to operation of domain service is denied although user is authorized A user of our system (Silverlight 4/WCF Ria Services) has a problem using Internet Explorer 9 and our application. Using FireFox isn´t a problem. I tried to reproduce the problem on other systems, with an equal configuration as the user´s system has, but i can´t reproduce the problem. So i think it´s a wrong configuration on the user´s system. The problem is that the access to all domain service operations is denied, although the user logged in successfully to our application. The server log contains for each operation that is called by the above user the following entry: Exception of type System.UnauthorizedAccessException logged Extended Properties: StackTrace - System.UnauthorizedAccessException: Access to operation 'xxxx' was denied. at System.ServiceModel.DomainServices.Server.DomainService.ValidateMethodCall(DomainOperationEntry domainOperationEntry, Object[] parameters, List`1 validationResults) at System.ServiceModel.DomainServices.Server.DomainService.Query(QueryDescription queryDescription, IEnumerable`1& validationErrors, Int32& totalCount) Each DomainService class is decorated with the RequiresAuthentication-Attribute. No other attributes are applied on classes or methods. We are using a custom authentication service derived from AuthenticationBase and a custom user class derived from UserBase. The user has the following programm versions: IE9 Version: 9.0.8112.16421 Silverlight Version : 4.0.60531.0 A: Ok, i found the solution. The problem was that some Internet Options of the IE 9 in the Advanced Privacy Settings were set wrong. The automatic cookie handling was overridden (CheckBox checked) and all cookies (First-party and Third-Party) were blocked. Also session cookies were denied. After disabling the override of automatic cookie handling or allowing session cookies, the user can use our application as expected in the IE 9.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606891", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I output a value to a register with a Verilog task? My understanding of Verilog tasks is that they act like subroutines and are able to accept both input and output parameters. Using $display, I can peek at the values of my register variables along the way. For some reason my output register does not seem to overwrite the argument. Here is an example: `timescale 1 ps / 1 ps `default_nettype none module testbench; reg clk; reg data_reg = 8'h00; always begin // 100MHz clock clk = 1'b1; #(5000); clk = 1'b0; #(5000); end task copy(input reg [7:0] din, output reg [7:0] dout); begin $display("copy: before: din=%h, dout=%h",din,dout); @(negedge clk); dout = din; @(negedge clk); $display("copy: after: din=%h, dout=%h",din,dout); end endtask initial begin $display("data_reg=%h",data_reg); copy(8'hBC, data_reg); $display("data_reg=%h",data_reg); copy(8'h00, data_reg); $display("data_reg=%h",data_reg); $display("done"); $finish; end endmodule And here is the output of the icarus-verilog simulator: data_reg=0 copy: before: din=bc, dout=xx copy: after: din=bc, dout=bc data_reg=0 copy: before: din=00, dout=bc copy: after: din=00, dout=00 data_reg=0 done Why doesn't the register data_reg get overwritten when the copy task is called? A: You forgot to set the width for reg data_reg so it is 1 bit wide and you happen to be assigning an even value to it so it is zero.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606892", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: WebSockets, GlassFish, Grizzly -- can't connect I am trying to get started with WebSockets, and trying to write a simple application to send messages back and forth via a websoket. However, it looks like the socket that I am trying to create never gets connected. Why can that be? Below is the code of my WebSockets class. When .onConnect() is called, it logs: I am socket, I was connected. Am i connected? - false Update: in JavaScript, where I create the socket in question, the readyState is 1, which means "socket open, communication is possble". import a.b.Misc; //writes logs. import com.sun.grizzly.websockets.BaseServerWebSocket; import com.sun.grizzly.websockets.DataFrame; import com.sun.grizzly.websockets.WebSocketListener; public class ChatWebSocket_v2 extends BaseServerWebSocket { private String user; public ChatWebSocket_v2(WebSocketListener... listeners) { super(listeners); } public String getUser() { if (user == null) { Misc.print("User is null in ChatWebSocket"); throw new NullPointerException("+=The user is null in chat web socket"); } return user; } public void setUser(String user) { Misc.print("Just set user: " + user); this.user = user; } @Override public void onMessage(String message) { Misc.print(message +"\n"); } @Override public void onMessage(byte[] message) { Misc.print(new String(message) +" << Bytes\n"); } @Override public void onConnect() { Misc.print("I am socket, i was connected. Am i connected? - " + this.isConnected()); } @Override public void onClose(DataFrame df) { Misc.print("I am socket, i was closed"); } } A: If you're just trying to make a connection somewhere, you might want to try this instead. There is a live working demo and you can download the javascript code and play with it yourself. Note that the javascript code only works if you have it installed on a server (due to browser security because it's 'fancy'.) There is also a step by step browser-based client tutorial in the works that I will post as soon as it's ready. Most proxy servers haven't been upgraded to handle websockets so they will screw up connection request and most people won't be able to connect to websocket servers from work. Firefox 7 (release) or Google Chrome 14 or later support the latest version of the websocket protocol that the demo server runs. If you want to try to get the grizzly demo working, you might have some debugging to do and maybe I'll help with that. Note that in comments below the article, other people said they couldn't get it working either and I haven't found any follow up. At this point it seems no better than the echo app above even if we do get it running and is possibly overly complicated and underly documented if you're just trying to get started. But if you want to try to get it running, you should 'git' the latest version of the code here, which was at least committed recently and may be fixed. Then make sure that app.url in the application javascript file is set to your installation directory. His is hard-coded as: url: 'ws://localhost:8080/grizzly-websockets-chat/chat', If you're using Firefox 7, the javascript needs to be modified to use the Moz prefix, for example: if (typeof MozWebSocket != "undefined") { // window.MozWebSocket or "MozWebSocket" in window ok } else if (window.WebSocket) { // he uses if ("WebSocket" in window) ok } else { do your print "browser doesn't support websockets" } .... then if the browser supports websockets websocket = new WebSocket(app.url); or websocket = new MozWebSocket(app.url); // depending on which it is. The HLL websocket server demo code has this all sorted out. (another) UPDATE: As I work through grizzly myself, I found on the Quick Start in the glassfish admin console, there's a hello sample that's pretty easy to set up and run. You'll find instructions there. The sample directory also contains a war file named: websocket-mozilla; so I guess its supposed to use websockets. Someone who's familiar with jsp should review the source code. All I can see is that it's using an http session. No mention of a websocket at all. It's a lot like the hello sample.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606895", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: UITableView got lag when scroll to larger row number I have a UITableView that each of its cell has a same-size UIImageView as contentView's subView. When I scroll it, at the beginning, it was quite smooth,but when it comes to larger row number, almost 50 row or more, the FPS become lower than 30,and the larger the row is ,the lower fps become. I checked that there is no memory leak. I‘m wondering if this is a common phenomenon? A: Most likely, you are doing something like [cellView addSubview:mySubview]; in your cellForRowAtIndexPath: method, irrespective of whether that cell was just created or re-used. The subviews are being stacked up leading to the problem that you are seeing.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606898", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Convert VARCHAR2 to TIMESTAMP in Oracle I have a VARCHAR2 value in the format '14-SEP-11 12.33.48.537150 AM' and I need to convert this to a TIMESTAMP as is. That is like, SELECT TO_DATE('14-SEP-11 12.33.48.537150 AM', '<format_string>') FROM DUAL; I want the return from the above query to be '14-SEP-11 12.33.48.537150 AM' in TIMESTAMP data format. What should be the 'format_string' for this. Please help since I tried many things but none works.. :( I am using Oracle 11gR2. Thanks. A: DATE and TIMESTAMP are two different datatypes. So you need to use the correct conversion function for each, which in your case would be TO_TIMESTAMP(). SELECT TO_TIMESTAMP('14-SEP-11 12.33.48.537150 AM', 'DD-MON-RR HH:MI:SS.FF AM') FROM DUAL; A: select from_tz(to_timestamp('14-SEP-11 12.33.48.537150 PM', 'DD-Mon-RR HH.MI.SS.FF AM'), 'EUROPE/LONDON') from dual
{ "language": "en", "url": "https://stackoverflow.com/questions/7606903", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: How can we speed-up flash builder debug launch.. other than heapsize change? Is there any configuration or method by which we can speedup debug or launch of application.. i have machine with 4 GB RAM, core i-7 processor. still it launches application from flash builder in 4 minutes. A: uncheck all the validators.. it will speed up the build process :) A: I have another optimization. Probably you don't depend on the design mode. So here is a simple trick which you can use to speed up the Flash Builder. Open the default sdk folder which you are using. (By default it's located /Applications/Adobe Flash Builder 4.5/sdks/{the default sdk 4.5.0} for Mac OS similar for windows (C:\Program Files\Adobe Flash Builder 4.5\sdks{the default sdk 4.5.0}) Then edit the file with name flex-sdk-description.xml Just change the value of the version tag to something like this 4.10.0 :) Save the file and restart the Flash Builder. After this change the builder will not use the design view. "Design View not Supported - incompatible SDK version" If you want to use it again just put the correct value i.e. 4.5.0 (Should be the same as the name of the folder in which is located the file). Best, Emil A: Here are more things that you can do to improve your (IDE) Eclipse/ Flex Builder http://www.redcodelabs.com/2012/03/eclipse-speed-up-flashbuilder/ * *Modify eclipse.ini *Create a ram disk(virtual disk) on memory,.. *Disable unneeded validators etc...
{ "language": "en", "url": "https://stackoverflow.com/questions/7606905", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Use of 'extern' keyword while defining the variable After seeing this answer I have this doubt. In my project, I have seen some extern variables declared and defined like below: file1.h extern int a; file1.c extern int a=10; But in the link I mentioned it says that in the c file it should be defined like: int a = 10; Does adding extern key word during the definition too has any purpose/meaning. Or does it matter by the way? A: It does not change the meaning. extern only makes sense when you declare a variable. Defining a variable with extern is the same because all global variables that are not marked static are symbols visible to the linker by default. Note that if you didn't want to initialise the variable, that is, not having the part = 10, the compiler will assume that extern int a is always a declaration and not a definition. In the same sense, having int a globally is always a definition and not just a declaration. A: It depends. In this case, it makes no difference, but it can. There are two issues here: definition vs. just declaration, and linkage. And C++ doesn't handle them in an orthogonal manner. In C++, the declaration of a variable or a reference is a definition if and only if neither the extern keyword nor an initialization are present. (Note that the rules are different for functions, types and templates.) So: extern int a; // not a definition int a; // definition extern int a = 42; // definition int a = 42; // definition The rules say you must have exactly one definition, so you put a definition in a source file, and the declaration in a header. With regards to linkage, a symbol declared as a variable or a reference has external linkage if it is declared at namespace scope, is not declared static, and is either not const (nor constexpr in C++11) or has been declared extern. The fact that const can give a variable internal linkage occasionally means that the extern is necessary: int const a = 42; // internal linkage extern int const a = 42; // external linkage Note that the extern doesn't have to be on the same declaration: extern int const a; // declaration, in header... int const a = 42; // external linkage, because of // previous extern Still, I've occasionally needed the extern; typically because I want to use a local constant to instantiate a template. (This is only an issue if the template parameter takes a pointer or a reference. You can instantiate a template with an int parameter with an int const a = 42;, because the template is instantiated with the value 42, and not the variable a.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7606909", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to determine the number of the input arguments in Java Is there some methods to determine the number of input arguments from console in Java. Or just compare args[i] to null? A: How about using args.length ? A: In public static void main(String[] args), args is an array. You can get the number of elements of an (any) array in Java with args.length. If there are no arguments, the array will have length 0, and args[0] will give you an ArrayIndexOutOfBoundsException. A: You could use args.length to count the arguments. You could use a library like Apache Commons CLI to parse the arguments.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606911", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: LoadKeyboardLayout() Function does not work in VB 2010 I want to change my default keyboard Layout for a installed another Keyboard Layout using my VB application.I googled about this and find Function LoadKeyboardLayout() Function to do that.But Is this support in vb 2010.When I wrote below code and there is no syntax error.But when I run the program there is an error called "PInvokeStackImbalance was detected... " How can I solve this in vb 2010. Here is my code: Private Const KLF_ACTIVATE As Long = &H1 Private Const KLF_NOTELLSHELL As Long = &H80 Private Const KLF_REORDER As Long = &H8 Private Const KLF_REPLACELANG As Long = &H10 Private Const KLF_RESET As Long = &H40000000 Private Const KLF_SETFORPROCESS As Long = &H100 Private Const KLF_SHIFTLOCK As Long = &H10000 Private Const KLF_SUBSTITUTE_OK As Long = &H2 Private Const KLF_UNLOADPREVIOUS As Long = &H4 Private Declare Function LoadKeyboardLayout _ Lib "user32.dll" _ Alias "LoadKeyboardLayoutA" ( _ ByVal pwszKLID As String, _ ByVal flags As Long) As Long 'Inside a button click event LoadKeyboardLayout("00000409", KLF_ACTIVATE) Can anyone help me... A: I think all you have to do is switch the longs to integers... Private Declare Function LoadKeyboardLayout Lib "user32.dll" _ Alias "LoadKeyboardLayoutA" ( ByVal pwszKLID As String, _ ByVal flags As Integer) As Integer
{ "language": "en", "url": "https://stackoverflow.com/questions/7606918", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why android onLongPress always is fired after onDoubleTap? I have onLongPress and onDoubleTap actions placed on the button according to this code: ... GestureDetector detector = new GestureDetector(this, new TapDetector()); public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); detector = new GestureDetector(this, new TapDetector()); ... } private class TapDetector extends GestureDetector.SimpleOnGestureListener { @Override public boolean onDoubleTap(MotionEvent e) { // Do something return true; } @Override public void onLongPress(MotionEvent e) { // Do something } } Button incomeButton = (Button) findViewById(R.id.income); button.setOnTouchListener(new OnTouchListener(){ @Override public boolean onTouch(View v, MotionEvent event) { detector.onTouchEvent(event); return true; } }); I always see onLongPress fired after onDoubleClick fired and executed. What is the reason of such counterintuitive behavior and how to avoid it? UPDATED I have changed my source code to be more specific public class MainActivity extends Activity { private GestureDetector detector; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); detector = new GestureDetector(this, new TapDetector()); Button button = (Button) findViewById(R.id.button); button.setOnTouchListener(new OnTouchListener(){ @Override public boolean onTouch(View v, MotionEvent event) { System.out.println("************* onTouch *************"); detector.onTouchEvent(event); return true; } }); } class TapDetector extends GestureDetector.SimpleOnGestureListener { @Override public void onLongPress(MotionEvent e) { System.out.println("************* onLongPress *************"); } @Override public boolean onDoubleTap(MotionEvent e) { System.out.println("************* onDoubleTap *************"); Intent intent = new Intent(); intent.setClass(getApplicationContext(), NewActivity.class); intent.putExtra("parameterName", "parameter"); startActivity(intent); return true; } } } This is a log after onDoubleTap I clicked. You can see onLongPress at the end - I never click it. I/System.out( 1106): ************* onTouch ************* I/System.out( 1106): ************* onTouch ************* I/System.out( 1106): ************* onTouch ************* I/System.out( 1106): ************* onDoubleTap ************* I/ActivityManager( 59): Starting activity: Intent { cmp=my.tapdetector/.NewActivity (has extras) } I/ActivityManager( 59): Displayed activity my.tapdetector/.NewActivity: 324 ms (total 324 ms) I/System.out( 1106): ************* onLongPress ************* UPDATE I have found the solution. To avoid onLongPress firing two changes needs to be done: First: detector.setIsLongpressEnabled(true); in onTouch(View v, MotionEvent event) button.setOnTouchListener(new OnTouchListener(){ @Override public boolean onTouch(View v, MotionEvent event) { System.out.println("************* onTouch *************"); detector.onTouchEvent(event); detector.setIsLongpressEnabled(true); return true; } }); Second: add detector.setIsLongpressEnabled(false); in onDoubleTap(MotionEvent e) public boolean onDoubleTap(MotionEvent e) { detector.setIsLongpressEnabled(false); System.out.println("************* onDoubleTap *************"); Intent intent = new Intent(); intent.setClass(getApplicationContext(), NewActivity.class); intent.putExtra("parameterName", "parameter"); startActivity(intent); return true; } A: Technically this shouldn't happen case MotionEvent.ACTION_DOWN: mLastMotionX = x; mLastMotionY = y; mCurrentDownEvent = MotionEvent.obtain(ev); mAlwaysInTapRegion = true; mInLongPress = false; if (mIsLongpressEnabled) { mHandler.removeMessages(LONG_PRESS); mHandler.sendEmptyMessageAtTime(LONG_PRESS, mCurrentDownEvent.getDownTime() + tapTime + longpressTime); } mHandler.sendEmptyMessageAtTime(SHOW_PRESS, mCurrentDownEvent.getDownTime() + tapTime); because on the ACTION_DOWN or ACTION_UP event, all of the LONG_PRESS messages events are removed from the queue. So on the second tap the following code will remove the long press events. mHandler.removeMessages(LONG_PRESS); Ninja edit : hacky workaround for your problem @Override public void onLongPress(MotionEvent e) { if(MainActivity.this.hasWindowFocus()) { Log.d("Touchy", "Long tap"); } } A: You see always the onLongPress fired because in your code you launch an intent before of consuming the onDoubleTap event. You can disable onLongPress by public void setIsLongpressEnabled (boolean isLongpressEnabled) and use the onDown method for performing your action.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606921", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: WP7 How to refresh separate Pivot Item? In wp7 i want to refresh separate pivot Item? Is Possible this? I am create 5 pivot items Dynamically . I want to refresh Each item separate . A: With WP7 there is no refresh or repaint concept. Silverlight uses retained-mode graphics, where the various UI elements are retained and managed. When you want to 'refresh' your UI, you simple have to change the properties of your UI elements. The framework takes care of reflecting this change on the screen. A: A good solution would be to data bind the content in each pivot item to a either separate view model (if you have many data items on that page) or controllable observable properties (list boxes) Then you only have to refresh either the property or viewmodel independently, this is what is done with mode data pages on a pivot control for performance (and delaying loading of data to speed up display of the pivot control page) Best thing to remember is that you are not refreshing the pivot page but the data displayed on it. If you want to dynamically control how many pivot items there are then you will have to control that programatically. A: I'm using next approach: every PivotItem is a separate UserControl, which is inherited from BaseUserControl. BaseUserControl has 2 abstract methods: OnPivotItemLoaded and OnSelected. By default, PivotItems are empty (or they can be created in runtime, like in your case). Then, when Pivot's Item is loaded (just subscribe its event), i'm calling private void PivotItemProfile_OnLoaded(object _sender, RoutedEventArgs _e) { SimpleLogger.WriteLine("Creating ProfileUserControl"); var pivotItem = _sender as PivotItem; if (pivotItem == null) return; if (pivotItem.Content == null) pivotItem.Content = new ProfileUserControl(); var item = (pivotItem.Content as BaseUserControl); if (item != null) item.OnPivotItemLoaded(); } Then, i'm also subscribed to Pivot's OnSelectionChanged event: private void PivotControl_OnSelectionChanged(object _sender, SelectionChangedEventArgs _e) { var pivotItem = MainPivot.SelectedItem as PivotItem; if (pivotItem == null) return; var item = (pivotItem.Content as BaseUserControl); if (item != null) item.OnPivotItemSelected(); } So, inside of PivotItem (UserControl) i can define, what i want to do at those events.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606924", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SQL query to match multiple values to a field in select statement I want to select distinct values of Column A where Column B = any members of a set S. Is there a way to do this directly in SQL without looping and then filtering afterwards in code? Thanks EDIT: The set S is a PHP array. Does this make a difference? A: Use the IN clause with a list of values, or a subquery (not sure if supported in MySql since I use Oracle). The match can be on more than one column. SELECT column_a FROM mytable WHERE column_b IN (1, 2, 3) SELECT column_a FROM mytable WHERE column_b IN (SELECT column_c FROM myothertable) A: SELECT DISTINCT columnA FROM yourTable WHERE columnB IN ( 'your', 'set', 'of', 'values' )
{ "language": "en", "url": "https://stackoverflow.com/questions/7606931", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to convert xml files to groovy syntax from command line is there any way to convert xml file to groovy syntax to be used in Xml MarkupBuilder? For example: the foo.xml file look like: <foo attribute1="value1" attribute2="value2"> <nestedFoo> sampleText </nestedFoo> </foo> Then execute the the command line that I'm looking for: <command line> foo.xml foo.groovy the foo.groovy will look something like this: foo(attribute1:'value1', attribute2:'value2') { nestedFoo('sampleTest') } Thank you very much. A: I came up with this: Given some example XML: def xml = """<foo attribute1="value1" attribute2="value2"> <nestedFoo> sampleText </nestedFoo> </foo>""" We can then parse it in using XmlParser, and work through the nodes, writing data to a writer def s = new XmlParser().parseText( xml ) // Closure for writing the xml to a writer as Groovy // builder style code def dumpNode dumpNode = { node, writer, indent = ' ' -> // Contents of the node, followed by the attributes def attrs = node.text()?.trim() attrs = attrs ? [ "'$attrs'" ] : [] attrs = node.attributes().inject( attrs ) { a, v -> a << "$v.key:'$v.value'" }.join( ', ' ) // write out the method definition writer << "${indent}${node.name()}( $attrs )" writer << ' {\n' node.children().each { if( it instanceof Node ) dumpNode( it, writer, " $indent" ) } writer << "$indent}\n" } def sw = new StringWriter() sw << 'println new StringWriter().with { out ->\n' sw << ' new groovy.xml.MarkupBuilder( out ).with { smb ->\n' dumpNode( s, sw ) sw << ' }\n' sw << ' out.toString()\n' sw << '}\n' println sw Running this code, prints out: println new StringWriter().with { out -> new groovy.xml.MarkupBuilder( out ).with { smb -> foo( attribute1:'value1', attribute2:'value2' ) { nestedFoo( 'sampleText' ) { } } } out.toString() } Then, if you run that in Groovy, you get: <foo attribute1='value1' attribute2='value2'> <nestedFoo>sampleText</nestedFoo> </foo>
{ "language": "en", "url": "https://stackoverflow.com/questions/7606935", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: how to make a UIAlertView to hide automatically without User Interaction? When the focus in a particluar rect of the screen , it need to show up a message and need to hide automatically . Whether alertview will be flexible or any other way is there to implement the stuffs in iPhone and iPad . A: You can use timer to close alert after some time, for example: [[NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(closeAlert:) userInfo:nil repeats:NO] retain]; For more information look here: NSTimer Class Reference A: You can dismiss the alert after displaying for some seconds. Something like this : (Dismiss after 5 seconds) UIAlertView *yourAlert = [[UIAlertView alloc]initWithTitle:@"title" message:@"message" delegate:nil cancelButtonTitle:nil otherButtonTitles:nil]; [yourAlert show]; [self performSelector:@selector(dismiss:) yourAlert afterDelay:5.0]; -(void)dismiss:(UIAlertView*)alert { [alert dismissWithClickedButtonIndex:0 animated:YES]; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7606937", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to Retrieve HTML File in mail Could any one help me out retrieving HTML file in mail? A: Your HTML should be attached to mail as attachment and your mail message should have multipart style. ten you will be able to fetch it with regular mail API.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606938", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Oracle REGEX functions I am working on Oracle 10gR2. I am working on a column which stores username. Let's say that one of the values in this column is "Ankur". I want to fetch all records where username is a concatenated string of "Ankur" followed by some numerical digits, like "Ankur1", "Ankur2", "Ankur345" and so on. I do not want to get records with values such as "Ankurab1" - that is anything which is concatenation of some characters to my input string. I tried to use REGEX functions to achieve the desired result, but am not able to. I was trying: SELECT 1 FROM dual WHERE regexp_like ('Ankur123', '^Ankur[:digit:]$'); Can anyone help me here? A: Oracle uses POSIX EREs (which don't support the common \d shorthand), so you can use ^Ankur[0-9]+$ Your version would nearly have worked, too: ^Ankur[[:digit:]]+$ One set of [...] for the character class, and one for the [:digit:] subset. And of course a + to allow more than just one digit. A: You were close Try regexp_like ('Ankur123', '^Ankur[[:digit:]]+$') instead. Note the [[ instead of the single [ and the + in front of the $. Without the + the regexp only matches for exactly one digit after the String Ankur.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606939", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can a connection be represented only by a small space in a HTTP server running on node.js? I have read that a HTTP server created in node.js does not create new threads for each incoming connection(request). Instead it executes a function that has been registered as a callback corresponding to the event of receiving a request. It is said that each connection is represented by some small space in the heap. I cannot figure this out. Are connections not represented by sockets ? Should sockets not be opened for every connection made to the node.js server and this would mean each connection cannot be represented by just a space allocation in the javascript heap ? A: It is described on the nodejs.org website that instead of spawning threads (2mb overhead per thread!) per connection, the server uses select(), epoll, kqueue or /dev/poll to wait until a socket is ready to read / write. It is this method that allows node to avoid thread spawning per connection, and the overhead is that associated with the heap allocation of the socket descriptor for the connection. This implementation detail is largely hidden from developers, and the net.socket API exposed by the runtime provides everything you need to take advantage of that feature without even thinking about it. Node also exposes its own event API through events.EventEmitter. Many node objects implement events to provide asynchronous (non-blocking) event notification, which is perfect for I/O operations, which in other languages - such as PHP - are synchronous (blocking) by default. In the case of the node net.socket API, events are triggered for several API methods dealing with socket I/O, and the callbacks that are passed by parameter to these methods are triggered when an event occurs. Events can have callback functions bound to them in a variety of different ways, accepting a callback function as a parameter is only a convenience for the developer. Finally, do not confuse OS events with nodejs events. In the case of the net API, OS events are passed to the nodejs runtime, but nodejs events are javascript. I hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606941", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to test if email is send (or received)? below is a part of a website where orders are sent to a small a computer that prints the email out directly on a receiptprinter. The problem is that sometimes (1 in 50 times) the email is never printet, even though you are send to the kvittering.php page. Any ideas of how I can make a test, that only forwards you to the kvittering.php if the email is 100% sent? Then I can eliminate the website as a source of error and focus on the printer. Any advice is welcome. <?php $headers = "From: www.testsite.dk \r\n"; $headers.= "Content-Type: text/plain; charset=iso-8859-1 "; $headers .= "Content-Transfer-Encoding: 8bit "; $body = "$name_field\nTel. $phone_field\n$email_field \nVil gerne bestille følgende:$menucard_to\nMed følgende ændringer\n $message"; header("Location: $redirect_field"); mail($to, $subject, $body, $headers); ?> <script> <!-- window.location= "kvittering.php" //--> </script> A: orders are sent to a small a computer that prints the email out directly on a recieptprinter. I'd strongly suggest you to choose one of hundreds more convenient and secure protocols, such as FTP, SSH XML-RPC, HTTP or any other. If you can't you have to: * *study the particular mailserver serviong this "small a computer" *obtain one of hundreds PHP SMTP scripts interacting with SMTP manually and use it instead of mail(). *study it's return values and check them with your sending code A: Probably, you can try embedding 1px image in e-mail and point its path to a PHP script which should trace opening an email (which means successful delivery) and deliver 1px blank PNG. You can find information on such READTAG on the net. Hope it will help you. A: Use PHPMailer class at first and connect to SMTP server some how. Maybe you can get an access to same SMTP where the printer is connected. And move header() function after mail() function. EDIT: Here is the article about redirects. A: The most basic way to check if the e-mail has been sent is just: <?php $headers = "From: www.testsite.dk\r\n"; $headers.= "Content-Type: text/plain; charset=iso-8859-1\r\n"; $headers.= "Content-Transfer-Encoding: 8bit"; $body = "$name_field\nTel. $phone_field\n$email_field \nVil gerne bestille følgende:$menucard_to\nMed følgende ændringer\n $message"; if(mail($to,$subject,$body,$headers)) { header("Location: $redirect_field"); echo' <script> <!-- window.location= "kvittering.php" //--> </script>'; } else { echo'Error...'; } ?>
{ "language": "en", "url": "https://stackoverflow.com/questions/7606944", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Behavior of a Java process in case of OutOfMemoryError What would be the behavior of a Java program on getting OutOfMemoryError. Is there any defined behavior? Will the process crash or would it go into wait/sleep state? Update: if I am not handling it in my code? A: And OutOfMemoryError is handled like any other exception: * *If it is caught, then nothing more happens. *If it is not caught, then either the threads or the threads groups uncaught exception handler handles it. This pretty much always leads to the thread being stopped. However there are two factors that are not really there in other exceptions: * *OutOfMemoryError is an Error and not an Exception. This means that it's very unlikely to be caught anywhere: You should not try to catch an Error generally (with very few exceptions) and it's not usually done, so the chances of it being handled are rather low. *When an OutOfMemoryError happens and no object become eligible for GC because of that, then you'll still have little memory left and chances are that you'll run into the exact same problem again later on. And if the thread this happens to is the only non-daemon thread (often, but not necessarily, that's the main thread, that executes the main method), then that thread getting killed results in the whole JVM shutting down (which is often perceived as "a crash"). So the tl;dr is: It will probably kill the thread, and if the memory-issue is not solved, then this can happen to more and more threads. A: You can't determine the state of program when OutOfMemoryError occurs. If you are not catching Throwable then your program will terminate with the stacktrace. Even if you are catching Throwable, you should call System.exit since there is no point in recovering from it. "Error" is generally thrown by JVM, as oppose to Exception, which is application/programmer specific. A: OutOfMemoryError should be considered unrecoverable and the behavior of the JVM after such an error has been raised is undefined, so there is no point in expending effort to handle it. Any operations done after this exception is thrown by the JVM will have undefined behavior. They may execute, but more likely they will just cause another error to be thrown.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606953", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Popup always stays on top I've WPF application which has one Main window on which I'm opening a Popup window. The problem I'm facing is the Popup window always stays on top. If I open some other application(any windows application) the main window goes into background but the Popup windows remain on top.However if I minimize the Mainwindow the Popup also minimizes. Please help on overcoming this issue. Update: I am opening the Popup as below myPopup.IsOpen = true; A: using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Windows; using System.Windows.Controls.Primitives; using System.Windows.Input; using System.Windows.Interop; /// <summary> /// Popup with code to not be the topmost control /// </summary> public class NonTopmostPopup : Popup { /// <summary> /// Is Topmost dependency property /// </summary> public static readonly DependencyProperty IsTopmostProperty = DependencyProperty.Register("IsTopmost", typeof(bool), typeof(NonTopmostPopup), new FrameworkPropertyMetadata(false, OnIsTopmostChanged)); private bool? _appliedTopMost; private bool _alreadyLoaded; private Window _parentWindow; /// <summary> /// Get/Set IsTopmost /// </summary> public bool IsTopmost { get { return (bool)GetValue(IsTopmostProperty); } set { SetValue(IsTopmostProperty, value); } } /// <summary> /// ctor /// </summary> public NonTopmostPopup() { Loaded += OnPopupLoaded; Unloaded += OnPopupUnloaded; } void OnPopupLoaded(object sender, RoutedEventArgs e) { if (_alreadyLoaded) return; _alreadyLoaded = true; if (Child != null) { Child.AddHandler(PreviewMouseLeftButtonDownEvent, new MouseButtonEventHandler(OnChildPreviewMouseLeftButtonDown), true); } _parentWindow = Window.GetWindow(this); if (_parentWindow == null) return; _parentWindow.Activated += OnParentWindowActivated; _parentWindow.Deactivated += OnParentWindowDeactivated; } private void OnPopupUnloaded(object sender, RoutedEventArgs e) { if (_parentWindow == null) return; _parentWindow.Activated -= OnParentWindowActivated; _parentWindow.Deactivated -= OnParentWindowDeactivated; } void OnParentWindowActivated(object sender, EventArgs e) { Debug.WriteLine("Parent Window Activated"); SetTopmostState(true); } void OnParentWindowDeactivated(object sender, EventArgs e) { Debug.WriteLine("Parent Window Deactivated"); if (IsTopmost == false) { SetTopmostState(IsTopmost); } } void OnChildPreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e) { Debug.WriteLine("Child Mouse Left Button Down"); SetTopmostState(true); if (!_parentWindow.IsActive && IsTopmost == false) { _parentWindow.Activate(); Debug.WriteLine("Activating Parent from child Left Button Down"); } } private static void OnIsTopmostChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e) { var thisobj = (NonTopmostPopup)obj; thisobj.SetTopmostState(thisobj.IsTopmost); } protected override void OnOpened(EventArgs e) { SetTopmostState(IsTopmost); base.OnOpened(e); } private void SetTopmostState(bool isTop) { // Don’t apply state if it’s the same as incoming state if (_appliedTopMost.HasValue && _appliedTopMost == isTop) { return; } if (Child == null) return; var hwndSource = (PresentationSource.FromVisual(Child)) as HwndSource; if (hwndSource == null) return; var hwnd = hwndSource.Handle; RECT rect; if (!GetWindowRect(hwnd, out rect)) return; Debug.WriteLine("setting z-order " + isTop); if (isTop) { SetWindowPos(hwnd, HWND_TOPMOST, rect.Left, rect.Top, (int)Width, (int)Height, TOPMOST_FLAGS); } else { // Z-Order would only get refreshed/reflected if clicking the // the titlebar (as opposed to other parts of the external // window) unless I first set the popup to HWND_BOTTOM // then HWND_TOP before HWND_NOTOPMOST SetWindowPos(hwnd, HWND_BOTTOM, rect.Left, rect.Top, (int)Width, (int)Height, TOPMOST_FLAGS); SetWindowPos(hwnd, HWND_TOP, rect.Left, rect.Top, (int)Width, (int)Height, TOPMOST_FLAGS); SetWindowPos(hwnd, HWND_NOTOPMOST, rect.Left, rect.Top, (int)Width, (int)Height, TOPMOST_FLAGS); } _appliedTopMost = isTop; } #region P/Invoke imports & definitions #pragma warning disable 1591 //Xml-doc #pragma warning disable 169 //Never used-warning // ReSharper disable InconsistentNaming // Imports etc. with their naming rules [StructLayout(LayoutKind.Sequential)] public struct RECT { public int Left; public int Top; public int Right; public int Bottom; } [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect); [DllImport("user32.dll")] private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags); static readonly IntPtr HWND_TOPMOST = new IntPtr(-1); static readonly IntPtr HWND_NOTOPMOST = new IntPtr(-2); static readonly IntPtr HWND_TOP = new IntPtr(0); static readonly IntPtr HWND_BOTTOM = new IntPtr(1); private const UInt32 SWP_NOSIZE = 0x0001; const UInt32 SWP_NOMOVE = 0x0002; const UInt32 SWP_NOZORDER = 0x0004; const UInt32 SWP_NOREDRAW = 0x0008; const UInt32 SWP_NOACTIVATE = 0x0010; const UInt32 SWP_FRAMECHANGED = 0x0020; /* The frame changed: send WM_NCCALCSIZE */ const UInt32 SWP_SHOWWINDOW = 0x0040; const UInt32 SWP_HIDEWINDOW = 0x0080; const UInt32 SWP_NOCOPYBITS = 0x0100; const UInt32 SWP_NOOWNERZORDER = 0x0200; /* Don’t do owner Z ordering */ const UInt32 SWP_NOSENDCHANGING = 0x0400; /* Don’t send WM_WINDOWPOSCHANGING */ const UInt32 TOPMOST_FLAGS = SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOSIZE | SWP_NOMOVE | SWP_NOREDRAW | SWP_NOSENDCHANGING; // ReSharper restore InconsistentNaming #pragma warning restore 1591 #pragma warning restore 169 #endregion } A: Popups do - as far as i know - not suppot such a behavior, their intended usage is for ComboxBox-dropdowns and the like as far as i can tell. To realize something like that you can use a normal Window and set its Owner to the main window on which it should be dependent. This will cause the popup-window to stay on top of its owner & to minimize together with the owner. e.g. public class ChildWindow: Window { public ChildWindow(Window owner) { this.Owner = owner; } } var popup = new ChildWindow(mainWindow); popup.Show(); (Windows cannot be re-opened once closed, so to reuse a window you just have to Hide() it when the user tries to close it (handle Closing event and cancel using event args)) A: H.B. is correct - WPF Popup control was not intended do be not top-most. On the other hand - check out the following blog post on using user32 for achieving your goal: http://chriscavanagh.wordpress.com/2008/08/13/non-topmost-wpf-popup/ A: Check the Window.Topmost property whitch is indicates that window should be always on top. PopupWindow wnd = new PopupWindow(); wnd.ShowDialog(); A: Are you creating the PopUp using the WPF control? The way this control paints popup leads to the behaviour you are describing. Consider creating a new Window showing the content you´d like to display. A: This solved my problem. PopupForm pf = new PopupForm(); pf.Owner = this; pf.Topmost = false; pf.ShowDialog() A: By default popups were designed to behaves as you comment, to be topmost always. Altering this behavior using hacks or things like that will complicate your life since you will have to lead with some other problems that for sure will arise. Anyway, too late, but may be this can help you or others: https://chriscavanagh.wordpress.com/2008/08/13/non-topmost-wpf-popup/ Note that this has some issues.... read all the comments published there. Among other issues, it makes all childs to be non-topmost so comboboxes are affected. Comboboxes will have problems with it as they rely on having a topmost popup for when they are drop down, so if you have any combobox inside your popup it will break. Also there are other problems related to the popup position, when you resize and then move the main window where the popup is it, popup remains in the same position. People there are proposing some approaches for these issues. I don't know if all are resolved but you can give it a try or try to resolve them if it is up to you. Other people trying to face with this are explaining their proposals here also (although none of them seems to be the perfect solution, it looks like there is not a perfect one, all of them have drawnbacks, but again as I have said, trying to alter the default behavior for which a thing was designed for will lead into continuous problems) : WPF Popup ZOrder A: Create your PopUp window modal to the parent control only, as demonstrated by Billy Holli and Brad Leach. That way it will stay on top of the application/window which opened the popup control, but will not stay on top of other windows/applications any longer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606954", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "21" }
Q: how Implement usercontrol in winforms mvp pattern? I want to Implement MVP pattern. I have a user control that has some Textboxes and when I put it in form I call a method from usercontrol and fill textboxes. But in mvp pattern I don't know how I can access to usercontrol1.fill(). Do you have an example that could help me? A: Here is an example implementation of the pattern. The Presenter only knows about the interface having a show method. The Presenter calls it, but the only the form (aka View) implements how the form should be displayed. public interface IMyFormView { void Show(); } public class MyForm : IMyFormView { public MyForm() { var presenter = new MyFormPresenter(this); presenter.Init(); } public void Show() { usercontrol1.fill(); } } public class MyFormPresenter { private IMyView _view; public MyFormPresenter(IMyView view) { _view = view; } public void Init() { _view.Show(); } } If you need to pass data into the view, then you can pass a view model through the Show-method or set custom Properties on the view. A: If your user control is placed into a form, and assuming that the form is a view in your project, then it is this view who has the responsibility of accessing the user control. You should not access any method of the user control directly from the presenter. In fact the presenter should not have any knowledge of the existence of those methods or even the user control. The presenter only knows of the existence of a view who implements an existing interface for that view. So, your view (the form) is the one that will know and call the method of this usercontrol. To pass values from the presenter to fill the user control placed in your form, the interface that is implemented by your view should expose a public property with the set method, (and a get method if you are planning to also read those values). As your view is implementing this interface, in the implementation of the set method of this property, you can there call any method of the user control, as the user control is included in your form and your form knows of the existence of the user control and its methods. You shouldn't have any problem accessing it from there. In the same way, if you need to read the values from the user control, this should be done in the view, on the get implementation of this property. The presenter just reads the property using the get method defined in the interface, and the view will know how to access the values and return them.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606955", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: pluginthreadasynccall hangs the browser I need to call a javascript function from my plugin. In order to do that I have spawned a thread using npnfuncs->pluginthreadasynccall(savedinstance, wcfEventForwarder, NULL). Inside wcfEventForwarder thread function, I am waiting for messages (on a POSIX message Q) which are posted by another library. My intention is to receive these messages and then pass the data (received in these messages) to Javascript. The issue is, when I am spwaing the thread using pluginthreadasynccall(...) from Invoke, the browser is hanging and I am not able to interact with the browser any more. Can you please help me with a solution? Regards, Souvik A: You have completely misunderstood the purpose of NPN_PluginThreadAsyncCall; it is not to start a new thread, but to run something on the main thread. Your wcfEventForwarder function will be called on the main thread, so if you then block it's going to hang the whole plugin. the purpose of this function call is to give you a way to trigger a call back on the main thread since other then NPN_PluginThreadAsyncCall, no NPN_ functions can be called on other threads. If you want to spawn another thread, you should do it yourself using something like boost::thread or the threading APIs directly (pick your flavor). You should also note that some of the newer browsers have apparently stopped supporting NPN_PluginThreadAsyncCall; in particular, it doesn't seem to work in Safari 5.1 on windows or mac and I've had problems with it on multiple other browsers (firefox and chrome) in certain configurations on Mac. A: Are you calling NPN_PluginThreadAsyncCall from another thread , or inside the "plug-in thread"?
{ "language": "en", "url": "https://stackoverflow.com/questions/7606956", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to use multiple database in symfony I'm creating a project in symfony, but suddenly I'm having trouble when there are two databases for my project like this: all: gapi_1: class: sfDoctrineDatabase param: dsn: mysql:host=localhost;dbname=gapi_1 username: root password: gapi_2: class: sfDoctrineDatabase param: dsn: mysql:host=localhost;dbname=gapi_2 username: root password: I'm very confused about how to access database in my action pages. Please help me to access the symfony multiple database in same action.class.php file. A: Doctrine_Manager::getInstance()->setCurrentConnection('gapi_1'); and Doctrine_Manager::getInstance()->setCurrentConnection('gapi_2'); outside of the context i think like that (not sure): $databaseManager = new sfDatabaseManager($this->configuration); $db1 = $databaseManager->getDatabase('gapi_1'); $db1->getDoctrineConnection();
{ "language": "en", "url": "https://stackoverflow.com/questions/7606958", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: The import org.ksoap2.transport.HttpTransportSE cannot be resolved I downloaded ksoap2 from this link: after importing the downloaded .jar file into an Android project in Eclipse, I got import error for only the first import line (HttpTransportSE). I searched but nobody else has had/posted this issue. How could this be? thanks! import org.ksoap2.transport.HttpTransportSE; //ERROR:The import org.ksoap2.transport.HttpTransportSE cannot be resolved import org.ksoap2.SoapEnvelope; import org.ksoap2.serialization.SoapObject; import org.ksoap2.serialization.SoapSerializationEnvelope; A: You've downloaded the J2ME package, but HttpTransportSE is part of the J2SE jar file. Shouldn't ksoap2-j2se-full-2.1.2.jar work just fine with Android? A: Use this library its specific for android and it worked for me (Ksoap2-j2se-full didn't work for me as well) http://code.google.com/p/ksoap2-android/ A: You should use ksoap2-android-assembly-2.6.3-jar-with-dependencies.jar file. visit http://code.google.com/p/ksoap2-android/wiki/HowToUse?tm=2 A: You will Have to add it to Library. (I am using Android Studio) Right click the library file in the Android Studio(shown under project_name/app/libs/ -> there will an option "Add As Library", select that Then A dialogue box will appear where you will have to Select the Module Thats IT! :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7606963", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: in atk4, how do i use ajax to update a view I currently have a page defined which displays some data in rows. At the end of each row, there is a view which shows a total which is extracted from mysql. $r->add('View_PointsLeft', 'pleft', 'pointsleft') ->setPoints($row['points_left']) ->setBacklog($row['backlog_ref']) ->setID($row['id'].'-points-left'); The view is defined with a template like this <!-- points left --> <div class='target points_left'> <div class='sticky green'> <div class='story'><?$backlog?></div> <div id='<?$name?>' class='big_points big_point_margin'><?$pointsleft?></div> </div> </div> <!-- end 0000-points-left --> The data to populate the view is selected using a sql in the page which is looped through and the /lib/view/pointsleft.php code has set methods which are passed parameters from the page and update the fields in the template. class View_PointsLeft extends View_Sticky { function init(){ parent::init(); } function setPoints($points){ $this->template->set('pointsleft',$points); return $this; } function setBacklog($backlog){ $this->template->set('backlog',$backlog); return $this; } function defaultTemplate(){ return array('view/scrumwall/pointsleft'); } } I want to update the database when something is changed on the page and also update the total view (to decrement the counter). First, I'm wondering if i have approached this the wrong way (should each view should be self contained) - should i just pass the id field to the view, attach the relevant model to the view inside lib/view/pointsleft.php and call the set fields using the model values ? Secondly, If i change it that way, does it then make it easier to update the view with a particular id when the database value is changed using ajax and if so , how do i do this ? Thirdly - if i want to also trigger an update into the database based on an action on the client side javascript, where would i put this code e.g. in the non atk4 version of my code, i had a script called using $.post("update.php") which would update mysql. Where would i put such a script in ATK4 ? Thanks in advance. Update after answer from Romans Man, ATK4 rocks ! - it does more than i expected and i was busy creating functions inside the view to populate each field name, so now having redone it using addModel, the call from the page looks like this $r->add('View_PointsLeft', 'pleft', 'pointsleft') ->loadData($row['id']); the templates/view looks like this <div id='<?$name?>' class='target points_left'> <div class='sticky green'> <div class='story'><?$backlog_ref?></div> <div class='big_points big_point_margin'><?$points_left?></div> </div> </div> and the lib/view code looks like this <?php class View_PointsLeft extends View_Sticky { function loadData($id){ $this->setModel('Story')->loadData($id); } function init(){ parent::init(); } function defaultTemplate(){ return array('view/scrumwall/pointsleft'); } } Update after code example from Romans After following the code example Romans provided, i now add the URL call using jquery selectors at the bottom of my page code and do some jiggery pokery to get the task and status from the id fields (not sure about using HTML5 only stufff using data-id so just set the normal id and extract from that). Previously the drop code was in my own univ.js script but i dont have access to the php variables from there so i move it into the page $p->js(true)->_selector('.movable')->draggable(); $p->js(true)->_selector('.target')->droppable(array( 'drop'=>$this->js(null,'function(event,ui){'. ' target=$(this).attr("id").split("-");'. ' zone=target[2];'. ' sticky=$(ui.draggable).attr("id").split("-");'. ' task=sticky[1];'. ' switch (zone) {'. ' case "verify": newStatus="V";'. ' break;'. ' case "in": newStatus="P";'. ' break;'. ' case "to": newStatus="I";'. ' break;'. ' case "done": newStatus="D";'. ' break;'. '} $.univ().ajaxec({ 0:"'.$this->api->getDestinationURL().'",'. 'task: task, status: newStatus }); } ') )); and i have a if block which looks like this in the page. I add Model_Task and load the values based on the GET parameter so i then also have more information including the story it relates to so i can also update the points if the status is now done. if($_GET['task'] && $_GET['status']) { $new_status=$_GET['status']; $task_id=$_GET['task']; $t=$p->add('Model_Task')->loadData($task_id); $old_status=$t->get('status'); $task_points=$t->get('points'); if ($new_status<>$old_status & ($new_status=='D' | $old_status=='D')) { $s=$p->add('Model_Story')->loadData($t->get('story_id')); if ($old_status='D') { $s->set('points_left',$s->get('points_left')+$task_points); } else { $s->set('points_left',$s->get('points_left')-$task_points); } $s->update(); $story=$t->get('story_id'); } $t->set('status',$new_status); $t->update(); } i can then calculate the new number of points and update the story with points left and update the task with the new_status by setting the model values and using update(). If i now move one of the draggables, it works but opens a new window showing again the whole page and reporting Error in AJAXec response: SyntaxError: syntax error I think opening the extra window is because of the error but the error is something to do with the response having all the html for the whole page. I dont actually want any reload from the ajax call unless the status is a particular one. Also the last thing i need to do is only reload one view on the page for the particular story that was updated. I've tried by creating an array and adding the short variables to it like this when the page is first loaded $this->pl_arr[$row['id']]=$r->add('View_PointsLeft', 'pleft', 'pointsleft') ->loadData($row['id']); and then in the if block while processing the GET, to recall it $pleft=$this->pl_arr[$story]; $pleft->js()->reload()->execute(); but it fails with an error Error in AJAXec response: SyntaxError: missing ; before statement Fatal error: Call to a member function js() on a non-object in C:\wamp\www\paperless\page\scrumwall.php on line 247 Final update The last error is caused because i didnt use for the id in the outer div of the whole view i wanted to update. Once i changed this it is no longer null. So the first time the page is loaded, i store all the view names in an associative array in a loop as i put them on the page $st = $p->add('Model_Story'); $result = $st->getRows(); foreach ($result as $row) { if (is_array($row)) { $r=$p->add('View_Scrumwall_StoryRow') ->setWorkspace('ws-'.$row['id']); ... other code here ... $points_left[$row['id']]=$r->add('View_PointsLeft', null, 'pointsleft') ->loadData($row['id']); } and then have the if GET block like this if($_GET['task'] && $_GET['status']) { $new_status=$_GET['status']; $task_id=$_GET['task']; $t=$p->add('Model_Task')->loadData($task_id); $old_status=$t->get('status'); $task_points=$t->get('points'); if ($new_status<>$old_status && ($new_status=='D' || $old_status=='D')) { $s=$p->add('Model_Story')->loadData($t->get('story_id')); if ($new_status=='D') { $s->set('points_left',$s->get('points_left')-$task_points); } else { $s->set('points_left',$s->get('points_left')+$task_points); } $s->update(); $story=$t->get('story_id'); //reload the points left sticky note for the story of the task $js[]=$points_left[$story]->js()->reload(); } $t->set('status',$new_status); $t->update(); $js[]=$this->js()->reload(); $this->js(null,$js)->execute(); } Note that if I only want to update one view on the page, i can just call that chaing that object with reload and execute e.g. $pl->js()->reload()->execute but if i want to update several views on the page, i need to put them in an array (here called js[]) and then call execute like this - you can also see an example of this in Roman's codepad example. $js[]=$points_left[$story]->js()->reload(); $js[]=$this->js()->reload(); $this->js(null,$js)->execute(); Problem solved with ATK4 :) A: Your structure seem to be OK. If you use setModel() on it which would have "pointsleft" and "backlog" fields, those would be automatically filled in. I don't see how setID is defined though, but you could extend setModel, call parent and then execute that too. Another thing I noticed, is in your template the most top-level div should have id=''. This gives your view unique selector which js() uses by default. The .post function you are looking for is univ()->ajaxec(). It sends data to the server, receives javascript and executes it, hence the name. It behaves similarly to the form. $mybutton->js('click')->ajaxec($this->getDestinationURL(null,array('a'=>'b')); if($_GET['a']){ // update database $r->getElement('plfat')->js()->reload()->execute(); } Usually to make your code universal, you can drop this above code inside the view, but instead of 'a' you should better use the name of the object, like this. This eliminates the need for a separate page handling update: $this->mybutton->js('click')->ajaxec($this->getDestinationURL(null, array($this->name=>'reload')); if($_GET[$this->name]){ // update database $this->js()->reload()->execute(); } Update To clarify the sequence of how it's executed: * *The page is rendered into HTML sent to your browser. *Along with the page Javascript chains are sent. All of them which define 1st argument to js, such as js(true), js('click'). in my code i have js('click') so it's sent to browser. *User performs the action such as clicking on a button. This triggers ajaxec() function *ajaxec function performs AJAX request to the page with the arguments you specify there. *PHP again is executed, but this time it goes inside if() branch. A js() without argument is created and ->execute() sends javascript to the browser. *browser receives output of the js()...->execute() and evaluates it. In our case it contains reload() for some other element. *atk4_loader widget is used to perform reload of other part of the page it sends AJAX request to server *PHP is executed with cut_object argument. It re-initializes original page, but renders only one object selectively. Output for that object is sent back to the frontend. *PHP also re-generates JS chains like in #2 but only relevant to that object *Frontend's atk4_loader receives the code, replaces HTML of the element and re-evaluates the javascript. *back to #3 It sounds like a lot of actions. In reality that's 2 requests per click and you can eliminate one if you do reload right away. Note that you can also pass arguments to reload() which you can then fetch from "get". I don't fully understand what triggers the action in your original script, perhaps we can find this out in https://chat.stackoverflow.com/rooms/2966/agile-toolkit-atk4 ? A: Ok, for a cleaner answer, I've put together a sample: http://codepad.agiletoolkit.org/dragaction.html Probably example here answers the question better. In your case, since you are working with models, it should be easier to set this up. For the performance I decided to use 2 Listers, but in theory you can also have each person and task as a view. I'm storing associations in session (through memorize) in your case you would store them in database.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606965", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to get a sortable set in hibernate We've generally been using Sets for one to many and many to many collections in hibernate. This has worked fine for until now. But now we need more and more to do in-memory sorting of child collections at the controller layer because different views need to see child collections in different orders. We can't just specify an order at the entity declaration that works for all our views. Our issue is that you cannot Collections.sort a Set, and we're afraid of wrapping our Set in a List because that could break our binding (especially in a parent child relation). So we're thinking of changing all our Set to List in the entities (without an index column), but that seems extreme and I've read of issues with bidirectional one to many and many to many list relations. Any suggestions? A: You can let your set objects implement the Comparable<> interface. In this way using the compareTo function (that you must implement) you can specify an order for your sets. Hibernate, initializing the set, will use the order specified in the compareTo function. A: Google Collections has a ImmutableSortedSet, maybe that could help. A: You can define a Formula (in criteria as well) or a SortedSet and implements the comparator. In the definition of the set you can also (in 3.3) define a order-by element (SQL). Example: Formula: Made in DBMS for a particular relation. <many-to-one name="homeAddress" class="Address" insert="false" update="false"> <column name="person_id" not-null="true" length="10"/> <formula>'ORDER BY LENGTH(homeAddress)'</formula> </many-to-one> Formula in Criteria: Made in DBMS. sortedUsers = s.createFilter( group.getUsers(), "order by this.name" ).list(); Sorted: Made in Java and application wide for a particular relation. <map name="holidays" sort="my.custom.HolidayComparator"> <key column="year_id"/> <map-key column="hol_name" type="string"/> <element column="hol_date" type="date"/> </map> Order-by clause: Made in DBMS and application wide for a particular relation. <set name="aliases" table="person_aliases" order-by="lower(name) asc"> <key column="person"/> <element column="name" type="string"/> </set> A: I thinks that sorted set can help you. For example: @OneToMany() @Sort(comparator = SomeComparator.class, type = SortType.COMPARATOR) private SortedSet<Item> items= new TreeSet<Item>(SomeComparator.instance()); Implement your own comparator and use it for sorted sets.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606966", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Will this code cause memory leak on my MVC application? public class SomeViewModel { public List<Something> listOfSomethings = new List<Something>(); public Entity EntityObj; etc... etc.. .. } public class Controller() { public SomeViewModel viewModel; public ActionResult SomeAction() { viewModel = populateViewModel(); return View(viewModel); } } The SomeViewModel is a large object that is populated in the controller's action. Will it be GC'd or cleared from memory when the controller is disposed? A: There is no point of this public SomeViewModel viewModel; field in your controller. Controller actions are independant meaning that if you first invoke SomeAction which sets a value for this field and then invoke some other action do not expect this field to survive. So you should simply use this: public class HomeController: Controller { public ActionResult SomeAction() { var viewModel = populateViewModel(); return View(viewModel); } public ActionResult SomeOtherAction() { var viewModel = populateViewModel(); return View(viewModel); } } This being said your current code doesn't seem to have memory leaks because once the request ends the Controller class will be eligible for GC and so all its instance fields including the view model. A: if populateViewModel method does not use disaposable resources (as data context) or uses and disposes them, your code should be fine.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606968", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: encrypting an object in javascript var Obj = {}; Obj.ID = e.row.ID; Obj.firstName = e.row.firstName; Obj.lastName = e.row.lastName; This is my object, and i save this object in a file. now before saving into file, i want to encrypt it and save and while reading i want to decrypt and read. var newFile = FileSystemPath; newFile.write(JSON.stringify(object)); * *Should i encrypt the object before stringifying it or after it. *What are the ways to encrypt an object in javascript. Any examples would be great. A: You can't really encrypt objects, but you can encrypt strings, so you should probably first do a object serialization (JSON.stringify) and then encrypt it with a symmetric encryption algorithm so you would be able to decode the object later. I can't really provide a good example, because javascript will always have serious security problems (being a client-side programming language), and even if you try a rather complex algorithm (such as AES) it will still be vulnerable, because the user can just see your source code, thus see your encription/decription algorithms. If you just want to alter the string a bit so it can't be deciphered on the first look, you can simply use some built-in javascript methods (such as encodeURI/decodeURI) or you can do some character replacements or even use salts. Here's a sample demo of how you can "encrypt" an object : function encrypt(o, salt) { o = JSON.stringify(o).split(''); for(var i = 0, l = o.length; i < l; i++) if(o[i] == '{') o[i] = '}'; else if(o[i] == '}') o[i] = '{'; return encodeURI(salt + o.join('')); } function decrypt(o, salt) { o = decodeURI(o); if(salt && o.indexOf(salt) != 0) throw new Error('object cannot be decrypted'); o = o.substring(salt.length).split(''); for(var i = 0, l = o.length; i < l; i++) if(o[i] == '{') o[i] = '}'; else if(o[i] == '}') o[i] = '{'; return JSON.parse(o.join('')); } var obj = { key : 'value', 3 : 1 }; var salt = "some string here"; var encrypted = encrypt(obj, salt); var decrypted = decrypt(encripted, salt); Of course, this is just an example and you should modify it in order to encrypt more complex objects, where you need to encrypt functions, or where the object has circular references.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606970", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Measuring Site Load Times via performance api I listened to a talk by Steve Souders a few days ago and he mentioned the new performance spec that newer browsers are implementing and it was pretty intriguing. In his speech he mentioned the following example as a means of measuring perceived page load time: var timing = performance.timing; var loadtime = timing.loadEventEnd - timing.navigationStart; alert("Perceived time:"+loadtime); Clearly this is a basic example, but when trying it on my development environment, I get crazy numbers like -1238981729837 as the answer because loadEventEnd is < 0. Obviously something is amiss and there are many improvements that can be made to this example to give more information and produce a greater reliability. (I am aware this is only implemented in a few browsers). So, what are some suggestions on how to use this api to track page load times via Javascript for analysis of my site performance? A: I have had no trouble using it, but I haven't tried measuring performance on a local machine- it works fine on a website. It is interesting to look at other sites, to have something to compare your numbers with. for instance, these are good numbers for the size of the pages and their resources- http://stackoverflow.com/questions/7606972/measuring-site-load-times- Friday, September 30, 2011 4:03:52 AM // (timestamp:1317369511747) navigationStart= 0 milliseconds elapsed // fetchStart= 0 domainLookupStart= 0 domainLookupEnd= 0 requestStart= 0 // responseStart= 359 responseEnd= 359 domLoading= 359 // unloadEventStart= 375 unloadEventEnd= 375 // domInteractive= 515 domContentLoadedEventStart= 515 // domContentLoadedEventEnd= 531 // domComplete= 2496 loadEventStart= 2496 // (timestamp:1317369514243) loadEventEnd= 2496 milliseconds elapsed http://www.yankeeweb.com/webshop.html Friday, September 30, 2011 4:22:25 AM // (timestamp:1317370911738) navigationStart= 0 milliseconds elapsed // fetchStart= 0 domainLookupStart= 0 // domainLookupEnd= 281 connectStart= 281 // connectEnd= 296 requestStart= 296 // responseStart= 546 // responseEnd= 562 domLoading= 562 // domInteractive= 1264 domContentLoadedEventStart= 1264 domContentLoadedEventEnd= 1264 // domComplete= 1622 loadEventStart= 1622 // (timestamp:1317370913360) loadEventEnd= 1622 milliseconds elapsed What you really need are the numbers other people get when visiting your site- you could include it in a form questionaire or mailing, (from firefox 7 and chrome, so far.) // code run in firefox scratchpad: (function(){ if(!window.performance || !performance.timing) return; var timestamp, first, hstr, L, ptA= ['navigationStart', 'unloadEventStart', 'unloadEventEnd', 'redirectStart', 'redirectEnd', 'fetchStart', 'domainLookupStart', 'domainLookupEnd', 'connectStart', 'connectEnd', 'secureConnectionStart', 'requestStart', 'responseStart', 'responseEnd', 'domLoading', 'domInteractive', 'domContentLoadedEventStart', 'domContentLoadedEventEnd', 'domComplete', 'loadEventStart', 'loadEventEnd'].map(function(itm){ timestamp= performance.timing[itm]; if(isFinite(timestamp) && timestamp!== 0){ if(!first) first= timestamp; return [itm, timestamp, timestamp-first]; } else return [1, NaN]; }).filter(function(itm){ return !isNaN(itm[1]); }); ptA= ptA.sort(function(a, b){ return a[1]-b[1]; }); if(report=== 1) return ptA; L= ptA.length-1; ptA= ptA.map(function(itm, i){ if(i> 0 && ptA[i-1][2]!== itm[2]) itm[0]= '//\n'+itm[0]; if(i=== 0 || i=== L){ itm[0]= '//\n(timestamp:'+itm[1]+ ')\n'+itm[0]; itm[2]+= ' milliseconds elapsed \n'; } return itm[0]+'= '+itm[2]; }); hstr= '\n'+location.href+'\n'+ new Date().toLocaleString()+'\n'; return hstr+ptA.join('\n'); })() A: Good answer from Ionut Popa. crazy numbers like -1238981729837 as the answer because loadEventEnd is < 0 loadEventEnd is not less than zero, it is zero. As the Navigation Timing spec states: 'This attribute must return the time when the load event of the current document is completed. It must return zero when the load event is not fired or is not completed.' Therefore timing.loadEventEnd - timing.navigationStart will be negative. FWIW, here's a non-jQuery version: window.onload = function(){ setTimeout(function(){ var t = performance.timing; console.log(t.loadEventEnd - t.responseEnd); }, 0); } A: You need to measure the loadEventEnd after the onload event has finished or else it will be reported as 0, as never happened. (jquery example for attaching to the onload event) $(window).load(function(){ setTimeout(function(){ window.performance = window.performance || window.mozPerformance || window.msPerformance || window.webkitPerformance || {}; var timing = performance.timing || {}; var parseTime = timing.loadEventEnd - timing.responseEnd; console.log('Parsetime: ', parseTime); }, 0); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7606972", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: QT : Exited with saying " During startup program exited with code 127" I Had a Qt program which was working fine in Linux . We migrated our linux from 32bit to 64 bit and while trying to run the same program again throws me a error given below "During Startup program exited with code 127" In the Output window I also see the following: &"warning: GDB: Failed to set controlling terminal: Invalid argument\n" &"Cannor exec /bin/tcsh: No such file or directory.\n" does anyone have any idea on this error?? A: A Thread in QtCentre has the same problem solved. Look at here Hope that helps...
{ "language": "en", "url": "https://stackoverflow.com/questions/7606973", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get device descriptor and configuration descriptor of usb device in Mac? I have minimum exposure to xcode and I/Okit framework. I have seen device descriptor and configuration descriptor of a usb device in USB prober. I have written an xcode program using I/O kit framework which gives the usb device name as output, when we give product id and vendor id of that device as input. /*Take the vendor and product id from console*/ printf("\nEnter the vendor id : "); scanf("%lx",&usbVendor); printf("\nEnter the product id :"); scanf("%lx",&usbProduct); /* Set up a matching dictionary for the class */ matchingDict = IOServiceMatching(kIOUSBDeviceClassName); if (matchingDict == NULL) { return -1; // fail } // Create a CFNumber for the idVendor and set the value in the dictionary numberRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &usbVendor); CFDictionarySetValue(matchingDict, CFSTR(kUSBVendorID), numberRef); CFRelease(numberRef); // Create a CFNumber for the idProduct and set the value in the dictionary numberRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &usbProduct); CFDictionarySetValue(matchingDict, CFSTR(kUSBProductID), numberRef); CFRelease(numberRef); numberRef = NULL; /*Get an iterator.*/ kr = IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDict, &iter); if (kr != KERN_SUCCESS) { return -1;// fail } /* iterate */ while ((device = IOIteratorNext(iter))) { /*Display the device names */ io_name_t deviceName; kr = IORegistryEntryGetName(device, deviceName); if (KERN_SUCCESS != kr) { deviceName[0] = '\0'; } printf("\ndeviceName:%s",deviceName); /*Free the reference taken before continuing to the next item */ IOObjectRelease(device); } /*Release the iterator */ IOObjectRelease(iter); return 0; } I need to modify this, so that on giving vendor and product id of usb device, i will get the device descriptor and configuration descriptor( as shown in USB prober) as output. Here i just gave an example, code can change but the output must be the descriptor( atleast the device decriptor). Thanks in advance... A: I think u should download the source code of USBProber rather than figure it out by yourself. All the information presents in the USBProber u could get sooner or later by analyzing the source code. Here is link to download the source code of IOUSBFamily, with USBProber inside it. http://opensource.apple.com/tarballs/IOUSBFamily/ A: To get the configuration descriptors you can use code like this: IOUSBDeviceInterface650** dev = ...; IOUSBConfigurationDescriptor* configDesc = nullptr; // Get the configuration descriptor for the first configuration (configuration 0). kern_return_t kr = (*dev)->GetConfigurationDescriptorPtr(dev, 0, &configDesc); if (kr != kIOReturnSuccess) return an_error; // Now use configDesc->... Unfortunately there doesn't seem to be a function to get the device descriptor. There are functions to get some of it: kr = (*dev)->GetDeviceClass(dev, &desc.bDeviceClass); kr = (*dev)->GetDeviceSubClass(dev, &desc.bDeviceSubClass); kr = (*dev)->GetDeviceProtocol(dev, &desc.bDeviceProtocol); kr = (*dev)->GetDeviceVendor(dev, &desc.idVendor); kr = (*dev)->GetDeviceProduct(dev, &desc.idProduct); kr = (*dev)->GetDeviceReleaseNumber(dev, &desc.bcdDevice); kr = (*dev)->GetNumberOfConfigurations(dev, &desc.bNumConfigurations); But I don't see a way to get iManufacturer, iProduct, iSerial, bMaxPacketSize0, or bcdUSB. There is a way around this - instead of using the built-in functions you can just do a control request to get the device descriptor (and configuration descriptors if you like) manually using a control transfer. The USB 2.0 spec describes how to do this. Basically you: * *Do a control transfer with bmRequestType = Device | Standard | In, bRequest = USB_GET_DESCRIPTOR_REQUEST, wValue = (USB_DEVICE_DESCRIPTOR_TYPE << 8), wIndex = 0, wLength = 2. That will fail because the descriptor is longer than 2, but it gets you the descriptor header which includes its length. *Repeat that request but with the correct length. *For configuration descriptors, do a third request with length wTotalLength. You can do it with one less request since you know the size of the descriptors in advance, but I like to do it like that because then you can wrap it up in a very general getDescriptor() method. In theory you can do it as simply as this: IOUSBDeviceDescriptor devDesc; IOUSBDevRequest request; request.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice); request.bRequest = kUSBRqGetDescriptor; request.wValue = kUSBDeviceDesc << 8; request.wIndex = 0; request.wLength = sizeof(devDesc); // 18 request.pData = &devDesc; request.wLenDone = 0; kern_return_t kr = (*dev)->DeviceRequest(dev, &request); But for some reason that is giving me a kIOUSBPipeStalled error. Not sure why. Edit: I forgot the << 8. Now it works. :-) A: The header IOKit/usb/USBSpec.h has a documented list of property keys corresponding to values inside the different descriptors. You can use those with IORegistryEntrySearchCFProperty (or similar functions) to get the descriptor values. This way you don't need a device request from an IOUSBDeviceInterface, which is advantageous because: * *the documentation (comments) say that all device requests require an opened USB device and you may not have permission to do that for all devices (it's possible the documentation is wrong, at least for descriptor requests, but I have no guarantee of that and it seems better to follow it anyway) *device requests can block for an indeterminate amount of time *the manufacturer, product, and serial number strings (which are referenced by the device descriptor, but are not technically part of it) are not retrieved in this request A: For getting device descriptor and configuration decriptor, we can use functions in IOUSBDeviceInterface class Link: http://developer.apple.com/library/mac/#documentation/Darwin/Reference/IOKit/IOUSBLib_h/Classes/IOUSBDeviceInterface/index.html#//apple_ref/doc/com/intfm/IOUSBDeviceInterface/ For getting interface descriptor and end point descriptor, we can use functions in IOUSBInterfaceInterface class Link: http://developer.apple.com/library/mac/#documentation/Darwin/Reference/IOKit/IOUSBLib_h/Classes/IOUSBInterfaceInterface/
{ "language": "en", "url": "https://stackoverflow.com/questions/7606975", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: jqgrid not working in IE8 and firefox 3.6.6 My jqgrid is working in Firefox 7 and IE9 but not in IE8 or Firefox 3.6.6. I am using latest version of jqgrid. Here are the script files I've included: <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" /> <link href="@Url.Content("~/Content/themes/ui-lightness/jquery.ui.all.css")" rel="stylesheet" type="text/css" /> <link href="@Url.Content("~/Content/ui.jqgrid.css")" rel="stylesheet" type="text/css" /> <link href="@Url.Content("~/Content/ui.multiselect.css")" rel="stylesheet" type="text/css" /> <link href="@Url.Content("~/Content/themes/ui-lightness/jquery-ui-1.8.16.custom.css")" rel="stylesheet" type="text/css" /> <script src="@Url.Content("~/Scripts/jquery-1.6.2.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/grid.locale-en.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery.jqGrid.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Content/ui/minified/jquery.ui.core.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Content/ui/minified/jquery.ui.widget.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Content/ui/minified/jquery.ui.mouse.min.js")" type="text/javascript"></script> This is my script in case if it's needed: $(document).ready(function () { $('#jobs').jqGrid({ url: '/SearchJob/Jobs/', postData: { 'JobTitle': function () { return $('#JobTitle').val(); }, 'City': function () { return $('#City').val(); }, 'SelectJobType': function () { return $('#SelectJobType option:selected').val(); }, 'SalaryStartRange': function () { return $('#SalaryStartRange').val(); }, 'SalaryEndRange': function () { return $('#SalaryEndRange').val(); }, 'SelectCategory': function () { return $('#SelectCategory option:selected').val(); }, 'SelectIndustry': function () { return $('#SelectIndustry option:selected').val(); }, 'CompanyName': function () { return $('#CompanyName').val(); }, 'Keywords': function () { return $('#Keywords').val(); }, 'SelectSalaryType': function () { return $('#SelectSalaryType option:selected').val(); } }, datatype: 'json', mtype: 'POST', colNames: ['Title', 'Category', 'Company Name', 'Location', 'Salary Range', 'Date Posted'], colModel: [ { name: 'Title', index: 'title', width: 150, align: 'left', formatter: 'showlink', formatter: linkformatter }, { name: 'Category', index: 'Category', width: 150, align: 'center' }, { name: 'CompanyName', index: 'CompanyName', width: 150, align: 'center' }, { name: 'CombinedLocation', index: 'CombinedLocation', width: 150, align: 'center' }, { name: 'salaryRange', index: 'salaryRange', width: 150, align: 'center' }, { name: 'DatePosted', index: 'DatePosted', width: 150, align: 'center' }, ], shrinkToFit: true, rownumbers: true, loadonce: false, pager: jQuery('#jobPager'), rowNum: 10, rowList: [5, 10, 20, 50], sortname: 'jobid', sortorder: "desc", viewrecords: true, imgpath: '', caption: 'Jobs', width: '100%', height: "100%" }); $('#search').click(function () { $('#jobs').trigger('reloadGrid'); return false; }); }); linkformatter = function (cellValue, opts, rowObject) { console.log(rowObject); return "<a href='@Url.Action("JobView", "RecruiterProfile")/" + rowObject[rowObject.length - 1] + "'>" + cellValue + "<a/>"; } Attached is the error that I get in IE8 and Firefox 3.6: Removing screenshots because I am not allowed to post. If anybody drops here in future the error was of console. Removed in from my formatter function and it worked! Update: The error only comes in Firefox 3.6 if I have disabled Firebug. I enable Firebug and everything works as expected. What am I doing wrong? Am I including the wrong script files? A: I think you should write.. window.console.log(rowObject); In place of console.log(rowObject); or you might get answer from here.... http://www.sitepoint.com/forums/showthread.php?575320-how-not-to-let-console.log%28%29-to-cause-error-on-IE-or-other-browsers A: console.log(rowObject); in IE8 or Firefox 3.6.6,It does not console object.It's will be working when you remove this. A: You answerd almost yourself on your question in the last "Update" part: You have to test if (window.console) { window.console.log(rowObject); } or if (console) { console.log(rowObject); } because console is not always exist.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606976", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How detect iphone battery level in application running in background? I am developing an iphone application which includes battery level tracking. The main requirement of my application is to run application in background and comes on foreground when battery level reaches to low. I knew battery level tracking in iphone is not a big task but how can i do it from the background? can it be possible to do this type of work in background. Any idea will appreciable. Thanks in advance. A: This can be done only on devices which support multitasking , You can look for more details here.. http://developer.apple.com/library/ios/#documentation/iphone/conceptual/iphoneosprogrammingguide/BackgroundExecution/BackgroundExecution.html The page does give some info regarding performing tasks in background..
{ "language": "en", "url": "https://stackoverflow.com/questions/7606984", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Error Changing Visual Studio Version in run-command(Start -> Run -> devenv) I am trying to change the version of Visual studio in run command. I am following the steps given in one of the post : Change Visual Studio Version in run-command(Start -> Run -> devenv) But I am getting following error - "Can not edit - error writing the values new content". I am using Windows 7. I dont have admin rights. I think i have "power user" type admin rights. Any help is appreciated. Thanks A: You get the error because you do not have permission to edit the registry. Try the follwing: * *Right-click on the key (int this case 'App paths') and click on 'Permissions'; *Select your username, check the option “Full Control” below and click on “OK”: *Now try the steps from the linked post again
{ "language": "en", "url": "https://stackoverflow.com/questions/7606986", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Read any key to continue Java How can I implement the press ANY key to continue in Java. In C I use getch() and it works fine but Java I must press enter in every read method implement in every OutputStream class. Thanks in advance. A: The only way which I found was whith JNI and C. A: I found a code, Equivalent function to C's “_getch() I have given answer for this question Equivalent function to C's "_getch()" in Java? see my answer here or use the code public static void getCh() { final JFrame frame = new JFrame(); synchronized (frame) { frame.setUndecorated(true); frame.getRootPane().setWindowDecorationStyle(JRootPane.FRAME); frame.addKeyListener(new KeyListener() { public void keyPressed(KeyEvent e) { synchronized (frame) { frame.setVisible(false); frame.dispose(); frame.notify(); } } public void keyReleased(KeyEvent e) { } public void keyTyped(KeyEvent e) { } }); frame.setVisible(true); try { frame.wait(); } catch (InterruptedException e1) { } } } A: You can use following code if you're using windows. new ProcessBuilder("cmd", "/c", "pause").inheritIO().start().waitFor(); and import following package. import java.io.IOException; and change main function to this. public static void main(String args[]) throws IOException, InterruptedException
{ "language": "en", "url": "https://stackoverflow.com/questions/7606989", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Extracting multiple object values I have an object like this: object["key1"] = "text1" object["key2"] = "text2" object["key3"] = "text1" object["key4"] = "text3" How can I give out (e.g. alert) the elements with the same values (text1, text2 and so on)? In the above example it should be object["key1"] and object["key2"]. Thanks A: You could "invert" your object (properties become values, values become properties): var byValue = {}; for (var prop in object) { if (!(object[prop] in byValue)) { byValue[object[prop]] = []; } byValue[object[prop]].push(prop); } This should yield this structure: { 'text1': ['key1', 'key3'], 'text2': ['key2'], 'text3': ['key4'] } Then, you can detect those values that had duplicate keys: for (var value in byValue) { if (byValue[value].length > 1) { alert(byValue[value].join(', ')); } } A: I updated my script http://jsfiddle.net/HerrSerker/LAnRt/ This does not check for identity in complex values, just for equality (see foo example) A: I have sorted the array and then considered that you would want to alert,or do any functionality, only once for every repeated element. WARNING: Sorting can get heavy with the size of the array http://jsfiddle.net/SPQJ7/ The above fiddle is already setup and working with multiple reapeated elements
{ "language": "en", "url": "https://stackoverflow.com/questions/7606990", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MVC - RegisterRoutes I would like to rewrite the url from http://localhost:51639/home/index?id=123 to http://localhost:51639/home/product Here is my code in Global.asax.cs public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults ); } What can I do? Thanks a lot A: Important is the order, because MVC searchs first a fit with RouteCollection and return a url. public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute(null, "home/product/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional} ); routes.MapRoute("Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults ); } A: If you're using MVC 5, you can use a custom route parameter, i.e. [Route("home/product/{id:int}")]. It's really useful for one off routes, and since you can specify a type in the parameter that's passed, it doesn't conflict with other deep routes you might need. http://blogs.msdn.com/b/webdev/archive/2013/10/17/attribute-routing-in-asp-net-mvc-5.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7606991", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to add sequences to a migration and use them in a model? I want to have a "Customer" Model with a normal primary key and another column to store a custom "Customer Number". In addition, I want the db to handle default Customer Numbers. I think, defining a sequence is the best way to do that. I use PostgreSQL. Have a look at my migration: class CreateAccountsCustomers < ActiveRecord::Migration def up say "Creating sequenze for customer number starting at 1002" execute 'CREATE SEQUENCE customer_no_seq START 1002;' create_table :accounts_customers do |t| t.string :type t.integer :customer_no, :unique => true t.integer :salutation, :limit => 1 t.string :cp_name_1 t.string :cp_name_2 t.string :cp_name_3 t.string :cp_name_4 t.string :name_first, :limit => 55 t.string :name_last, :limit => 55 t.timestamps end say "Adding NEXTVAL('customer_no_seq') to column cust_id" execute "ALTER TABLE accounts_customers ALTER COLUMN customer_no SET DEFAULT NEXTVAL('customer_no_seq');" end def down drop_table :accounts_customers execute 'DROP SEQUENCE IF EXISTS customer_no_seq;' end end If you know a better "rails-like" approach to add sequences, would be awesome to let me know. Now, if I do something like cust = Accounts::Customer.new cust.save the field customer_no is not pre filled with the next value of the sequence (should be 1002). Do you know a good way to integrate sequences? Or is there a good plugin? Cheers to all answers! A: I believe that roboles answer is not correct. I tried to implement this on my application (exactly the same env: RoR+PostgreSQL), and I found out that when save is issued on RoR with the object having empty attributes, it tries to perform an INSERT on the database mentioning that all VALUES shall be set to NULL. The problem is the way PostgreSQL handles NULLs: in this case, the new row will be created but with all values empty, i.e. the DEFAULT will be ignored. If save only wrote on the INSERT statement attributes filled on RoR, this would work fine. In other words, and focusing only on the type and customer_no attribute mentioned above, this is the way PostgreSQL behaves: SITUATION 1: INSERT INTO accounts_customers (type, customer_no) VALUES (NULL, NULL); (this is how Rails' save works) Result: a new row with empty type and empty customer_no SITUATION 2: INSERT INTO accounts_customers (type) VALUES (NULL); Result: a new row with empty type and customer_no filled with the sequence's NEXTVAL I have a thread going on about this, check it out at: Ruby on Rails+PostgreSQL: usage of custom sequences A: I faced a similar problem, but I also put :null => false on the field hopping that it will be auto-populated with nextval. Well, in my case AR was still trying to insert NULL if no attribute was supplied in the request, and this resulted in an exception for not-null constraint violation. Here's my workaround. I just deleted this attribute key from @attributes and @changed_attributes and in this case postgres correctly put the expected sequence nextval. I've put this in the model: before_save do if (@attributes["customer_no"].nil? || @attributes["customer_no"].to_i == 0) @attributes.delete("customer_no") @changed_attributes.delete("customer_no") end end Rails 3.2 / Postgres 9.1 A: If you're using PostgreSQL, check out the gem I wrote, pg_sequencer: https://github.com/code42/pg_sequencer It provides a DSL for creating, dropping and altering sequences in ActiveRecord migrations. A: I have no suggestions for a more 'rails way' of handling custom sequences, but I can tell you why the customer_no field appears not to be being populated after a save. When ActiveRecord saves a new record, the SQL statement will only return the ID of the new record, not all of its fields, you can see where this happens in the current rails source here https://github.com/rails/rails/blob/cf013a62686b5156336d57d57cb12e9e17b5d462/activerecord/lib/active_record/persistence.rb#L313 In order to see the value you will need to reload the object... cust = Accounts::Customer.new cust.save cust.reload If you always want to do this, consider adding an after_create hook in to your model class... class Accounts::Customer < ActiveRecord::Base after_create :reload end
{ "language": "en", "url": "https://stackoverflow.com/questions/7606994", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "19" }
Q: How to apply shape and selector simultaneously for Button? I have applied a shape for a button like: <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" > <gradient android:startColor="#DD000000" android:endColor="#DD2d2d2d" android:angle="90"></gradient> <corners android:radius="15dip"></corners> </shape> Now I want to use a selector like: <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@drawable/active" android:state_pressed="true" /> <item android:drawable="@drawable/passive"/> for this Button as well. Is it possible ...??? A: You can also create a shape that is using a selector inside. If your shape is just changing its color in different states, this is a lot cleaner. color/color_selector.xml <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:color="@color/blue_dark" android:state_pressed="true" /> <item android:color="@color/blue_light" /> </selector> drawable/shape.xml <shape xmlns:android="http://schemas.android.com/apk/res/android"> <solid android:color="@color/color_selector" /> <corners android:bottomLeftRadius="6dip" android:bottomRightRadius="6dp" /> <padding android:bottom="0dip" android:left="0dip" android:right="0dip" android:top="0dip" /> </shape> A: Well I know it's way too late But here is a solved example <TextView android:id="@+id/txt_out_going_calls" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="04dp" android:layout_weight="1" android:background="@drawable/header_text_view_selector" android:gravity="center" android:text="@string/outgoing_calls_tab_button_text" android:textColor="@color/home_text_color" /> and my header_text_view_selector <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_selected="true"> <shape xmlns:android="http://schemas.android.com/apk/res/android"> <solid android:color="@color/home_fragment_tab_color_selected"/> <corners android:radius="25dip" /> <padding android:bottom="08dip" android:left="9dip" android:right="9dip" android:top="08dip" /> </shape> </item> <item android:state_selected="false"> <shape> <solid android:color="@color/home_fragment_tab_color_simple"/> <corners android:radius="25dip" /> <padding android:bottom="08dip" android:left="9dip" android:right="9dip" android:top="08dip" /> </shape> </item> </selector> So basically i m creating a rounded textview with selector. Here i m handling only state_selected and not_selected. Hope it helps A: This is my way, and it works! <item android:state_pressed="true"> <shape android:shape="oval"> <gradient android:centerX=".6" android:centerY=".40" android:endColor="@color/colorPrimary" android:gradientRadius="20" android:startColor="@color/colorPrimary" android:type="radial" /> <stroke android:width="1dp" android:color="#FFFFFF" /> <size android:width="55dp" android:height="55dp" /> </shape> </item> <item android:state_focused="false"> <shape android:shape="oval"> <gradient android:centerX=".6" android:centerY=".40" android:endColor="@android:color/transparent" android:gradientRadius="20" android:startColor="@android:color/transparent" android:type="radial" /> <stroke android:width="1dp" android:color="#FFFFFF" /> <size android:width="55dp" android:height="55dp" /> </shape> </item> A: Detailed to the point answer Create a color resource in res/values/colors.xml <?xml version="1.0" encoding="utf-8"?> <resources> <item name="yellow" type="color">#F7B500</item> <item name="yellow_dark" type="color">#AC7E00</item> <integer-array name="androidcolors"> <item>@color/yellow</item> <item>@color/yellow_dark</item> </integer-array> </resources> Create a drawable at res/drawable/bg_yellow_round.xml <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" > <solid android:color="@color/yellow" /> <stroke android:width="2dp" android:color="@color/yellow" /> <corners android:bottomLeftRadius="20dp" android:bottomRightRadius="20dp" android:topLeftRadius="20dp" android:topRightRadius="20dp" /> </shape> Create another drawable, you want for transition at same place and name it res/drawable/bg_yellow_dark_round.xml <solid android:color="@color/yellow_dark" /> <stroke android:width="2dp" android:color="@color/yellow_dark" /> <corners android:bottomLeftRadius="20dp" android:bottomRightRadius="20dp" android:topLeftRadius="20dp" android:topRightRadius="20dp" /> Now create a color state list at res/color/btn_selector_yellow.xml <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android" android:exitFadeDuration="@android:integer/config_shortAnimTime"> <item android:drawable="@color/yellow" android:state_focused="true" android:state_pressed="false"/> <item android:drawable="@drawable/bg_yellow_dark_round" android:state_pressed="true"/> <item android:drawable="@drawable/bg_yellow_round"/> </selector> Now set it to your button as following <Button android:id="@+id/button1" android:layout_width="248dp" android:layout_height="44dp" android:layout_gravity="center_horizontal" android:layout_marginBottom="10dp" android:layout_marginTop="20dp" android:background="@color/btn_selector_yellow" android:text="AZ_ is so cool" /> Now this will do transition from to . A: My example is a circle button with state_pressed. code bellow: <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_pressed="true"> <shape android:shape="oval"> <solid android:color="@color/light_primary_color" /> </shape> </item> <item> <shape android:shape="oval"> <solid android:color="@color/accent_color" /> </shape> </item> </selector> A: use this way: <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_pressed="true" > <shape>.......</shape> </item> .......... .......... </selector> A: shape.xml <shape xmlns:android="http://schemas.android.com/apk/res/android"> <solid android:color="@color/star_off"/> <corners android:radius="5dp"/> <padding android:left="0dp" android:top="0dp" android:right="0dp" android:bottom="0dp" /> </shape> selector.xml <selector xmlns:android="http://schemas.android.com/apk/res/android" android:exitFadeDuration="@android:integer/config_mediumAnimTime"> <item android:drawable="@color/tab_focused" android:state_focused="true" android:state_pressed="false"/> <item android:drawable="@color/tab_pressed" android:state_pressed="true"/> <item android:drawable="@drawable/shape"/> </selector> A: Use your shape name as you use any image and use it selector as you use image. Try out you will not face any problem. Is that what you were asking? A: To be more reusable, you can set states on single properties. Avoid duplicating your shapes <selector xmlns:android="http://schemas.android.com/apk/res/android" > <item> <shape android:shape="rectangle" > <corners android:radius="5dp"/> <solid android:state_enabled="false" android:color="@color/transparent" /> <solid android:state_enabled="true" android:color="@color/background" /> <stroke android:width="@dimen/dividerHeight" android:color="@color/dividerLight" /> </shape> </item> </selector> I was able to set background programmatically once disabled using this method.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606995", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "91" }
Q: JPA Hibernate manyToMany with non-unique key I have two entities (tables): Department and Person. Both tables have a field CODE which is not unique. How can I define manyToMany bidirectional relations between these tables? * *Department has collection Persons which contains all entities with Person.CODE eq Department.CODE *Partner has collection Departments which contains all entities with Department.CODE eq Partner.CODE I need the relation definition - no sql or hpql query. it is no problem to do it with HPQL, but I need annotation. Select persons for given departmentID: select P.* from Person P, Deparment d where d.department_id = ? and p.code = d.code and ? between d.validFrom and d.validTill and ? between p.validFrom and p.validTill It is possible with hibernate formula? A: You would definitely need a third table in the DB to own the many-to-many relation to start with, call it department_person. Declare two foreign keys from this that refer to Persons and to Departments table. Afterwards, you could either: 1) define a new JPA entity DepartmentPerson and define to many-to-one relations from each foreign key. You should consequently create two one-to-many relations which would point from Persons to DepartmentPerson and from Department to DepartmentPerson yielding the Collections you need. 2) define a many-to-many relation in one of the two initial entities stating that department_person is the owner of the relation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7607001", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Slash in virtual directory name (IIS) I have a website on IIS 6 running PHP. Let's say the address is: http://mysite I want to create a virtual directory to run an ASP.NET MVC 3 app under this address. I want the virtual directory to look like this: http://mysite/api/v2 I cannot create a virtual directory called 'api/v2' because it contains slash. Is it possible to create virtual directory two levels down like this? A: It know it is stupid but for some weird reason you cannot type / in IIS7 under virtual directory but you can copy/paste value like app/v2 into that textbox. hope this helps. A: Checkout the following article for nesting virtual directories. A: I have to create physical directory under the root called 'api' (this is possible in PHP), then create a virtual directory called 'v2' under that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7607002", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: error: comp. bet. signed/unsigned integer expressions CODEBLOCKS the assignment is: have a number saved in a string, then convert from a string to an integer--> convert that number to a decimal number from N-base the user inputs. #include <iostream> using namespace std; int main() { string snum; int n=0, base, res; cout << "enter n: "; cin >> snum; cout << "enter base: "; cin << base; //THIS IS LINE 13 for (int i=0; i<snum.length(); i++) // des order { int digit = snum.at(i) - '0'; n = (n*1) + digit; if ( base <= 10 ) res = base * n; cout << "n is " << res << endl; } } Im getting error: NO MATCH BETWEEN SIGNED AND UNSIGNED INTEGER EXPRESSIONS [Line 13] ty all!! *if u find any problems in logic please let me know! *using codeblocks A: with cin << base; //THIS IS LINE 13 you mean cin >> base; EDIT: you should convert the number differently, instead of grabbing each character take the whole string and convert it to a number. You can use a stream for that or just atoi( sum.c_str() ) to get the integer number. thereafter convert the value to whatever base you want. e.g. snum=12 (converted to integer from input string) base=8 12 - 8 (>8, number of times you can subtract) --> 1 4 - 8 (<8 use remainder) --> 4 output == 14
{ "language": "en", "url": "https://stackoverflow.com/questions/7607009", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Dynamically Binding gridview with dynamic column and dynamic rows with Editing and updating in gridview? I am new in .net application development.Please help me to find the solution. My requirement is I am getting filled data table from database.Now i want to fill it in GridView.The problem is that the column name and number of columns changed as per the selected value in Dropdownlist and the DataTable is filled as per the selected value in Dropdownlist.Now i want to generate The columns and rows of the GridView Dynamically and also want to edit and update the created row.The Number of column and row are not fixed It varies as per the selected Prediction in Dropdawnlist.So Please Help me to solve the problem. Thanks In Advance A: Actually GridView control have an ability to autogenerate columns. Checkout this tutoral for beginers about data accessing in ASP.NET: http://www.asp.net/data-access/tutorials In two words: <asp:sqldatasource id="CustomersSource" selectcommand="SELECT CustomerID, CompanyName, FirstName, LastName FROM SalesLT.Customer" connectionstring="<%$ ConnectionStrings:AWLTConnectionString %>" runat="server"/> <asp:gridview id="CustomersGridView" datasourceid="CustomersSource" autogeneratecolumns="True" runat="server"> </asp:gridview>
{ "language": "en", "url": "https://stackoverflow.com/questions/7607015", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Proper way to stretch elements? Currently I have: http://jsfiddle.net/walkerneo/JnEpS/3/ Assuming I want the following: * *Gray boxes change height on resize, but constant width *Blue box changes height and width on resize *Cyan box changes width but not height on resize What is the proper way to do it? The way in the jsfiddle is done by stretching the element by setting its position to absolute and making its left, right, top, and bottom to 0px. I'm loving how easy this is compared to using table display properties or lengthy code, but I get the feeling it's something that shouldn't be done. Is this proper code? If not, what is? A: That is the "proper" way to do it. I can't think of any other way to go about it that doesn't involve tables that might not even work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7607017", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: jQuery Mobile dropdown menu in header wont work I have made my own dropdown menu in the header on a jQuery mobile page: <div data-role="header"> <ul id="menu"> <li><a href="#" data-role="button" data-icon="gear" data-rel="dialog">Menu</a> <ul> <li><a href="">Forgot to accept</a></li> <li><a href="">Remove me from group</a></li> </ul> </li> </ul> <h1><?php echo $group_data['name']; ?></h1> ... The problem is now that the drop menus css is set to position: absolute and the parent li is set to position relative as normal. The problem now is that the li won't appear on top, but instead appears under the div with data-role="content". So my quistion is how i can force the submenu to appear on top of all other div/layers (what you know call them)? The css for my menu: #menu { list-style: none; padding: 0; margin: 3px 0 0 5px; /* To make the menu button appear propper in the header */ } #menu li { float: left; position: relative; } #menu ul { position: absolute; display: none; list-style: none; color: #949494; padding: 0; margin: 3px 0 0 0; } #menu ul li{ line-height: 50%; float: none; } #menu ul a{ color: #0291ff; text-decoration: none; font-size: 12px; line-height: 150%; } #menu ul a:Hover{ color: #000; } A: You need to set the position even though you're using position: absolute. #menu ul { position: absolute; top: 0; left: 0; ... }
{ "language": "en", "url": "https://stackoverflow.com/questions/7607018", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: HyperNext Android Creator and making Android apps I've been trying to learn how to make Android apps and installed Eclipse and Android SDK but found it hard going as I'm not a programmer and only know a little Java. I then tried HyperNext Android Creator and found it much easier as it did have me creating some small apps quite quickly. Actually just modifying their projects and some tinkering to see how things work. The problem is which is the best way to go as the whole Android scene is moving quickly and even App Inventor is no longer supported by Google. I wonder if there are any major changes coming with Android SDK that will prevent HAC working. Perhaps Google will follow Apple and discourage non standard Android development tools? Any thoughts on the future of Android and developing for it? A: I am also using HAC but can't see any info on the their website about how it builds an Android app. I've just assumed that because it uses the Android SDK it is stable and will continue to work. However, in order to make a judgement we need to know the details of how it builds an Android app. Their HyperNext Studio apps for Windows and Mac seems to use a runtime engine for each platform that executes the apps code but I've seen no mention of this for Android. Its hard to see Google restricting the languages used to develop Android apps as their Android culture is more open than Apple's iOS do and they need to get as many apps out to Market as possible. About Googles plans, perhaps someone can comment on this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7607025", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: paste image without background PIL I am trying to paste many small grayscale images into a bigger one. All images are jpegs. The small images had been previously rotated, so they have black background. What I wanted to do is to paste them without a background color, in other words, I need the background color to be transparent. Thank you for your suggestions, A: to my knowledge, jpg does not support transparency, you probably want your output to be a png, and you will need to set the alpha channel to be nothing http://www.talkgraphics.com/showthread.php?22385-How-do-I-make-jpeg-image-background-transparent
{ "language": "en", "url": "https://stackoverflow.com/questions/7607027", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Alternative IP address for same SVN server, with TortoiseSVN I've been looking through the many svn questions on this site but haven't found one which I think applies to my situation. Its pretty simple. Can I add an alternate IP address to my TortoiseSVN working copy, so if the primary IP address fails, the alternate one is used? In particular, I want to use the networks external IP address when out the office, but use a private LAN address when in the office. Both addresses point to the same PC, same SVN repo. No mirror. I'd like to do it without having to run svn switch --relocate twice (or more) every day. Thanks for your suggestions Si A: The simplest solution I can think of, is to modify your hosts file if you're on Windows and point the two ip addresses to the host name of your svn server. A: Use the Host and change-it or use only your external IP fix. 127.0.0.1 svninternal # x.x.x.x svninternal
{ "language": "en", "url": "https://stackoverflow.com/questions/7607030", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: customizing the NSPredicateEditor I want to customize the NSPredicateEditorRowTemplate, but I needn't the subtraction sign in the first RowTemplate, the second, and the third, like the Finder application. A: If you tell the NSPredicateEditor that it cannot remove all the rows in the editor, then the editor will automatically remove the (-) button when necessary. You can do this by unchecking the "Can Remove All Rows" checkbox when editing the predicate editor in a xib, or by doing it programmatically with the -setCanRemoveAllRows: method.
{ "language": "en", "url": "https://stackoverflow.com/questions/7607032", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to add layer to OpenLayers, but without it getting automatically added in LayerSwitcher Control? I have a Openlayer web map with LayerSwitcher control added. I need this to switch some of my layers. But I am also adding and removing some layers, which are temperory and i donot want them added to the LayerSwitcher Control. So is there a way to add layer to OpenLayers, but without it getting automatically added in LayerSwitcher Control? A: Figured this out. I need to add 'displayInLayerSwitcher: false' in the layer options.
{ "language": "en", "url": "https://stackoverflow.com/questions/7607034", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Duplicates in results from .ToArray in LinQ query I did a query which should return only 3 rows, but I get 36 rows with the rest being duplicates. var query = from a in db.as join b in db.bs on a.pri equals b.for join c in db.cs on b.pri equals c.for where b.Age == age select new string[] { a.Name, a.Gender, b.Amount, c.Location, }; string[][] results = query.ToArray(); return results; Could it be the .ToArray causing it to have multiple duplicates? A: One quick solution is make use of Distinct method string[][] results = query.Distinct().ToArray(); which may resolve your problem. if not please share the data of you table....
{ "language": "en", "url": "https://stackoverflow.com/questions/7607035", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to generate JsonStringer for this Json Data Format? hello i have a JSON data format can anyone please help me to make dynamic JSONStringer object for this String {"Text":"Hello Simple Text", "Files":[{"ContentType":"image/png", "Content":"iVBORw0KGgoAAAANSUhEUgAAAR8AAACMCAIAAADKsDpDAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAAB3RJTUUH2wYWDzIB3zSYdQAAAAd0RVh0QXV0aG9yAKmuzEgAAAAMdEVYdERlc2NyaXB0aW9uABMJISMAAAAKdEVYdENvcHlyaWdodACsD8w6AAAADnRFWHRDcmVhdGlvbiB0aW1lADX3DwkAAAAJdEVYdFNvZnR3YXJlAF1w/zoAAAALdEVYdERpc2NsYWltZXIAt8C0jwAAAAh0RVh0V2FybmluZwDAG+aHAAAAB3RFWHRTb3VyY2UA9f+D6wAAAAh0RVh0Q29tbWVudAD2zJa/AAAABnRFWHRUaXRsZQCo7tInAAABAElEQVR4nO2de1zUVf7/3+dzmwsMoCgDXgARBO/"}], "AuthToken":"XkWQRd65+H+iPtlOoAEYAR0jrzB1o3UV"} i have used jsonstr = new JSONStringer().object().key("Text") .value(msg).key("Files").array().object().key( "ContentType").value("image/png").key( "Content").value(enimg) .endObject().endArray().key("AuthToken").value(token) .endObject(); but the server is giving me fault message in return, not accepting the data. A: actually i was doing the right thing..everything was OK.. the problem was with org.json package it was not accurate with Base64 string i switched to another library and all worked.. https://stackoverflow.com/questions/338586/a-better-java-json-library see the above question for another json libraries that was problem with org.json i switched to another..and all it works nesting too deep in JSON... should I switch to XML? A: This is a way to do what you want: // Creating root JSONObject JSONObject json = new JSONObject(); // Put in it a String field json.put("Text", "Hello sample"); // Creating a JSONArray JSONArray arr = new JSONArray(); //Creating the element to populate the array JSONObject element = new JSONObject(); element.put("ContentType","image/png"); element.put("Content","iVBORw0K...gDXgARBO/"); // Put it in the array arr.put(element); // Put the array and other fileds in the root JSONObject json.put("Files", arr); json.put("AuthToken", "XkWQ...o3UV"); // Get the JSON String String s = json.toString(); // Get formatted and indented JSON String String s2 = json.toString(4); // 4 is the number of spaces to indent the string A: You can use JSONObject class for this purpose http://developer.android.com/reference/org/json/JSONObject.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7607038", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: NullPointerException when going back through activities I'm debugging my application, and getting a 'strange' exception. It's not consistent and therefore really hard to solve. I'll post some code below. The class that gives my exception: private ArrayList<String> idList; @Override public void onCreate( Bundle savedInstanceState ) { super.onCreate( savedInstanceState ); if ( idList == null ) { idList = new ArrayList<String>(); } } @Override public void finishFromChild( Activity child ) { LocalActivityManager manager = getLocalActivityManager(); int index = idList.size()-1; if ( index < 1 ) { finish(); return; } manager.destroyActivity( idList.get( index ), true ); idList.remove( index ); index--; String lastId = idList.get( index ); Activity lastActivity = manager.getActivity( lastId ); Intent lastIntent = lastActivity.getIntent(); Window newWindow = manager.startActivity( lastId, lastIntent ); setContentView( newWindow.getDecorView() ); } public void startChildActivity( String id, Intent intent ) { if ( "restart".equalsIgnoreCase( id ) ) { idList.clear(); } Window window = getLocalActivityManager().startActivity( id, intent.addFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP ) ); if ( window != null ) { idList.add( id ); setContentView( window.getDecorView() ); } } public Activity getCurrentActivity() { int length = idList.size(); if ( idList.isEmpty() ) { return null; } else { return getLocalActivityManager().getActivity( idList.get( length-1 ) ); } } @Override public boolean onKeyDown( int keyCode, KeyEvent event ) { if ( keyCode == KeyEvent.KEYCODE_BACK ) { return true; } return super.onKeyDown( keyCode, event ); } @Override public boolean onKeyUp( int keyCode, KeyEvent event ) { if ( keyCode == KeyEvent.KEYCODE_BACK ) { onBackPressed(); return true; } return super.onKeyUp( keyCode, event ); } @Override public void onBackPressed() { int length = idList.size(); if ( length > 1 ) { Activity current = getLocalActivityManager().getActivity( idList.get( length-1 ) ); current.finish(); } } The exception itself: 09-30 08:44:12.571: ERROR/AndroidRuntime(10557): FATAL EXCEPTION: main 09-30 08:44:12.571: ERROR/AndroidRuntime(10557): java.lang.NullPointerException 09-30 08:44:12.571: ERROR/AndroidRuntime(10557): at com.dezide.android.troubleshooter.view.TabGroupActivity.finishFromChild(TabGroupActivity.java:46) 09-30 08:44:12.571: ERROR/AndroidRuntime(10557): at android.app.Activity.finish(Activity.java:3290) 09-30 08:44:12.571: ERROR/AndroidRuntime(10557): at com.dezide.android.troubleshooter.view.TabGroupActivity.onBackPressed(TabGroupActivity.java:106) 09-30 08:44:12.571: ERROR/AndroidRuntime(10557): at com.dezide.android.troubleshooter.view.TabGroupActivity.onKeyUp(TabGroupActivity.java:93) 09-30 08:44:12.571: ERROR/AndroidRuntime(10557): at android.view.KeyEvent.dispatch(KeyEvent.java:1281) 09-30 08:44:12.571: ERROR/AndroidRuntime(10557): at android.app.Activity.dispatchKeyEvent(Activity.java:2075) 09-30 08:44:12.571: ERROR/AndroidRuntime(10557): at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchKeyEvent(PhoneWindow.java:1673) 09-30 08:44:12.571: ERROR/AndroidRuntime(10557): at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:796) 09-30 08:44:12.571: ERROR/AndroidRuntime(10557): at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:796) 09-30 08:44:12.571: ERROR/AndroidRuntime(10557): at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:796) 09-30 08:44:12.571: ERROR/AndroidRuntime(10557): at android.widget.TabHost.dispatchKeyEvent(TabHost.java:275) 09-30 08:44:12.571: ERROR/AndroidRuntime(10557): at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:796) 09-30 08:44:12.571: ERROR/AndroidRuntime(10557): at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:796) 09-30 08:44:12.571: ERROR/AndroidRuntime(10557): at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchKeyEvent(PhoneWindow.java:1697) 09-30 08:44:12.571: ERROR/AndroidRuntime(10557): at com.android.internal.policy.impl.PhoneWindow.superDispatchKeyEvent(PhoneWindow.java:1111) 09-30 08:44:12.571: ERROR/AndroidRuntime(10557): at android.app.Activity.dispatchKeyEvent(Activity.java:2070) 09-30 08:44:12.571: ERROR/AndroidRuntime(10557): at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchKeyEvent(PhoneWindow.java:1673) 09-30 08:44:12.571: ERROR/AndroidRuntime(10557): at android.view.ViewRoot.deliverKeyEventToViewHierarchy(ViewRoot.java:2493) 09-30 08:44:12.571: ERROR/AndroidRuntime(10557): at android.view.ViewRoot.handleFinishedEvent(ViewRoot.java:2463) 09-30 08:44:12.571: ERROR/AndroidRuntime(10557): at android.view.ViewRoot.handleMessage(ViewRoot.java:1752) 09-30 08:44:12.571: ERROR/AndroidRuntime(10557): at android.os.Handler.dispatchMessage(Handler.java:99) 09-30 08:44:12.571: ERROR/AndroidRuntime(10557): at android.os.Looper.loop(Looper.java:144) 09-30 08:44:12.571: ERROR/AndroidRuntime(10557): at android.app.ActivityThread.main(ActivityThread.java:4937) 09-30 08:44:12.571: ERROR/AndroidRuntime(10557): at java.lang.reflect.Method.invokeNative(Native Method) 09-30 08:44:12.571: ERROR/AndroidRuntime(10557): at java.lang.reflect.Method.invoke(Method.java:521) 09-30 08:44:12.571: ERROR/AndroidRuntime(10557): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868) 09-30 08:44:12.571: ERROR/AndroidRuntime(10557): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626) 09-30 08:44:12.571: ERROR/AndroidRuntime(10557): at dalvik.system.NativeStart.main(Native Method) The problem is that it does not always fail at the same place. Sometimes I can press back 20 times before the exception occurs, sometimes only 5. EDIT: Adding more code. My GuideActivity, which is where you make the steps, and launches each of them as a new activity: public void onCreate( Bundle savedInstanceState ) { super.onCreate( savedInstanceState ); if ( "startguide".equalsIgnoreCase( getIntent().getStringExtra( "action" ) ) ) { try { startGuide( getIntent().getStringExtra( "guide" ) ); } catch( Exception e ) { e.printStackTrace(); } } else if ( "nextstep".equalsIgnoreCase( getIntent().getStringExtra( "action" ) ) ) { String session = getIntent().getStringExtra( "session" ); String step = getIntent().getStringExtra( "step" ); String response = getIntent().getStringExtra( "response" ); try { nextGuideStep( session, step, response ); } catch( Exception e ) { e.printStackTrace(); } } } public GuideStep getCurrentStep() { return currentStep; } public void setCurrentStep( GuideStep currentStep ) { this.currentStep = currentStep; } public void startGuide( String name ) throws Exception { GuideStep guideStep = model.startGuide( name ); currentStep = guideStep; setContentView ( R.layout.main ); LinearLayout linearLayout = ( LinearLayout ) findViewById( R.id.linearLayout ); TextView stepTitle = ( TextView ) findViewById( R.id.stepTitle ); TextView explanation = ( TextView ) findViewById( R.id.explanation ); stepTitle.setText( guideStep.getStepTitle() ); if ( guideStep.getExplanation() != "" ) { explanation.setText( Html.fromHtml( guideStep.getExplanation() ) ); } responses = guideStep.getResponses(); ListView listView = new ListView( this ); linearLayout.addView( listView ); listView.setAdapter( new CustomAdapter( this, R.layout.list_item, responses ) ); listView.setTextFilterEnabled( true ); listView.setOnItemClickListener( new OnItemClickListener() { public void onItemClick( AdapterView<?> parent, View view, int position, long id ) { try { Intent i = new Intent().setClass( getParent(), GuideActivity.class ); i.putExtra( "action", "nextstep" ); i.putExtra( "session", currentStep.getSession() ); i.putExtra( "step", currentStep.getStep() ); i.putExtra( "response", currentStep.getResponse( position ).getId() ); TabGroupActivity parentActivity = ( TabGroupActivity )getParent(); parentActivity.startChildActivity( currentStep.getStepTitle(), i ); } catch( Exception e ) { e.printStackTrace(); } } }); } public void nextGuideStep( String session, String step, String responseId ) throws Exception { GuideStep guideStep = model.nextGuideStep( session, step, responseId ); currentStep = guideStep; setContentView ( R.layout.main ); LinearLayout linearLayout = ( LinearLayout ) findViewById( R.id.linearLayout ); TextView stepTitle = ( TextView ) findViewById( R.id.stepTitle ); TextView explanation = ( TextView ) findViewById( R.id.explanation ); TextView didThisAnswerYourQuestion = ( TextView ) findViewById( R.id.didThisAnswerYourQuestion ); ScrollView scrollView = ( ScrollView ) findViewById( R.id.scrollView ); stepTitle.setText( guideStep.getStepTitle() ); if ( guideStep.getExplanation() != "" ) { explanation.setText( Html.fromHtml( guideStep.getExplanation() ) ); } responses = guideStep.getResponses(); if ( guideStep.getStepTitle() != "" ) { ListView listView = new ListView( this ); linearLayout.addView( listView ); listView.setAdapter( new CustomAdapter( this, R.layout.list_item, responses ) ); listView.setTextFilterEnabled( true ); listView.setOnItemClickListener( new OnItemClickListener() { public void onItemClick( AdapterView<?> parent, View view, int position, long id ) { try { Intent i = new Intent().setClass( getParent(), GuideActivity.class ); i.putExtra( "action", "nextstep" ); i.putExtra( "session", currentStep.getSession() ); i.putExtra( "step", currentStep.getStep() ); i.putExtra( "response", currentStep.getResponse( position ).getId() ); TabGroupActivity parentActivity = ( TabGroupActivity )getParent(); parentActivity.startChildActivity( currentStep.getStepTitle(), i ); } catch( Exception e ) { e.printStackTrace(); } } }); } else { stepTitle.setVisibility( View.GONE ); didThisAnswerYourQuestion.setVisibility( View.GONE ); RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.FILL_PARENT ); params.addRule( RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE ); params.height = 350; scrollView.setLayoutParams( params ); } } public boolean availableForFeedback() { return currentStep != null; } } My starting Activity: public void onCreate( Bundle savedInstanceState ) { super.onCreate( savedInstanceState ); try { populateSections(); } catch( Exception e ) { e.printStackTrace(); } } private void populateSections() throws Exception { setContentView( R.layout.sections ); ArrayList<XmlSection> sections = new ArrayList<XmlSection>(); Portal portal = model.getPortal(); sections = portal.getSections(); final ArrayList<XmlSection> tempSections = sections; ListView listView = ( ListView ) findViewById( R.id.sectionList ); listView.setAdapter( new CustomAdapter( this, R.layout.list_item, sections ) ); listView.setTextFilterEnabled( true ); listView.setOnItemClickListener( new OnItemClickListener() { public void onItemClick( AdapterView<?> parent, View view, int position, long id ) { try { Intent i = new Intent().setClass( SectionActivity.this, JAndroidTroubleshooterActivity.class ); i.putExtra( "name", tempSections.get( position ).getName() ); startActivity( i ); } catch( Exception e ) { e.printStackTrace(); } } }); } The activity that my main activity launches: @Override public void onCreate( Bundle savedInstanceState ) { super.onCreate( savedInstanceState ); Resources res = getResources(); TabHost tabHost = getTabHost(); TabHost.TabSpec spec; Intent intent; intent = new Intent().setClass( this, TabGroupGuideActivity.class ); intent.putExtra( "name", getIntent().getStringExtra( "name" ) ); spec = tabHost.newTabSpec( "guides" ).setIndicator( "Guides", res.getDrawable( R.drawable.guides ) ) .setContent( intent ); tabHost.addTab( spec ); intent = new Intent().setClass( this, TabGroupFaqActivity.class ); intent.putExtra( "name", getIntent().getStringExtra( "name" ) ); spec = tabHost.newTabSpec( "faqs" ).setIndicator( "FAQs", res.getDrawable( R.drawable.faq ) ) .setContent( intent ); tabHost.addTab( spec ); } private Activity getCurrentTab() { Activity activity = getLocalActivityManager().getActivity( getTabHost().getCurrentTabTag() ); return activity; } private void optionRestart() { if ( getCurrentTab() instanceof TabGroupFaqActivity ) { Intent i = new Intent().setClass( this, FaqActivity.class ); TabGroupFaqActivity activity = ( TabGroupFaqActivity ) getCurrentActivity(); i.putExtra( "name", activity.getCurrentSection() ); activity.startChildActivity( "restart", i ); } if ( getCurrentTab() instanceof TabGroupGuideActivity ) { Intent i = new Intent().setClass( this, GuideListActivity.class ); TabGroupGuideActivity activity = ( TabGroupGuideActivity ) getCurrentActivity(); i.putExtra( "name", activity.getCurrentSection() ); activity.startChildActivity( "restart", i ); } } private void optionFeedback() { if ( getCurrentTab() instanceof TabGroupFaqActivity ) { Activity currentTab = ( ( TabGroupFaqActivity ) getCurrentTab() ).getCurrentActivity(); Article currentArticle = ( ( FaqActivity ) currentTab ).getCurrentArticle(); if ( currentArticle != null ) { Intent i = new Intent().setClass( this, FeedbackActivity.class ); i.putExtra( "perform", "feedbackfaq" ); i.putExtra( "title", currentArticle.getTitle() ); startActivity( i ); } else { Toast toast = Toast.makeText( getApplicationContext(), "You have to select an article to submit feedback", 500 ); toast.show(); } } if ( getCurrentTab() instanceof TabGroupGuideActivity ) { Activity currentTab = ( ( TabGroupGuideActivity ) getCurrentTab() ).getCurrentActivity(); GuideStep currentStep = ( ( GuideActivity ) currentTab ).getCurrentStep(); if ( currentStep != null && "false".equalsIgnoreCase( currentStep.getTerminalStep() ) ) { Intent i = new Intent().setClass( this, FeedbackActivity.class ); i.putExtra( "perform", "feedbackguide" ); i.putExtra( "session", currentStep.getSession() ); i.putExtra( "action", currentStep.getStepTitle() ); i.putExtra( "title", currentStep.getGuideTitle() ); startActivity( i ); } else { Toast toast = Toast.makeText( getApplicationContext(), "You cannot submit feedback for the last step of a guide", 500 ); toast.show(); } } } private void optionHome() { Intent i = new Intent().setClass( this, SectionActivity.class ); i.setFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP ); startActivity( i ); } @Override public void onConfigurationChanged( Configuration newConfig ) { super.onConfigurationChanged( newConfig ); } @Override public boolean onCreateOptionsMenu( Menu menu ) { MenuInflater inflater = getMenuInflater(); inflater.inflate( R.menu.menu, menu ); return true; } @Override public boolean onOptionsItemSelected( MenuItem item ) { switch ( item.getItemId() ) { case R.id.menuRestart: optionRestart(); return true; case R.id.menuHome: optionHome(); return true; case R.id.menuFeedback: optionFeedback(); return true; default: return super.onOptionsItemSelected( item ); } } My tab group activity: @Override public void onCreate( Bundle savedInstanceState ) { super.onCreate( savedInstanceState ); currentSection = getIntent().getStringExtra( "name" ); startChildActivity( "GuideListActivity", new Intent( this, GuideListActivity.class ).putExtra( "name", getIntent().getStringExtra( "name" ) ) ); } public String getCurrentSection() { return currentSection; } And last, my activity that list guides: public void onCreate( Bundle savedInstanceState ) { super.onCreate( savedInstanceState ); try { populateGuideList( getIntent().getStringExtra( "name" ) ); } catch( Exception e ) { e.printStackTrace(); } } public void populateGuideList( String name ) throws Exception { setContentView( R.layout.guides ); Section section = model.getSection( name ); guides = section.getGuides(); ListView listView = ( ListView ) findViewById( R.id.guideList ); listView.setAdapter( new CustomAdapter( this, R.layout.list_item, guides ) ); listView.setTextFilterEnabled( true ); listView.setOnItemClickListener( new OnItemClickListener() { public void onItemClick( AdapterView<?> parent, View view, int position, long id ) { try { XmlGuide guide = guides.get( position ); Intent i = new Intent().setClass( getParent(), GuideActivity.class ); i.putExtra( "guide", guide.getName() ); i.putExtra( "action", "startguide" ); TabGroupActivity parentActivity = ( TabGroupActivity )getParent(); parentActivity.startChildActivity( guide.getName(), i ); } catch( Exception e ) { e.printStackTrace(); } } }); } A: I think it may help: public void startChildActivity(String id, Intent intent) { id+=System.currentTimeMillis(); //rest of your code. } Edit: it need a little elaboration. There are Activity A, B and C * *You start A with Id "A" *then you start B with Id "B" *then you start C with Id "C" *and from C you again start another instance of B with id "B" (it may happen, because B may be a ResultListScreen which may called for several time with Load More type button) The problem is that in ArrayList<String> idList when you finish from last B manager.destroyActivity( idList.get( index ), true ); line is called which destroys Activity having id "B", which are 2 in stack. both B are deleted and C is pushed. and when you finish C and there is no B in the stack but its Id is available is ArrayList<String> idList and you get its Activity which is null if not found. That's all. id+=System.currentTimeMillis(); in this line of code you assign a unique id every time you start new Activity by using System's current time. A: NullPointerException mainly occurs when you are trying to direct to something that does not exist....For ex: You forget to add image in resource folder, and say setBackground(image) or maybe you forgot to mention an activity in the manifest file and are trying to access that activity using Intent.Make sure you have all the resources in your res folder and all activities mentioned in the manifest file A: I found better solution here: http://code.google.com/p/android/issues/detail?id=12359 If you are doing id+System.currentTimeMillis() you could get in next problems: * *a+b = c+d sometimes, so there is small possibility that you still get NPE *you need to store id somewhere to be able to close it for example
{ "language": "en", "url": "https://stackoverflow.com/questions/7607039", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: issues with SVN to check out the code I'm trying to checkout the code of javamaildir from source forge, i configured SVN on my local machine(Windows XP OS) and trying to point to trunk on javamaildir code. But I 'm getting the error RA layer request failed svn: PROPFIND request failed on '/viewvc/javamaildir/javamaildir/trunk' svn: PROPFIND of '/viewvc/javamaildir/javamaildir/trunk': 302 Found (http://javamaildir.svn.sourceforge.net) Can anybody help me why i am getting this error A: That appears to be the web viewer URL. The SVN URL should probably be: https://javamaildir.svn.sourceforge.net/svnroot/javamaildir/javamaildir/trunk
{ "language": "en", "url": "https://stackoverflow.com/questions/7607040", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Counter is updated only once despite clicks I'm trying to build a counter where the admin user of the web site may update a counter by clicking a link. When the user clicks the counter link $.get sends the data to a mySQL record and the record is updated. The number is then sent back to Jquery which updates the counter without refreshing. Up to this point everything works. The problem happens when the user clicks more than once. The MySQL record is updated correctly but the counter is updated only the first time the user clicks the link. Here's my code: <div class='counter' id='4592'><a href=''>Counter: 24</a></div> $.get("jquery.php", { id: $(this).attr('id'), counter: 'increase' }, function(data) { $('.counter').replaceWith('<div class="counter" id="' + $(this).attr('id') + '"><a href="">Counter: ' + data + '</a></div>'); } ); PHP: $id = $_GET['id']; $num = $_GET['counter']; switch ($num) { case 'increase': // ---- Before updating the record get the number saved in the database $qry = mysql_query("SELECT counter FROM table WHERE id='".$id."'") or die(mysql_error()); $number = mysql_fetch_array($qry); $n = $number['counter']; // ---- Increase the counter and update the record $a = $n + 1; mysql_query("UPDATE table SET counter = '".$a."' WHERE id = '".$id."'"); // --- Send data back echo "Counter: ".$a; break; } A: $.get requests are cached by default, so every subsequent request is not actually goes to the server. Use $.ajax request passing cache: false as a parameter or use ajaxSetup to turn off caching globally. A: Few queries - 1. $(this).attr('id') does it work on the callback. Are you getting the correct id ? 2. Replace with replaces the content. Why are you adding the div again to counter ? 3. This should work fine :- $('.counter').replaceWith('<a href="">Counter: ' + data + '</a>'); A: You should setup the defaults of your $.get jquery method for cache: $.get = function(url, callback) { $.ajax({ async : false, type: "GET", url: url, success: callback, cache: true }); }; The other method is using that: $.ajaxSetup({cache : true}); $.get(...); $.ajaxSetup({cache : false});
{ "language": "en", "url": "https://stackoverflow.com/questions/7607041", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Customize the facebook like button I have put up my code in jsfiddle. The link is http://jsfiddle.net/QWAYE/1/ I have also put another sample code in this link http://jsfiddle.net/MCb5K/ The first link is working fine for me and i want to make it look like the second link but dont know what changes i need to do. Please suggest what change i need to do. Also i want to display only the number of person who likes the page and not the name. Right now the name of person is displayed and not the number like how it is showing in the second link. How to do that? Note: I dont want the send button and the rest of the text, only need like button and the number of likes A: You can use the like plugin on the facebook developer page. Go to this link and you will be able to display what you want on the facebook iframe. http://developers.facebook.com/docs/reference/plugins/like/ You select layout style -> button_count
{ "language": "en", "url": "https://stackoverflow.com/questions/7607042", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to display modal window to overlapping the iframe? Am trying to display a file in a modal window when a button in an iframe is clicked. The iframe is present in a main window and an iframe is also there where we have kept a button to view the file in a modal window. The modal window is working fine, but it opens in the iframe itself, but i want that to come out of the iframe and get displayed as a modal window. HTML and Javascript for the view button where the modal window is called in onClick() <span class="btn" title='hh' onClick="window.parent.showModal('../sales_stock/stockForm.php',1160,600);">Add New Stock Statement</span> the show modal function is responsible for poping up the modal window. I want to know what i should do to make the modal window pop out of the iframe. A: If your iframe content from the same domain as you page you can subscribe to the click event from the main page and show popup from the main page. You can't overlap iframe borders from inside. On the main page: $("#myframe").contents().find("#button-inside-of-iframe").click(function(){ $('#mypopup').show(); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7607060", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Extract feeds from web page I'm looking for a code snippet (language is not important here) that will extract all feeds (RSS, atom etc.) that is associated with this page. So input is URL and output list of channels. Important is completeness, it means if the page has associated some information channel it should be found. I'm asking preferably for what to find in HTML code and where to find to cover completeness. thank you A: You find feeds in the head tag in html files. There they should be specified as link tags with an associated content type and a href attribute specifying it's location. To extract all feed urls from a page using python you could use something like this: import urllib from HTMLParser import HTMLParser class FeedParser(HTMLParser): def __init__(self, *args, **kwargs): self.feeds = set() HTMLParser.__init__(self, *args, **kwargs) def handle_starttag(self, tag, attrs): if tag == 'link': try: href = [attr[1] for attr in attrs if attr[0] == 'href'][0] except IndexError: return None else: if ('type', 'application/atom+xml') in attrs or ('type', 'application/rss+xml') in attrs: self.feeds.add(href) def get_all_feeds_from_url(url): f = urllib.urlopen(url) contents = f.read() f.close() parser = FeedParser() parser.feed(contents) parser.close() return list(parser.feeds) This code would have to be extended quite a bit though if you want to cover all the quirky ways a feed can be added to a html page.
{ "language": "en", "url": "https://stackoverflow.com/questions/7607066", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Automatic translation for HTML files I want translate a web page for multiple languages. I can create a .html file for each language, but I would like only one .html file and use an automatic way for translations. Is it be possible? A: It is not possible for a static website. I suggest you stick to having separate files for each locale. A: The easiest way for you to achieve that (since you are obviously the beginner) would be to actually use PHP and generate appropriate language web page on the fly. Alternatively (but I must warn you that this approach may result in very unresponsive web page) you can use JavaScript to translate your web page - in fact jQuery plus Globalize. However, this force you to use common anti-pattern, that is you would need to force users to choose their language as oppose to automatically infer it from web browser's settings. Either way, you have a lot of things to learn...
{ "language": "en", "url": "https://stackoverflow.com/questions/7607069", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: jQuery Google Charting - changing series data I am sure there is a simple solution to this but I can't seem to get it working. I need to change the series data for my chart: This works (in my function): var data = [$.gchart.series('title1', [50], '#F5B800'), $.gchart.series('title2', [40], 'red')]; $('#chart').gchart('change', {series: data}); but I would like to set the series values dynamically from a passed value: (ex) value1 = '[70]'; var data = [$.gchart.series('title1', value1, '#F5B800'), $.gchart.series('title2', [40], 'red')]; $('#chart').gchart('change', {series: data}); This causes a js error and the chart does not render. I've tried a number of combinations without any success. Any ideas? A: Try: value1 = "70"; var data = [$.gchart.series('title1', (value1), '#F5B800'), $.gchart.series('title2', [40], 'red')]; $('#chart').gchart('change', {series: data});
{ "language": "en", "url": "https://stackoverflow.com/questions/7607072", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Order a list by a string value with the same name as the property I'm sure there's a better way to do this but I don't know how. Could I use what they call reflection? I want to order the resultList by the value in id where the id has the same value as the name of the property to order by. var resultList = repository.GetPersons(); // Order the result based on the value in the string id if (id == "organisation") resultList = resultList.OrderBy(p => p.organisation); else if (id == "surname") resultList = resultList.OrderBy(p => p.surname); else if (id == "lastname") resultList = resultList.OrderBy(p => p.lastname); else if (id == "adress") resultList = resultList.OrderBy(p => p.adress); } A: This will surely helps you : Dynamic LINQ OrderBy using String Names! Class public class Person { public DateTime DateOfBirth { get; set; } .... } Use // First we define the parameter that we are going to use // in our OrderBy clause. This is the same as "(person =>" // in the example above. var param = Expression.Parameter(typeof(Person), "person"); // Now we'll make our lambda function that returns the // "DateOfBirth" property by it's name. var mySortExpression = Expression.Lambda<Func<Person, object>> (Expression.Property(param, "DateOfBirth"), param); // Now I can sort my people list. Person[] sortedPeople = people.OrderBy(mySortExpression).ToArray(); A: You could use Dynamic LINQ.
{ "language": "en", "url": "https://stackoverflow.com/questions/7607081", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: CORBA : How to pass a QT object as a parameter I'm new to CORBA and is trying to create a Corba interface for my QT Application. I checked the data types that you could use with CORBA, but I'm not sure if I could use a QT object as a parameter in a CORBA function. What I would want to pass is QWSPointerCalibrationData. Let's say I have a CORBA server code : //pass data.screenPoints and data.devPoints CORBA::Boolean Calibrate( QWSPointerCalibrationData data ) { ... } * *Is this possible? *If yes, how do I declare it in the IDL file? *if not, what CORBA data type can I use so I could pass these type of data? A: As you have the code, this is not possible. You have to specify IDL types equivalent to those that you're using in your application, and also provide (sigh, yes) conversion functions between those types defined in CORBA IDL and the ones defined in your application. As an advantage, you blind your application to future changes in the communication (or RPC) technology, as you're using internally your own types. In this case, looking at the documentation, the QWSPointerCalibrationData type has two data members: QPoint devPoints[5] QPoint screenPoints[5] Then you should declare in your IDL first the QPoint type and then the QWSPointerCalibrationData (I prepend the names with C_ to denote CORBA types): // IDL struct C_Point { long x; long y; }; typedef sequence<C_Point> Points; struct C_WSPointerCalibrationData { Points devPoints; Points screenPoints; }; Then, your server method has to be: CORBA::Boolean Calibrate( C_QWSPointerCalibrationData const& data ) { QWSPointerCalibrationData qpcd = convert_from_CORBA_QWSPointerCalibrationData(data); // use qpcd as usual here } and you have to write the convert_from_CORBA_QWSPointerCalibrationData function yourself (and the corresponding that converts that type to the CORBA counterpart). There are some tools available to do that conversion, but yes, it is a pity, that must be done.
{ "language": "en", "url": "https://stackoverflow.com/questions/7607083", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Unable to Add custom view to Android Action bar,why? I am trying to add my custom view into Action bar. final View addView=getLayoutInflater().inflate(R.layout.home_actionbar_buttons, null); getActionBar().setCustomView(addView); my XML, <LinearLayout android:id="@+id/linearLayout1" xmlns:android="http://schemas.android.com/apk/res/android" android:layout_height="wrap_content" android:layout_width="match_parent"> <Button android:text="Refresh" android:layout_height="wrap_content" android:id="@+id/btn_refresh" android:layout_width="wrap_content"></Button> </LinearLayout but i get nullpointer exception. when i debug,addView object gets populated and its not null. is ViewGroupRoot mandatory while inflating? EDIT 1: Logcat 09-30 12:50:11.625: DEBUG/PackageManager(74): Activities: com.example.actionbar.MainActivity 09-30 12:50:11.645: INFO/ActivityManager(74): Force stopping package com.example.actionbar uid=10047 09-30 12:50:11.825: INFO/installd(34): move /data/dalvik-cache/data@app@com.example.actionbar-1.apk@classes.dex -> /data/dalvik-cache/data@app@com.example.actionbar-1.apk@classes.dex 09-30 12:50:11.825: DEBUG/PackageManager(74): New package installed in /data/app/com.example.actionbar-1.apk 09-30 12:50:12.215: DEBUG/PackageManager(74): generateServicesMap(android.accounts.AccountAuthenticator): 3 services unchanged 09-30 12:50:12.306: DEBUG/PackageManager(74): generateServicesMap(android.content.SyncAdapter): 5 services unchanged 09-30 12:50:12.475: WARN/RecognitionManagerService(74): no available voice recognition services found 09-30 12:50:12.605: DEBUG/dalvikvm(143): GC_EXPLICIT freed 2K, 17% free 14616K/17415K, paused 5ms+26ms 09-30 12:50:12.985: INFO/AccountTypeManager(202): Loaded meta-data for 1 account types, 0 accounts in 14ms 09-30 12:50:13.555: DEBUG/dalvikvm(143): GC_FOR_ALLOC freed 1125K, 17% free 14564K/17415K, paused 121ms 09-30 12:50:14.435: DEBUG/dalvikvm(143): GC_FOR_ALLOC freed 4109K, 33% free 11749K/17415K, paused 155ms 09-30 12:50:15.254: DEBUG/dalvikvm(143): GC_CONCURRENT freed 1055K, 29% free 12509K/17415K, paused 5ms+10ms 09-30 12:50:15.894: DEBUG/dalvikvm(143): GC_CONCURRENT freed 1109K, 24% free 13406K/17415K, paused 6ms+6ms 09-30 12:50:16.404: DEBUG/dalvikvm(143): GC_CONCURRENT freed 1084K, 18% free 14348K/17415K, paused 5ms+6ms 09-30 12:50:16.924: DEBUG/dalvikvm(74): GC_EXPLICIT freed 752K, 47% free 14474K/26951K, paused 49ms+21ms 09-30 12:50:16.944: DEBUG/AndroidRuntime(1196): Shutting down VM 09-30 12:50:16.994: INFO/AndroidRuntime(1196): NOTE: attach of thread 'Binder Thread #3' failed 09-30 12:50:17.044: DEBUG/dalvikvm(1196): GC_CONCURRENT freed 111K, 84% free 331K/2048K, paused 4ms+1ms 09-30 12:50:17.044: DEBUG/jdwp(1196): Got wake-up signal, bailing out of select 09-30 12:50:17.044: DEBUG/dalvikvm(1196): Debugger has detached; object registry had 1 entries 09-30 12:50:17.974: DEBUG/AndroidRuntime(1210): >>>>>> AndroidRuntime START com.android.internal.os.RuntimeInit <<<<<< 09-30 12:50:17.974: DEBUG/AndroidRuntime(1210): CheckJNI is ON 09-30 12:50:19.174: DEBUG/AndroidRuntime(1210): Calling main entry com.android.commands.am.Am 09-30 12:50:19.234: INFO/ActivityManager(74): Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=com.example.actionbar/.MainActivity } from pid 1210 09-30 12:50:19.264: WARN/WindowManager(74): Failure taking screenshot for (216x135) to layer 21005 09-30 12:50:19.315: DEBUG/AndroidRuntime(1210): Shutting down VM 09-30 12:50:19.384: INFO/AndroidRuntime(1210): NOTE: attach of thread 'Binder Thread #3' failed 09-30 12:50:19.384: INFO/ActivityManager(74): Start proc com.example.actionbar for activity com.example.actionbar/.MainActivity: pid=1218 uid=10047 gids={} 09-30 12:50:19.484: DEBUG/dalvikvm(1210): GC_CONCURRENT freed 112K, 83% free 358K/2048K, paused 1ms+1ms 09-30 12:50:19.484: DEBUG/jdwp(1210): Got wake-up signal, bailing out of select 09-30 12:50:19.484: DEBUG/dalvikvm(1210): Debugger has detached; object registry had 1 entries 09-30 12:50:22.095: DEBUG/AndroidRuntime(1218): Shutting down VM 09-30 12:50:22.095: WARN/dalvikvm(1218): threadid=1: thread exiting with uncaught exception (group=0x40014760) 09-30 12:50:22.134: ERROR/AndroidRuntime(1218): FATAL EXCEPTION: main 09-30 12:50:22.134: ERROR/AndroidRuntime(1218): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.actionbar/com.example.actionbar.MainActivity}: java.lang.NullPointerException 09-30 12:50:22.134: ERROR/AndroidRuntime(1218): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1736) 09-30 12:50:22.134: ERROR/AndroidRuntime(1218): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1752) 09-30 12:50:22.134: ERROR/AndroidRuntime(1218): at android.app.ActivityThread.access$1500(ActivityThread.java:123) 09-30 12:50:22.134: ERROR/AndroidRuntime(1218): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:993) 09-30 12:50:22.134: ERROR/AndroidRuntime(1218): at android.os.Handler.dispatchMessage(Handler.java:99) 09-30 12:50:22.134: ERROR/AndroidRuntime(1218): at android.os.Looper.loop(Looper.java:126) 09-30 12:50:22.134: ERROR/AndroidRuntime(1218): at android.app.ActivityThread.main(ActivityThread.java:3997) 09-30 12:50:22.134: ERROR/AndroidRuntime(1218): at java.lang.reflect.Method.invokeNative(Native Method) 09-30 12:50:22.134: ERROR/AndroidRuntime(1218): at java.lang.reflect.Method.invoke(Method.java:491) 09-30 12:50:22.134: ERROR/AndroidRuntime(1218): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841) 09-30 12:50:22.134: ERROR/AndroidRuntime(1218): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599) 09-30 12:50:22.134: ERROR/AndroidRuntime(1218): at dalvik.system.NativeStart.main(Native Method) 09-30 12:50:22.134: ERROR/AndroidRuntime(1218): Caused by: java.lang.NullPointerException 09-30 12:50:22.134: ERROR/AndroidRuntime(1218): at com.example.actionbar.MainActivity.onCreate(MainActivity.java:16) 09-30 12:50:22.134: ERROR/AndroidRuntime(1218): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1048) 09-30 12:50:22.134: ERROR/AndroidRuntime(1218): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1700) 09-30 12:50:22.134: ERROR/AndroidRuntime(1218): ... 11 more 09-30 12:50:24.615: DEBUG/dalvikvm(406): GC_EXPLICIT freed 8K, 6% free 6199K/6531K, paused 4ms+382ms 09-30 12:50:26.825: DEBUG/dalvikvm(143): GC_EXPLICIT freed 991K, 16% free 14644K/17415K, paused 977ms+245ms 09-30 12:50:28.545: WARN/ActivityManager(74): Force finishing activity com.example.actionbar/.MainActivity 09-30 12:50:28.545: WARN/WindowManager(74): Failure taking screenshot for (216x135) to layer 21010 09-30 12:50:29.178: WARN/ActivityManager(74): Activity pause timeout for ActivityRecord{40a10fe0 com.example.actionbar/.MainActivity} 09-30 12:50:29.287: WARN/ActivityManager(74): Launch timeout has expired, giving up wake lock! 09-30 12:50:30.925: WARN/ActivityManager(74): Activity idle timeout for ActivityRecord{40a10fe0 com.example.actionbar/.MainActivity} 09-30 12:50:33.144: INFO/Process(1218): Sending signal. PID: 1218 SIG: 9 09-30 12:50:33.344: INFO/ActivityManager(74): Process com.example.actionbar (pid 1218) has died. 09-30 12:50:33.554: WARN/InputManagerService(74): Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy@406a8790 09-30 12:50:33.874: INFO/Process(1179): Sending signal. PID: 1179 SIG: 9 09-30 12:50:36.494: DEBUG/dalvikvm(420): GC_EXPLICIT freed 10K, 6% free 6195K/6531K, paused 7ms+5ms 09-30 12:50:40.959: WARN/ActivityManager(74): Activity destroy timeout for ActivityRecord{40a10fe0 com.example.actionbar/.MainActivity} 09-30 12:50:41.595: DEBUG/dalvikvm(202): GC_EXPLICIT freed 174K, 5% free 6733K/7047K, paused 10ms+4ms 09-30 12:50:46.618: DEBUG/dalvikvm(345): GC_EXPLICIT freed 17K, 5% free 6277K/6599K, paused 7ms+9ms EDIT 2: Added setCustomView(R.layout.mylayout.xml); before adding to customView into actionbar still not able to see the button in action bar A: I think your problem is most likely that the getActionBar() call is failing due to the action bar not being included in your activity. Try adding the following attribute: android:targetSdkVersion="11" to the 'uses-sdk' node in your manifest. By targeting a honeycomb SDK, you'll get an action bar included in your activity. You can also achieve this by setting the theme of your application to one of the Holo themes. e.g. android:theme="@android:style/Theme.Holo.Light" If you include that attribute in the application node of the manifest, you should also get an action bar to play with. You also need to set the display options on the action bar to DISPLAY_SHOW_CUSTOM for any custom view to appear. Try adding this line after setting the custom view: getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); Check out this page for under 'Using the Action Bar' for more detail: http://developer.android.com/reference/android/app/ActionBar.html Hope that helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/7607085", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: SWFUpload Not Initialising I've loaded the SWFUpload Javascript (confirmed the location is correct for all files loaded) and I've added the code to load a basic SWFUploader, but the problem is, I don't see any button. I don't see anything. Does the following code look correct? <!DOCTYPE html> <html lang="en"> <head> <script type="text/javascript" src="<?php echo base_url() ?>assets/fu/swfupload.js"> </script> <script> var swfu; window.onload = function () { var settings_object = { upload_url : "<?php echo base_url() ?>index.php/upload", flash_url : "<?php echo base_url() ?>assets/fu/Flash/swfupload.swf", file_size_limit : "20 MB", button_placeholder_id : "element_id", button_width : 61, button_height : 22, button_text : "<b>Click</b> <span class="redText">here</span>", button_text_style : ".redText { color: #FF0000; }", button_text_left_padding : 3, button_text_top_padding : 2, button_action : SWFUpload.BUTTON_ACTION.SELECT_FILES, button_disabled : false, button_cursor : SWFUpload.CURSOR.HAND, button_window_mode : SWFUpload.WINDOW_MODE.TRANSPARENT, }; swfu = new SWFUpload(settings_object); }; </script> </head> <body> <h1>Upload Test</h1> </body> </html> A: Try this out : <script type="text/javascript"> var upload1; window.onload = function() { upload1 = new SWFUpload({ // Backend Settings upload_url: "<?php echo base_url(); ?>youURL", post_params: {session_id: '<?= session_id() ?>'}, // File Upload Settings file_post_name: "resume_file", file_size_limit: "10 MB", // 10MB file_types: "*.jpg;", file_types_description: "Allowed Types: ", file_upload_limit: "1", file_queue_limit: "0", // Event Handler Settings (all my handlers are in the Handler.js file) file_dialog_start_handler: fileDialogStart, file_queued_handler: fileQueued, file_queue_error_handler: fileQueueError, file_dialog_complete_handler: fileDialogComplete, upload_start_handler: uploadStart, upload_progress_handler: uploadProgress, upload_error_handler: uploadError, upload_success_handler: uploadSuccess, upload_complete_handler: function() { window.location = 'url_to_load_when_done' }, // Button Settings button_image_url: "/swf/XPButtonUploadText_61x22.png", // location that contains button image button_placeholder_id: "spanButtonPlaceholder1", button_width: 61, button_height: 22, // Flash Settings flash_url: "/swf/swfupload.swf", custom_settings: { progressTarget: "fsUploadProgress1", cancelButtonId: "btnCancel1" }, // Debug Settings debug: false }); } </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/7607095", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to locate silverlight controls to the same location when browsing? I'm trying to create a login screen in silverlight and i was taken two textboxes and put them in two of rows in Grid layout but when i run the app textboxes taking right alignment and stick with end of the window right side, any one help me to get out of this. Thanks, @nagaraju. A: With personal experience with Silverlight, i would recommend using blend 4 for these things. Because it will give you a more direct feel and a look. Most Grids can have a free form, so that you can put anything anywhere.Though if your just writing XAML for it you may be off on your padding and margins for the Textboxes in the the Grid. Also if that's happening their is a Case where your TextBoxes may not be in the Grid, if that's the case it will try and throw it out of the picture but your canvas size is most likely set to the size of the Login Screen so it cant throw it out. Alas putting it in the right lower hand side. I would definitely mess around with the different options inside blend to get that working, if your a Windows Phone DEV then you should have blend 4...but if your a Silverlight WEB DEV you would have to download Sketch Flow or Blend 4 Ultimate. Also if your a student you may access Dreamspark.com and get Ultimate for free. I hope this helps! :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7607097", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Global change to timezone in application I have an MVC3 application that is recently published to a web server. This server has a different timezone than mine, and that means DateTime.Now on this server is different from my own. That also means that all times shown on the website is shown wrong for me. The user base for this application all live in the same time zone, so I am looking for a method to override the servers time zone, and use my own timezone instead. I really don't want to just add or deduct hours based on the difference, since that will get messed up when daylight saving occurs. A: You could use something like this to convert the current UTC date/time to your local time: TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time"); DateTime localTime = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, tzi); Just change the Id passed into TimeZoneInfo.FindSystemTimeZoneById to be your local time zone identifier.
{ "language": "en", "url": "https://stackoverflow.com/questions/7607100", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I set a custom font for the whole application? Is there any way to How to Apply global font [new custom font] to whole application in iphone objective-c. I know that we can use below method to set font for each label [self.titleLabel setFont:[UIFont fontWithName:@"FONOT_NAME" size:FONT_SIZE]]; But I want to change for whole application. Please help me if anyone know. A: Apparently to change ALL UILabels altogether you will need to setup a category on UILabel and change the default font. So here's a solution for you: Create a file CustomFontLabel.h @interface UILabel(changeFont) - (void)awakeFromNib; -(id)initWithFrame:(CGRect)frame; @end Create a file CustomFontLabel.m @implementation UILabel(changeFont) - (void)awakeFromNib { [super awakeFromNib]; [self setFont:[UIFont fontWithName:@"Zapfino" size:12.0]]; } -(id)initWithFrame:(CGRect)frame { id result = [super initWithFrame:frame]; if (result) { [self setFont:[UIFont fontWithName:@"Zapfino" size:12.0]]; } return result; } @end Now ... in any view controller you want these custom font labels, just include at the top: #import "CustomFontLabel.h" That's all - good luck A: Ican's solution with category might be prefered just to save the day. But avoid using category to override existing methods as apple explains: Avoid Category Method Name Clashes ... If the name of a method declared in a category is the same as a method in the original class, or a method in another category on the same class (or even a superclass), the behavior is undefined as to which method implementation is used at runtime. ... Note also that overriding -(id) init; would be safer than overriding -(id)initWithFrame:(CGRect)frame. You would not face with the problem of not receiving touch events when clicking on a label on UIButtons. A: Is this what you mean? @interface GlobalMethods +(UIFont *)appFont; @end @implementation GlobalMethods +(UIFont *)appFont{ return [UIFont fontWithName:@"someFontName" size:someFontSize]; } @end ... [self.titleLabel setFont:[GlobalMethods appFont]]; In case you want to do it somehow automatically (without using setFont on each control), I don't believe it's possible. A: If you can limit your application – or this particular feature – to iOS 5, there’s a new API coming that lets you skin the default UI very conveniently. I can’t give you details, since they are still under NDA at the time I am writing this. Take a look at iOS 5 beta SDK to find out more. A: CustomLabel.h #import <UIKit/UIKit.h> @interface VVLabel : UILabel @end CustomLabel.m #import "CustomLabel.h" #define FontDefaultName @"YourFontName" @implementation VVLabel - (instancetype)initWithCoder:(NSCoder *)aDecoder { self = [super initWithCoder: aDecoder]; if (self) { // Initialization code // Static font size self.font = [UIFont fontWithName:FontDefaultName size:17]; // If you want dynamic font size (Get font size from storyboard / From XIB then put below line) self.font = [UIFont fontWithName:FontDefaultName size:self.font.pointSize]; } return self; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7607108", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: iPhone: UIBarButtonItem as first responder? Is it only classes inheriting from UIControl that can become "first responder"? I need a button in the navigation bar that brings up a UIPickerView using the inputView/inputAccessoryView properties. I know that I can use the customView property of the UIBarButtonItem and create a custom UIButton, but this would need "Photo Shopping" to create an image similar to the UIBarButtonItem "Done" style button (which is what I want). Any suggestions how/if I can get UIBarButtonItem to become first responder? A: Basically any class which inherits from UIResponder (not just UIControl, but also UIView subclasses) can become first responders, but UIBarButtonItem inherits from UIBarItem and NSObject. Hence it can not become the first responder. Out of curiosity, what you are doing is not possible by just displaying the UIPickerView on a button press?
{ "language": "en", "url": "https://stackoverflow.com/questions/7607110", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Center [UIColor colorWithPatternImage]? I couldn't find anything on how you can center the 'image' when you use (maybe you can't): [self setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"background"]]]; Setting my [self setContentMode:UIContentModeCenter]; doesnt help. Do I have to manually draw the image (either in drawRect or set the content of the CALayer? Which one if preferable? A: I think you're on the wrong path here: you create a UIColor from a pattern (pattern already implies this is a repeating image). All in all- you can't have your pattern not repeat and centered. If you just want simple image as background of your UIView, just add it as a subview and center it. UIImage* img = [UIImage imageNamed:@"yourfile.png"]; UIImageView* imgView = [[UIImageView alloc]initWithImage: img]; [yourUIView addSubview: imgView]; imgView.center = CGPointMake(yourUIView.frame.size.width/2, yourUIView.frame.size.height/2); Now - add more subviews to your "yourUIView" view and they'll show on top of the image - thus the image becoming the background. So... no need to draw anything yourself.
{ "language": "en", "url": "https://stackoverflow.com/questions/7607113", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Pdf Not Generated using wkhtmltopdf using automated linux Bash Shell Script? I am trying to generate pdf using automated bash shell script, that script after every min checks the content of a file url.txt which conatins all urls line by line and i am using wkhtmltopdf for pdf generation But the problem is pdf is not generated in the automated process but if i manually invoke that script pdf is generated. If anyone knows the solution please provide it to me? Code of script is: while read line; do wkhtmltopdf $line /var/www/images/Upload_files/name_of_file.pdf done < /var/www/url/url.txt A: If you run it in cron then the most likely reason that it wouldn't work is because lack of an X server. In that case one solution is to use Xvfb Try running your wkhtmltopdf using xvfb-run like this in a no-X environment, say, by ssh-ing to localhost and verify that the $DISPLAY environment variable is not set: $ xvfb-run -e /tmp/xvfb-error.log -s'-screen 0 1024x768x24' wkhtmltopdf somefile.html output.pdf If that works fine then put in in a cron job that runs every 1 minute to test whether that one liner works under cron. Otherwise check the /tmp/xvfb-error.log file to see if xvfb gives any error. It would be helpful if you can state the error message that you got when it doesn't work
{ "language": "en", "url": "https://stackoverflow.com/questions/7607117", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to parse this json data to java Here is the json code..i am new to json parsing..so please let me know how to parse this json data to java. thanks in advance!! { "geometry" : { "location" : { "lat" : 13.0561990, "lng" : 80.2348820 } }, "icon" : "http://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png", "id" : "cf67cea9c203824f58eaf5abe98a08912593bf90", "name" : "Mahalingapuram Branch", "reference" : "CnRsAAAAlAu76wP4EspUn8qk6yUBndsDI7RaEmDaXHc2gP1bomAP_22ZeswWfj3ganEwX9jO2BYjRo6eoeKlwrSeMNDv5h94zqnsNncDntlKN_MqC-gegTBZLX5YxOSA-vzuk6bKe3BJlHytW_wKJJs0Nxf3jRIQT1yYWTlDdMhk9EyS8ulMghoUZK5J51RRVKo12LPdHm_qCQWX_VA", "types" : [ "establishment" ], "vicinity" : "Mahalingapuram Main Road, Nungambakkam, Chennai" } after parsing the java code here but error occur public static void main(String[] args) throws Exception{ InputStream is = JsonParsing.class.getResourceAsStream( ""); String jsonTxt = IOUtils.toString( is ); JSONObject json = (JSONObject)JSONSerializer.toJSON(jsonTxt); JSONObject html_attribution = json.getJSONObject(“html_attribution"); JSONObject geometry= json.getJSONObject(“geometry”); JSONObject location= json.getJSONObject(“location”); double latitude = json.getDouble("latitude"); double longitude = json.getDouble("longitude"); String icon= result.getString("icon"); String id = result.getString("id"); String reference= result.getString("reference"); String name = result.getString("name"); String vicinity = result.getstring("vicinity"); System.out.println("html_attribution: " + html_attribution); System.out.println("location: " + location); System.out.println(“latitude: “ + latitude); System.out.println(“latitude: “ + longitude); System.out.println("result: " + result); } A: I use the following: http://code.google.com/p/google-gson/ Serialize to JSON: Gson gson = new GsonBuilder().create(); String jsonOutput = gson.toJson(someObject); De-serialize from JSON: BagOfPrimitives obj = gson.fromJson(json, BagOfPrimitives.class); A user guide can be found here: https://sites.google.com/site/gson/gson-user-guide A: Use a java library from http://www.json.org/. A: Take a look at the GSON Google project. Its a library that lets you get all your JSON data into Java objects. Its quite simple. A: JSONObject geometry = json.getJSONObject("geometry"); JSONObject location = json.getJSONObject("location"); String lat = location.getString("lat"); String lng = location.getString("lng"); icon = json.getString("icon"); id = json.getString("id"); name = json.getString("name"); reference = json.getString("reference"); vicinity = json.getString("vicinity"); JSOnArray types = json.getJSONArray("types"); for (int i=0;i<=types.length();i++) { JSonObject temJson = (JSONObject) types.get(i); String Varialb = temJson.get(i); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7607119", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Git merge conflict to always take the newest file How can I make a git conflict ALWAYS get resolved by taking the newest file (latest changed timestamp), completley without a prompt? I am building a syncscript with git backend, and I never want to actually merge a file, just override all older copies with the one that was edited/deleted/added last. Edit: With newest file, I mean newest commit containing that file. A: I came up this little merge driver that does what I want. For my purpose it is hard coded to the "master" branch and to the "origin" remote. I do not know how to make these parts dynamic. #!/usr/bin/env sh if git merge-file -p -q "$2" "$1" "$3" > /dev/null; then git merge-file "$2" "$1" "$3"; else MINE=$(git log --format="%ct" --no-merges master -1); THEIRS=$(git log --format="%ct" --no-merges origin/master -1); if [ $MINE -gt $THEIRS ]; then git merge-file -q --ours "$2" "$1" "$3"; else git merge-file -q --theirs "$2" "$1" "$3"; fi fi In short I look for the last commit with git-log that was not a merge, formatted as UNIX timestamp, then I compare them and run a custom git-merge with eiter ours or their version. As a little bonus, it first makes a check to see if it is possible to merge the file without conflict. If that is possible, it merges both files. A: I think you will have to write your own merge-driver for this. See "git help gitattributes", the "Defining a custom merge driver" sections for details on how to do just that. A: Based on @Lilleman answer which is good but has a bug: if a file is modified on local master which is older than origin/master the expected behaviour is to pick origin/master but if you add a commit on top of local master it will pick the local (older version) of the file. git log needs to be executed with an extra argument which is the file path. here a better version including variable branch names it's a bit hacky but it works merge #!/bin/sh cd `findup .git` PATH=$PATH:$( dirname "${BASH_SOURCE[0]}" ) HEAD=`git rev-parse --abbrev-ref HEAD` echo "* merge=newest" > .gitattributes sed -ie '/merge "newest"/,+2d' .git/config echo "[merge \"newest\"]" >> .git/config echo -e "\tname = Merge by newest commit" >> .git/config echo -e "\tdriver = git-merge-newest %O %A %B %L %P $HEAD $1" >> .git/config git merge $1 sed -ie '/merge "newest"/,+2d' .git/config rm .gitattributes cd - git-merge-newest #!/bin/sh if git merge-file -p -q "$2" "$1" "$3" > /dev/null; then git merge-file "$2" "$1" "$3"; else MINE=$(git log --format="%ct" --no-merges "$6" -1 $5); THEIRS=$(git log --format="%ct" --no-merges "$7" -1 $5); if [ $MINE -gt $THEIRS ]; then git merge-file -q --ours "$2" "$1" "$3" >/dev/null else git merge-file -q --theirs "$2" "$1" "$3">/dev/null fi fi findup used #!/bin/sh pwd="`pwd`" start="$pwd" while [ ! "$pwd" -ef .. ]; do [ -e "$1" ] && echo -n "$pwd" && exit cd .. || exit 1 pwd="`pwd`" done exit 1 A: If anyone came here searching for a solution to avoid resolve conflicts arose from automatically generated files such as package-lock.json, pubspec.lock, *.pbxproj, then you can create a .gitattributes file defining a merge strategy package-lock.json merge=union See more info on git attributes
{ "language": "en", "url": "https://stackoverflow.com/questions/7607125", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Advantage and Disadvantage of N2CMS I am currently gathering knowledge on various CMS option's available for .Net(free/open-source). I came across DotNetNuke and N2CMS. Was just wandering thru the source code of n2cms and found it quiet useful. Even thought i don't have much idea about the disadvantage's . Please let me know, if any one of you have worked on n2cms and can let me know the disadvantage and any other OPEN SOURCE CMS option's available. Thanks! A: Disadvantages of N2CMS: * *It does not "feel" like an enterprise-level app, it feels a lot lighter. That's not to say it's not up for a match at that level, but I think it says more about the clever implementation which hides away a lot of the complexity. Note that N2CMS is not a 2+-tiered application, but it looks like there's a recent branch exploring the loading of data from other places (like from an extra tier). *This brings in another disadvantage: it's documentation leaves a lot to be desired. This is due to the small active community and the quickly evolving code. So you'll have a lot of code digging ahead if you want to take full advantage of the ultra-flexible N2CMS. Mind too that the maintainer (libardo) is a very quick responder, both for technical assistance as for bug fixing! *Persistence happens with only 4 tables (if that still holds). "Regular" DB optimization might therefore be impossible. Otoh, premature optimzation is the root of all evil, and on top of that, because you're dealing with NHibernate, you can pull some tricks on that level. *I'm afraid that while still small, Orchard - a somewhat comparable CMS - might catch up on N2CMS, because it has some large players behind it who attract community. Either N2CMS will have to walk an equally "commercial" route, or it is going to be surpassed by Orchard at some time. Having created some NuGet packages was a very good step in that regard! My take on N2 is that it's one of the best CMS's around for developers. A: Consider Umbraco, its architecture is definitely better than DNN's. DNN is an abomination from hell. Most end users hate it with a passion. I like N2CMS, but it's a often a hard sell because the community around it isn't really big... A: Advantage of N2CMS: * *Editing User Experience / Preview Funtionallity - I can navigate the site via it's [frontend] menus, and the cms tree on the left will be synced instantly. Or if the backend is closed, i have a small toolbar that allows to edit the a page immediately or to open the backend right where i am. This is for me also the most important feature N2CMS has and Umbraco is missing.
{ "language": "en", "url": "https://stackoverflow.com/questions/7607126", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Hibernate: Parent-Child Relationship to Itself I have two tables: TABLE NAME: TABLE_A A_ID A_CODE A_DESC TABLE NAME: TABLE_B B_ID B_TABLE_A_PARENT_ID B_TABLE_A_CHILD_ID Where: The TABLE_A's A_ID can be entered in TABLE_B's B_TABLE_A_PARENT_ID and B_TABLE_A_CHILD_ID to create relationship to itself. My Code: @Entity @Table(name = "TABLE_A") public class TableA{ private int id; private String code; private String desc; private Set<TableB> tableBSet= new HashSet<TableB>(0); @OneToMany(fetch = FetchType.LAZY, mappedBy = "tableA", cascade = CascadeType.ALL) public Set<TableB> getTableBSet() { return tableBSet; } public void setTableBSet(Set<TableBSet> tableBSet) { this.tableBSet = tableBSet; } } On another class: @Entity @Table(name = "TABLE_B") public class TableB{ private TableB_Id id; private TableA parentA; private TableA childA; @EmbeddedId @AttributeOverrides({ @AttributeOverride(name = "parentTableId", column = @Column(name = "B_TABLE_A_PARENT_ID", nullable = false, precision = 22, scale = 0)), @AttributeOverride(name = "childTableId", column = @Column(name = "B_TABLE_A_CHILD_ID", nullable = false, precision = 22, scale = 0)) }) public TableB_id getId() { return this.id; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "B_TABLE_A_PARENT_ID", nullable = false, insertable = false, updatable = false) public TableA getParentA() { return this.parentTable; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "B_TABLE_A_CHILD_ID", nullable = false, insertable = false, updatable = false) public TableA getChildA() { return this.childA; } } On the ID class: @Embeddable public class TableB_Id { private int parentTableId; private int childTableId; @Column(name = "B_TABLE_A_PARENT_ID", nullable = false, precision = 22, scale = 0) public Integer getParentTableId() { return this.parentTableId; } @Column(name = "B_TABLE_A_CHILD_ID", nullable = false, precision = 22, scale = 0) public Integer getChildTableId() { return this.childTableId; } } When I run the server I get the following error: Caused by: org.hibernate.AnnotationException: mappedBy reference an unknown target entity property: com.parentchild.TableB.tableA in com.parentchild.TableA.tableB I think the offending code is the first block of code above in TableA but I don't know what to do. Please help kindly me. @OneToMany(fetch = FetchType.LAZY, mappedBy = "tableA", cascade = CascadeType.ALL) public Set<TableB> getTableBSet() { return tableBSet; } Thank you in advance! A: Recently, I mapped @Many-To-Many with composite primary key: you can easily change it to @One-To-Many. here is complete code and explainations: Mapping ManyToMany with composite Primary key and Annotation: A: Reason for that error message is that there is no persistent property named "tableA". Value of mappedBy is supposed to be persistent property. So change it to whatever is supposed to be inverse side. Maybe you want it to be "parentId" or "childId", I don't know, cannot be both. Then you will still have for example following problems: * *No @Id for TableA *public TableB_id : capital I *public class TableB_Id doesn't implement Serializable (it should because it is used as id). *"public void setTableBSet(Set tableBSet) {" Maybe element type should be TableB *there is no id for TableA *In TableB "return this.parentTable" you do not have such a variable *you use property based access without setters
{ "language": "en", "url": "https://stackoverflow.com/questions/7607128", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: iphone : How to draw line on Label? I want to make my label as shown in the image I know I can get this effect by putting image view on it. but is there any other method to do ? How can I put line on label ? A: Try this, UILabel *blabel = [[UILabel alloc] initWithFrame:CGRectMake(XX, 6, 271, 26)]; blabel.text = @"Hellooooooo"; blabel.textAlignment = UITextAlignmentCenter; blabel.backgroundColor = [UIColor clearColor]; blabel.textColor = [UIColor blackColor]; blabel.font = [UIFont systemFontOfSize:14]; [scrollDemo addSubview:blabel]; //underline code CGSize expectedLabelSize = [@"Hellooooooo" sizeWithFont:blabel.font constrainedToSize:blabel.frame.size lineBreakMode:UILineBreakModeWordWrap]; UIView *viewUnderline=[[UIView alloc] init]; viewUnderline.frame=CGRectMake((blabel.frame.size.width - expectedLabelSize.width)/2, expectedLabelSize.height + (blabel.frame.size.height - expectedLabelSize.height)/2, expectedLabelSize.width, 1); viewUnderline.backgroundColor=[UIColor blackColor]; [scrollDemo addSubview:viewUnderline]; [viewUnderline release]; The line above will appear below the text. You just need to change Y for UIView and it'll do wonders :) A: Place a UIImageView with line image on your label so when you run application it will fit. A: put another label with "_" over it transparent background. A: you can create UIView with line's height and width and give background color to it. Put UIView over your UILabel . A: For one of my projects I've created an UILabel subclass, which supports multiline text, underline, strikeout, underline/strikeout line offset, different text alignment and different font sizes. Please see provided link for more info and usage example. https://github.com/GuntisTreulands/UnderLineLabel
{ "language": "en", "url": "https://stackoverflow.com/questions/7607135", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: QList with columns Does anyone know of an easy way to create a QlistView or QListWidget with columns? All I need is a list with 2 columns that is undeitable and sortable.
{ "language": "en", "url": "https://stackoverflow.com/questions/7607136", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: fragments best practice I have a content provider in my Android 3.1 Application, and are calling startActivity() with Intents that has content://my.package/xxx Uris, and Intent.ACTION_VIEW actions. In my andoroid-manifest.xml I have my content provider's mime-types set up so that my Activity picks up the intents. Evert thing works fine. Here is my situation * *When an Activity with fragments is drawn, all fragments receive their life cycle events. *I don't want all fragments to be redrawn/updated on the Intent. Because the incoming URI is usually just passed along to a the query method on my content provider. The intent is usually only relevant to a specific fragment. How do I stop things from happening in fragments that has nothing to do with the current Intent? A: Can you post some code that's relevant to your problem? In particular, the portion of yoru Activity class code that deals with Fragment management, and the layout's .xml file? If you are declaring the fragments directly in the layout's .xml file, the fragments will be instantiated every time. If you do not want this behavior, instantiate and add fragments only programmatically (using FragmentTransacations with the FragmentManager in your activity code, and remove them from the .xml declaration.
{ "language": "en", "url": "https://stackoverflow.com/questions/7607138", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Windows Phone 7 FTP using Sockets I have some Windows Mobile Smart Device applications coded in Visual Studio C# that use FTP for the send/receive mechanism. It's not ideal, but it works. I've been investigating whether these can be ported over to Windows Phone 7 and the major problem is the lack of FTP in Windows Phone. With 7.5/7.1/Mango I'm interested whether Sockets can be used but I can't find a decent wrapper out there. I've started work on my own but I was wondering if I'm just replicating work already available. A: Our SecureBlackbox component suite includes FTP/FTPS and SFTP client components for Mango.
{ "language": "en", "url": "https://stackoverflow.com/questions/7607139", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How can I benchmark malloc implementations? I am comparing between different malloc implementations and I would like to compare their run time and memory usage. In particular, I am interested in the runtime and in the maximum resident memory. It is important that the maximum resident memory will be the real one (without the code segment etc.). I cannot use tools like valgrind, since it replaces the malloc implementation. Also, I run the tests on programs that I have not written, and I prefer not to change their source code. A: You can use rdtscbench for the runtime measurement. See: https://github.com/petersenna/rdtscbench
{ "language": "en", "url": "https://stackoverflow.com/questions/7607140", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: not getting Font effect in PDF when convert HTML To PDF file Using this below Code i am Abel to convert a HTML text To PDF and my code can generate PDF File on particular location . but problem is...... i give font style in body tags so when PDF is generate i am not getting this font style effect in generate PDF ex. // Here On Body Tag I have given a Zurich BT font style StyleSheet styles = new StyleSheet(); //styles.loadTagStyle("body", "font-family", "Zurich BT"); styles.loadTagStyle("body", "font", "Zurich BT"); so here my font style is Zurich BT but i have just got plane simple text on generate PDF not get any effect on text. i am using itextpdf-5.1.1 version and my code is.... ByteArrayOutputStream baos = new ByteArrayOutputStream(); Document pdfDocument = new Document(); Reader htmlreader = new StringReader("<html><head></head><body>" + " <font> HELLO MY NAME IS JIMIT TANK </font> </html></body>"); PdfWriter.getInstance(pdfDocument, baos); pdfDocument.open(); // Here On Body Tag I am giving a Zurich BT font style StyleSheet styles = new StyleSheet(); //styles.loadTagStyle("body", "font-family", "Zurich BT"); styles.loadTagStyle("body", "font", "Zurich BT"); ArrayList arrayElementList = HTMLWorker.parseToList(htmlreader,styles); for (int i = 0; i < arrayElementList.size(); ++i) { Element e = (Element) arrayElementList.get(i); pdfDocument.add(e); } pdfDocument.close(); byte[] bs = baos.toByteArray(); String pdfBase64 = Base64.encodeBytes(bs); //output File pdfFile = new File("c:/pdfExample.pdf"); FileOutputStream out = new FileOutputStream(pdfFile); out.write(bs); out.close(); A: Use iTextSharp Paragraph class and set font and style to it like this Document doc = new Document(PageSize.A4); Paragraph paraReportTitle = new Paragraph(); //paraReportTitle.Font = new Font(Font.FontFamily.HELVETICA, 13f, Font.BOLD); paraReportTitle.Font = new Font(Font.FontFamily.HELVETICA, 8f, Font.NORMAL); doc.Add(paraReportTitle); Setting style to html will not work. You can also use the BaseFont class in iTextSharp
{ "language": "en", "url": "https://stackoverflow.com/questions/7607143", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What are the best practices for passing JSP variables to html tag's attributes? I have a code like <div id="test<%=j%>" class="test" > </div> and my editor shows problems with the matching divs. I suspect this is responsible for a lot of ghosts in my code where values are not populated in beans, etc. Is this a correct way of doing this? Any guidelines or best practices that I should follow? A: This code is syntactically correct. The problem is your editor, which doesn't handle JSP scriptlet expressions. But it's using scriplet expressions, which should not be used anymore (for years). Use the JSP expression language, the JSTL, and other custom tag libraries. Avoid any scriptlet in the JSPs. Java code should be is Java classes (servlets or actions of your preferred MVC framework). <div id="test${j}" class="test"> </div> A: Best practices for JSP 2.0 and later recommend using JSTL in conjunction with Unified Expression Language. <%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %> ... <c:set var="j" value="0"> <div id="test${j}" class="test" > </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/7607147", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to copy a file to an arbitrary location when installing a VSIX project? I am developing a Visual Studio 2010 extension (VSIX project) to add some extra properties to the entities in the Entity Framework designer. In addition to registering the appropriate classes for MEF discovery, I would like a T4 include file to be copied to the %ProgramFiles%\ Microsoft Visual Studio 10.0\Common7\IDE\Extensions\Microsoft\Entity Framework Tools\Templates\Includes folder when the extension is installed, but I don't know how to do it and the VSIX properties page does not seem to show any option for this. So my question is: is there any way to have a given file being copied to a given location when a VSIX project is installed? A: Using VSIX only, no, there is not. Whole contents of VSIX package are during installation simply unzipped into your local extensions directory - and that's END regarding file installations. Whatever you want to copy anywhere, you must deal with it outside of the VSIX installer. For example - use different installer. Or, for another example, upon first-run of your plugin, somewhere in package.Initialize(), check whether the files in question exist in right places, and if not - copy them there. Of course, if you want to write to the ProgramFiles directory, you have another barrier in front of you: the UAC protection. To write there, you will need an another executable that your plugin will run in elevation (and asking the user for permission during that, etc) and it only it will be able to copy the files there. Well, of course, unless you happily assume that everyone always run their VisualStudios "as administrator" and simply ignore the UAC and your users' tears.
{ "language": "en", "url": "https://stackoverflow.com/questions/7607152", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: read cookies in javascript On textbox onchange property i have called one javascript function In that I have written this, function testbox1() { var strline1side1 = document.frmartwork.side1textbox1.value; document.cookie="lineside1="+strline1side1.replace(" "," ")+";path=/;"; } I want to assign this "lineside1" cookie value when page is reload window.onload=function() { document.frmartwork.side1textbox1.value = "here i want that cookie " } How can i do this? A: You should use jquery cookie plugin function testbox1() { var strline1side1 = document.frmartwork.side1textbox1.value; $.cookie('lineside1',strline1side1.replace(" "," ")); } window.onload=function() { document.frmartwork.side1textbox1.value = $.cookie('lineside1') } A: If you are using jQuery - use jQuery.cookies plugin. It's quiet simple to use. $.cookies('cookiename') // get value $.cookies('cookiename', value) // set value function testbox1() { $.cookies('lineside1', $('#side1textbox1').val()); } $(document).ready(function(){ $('#side1textbox1').val($.cookies('lineside1')); }); Also, if you start using jQuery - use it :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7607158", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Google AppEngine Java Web Technologies In the last period, I tried to learn something about the Google cloud technology and I quite liked it. I made a test project for learning GWT bound to GAE, too. In my opinion, the web toolkit is a nice framework for building a Web 2.0 UI from scratch, for those who always worked with Java, but... I think my team is not ready for that, unfortunately. So, I have to choose another front-end technology, rather than leave my mates writing thousands-code-lines JSP. What do you recommend to me? Last year I worked a little with Spring MVC and Struts, but since the project we're going to start is a "green field", I'd like to go for a state of art framework. Remember: * *traditional "page" approach (html views, forms, and so on) *must work on Google App Engine A: This link lists all the supported frameworks on GAE. After going through that list I'd either go with Spring MVC or Struts 1. Here is a CRUD tutorial with sprint MVC to get you started. A: If you have to go with GAE I would stick with GWT (if your devs are good they should be willing to learn :) ), or maybe a simple framework like apache click. Otherwise developing something other than simple Servlet/JSP is a pain even if it doesn't look so at the beginning of the project. A: Try PLAY (http://www.playframework.org/), watch the video and I think you would be sold. It supports GAE through a plugin (http://www.playframework.org/modules/gae). It states that it supports GAE 1.4 but we are using the 1.5.3 SDK and it works just fine. You can also use the siena plugin which is a hibernate-like layer for the GAE datastore. You can develop locally (and have the same file-backed datastore and in-memory memcache), once you are done, hit "gae:deploy", enter your email and password and you're done. A: Let me recommend you using Spring MVC, but using Thymeleaf [http://www.thymeleaf.org] --of which I'm author-- as a view-layer technology instead of JSPs. This combination will provide you with the traditional approach you require (HTML views, forms...) and at the same time will allow you to use a more elegant approach to prototyping and developing your HTML interface. Good luck with your projects. A: I would try Jello framework. It is a Java Application Framework optimized for Google App Engine including comprehensive Data Authorization model, a powerful RESTful engine, and out-of-the-box UI views.
{ "language": "en", "url": "https://stackoverflow.com/questions/7607162", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Changing a background image repeat file I was wondering if it's possible to change what file the background image repeats to when the old image runs out. So, if image01.jpg is set as the first background-image, when it runs out vertically image02.jpq would be added as the background image to complete the page? It might be a straight 'No', thts fine im just wondering A: With CSS3 you can have multiple backgrounds. You can specify a background-repeat for each of them. It is supported by all major browsers, except IE8 and before. http://www.css3.info/preview/multiple-backgrounds/ A: There's always a solution for something in CSS if you're willing to add more markup to your file. Your best bet is to wrap the element you have the first image in with a containing div with the background you would like to appear if the first image runs out. Like so: HTML: <div class="container"><span class="image"></span></div> CSS: .container { background: transparent url(image02.jpg) 100% 0 no-repeat /* Appears on the right */ width: 200px; /* The maximum width */ /* Can also add x pixels padding to ensure that x pixels of image02 are shown */ } .image { background: transparent url(image01.jpg) 0 0 no-repeat; /* Appears on the left */ } Of course you can always replace the <span> with an actual image as well. A: Don't forget that HTML is an element, too. html {/*insert tiling background image*/} body {/*insert normal background image*/} The body background will sit on top of the tiling html background. Works in every browser and won't require additional markup.
{ "language": "en", "url": "https://stackoverflow.com/questions/7607163", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Google analytics for android working but... Where can i check which sections/events of my app have been opened? I can see that GoogleAnalytics web tell me that one guy has done 11 visits to my Android App Its working but.... i dont know where i can check which sections/events of my app have been opened, and i have tracker.trackPageView("/section"); and tracker.trackEvent("licks", "Button", "clicked", 77);in each section/action where i can see it? A: Go to google analytics and it is here --> Standard Reporting / Content / Events / Overview, you can find there those events :-)
{ "language": "en", "url": "https://stackoverflow.com/questions/7607164", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to write build time stamp into apk * *Making some changes in Android Contacts package *Using mm (make) command to build this application Because I have to change and build this app again and again, so I want to add a build time stamp in the Contacts.apk to check the build time when we runn it in the handset. As we know, when we run mm command, the Android.mk (makefile) in Contacts package will be called. And now, we can get the build time using date-macro. But how we can write this build time stamp into a file that our application can read at runtime? Any suggestions? A: Method which checks date of last modification of classes.dex, this means last time when your app's code was built: try{ ApplicationInfo ai = getPackageManager().getApplicationInfo(getPackageName(), 0); ZipFile zf = new ZipFile(ai.sourceDir); ZipEntry ze = zf.getEntry("classes.dex"); long time = ze.getTime(); String s = SimpleDateFormat.getInstance().format(new java.util.Date(time)); zf.close(); }catch(Exception e){ } Tested, and works fine, even if app is installed on SD card. A: Install time : packageInfo.lastUpdateTime build time : zf.getEntry("classes.dex").getTime() Both are differnet time. You can check with the code below. public class BuildInfoActivity extends Activity { private static final String TAG = BuildInfoActivity.class.getSimpleName(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); try { PackageManager pm = getPackageManager(); PackageInfo packageInfo = null; try { packageInfo = pm.getPackageInfo(getPackageName(), 0); } catch (NameNotFoundException e) { e.printStackTrace(); } // install datetime String appInstallDate = DateUtils.getDate( "yyyy/MM/dd hh:mm:ss.SSS", packageInfo.lastUpdateTime); // build datetime String appBuildDate = DateUtils.getDate("yyyy/MM/dd hh:mm:ss.SSS", DateUtils.getBuildDate(this)); Log.i(TAG, "appBuildDate = " + appBuildDate); Log.i(TAG, "appInstallDate = " + appInstallDate); } catch (Exception e) { } } static class DateUtils { public static String getDate(String dateFormat) { Calendar calendar = Calendar.getInstance(); return new SimpleDateFormat(dateFormat, Locale.getDefault()) .format(calendar.getTime()); } public static String getDate(String dateFormat, long currenttimemillis) { return new SimpleDateFormat(dateFormat, Locale.getDefault()) .format(currenttimemillis); } public static long getBuildDate(Context context) { try { ApplicationInfo ai = context.getPackageManager() .getApplicationInfo(context.getPackageName(), 0); ZipFile zf = new ZipFile(ai.sourceDir); ZipEntry ze = zf.getEntry("classes.dex"); long time = ze.getTime(); return time; } catch (Exception e) { } return 0l; } } } A: in your build.gradle: android { defaultConfig { buildConfigField 'String', 'BUILD_TIME', 'new java.text.SimpleDateFormat("MM.dd.yy HH:mm", java.util.Locale.getDefault()).format(new java.util.Date(' + System.currentTimeMillis() +'L))' } } A: I use the same strategy as Pointer Null except I prefer the MANIFEST.MF file. This one is regenerated even if a layout is modified (which is not the case for classes.dex). I also force the date to be formated in GMT to avoid confusion between terminal and server TZs (if a comparison has to be made, ex: check latest version). It result in the following code: try{ ApplicationInfo ai = getPackageManager().getApplicationInfo(getPackageName(), 0); ZipFile zf = new ZipFile(ai.sourceDir); ZipEntry ze = zf.getEntry("META-INF/MANIFEST.MF"); long time = ze.getTime(); SimpleDateFormat formatter = (SimpleDateFormat) SimpleDateFormat.getInstance(); formatter.setTimeZone(TimeZone.getTimeZone("gmt")); String s = formatter.format(new java.util.Date(time)); zf.close(); }catch(Exception e){ } A: So Android Developer - Android Studio User Guide - Gradle Tips and Recipes - Simplify App Development actually documents what to add in order to have a release timestamp available to your app: android { ... buildTypes { release { // These values are defined only for the release build, which // is typically used for full builds and continuous builds. buildConfigField("String", "BUILD_TIME", "\"${minutesSinceEpoch}\"") resValue("string", "build_time", "${minutesSinceEpoch}") ... } debug { // Use static values for incremental builds to ensure that // resource files and BuildConfig aren't rebuilt with each run. // If they were dynamic, they would prevent certain benefits of // Instant Run as well as Gradle UP-TO-DATE checks. buildConfigField("String", "BUILD_TIME", "\"0\"") resValue("string", "build_time", "0") } } } ... In your app code, you can access the properties as follows: ... Log.i(TAG, BuildConfig.BUILD_TIME); Log.i(TAG, getString(R.string.build_time)); I'm including this here since all of the other solutions appear to be from before the official example. A: I know this is really old, but here's how I did it using ant within eclipse: build.xml in project root <project name="set_strings_application_build_date" default="set_build_date" basedir="."> <description> This ant script updates strings.xml application_build_date to the current date </description> <!-- set global properties for this build --> <property name="strings.xml" location="./res/values/strings.xml"/> <target name="init"> <!-- Create the time stamp --> <tstamp/> </target> <target name="set_build_date" depends="init" description="sets the build date" > <replaceregexp file="${strings.xml}" match="(&lt;string name=&quot;application_build_date&quot;&gt;)\d+(&lt;/string&gt;)" replace="&lt;string name=&quot;application_build_date&quot;&gt;${DSTAMP}&lt;/string&gt;" /> </target> </project> Then add an application_build_date string to your strings.xml <resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="app_name">your app name</string> <string name="application_build_date">20140101</string> ... </resources> Ensure the ant script is executed as a pre-build activity and you will always have a valid build date available to you within R.string.application_build_date. A: Since API version 9 there's: PackageInfo.lastUpdateTime The time at which the app was last updated. try { PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0); //TODO use packageInfo.lastUpdateTime } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } On lower API versions you must make build time yourself. For example putting a file into assets folder containing the date. Or using __ DATE__ macro in native code. Or checking date when your classes.dex was built (date of file in your APK). A: If you use Gradle, you can add buildConfigField with timestamp updated at build time. android { defaultConfig { buildConfigField "long", "TIMESTAMP", System.currentTimeMillis() + "L" } } Then read it at runtime. Date buildDate = new Date(BuildConfig.TIMESTAMP); A: Edit: My answer does not work anymore since option keepTimestampsInApk was removed. Working in 2020 is https://stackoverflow.com/a/26372474/6937282 (also https://stackoverflow.com/a/22649533/6937282 for more details) Original answer: A hint for solution "last modification time of classes.dex file" an newer AndroidStudio versions: In default config the timestamp is not written anymore to files in apk file. Timestamp is always "Nov 30 1979". You can change this behavior by adding this line to file %userdir%/.gradle/gradle.properties (create if not existing) android.keepTimestampsInApk = true See Issue 220039 (Must be in userdir, gradle.properties in project build dir seems not to work) A: For time stamping and versioning, build.gradle/android/defaultConfig: def buildDateStamp = new Date().format("yyyyMMdd").toInteger() versionCode buildDateStamp versionName "$buildDateStamp" buildConfigField "String", "BUILD_DATE_STAMP", "\"$buildDateStamp\"" Usage in code: BuildConfig.BUILD_DATE_STAMP resValue "string", "build_date_stamp", "$buildDateStamp" Usage in xml: "@string/build_date_stamp" Caveat: adding HHmm will cause errors (probably integer overflow)
{ "language": "en", "url": "https://stackoverflow.com/questions/7607165", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "64" }
Q: Contex Drawing + Pagination I am trying to draw contents of scrollview into a PDF context & I am facing problem with pagination. Following Code I have used: - (void)renderTheView:(UIView *)view inPDFContext:(CGContextRef)pdfContext { // Creating frame. CGFloat heightOfPdf = [[[self attributes] objectForKey:SRCPdfHeight] floatValue]; CGFloat widthOfPdf = [[[self attributes] objectForKey:SRCPdfWidth] floatValue]; CGRect pdfFrame = CGRectMake(0, 0, widthOfPdf, heightOfPdf); CGRect viewFrame = [view frame]; if ([view isKindOfClass:[UIScrollView class]]) { viewFrame.size.height = ((UIScrollView *)view).contentSize.height; [view setFrame:viewFrame]; } // Calculates number of pages. NSUInteger totalNumberOfPages = ceil(viewFrame.size.height/heightOfPdf); // Start rendering. for (NSUInteger pageNumber = 0; pageNumber<totalNumberOfPages; pageNumber++) { // Starts our first page. CGContextBeginPage (pdfContext, &pdfFrame); // Turn PDF upsidedown CGAffineTransform transform = CGAffineTransformIdentity; transform = CGAffineTransformMakeTranslation(0,view.bounds.size.height); transform = CGAffineTransformScale(transform, 1.0, -1.0); CGContextConcatCTM(pdfContext, transform); // Calculate amount of y to be displace. CGFloat ty = (heightOfPdf*(pageNumber)); CGContextTranslateCTM(pdfContext,0,-ty); [view.layer renderInContext:pdfContext]; // We are done drawing to this page, let's end it. CGContextEndPage (pdfContext); } } It creates required number of pages but places the content wrongly. Following figure explains it. Is there anything wrong in my code? A: I don't think you need the code which flips the PDF upside down. I've done this before (manual pagination, but without a scroll view) and never had to flip the context vertically. My main concern is that you are doing it on every iteration - if you have a valid reason for flipping it, you probably don't need it in the loop, but just once before the loop begins. Also the code CGContextTranslateCTM(pdfContext,0,-ty); might need to be replaced with CGContextTranslateCTM(pdfContext,0,heightOfPdf); If that doesn't work, try UIGraphicsBeginPDFPage(); instead of CGContextBeginPage(), that's the only major difference between your code and mine. A: Found this link to render a PDF, it says about multiple pages but haven't shown an implementation. It doesnt straight away answer to your question but it tells a simpler method to render a pdf with much less translation and transforms. Render PDF Generate Multipage PDF -anoop A: The portions you need to add to pdf pages put in seperate views inside the scroll and render tht view to the pdf context OR Just find the correct dimensions and draw using the CG method: UIImage *Logo=[UIImage imageNamed:@"small-logo-left-top130_133.png"]; CGPoint drawingLogoOrgin = CGPointMake(5,5); UIGraphicsBeginPDFContextToData(pdfData, CGRectZero, nil); UIGraphicsBeginPDFPageWithInfo(pageFrame, nil); CGContextRef pdfContext = UIGraphicsGetCurrentContext(); [Logo drawAtPoint:drawingLogoOrgin]; There are a lot of drawing methods to draw pdf. You can use that to draw all the contents. A: This github project can definitely help you. - (void) renderPageAtIndex:(NSUInteger)index inContext:(CGContextRef)ctx { CGPDFPageRef page = CGPDFDocumentGetPage(pdf, index + 1); CGAffineTransform transform = aspectFit(CGPDFPageGetBoxRect(page, kCGPDFMediaBox), CGContextGetClipBoundingBox(ctx)); CGContextConcatCTM(ctx, transform); CGContextDrawPDFPage(ctx, page); } A: You could consider using a UIScrollView to layout your separate PDF pages. The following method loads each PDF page in a view (PDFView) and adds it to the scroll view content in a centered fashion: - (void) loadPDFAtPath:(NSString *)path { NSURL *pdfUrl = [NSURL fileURLWithPath:path]; CGPDFDocumentRef document = CGPDFDocumentCreateWithURL((__bridge CFURLRef)pdfUrl); float height = 0.0; for(int i = 0; i < CGPDFDocumentGetNumberOfPages(document); i++) { CGPDFPageRef page = CGPDFDocumentGetPage(document, i + 1); PDFView *pdfView = [[PDFView alloc] initPdfViewWithPageRef:page]; CGRect pageSize = CGPDFPageGetBoxRect(page, kCGPDFCropBox); pv.frame = CGRectMake((self.frame.size.width / 2.0) - pageSize.size.width / 2.0, height, pageSize.size.width, pageSize.size.height); height += pageSize.size.height + SOME_SPACE_IN_BETWEEN_PAGES; // self is a subclass of UIScrollView [self addSubview:pdfView]; [pdfView setNeedsDisplay]; } CGPDFDocumentRelease(document); [self setContentSize:CGSizeMake(self.frame.size.width, height)]; } In this case, PDFView is responsible for rendering a single CGPDFPageRef in its drawRect or drawLayer implementation. A: this might help you. - (void) renderPageAtIndex:(NSUInteger)index inContext:(CGContextRef)ctx { CGPDFPageRef page = CGPDFDocumentGetPage(pdf, index + 1); CGAffineTransform transform = aspectFit(CGPDFPageGetBoxRect(page, kCGPDFMediaBox), CGContextGetClipBoundingBox(ctx)); CGContextConcatCTM(ctx, transform); CGContextDrawPDFPage(ctx, page); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7607167", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "54" }
Q: How to do webview animation in android suppose i have three text as heading.Any how you can take textview or anything.one text on left,one in center and one in right side.so i want an animation when i will slide the screen left then left text will be gone,center text will come to left and right text will come to center.Same thing for right slide.Can anyone suggest how can i achieve this type of animation.Plz help. A: You can try to create an animation variable : private Animation leftAnimation() { Animation outtoLeft = new TranslateAnimation( Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 1.0f, Animation.RELATIVE_TO_SELF, 0.0f); outtoLeft.setDuration(500); outtoLeft.setInterpolator(new AccelerateInterpolator()); return outtoLeft; } then set this action to your frame: public void onLeftArrowClick(View v) { frame.setAnimation(moveComingSoonToBottomAnim); // your Frame variable animVariable.startNow();// your anime variable frame.setVisibility(View.VISIBLE); rightFrame.setVisibility(View.GONE); // hide your right text view }
{ "language": "en", "url": "https://stackoverflow.com/questions/7607168", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to make dialog box appear on the left? I want to add OnclickListener for a button,where in I want to display the Dialog box on the left of the screen on click of it.I tried to implement that but it always appears on the center of the screen.Any idea on how to implement that? A: If I understand your question correctly - you want to align your dialog not appear on the center of the screen. Then look at this code sample. AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { if(item == 0) { } else if(item == 1) { } else if(item == 2) { } } }); AlertDialog dialog = builder.create(); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); WindowManager.LayoutParams WMLP = dialog.getWindow().getAttributes(); WMLP.x = 100; //x position WMLP.y = 100; //y position dialog.getWindow().setAttributes(WMLP); dialog.show(); Here x position's value is pixels from left to right. For y position value is from bottom to top. A: Before calling #show() on your AlertDialog you can adjust the gravity of the dialog window: AlertDialog dlg = ...; dlg.getWindow().getAttributes().gravity = Gravity.LEFT|Gravity.CENTER_VERTICAL; This would shift the dialog to the left of the screen. Adjust your gravity flags according to your taste. A: Just add following line in your java file and extra space will remove from dialog box. Dialog dialog; dialog=new Dialog(Activity.this,android.R.style.Theme_DeviceDefault_Light_Panel); Above code work for me. I hope it will be work for others too. Note: You need to pass activity context instead of normal context (getApplicationContext()).
{ "language": "en", "url": "https://stackoverflow.com/questions/7607172", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Locking global array in a reentrancy-desired function in a multithreaded program? Sorry if a question title is confusing. I just wanted to put all the things together. I have a piece of code like: int newThread(int(*pfunc)()) { pthread_t tid; pthread_create(&tid, NULL, pfunc, NULL); int i = 0; while(threads[i] != 0 && i < MAX_NUM_THREADS) { if ((MAX_NUM_THREADS - 1) == i) { puts("We've run out of threads' number limit\n"); return 1; } ++i; } threads[i] = tid; pthread_join(tid, NULL); return 0; } threads[] is a global array. I want to make this function reentrant, but this means I shouldn't use global variables as far as I understand. I guess that's because values of global variables can be unpredictable at a certain time. But in my case the array seems to be quite predictable. * *Is it ok, if I lock array with a mutex to make this function reentrant? *If yes, then how do I do it right? Just lock the first element before using it and unlock after? or is it better to lock/unlock every element while accessing it? *Is this even possible to make this function reentrant? A: To say a function is reentrant, it should only rely on local variables to be simultaneously called by two (or more threads) and return correct results. If the function rely on some shared data, (we can't really made it reentrant), we can make it thread-safe to be called simultaneously by two (or more) threads if all access to the shared data is serialized. To make your function thread-safe, you should lock the loop and the insertion into threads[]. If you lock only the loop part, somebody could modify the content of threads between the end of the loop and the affectation at rank i. pthread_mutex_t mymutex = PTHREAD_MUTEX_INITIALIZER; int newThread(int(*pfunc)()) { pthread_t tid; pthread_create(&tid, NULL, pfunc, NULL); int i = 0; pthread_mutex_lock(&mymutex); // take the lock while(threads[i] != 0 && i < MAX_NUM_THREADS) { if ((MAX_NUM_THREADS - 1) == i) { puts("We've run out of threads' number limit\n"); pthread_mutex_unlock(&mymutex); // don't forget to release the lock here too :) return 1; } ++i; } threads[i] = tid; pthread_mutex_unlock(&mymutex); // release the lock pthread_join(tid, NULL); return 0; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7607174", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }