text
stringlengths
8
267k
meta
dict
Q: VB.NET LINQ group join followed by another group I have two collections of objects in VB.NET that I want to link together using a join, and possibly group together. Basically my objects look like this: Institution * *ID *Name Visit * *ID *InstitutionID *Date *IsFollowUp *IsSelfScheduled A visit has to be to an institution, but an institution can also have no visits. I can link them together using LINQ, but I can't quite get the institutions that do not have any visits to appear in the list also (which is what I am looking for). I know I have to use a group join, but I can't work out how to incorporate the existing join as well. From p In visitList Where p.IsFollowUp = False AndAlso p.IsSelfScheduled = False Group p By Key = p.InstitutionID Into grp = Group Select InstitutionID = Key, Visits = grp, LastVisitDate = grp.FirstOrDefault().ProvisionalDate If the worst comes to the worst, I can implement a private class to do what I want, but it seems like it should be something simple in LINQ. Edit: Okay, using the link below that Tim posted, I managed to come up with something like this: From i In institutionList Select InstitutionID = i.ID, Name = i.Name, Inspections = ( From p In visitList Where p.InstitutionID = i.ID Select p ) It uses a sub-query to pull out the relevant information, but whether it is efficient or not, I have no idea. It seems to pull out the relevant information.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567468", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Collision between two character controller Hello everyone I am new in unity. I create two character on my project. They can move easily. But the problem is I cannot make collision between them. Please help me. Give me some code..... A: First, do you want to 'make' ridigbodies collide or detect the collision? Assuming the latter because that is mostly the objective, collision detection is a very wide topic, and it is difficult to give an exact answer without knowing what exactly is the problem you are facing, and since you are learning, i am giving some links which should be helpful in understanding and implementing collision detection in Unity3d. What you need to study in order to do collision detection is Raycasting. Second, about your specific problem (colliding character controllers) no code can be give since you didn't give any details about your game environment and what have you created, but this should be helpful (study the heading Character Controllers), but do study the basic of collisions and collision detection in detail. and the links: * *Unity3d documentation: Physics *A question about learning collision detection on Unity3d Forums *Apparently a good tutorial *Raycast script reference Hope this helps. In future do mention your specific problem, and what you have done so far, or if you want to start learning, do mention clearly what you want to learn.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567474", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: WCF service attempting to read mdf file I have a Silverlight application, developed in VS2010 and deployed on Server 2008. The application calls a WCF service within the project to read an mdf file, again within the application. After getting through a number of what can only be called bugs within the VS deployement system (missing out the svc.cs file, placing the references in a folder the service can't see) I have managed to get it running. The problem I'm having is that the service fails after a few seconds. Using WCF Storm I was able to run the service and get the following error information: removed, see comments and below has anyone any suggestions as to how to fix this? I'm getting to the end of my tether with WCF services! Thanks in advance Cap Edit: I have now activated errors in the web.config (thanks Upendra Chaudhari) and it has given the following error: <GetDataTypes> <MethodParameters> <FaultException1> <Detail> <HelpLink isNull="true" /> <InnerException> <HelpLink isNull="true" /> <InnerException isNull="true" /> <Message>A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)</Message> <StackTrace>at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning() at System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity) at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, SqlConnection owningObject) at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, TimeoutTimer timeout) at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject, TimeoutTimer timeout, SqlConnectionString connectionOptions, String newPassword, Boolean redirectedUserInstance) at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, String newPassword, SqlConnection owningObject, Boolean redirectedUserInstance) at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection) at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnection owningConnection, DbConnectionPool pool, DbConnectionOptions options) at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject) at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject) at System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject) at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection) at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) at System.Data.SqlClient.SqlConnection.Open() at System.Data.EntityClient.EntityConnection.OpenStoreConnectionIf(Boolean openCondition, DbConnection storeConnectionToOpen, DbConnection originalConnection, String exceptionCode, String attemptedOperation, Boolean&amp; closeStoreConnectionOnFailure)</StackTrace> <Type>System.Data.SqlClient.SqlException</Type> </InnerException> <Message>The underlying provider failed on Open.</Message> <StackTrace>at System.Data.EntityClient.EntityConnection.OpenStoreConnectionIf(Boolean openCondition, DbConnection storeConnectionToOpen, DbConnection originalConnection, String exceptionCode, String attemptedOperation, Boolean&amp; closeStoreConnectionOnFailure) at System.Data.EntityClient.EntityConnection.Open() at System.Data.Objects.ObjectContext.EnsureConnection() at System.Data.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption) at System.Data.Objects.ObjectQuery`1.System.Collections.Generic.IEnumerable&lt;T&gt;.GetEnumerator() at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source) at e_on_silverlight_bing.Web.Services.NewSiteService.GetDataTypes() in C:\Documents and Settings\richardsonl\My Documents\Visual Studio 2010\Projects\E-on Site Map\SilverlightApplication3\e-on silverlight bing.Web\Services\NewSiteService.svc.cs:line 65 at SyncInvokeGetDataTypes(Object , Object[] , Object[] ) at System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]&amp; outputs) at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc&amp; rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc&amp; rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(MessageRpc&amp; rpc) at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)</StackTrace> <Type>System.Data.EntityException</Type> </Detail> <Action>http://schemas.microsoft.com/net/2005/12/windowscommunicationfoundation/dispatcher/fault</Action> <Code>System.ServiceModel.FaultCode</Code> <Message>The underlying provider failed on Open.</Message> <Reason>The underlying provider failed on Open.</Reason> <Data> <KeysAndValues attr0="KeyValuePairArray" isNull="false" /> </Data> <InnerException isNull="true" /> <TargetSite>Void HandleReturnMessage(System.Runtime.Remoting.Messaging.IMessage, System.Runtime.Remoting.Messaging.IMessage)</TargetSite> <StackTrace>Server stack trace: at System.ServiceModel.Channels.ServiceChannel.ThrowIfFaultUnderstood(Message reply, MessageFault fault, String action, MessageVersion version, FaultConverter faultConverter) at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc&amp; rpc) at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout) at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs) 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&amp; msgData, Int32 type) at NewSiteService.GetDataTypes() at NewSiteServiceClient.GetDataTypes()</StackTrace> <HelpLink isNull="true" /> <Source>mscorlib</Source> </FaultException1> It looks like the service cannot see the database. I'm not particularly experienced with this sort of thing so I may be missing something important. Within VS2010 I have the mdf file inside App_Data within the webpage. The service is within the services folder. I have published the site and moved the files and folders to a new folder within wwwroot. Any ideas? Thanks again Cap A: Your problem is one of these: * *your connection string is wrong:you must open web.config file in your web part of your project and right that. *database system is inaccessible because: * *the database computer is turn off *firewall or antivirus of database system is active
{ "language": "en", "url": "https://stackoverflow.com/questions/7567477", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Returning early from a function I'm having a mental block, can someone remind me what the correct term for returning early from a function is, i.e. private MyObject DoSomeStuff(string myValue) { //What is this called?!?!? if(myValue == string.Empty) return null; MyObject obj = new MyObject(); obj.Value = myValue; return obj; } A: I believe it's called a guard clause. A: I would potentially call this an Interrupt. Or, simply, and Early Return. Break might work, too. A: I would call it a "precondition test".
{ "language": "en", "url": "https://stackoverflow.com/questions/7567482", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Converting a textbox into any other html element <form name="txt" method="post"> <input type="text" name="select" id="select" onclick="return selectbox();"> </form> Now through js or html can I change my textbox into a select or a list box. Is it possible by any way. //js code function selectbox() { var select=document.getElementById('select'); select.innerHTML="<select><option>1</option><option>2</option></select>"; } Something like this should happen. In the place of the textbox the below code should appear //new textbox <select><option>1</option><option>2</option></select> A: Yes, for example: var select = document.createElement("select"); select.innerHTML = "<option value='1'>One</option>" + "<option value='2'>Two</option>" + "<option value='3'>Three</option>"; select.id = "select"; select.name = "select"; select.onclick = function(){return selectbox()}; var currentSelect = document.getElementById("select"); currentSelect.parentNode.replaceChild(select, currentSelect); select.focus(); //Focus on the element This code snippet creates a <select> element, and adds new options to it through .innerHTML. Then, the attributes are set. Finally. the script selects the current element with id="select" from the HTML document, and replaces the element by the newly created element. A: Be more specific about what and how. You can try following function selectbox(Sender){ var select = document.createElement('select'); //UPDATE for(var i=1; i<=2; i++) select.options[select.options.length] = new Option(i, i); Sender.parentNode.appendChild(select); Sender.parentNode.removeChild(Sender); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7567485", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Voice Input to Populate Edit Text in android? I am working on voice input in android. I used the sample from http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/app/VoiceRecognition.html And while testing on Xperia X10, I got the "Speak now" dialog but before I input some voice it gets closed. I am trying to implement voice search e.g. If voice input is James Bond then I want to populate the James in first name Edit Text and Bond in Last name Edit Text. Which will search in database for the name. But while trying to use the API Demo sample, its not working. May be I am missing something. Will anybody post any sample for voice input rather than ApiDemos sample. Thanks in advance. A: You can use the following code for voice recognition. For a complete tutorial for voice recognition, Click Here. import android.app.Activity; import android.os.Bundle; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.speech.RecognizerIntent; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import java.util.ArrayList; import java.util.List; /** * A very simple application to handle Voice Recognition intents * and display the results */ public class VoiceRecognitionDemo extends Activity { private static final int REQUEST_CODE = 1234; private ListView wordsList; /** * Called with the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.voice_recog); Button speakButton = (Button) findViewById(R.id.speakButton); wordsList = (ListView) findViewById(R.id.list); // Disable button if no recognition service is present PackageManager pm = getPackageManager(); List<ResolveInfo> activities = pm.queryIntentActivities( new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0); if (activities.size() == 0) { speakButton.setEnabled(false); speakButton.setText("Recognizer not present"); } } /** * Handle the action of the button being clicked */ public void speakButtonClicked(View v) { startVoiceRecognitionActivity(); } /** * Fire an intent to start the voice recognition activity. */ private void startVoiceRecognitionActivity() { Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Voice recognition Demo..."); startActivityForResult(intent, REQUEST_CODE); } /** * Handle the results from the voice recognition activity. */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) { // Populate the wordsList with the String values the recognition engine thought it heard ArrayList<String> matches = data.getStringArrayListExtra( RecognizerIntent.EXTRA_RESULTS); wordsList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, matches)); } super.onActivityResult(requestCode, resultCode, data); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7567487", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "20" }
Q: Formatting float values This is probably a stupid question but anyway. I wan the number I set on my label to be formated nicely like this 20,000,000 . How do I do this ? For now I've set the number of decimal points to 0 so I just get the whole number without any places. [NSString stringWithFormat:@"%.0f", slider.value]; A: Check out the docs for NSNumberFormatter - you can do pretty much everything with that. A: you can use the following formatter: -(void)setCurrencyFormat { NSNumberFormatter *CurrencyFormat = [[NSNumberFormatter alloc] init]; [CurrencyFormat setNumberStyle:NSNumberFormatterCurrencyStyle]; label.text= [CurrencyFormat stringFromNumber:[NSNumber numberWithDouble:billAmountInDouble]]; NSString *st1=[NSString stringWithFormat:@"%@",[CurrencyFormat stringFromNumber:[NSNumber numberWithDouble:individualTaxInDouble]]]; label.text=st1; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7567494", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Switching between forms (VB.NET) I always get an exception when I try to switch between different forms in my program. Maybe you will help me to solve this issue. Here is the exception message: Control.Invoke must be used to interact with controls created on a separate thread I have attached the forms to very nice variables and this problem occurs when I try to use command like MyForm.Show(). It does not happen when the forms are not attached to variables, but then I have collosal problems with refreshing the textboxes and stuff. Hope to hear you soon! edit; I have 4 different forms. When I load the main module and main form, in the Sub (...) Handles MyBase.Load I execute the following code: In module: Public StartupForm As frmStartup Public RegularForm As frmRegularUse Public LoginForm As frmLogin Public PasswordForm As frmPassword Public SettingsForm As frmSettings In main form: RegularForm = Me StartupForm = frmStartup LoginForm = frmLogin PasswordForm = frmPassword SettingsForm = frmSettings This is the aproach I worked out to get the full control over refreshing the forms. It is a program for Motorola Scanner with Windows CE. Now, for example, when I enter the correct password in LoginForm, I want to switch to the RegularForm. When I try to use RegularForm.Show() or RegularForm.ShowDialog or RegularForm.BringToFront(), I get an exception. When I try to call the form with the frmRegularUse.Show() I can call the form, but it is being created in a different thread, I believe, so I loose control over it (when I try to put something from the keyboard, there is no response). A: I doubt the forms are getting created in a different thread, but if they are then STOP, go back, and fix that. All of your forms should be created and accessed from the main GUI thread. Secondly, I don't think you "newed" the forms. You need something like this: StartupForm = New frmStartup RegularForm = New frmRegularUse LoginForm = New frmLogin PasswordForm = New frmPassword SettingsForm = New frmSettings A: Actually, what I did is: Still I have the same code in the main module, which is: Public StartupForm As frmStartup Public RegularForm As frmRegularUse Public LoginForm As frmLogin Public PasswordForm As frmPassword Public SettingsForm As frmSettings I managed it to work in the simpliest possible way. For example - I run the Login form, and execute the following code (long story short): LoginForm = Me frmRegularUse.ShowDialog() I jump to the frmRegularUse form, where, once again, I execute: RegularForm = Me frmPasswordForm.ShowDialog() And so on... I made some tests and it works quite okay. Tomorrow I will try to make it a little bit more sophisticated. ;-)
{ "language": "en", "url": "https://stackoverflow.com/questions/7567495", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: (ios + phone gap) - Profile final app with instruments Is it possible to test a phonegap application for IOS with the inbuilt performance monitoring tool Instruments? When ever i run the APP in the instruments, it says "failed to get task for pid 123". I am using xcode 3.2.x and ios 4.2 A: This is a problem because of the provisioning profile which isn't configured properly. SO to have your instruments running you need your developer and distribution profiles set in the xcode configurations properly. Thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/7567497", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Overlap image over two rows in a listview I need create a listview with pinned overlay image over upper row and next row, like image example below. Thanks a lot. A: set the Layout parameters of image, ie size not exceed to the parent view LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(30, 30); yourImageView.setLayoutParams(layoutParams);
{ "language": "en", "url": "https://stackoverflow.com/questions/7567499", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Why are two AtomicIntegers never equal? I stumbled across the source of AtomicInteger and realized that new AtomicInteger(0).equals(new AtomicInteger(0)) evaluates to false. Why is this? Is it some "defensive" design choice related to concurrency issues? If so, what could go wrong if it was implemented differently? (I do realize I could use get and == instead.) A: This is partly because an AtomicInteger is not a general purpose replacement for an Integer. The java.util.concurrent.atomic package summary states: Atomic classes are not general purpose replacements for java.lang.Integer and related classes. They do not define methods such as hashCode and compareTo. (Because atomic variables are expected to be mutated, they are poor choices for hash table keys.) hashCode is not implemented, and so is the case with equals. This is in part due to a far larger rationale that is discussed in the mailing list archives, on whether AtomicInteger should extend Number or not. One of the reasons why an AtomicXXX class is not a drop-in replacement for a primitive, and that it does not implement the Comparable interface, is because it is pointless to compare two instances of an AtomicXXX class in most scenarios. If two threads could access and mutate the value of an AtomicInteger, then the comparison result is invalid before you use the result, if a thread mutates the value of an AtomicInteger. The same rationale holds good for the equals method - the result for an equality test (that depends on the value of the AtomicInteger) is only valid before a thread mutates one of the AtomicIntegers in question. A: I would argue that because the point of an AtomicInteger is that operations can be done atomically, it would be be hard to ensure that the two values are compared atomically, and because AtomicIntegers are generally counters, you'd get some odd behaviour. So without ensuring that the equals method is synchronised you wouldn't be sure that the value of the atomic integer hasn't changed by the time equals returns. However, as the whole point of an atomic integer is not to use synchronisation, you'd end up with little benefit. A: I suspect that comparing the values is a no-go since there's no way to do it atomically in a portable fashion (without locks, that is). And if there's no atomicity then the variables could compare equal even they never contained the same value at the same time (e.g. if a changed from 0 to 1 at exactly the same time as b changed from 1 to 0). A: On the face of it, it seems like a simple omission but it maybe it does make some sense to actually just use the idenity equals provided by Object.equals For instance: AtomicInteger a = new AtomicInteger(0) AtomicInteger b = new AtomicInteger(0) assert a.equals(b) seems reasonable, but b isn't really a, it is designed to be a mutable holder for a value and therefore can't really replace a in a program. also: assert a.equals(b) assert a.hashCode() == b.hashCode() should work but what if b's value changes in between. If this is the reason it's a shame it wasn't documented in the source for AtomicInteger. As an aside: A nice feature might also have been to allow AtomicInteger to be equal to an Integer. AtomicInteger a = new AtomicInteger(25); if( a.equals(25) ){ // woot } trouble it would mean that in order to be reflexive in this case Integer would have to accept AtomicInteger in it's equals too. A: AtomicInteger inherits from Object and not Integer, and it uses standard reference equality check. If you google you will find this discussion of this exact case. A: Imagine if equals was overriden and you put it in a HashMap and then you change the value. Bad things will happen:) A: equals is not only used for equality but also to meet its contract with hashCode, i.e. in hash collections. The only safe approach for hash collections is for mutable object not to be dependant on their contents. i.e. for mutable keys a HashMap is the same as using an IdentityMap. This way the hashCode and whether two objects are equal does not change when the keys content changes. So new StringBuilder().equals(new StringBuilder()) is also false. To compare the contents of two AtomicInteger, you need ai.get() == ai2.get() or ai.intValue() == ai2.intValue() Lets say that you had a mutable key where the hashCode and equals changed based on the contents. static class BadKey { int num; @Override public int hashCode() { return num; } @Override public boolean equals(Object obj) { return obj instanceof BadKey && num == ((BadKey) obj).num; } @Override public String toString() { return "Bad Key "+num; } } public static void main(String... args) { Map<BadKey, Integer> map = new LinkedHashMap<BadKey, Integer>(); for(int i=0;i<10;i++) { BadKey bk1 = new BadKey(); bk1.num = i; map.put(bk1, i); bk1.num = 0; } System.out.println(map); } prints {Bad Key 0=0, Bad Key 0=1, Bad Key 0=2, Bad Key 0=3, Bad Key 0=4, Bad Key 0=5, Bad Key 0=6, Bad Key 0=7, Bad Key 0=8, Bad Key 0=9} As you can see we now have 10 keys, all equal and with the same hashCode! A: equals is correctly implemented: an AtomicInteger instance can only equal itself, as only that very same instance will provably store the same sequence of values over time. Please recall that Atomic* classes act as reference types (just like java.lang.ref.*), meant to wrap an actual, "useful" value. Unlike it is the case in functional languages (see e.g. Clojure's Atom or Haskell's IORef), the distinction between references and values is rather blurry in Java (blame mutability), but it is still there. Considering the current wrapped value of an Atomic class as the criterion for equality is quite clearly a misconception, as it would imply that new AtomicInteger(1).equals(1). A: One limitation with Java is that there is no means of distinguishing a mutable-class instance which can and will be mutated, from a mutable-class instance which will never be exposed to anything that might mutate it(*). References to things of the former type should only be considered equal if they refer to the same object, while references to things of the latter type should often be considered equal if the refer to objects with equivalent state. Because Java only allows one override of the virtual equals(object) method, designers of mutable classes have to guess whether enough instances will meet the latter pattern (i.e. be held in such a way that they'll never be mutated) to justify having equals() and hashCode() behave in a fashion suitable for such usage. In the case of something like Date, there are a lot of classes which encapsulate a reference to a Date that is never going to be modified, and which want to have their own equivalence relation incorporate the value-equivalence of the encapsulated Date. As such, it makes sense for Date to override equals and hashCode to test value equivalence. On the other hand, holding a reference to an AtomicInteger that is never going to be modified would be silly, since the whole purpose of that type centers around mutability. An AtomicInteger instance which is never going to be mutated may, for all practical purposes, simply be an Integer. (*) Any requirement that a particular instance never mutate is only binding as long as either (1) information about its identity hash value exists somewhere, or (2) more than one reference to the object exists somewhere in the universe. If neither condition applies to the instance referred to by Foo, replacing Foo with a reference to a clone of Foo would have no observable effect. Consequently, one would be able to mutate the instance without violating a requirement that it "never mutate" by pretending to replace Foo with a clone and mutating the "clone".
{ "language": "en", "url": "https://stackoverflow.com/questions/7567502", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "32" }
Q: How to see processed jobs in Resque? Resque has a great web interface on which we can see the pending and failed jobs. But where are the 'proccessed jobs'? How can I know what I have done? A: There is a nice plugin called resque-status that might be of use to you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567504", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Javascript Relational Database Long story short : I'd like to treat several javascript associative arrays as a database (where the arrays are tables). The relations could be represented by special fields inside the arrays. I'm not interested in the persistence aspect of a database, I only want to be able to query the arrays with a SQL-like language and retrieve sets of data in the form of associative arrays. My question : Is there any javascript library that has such features ? Otherwise, is there any library that can at least take care of the SQL-like language part ? Thanks A: I believe the closest thing to what you need is the jLinq library. It can operate with js objects and arrays much in the same way you would do with a database, but in a slightly different way. You don't really write queries, but use methods to construct them. Overall it's way better I think. A: Some googling found this: http://ajaxian.com/archives/two-js-solutions-to-run-sql-like-statements-on-arrays-and-objects which seemed interesting. Can I ask why you want to do this? A: I came across this question while searching something sort of related. Wanted to share with you (9 years later, I do realize) that I have the same want/need, often, where the script I'm working on has a lot of cross-referencing to do between various sources of information. I use PowerShell. Enumerating arrays of objects, from within a loop, which is enumerating other objects, is just bad/slow/horrible. To date, my solution has been to take all my arrays and then make hashtables from them, where the key/name is a property value that is common across all the arrays (e.g. ObjectId (GUID)), and the value is the entire object from the array. With this, while in my loop which is enumerating Array#1, I can check for the presence of this current item in any of the other arrays simply by checking the existence of the key in the corresponding hashtables, and that way there's no enumerating the other array, there's just direct , equal effort access to the correct item in the array (but really coming from the newly built hashtable). So my arrays are just temporary collection buckets, then everything I do from there uses the hashtables, which are just index/lookup tables. What I was searching for when I stumbled here, was for solutions to keep track of all the different hashtables in the building/planning phase of my scripts.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567505", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Creating group in Xcode does not create folder in file system -- why? In Xcode IDE when I add a new group named 'Organizer' inside the default Classes group it is getting created. But when I physically see the folder in the Finder, that new group Organizer is not showing as a folder. Actually I want to maintain the sources in a particular structure i.e, how it exists in the XCode view. What should I do to achieve this? A: You should create all necessary folders within Finder and then add them to project (right mouse click -> Add files to XYZ project). While adding files, options should look like this: UPD: Xcode 9 finally supports automatic folder creation and file reordering for groups operations! A: If you are adding a new group named Organizer inside the default classes group you cant see the physical folder in finder. To make physical folder you should do following steps, 1. Prepare folder structure with files in it. 2. Drag that folder into xcode i.e. project navigation pan. 3. Check the box " Copy items into destination group's folder (if needed) " 4. Select " Create groups for any added folders " After doing this, you will get your folder in finder. Now if you want to add new file then just 1. Right click on folder and click " Add files to < Project_Name >" 2. Select proper file 3. Check the box " Copy items into destination group's folder (if needed) " 4. Select " Create groups for any added folders " 5. Finally click to add You will get that folder with new file added into that. Note : Keep in mind you get yellow colored folder. Thank You.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567511", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "21" }
Q: Intercepting singleton instances I'm receiving "Potential Lifestyle Mismatches" Component 'MyComponent' with lifestyle Singleton depends on 'Castle.TypedFactory.Interceptor' with lifestyle Transient Is there any issue using an Interceptor against multiples singletone instances? ,Component.For<ApiInterceptor>() , AllTypes.FromAssemblyContaining<MyServiceContract>() .Where(Component.IsInSameNamespaceAs<MyServiceContract>()) .Configure(c => c.Interceptors(typeof(ApiInterceptor))) .Configure(c => c.LifeStyle.Singleton) A: It's probably fine. There's a reason why this diagnostics is called potential lifestyle mismatches.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567512", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to add new row on top in Slickgrid? How to add new row on top instead of defaulted to bottom, in slickgrid dataview impelmentation also it is appreciated someone provide example of deleting a row. A: Here is an example function that will work with the example 1-simple.html example.. To Add a Row at the top: function addRow(){ var newRow = {title: "new Title", duration: "1 day"}; var rowData = grid.getData(); rowData.splice(0, 0, newRow); grid.setData(rowData); grid.render(); grid.scrollRowIntoView(0, false); } To Delete row, it is the same idea. Get the grid data collection/ slice the array to get the data out of you want to delete and then call setData and render... A: Sometimes Splice doesn't work. Try the code below: DataView.insertItem(insertBefore, item) ///Here insertBefore can be 0 function addRow() { var newRow = columns, newId = dataView.getLength(); newRow.id = newId + 1; dataView.insertItem(0, newRow); } and then you can call this function on button click. This really works. I have tried it myself.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567518", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Decrypt in Python an encrypted message in Java I'm trying to decrypt in Python (with M2Crypto) an encrypted message generated in Java with this library My code (which I actually found here) works decrypting messages encrypted by itself, but not from Java's library, I get the following error: EVPError: 'wrong final block length' I have tried both *aes_128_cbc* and *aes_128_ecb* and I get the same error. I guess the failure is that Java's result is Ascii's encoded and Python's code is expecting some other encoding (as it works with base64) but I don't know where to make the change (in my Python's code). I'm open to use any other Python encryption library. Thanks import M2Crypto from base64 import b64encode, b64decode ENC=1 DEC=0 def AES_build_cipher(key, iv, op=ENC): """""""" return M2Crypto.EVP.Cipher(alg='aes_128_cbc', key=key, iv=iv, op=op) def AES_encryptor(key,msg, iv=None): """""" #Decode the key and iv key = b64decode(key) if iv is None: iv = '\0' * 16 else: iv = b64decode(iv) # Return the encryption function def encrypt(data): cipher = AES_build_cipher(key, iv, ENC) v = cipher.update(data) v = v + cipher.final() del cipher v = b64encode(v) return v print "AES encryption successful\n" return encrypt(msg) def AES_decryptor(key,msg, iv=None): """""" #Decode the key and iv key = b64decode(key) print key print if iv is None: iv = '\0' * 16 else: iv = b64decode(iv) # Return the decryption function def decrypt(data): data = b64decode(data) cipher = AES_build_cipher(key, iv, DEC) v = cipher.update(data) v = v + cipher.final() del cipher return v print "AES dencryption successful\n" return decrypt(msg) if __name__ == "__main__": result = AES_decryptor(b64encode(SECRET_KEY), msg=encrypted_message) A: What does "ascii encoded" mean? As you know, my code expected base64 input and produced base64 output. Removing the calls to b64decode and b64encode in the encrypt and decrypt functions will let you pass in raw data, then it'll be up to you to decode the input from Java into raw bytes.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567520", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Making a button look pressed in I'm using Eclipse to write the android application. I've added some standard buttons from the Form Widgets tab and successfully got them opening new windows which display additional buttons. I would like the button that was pressed, to change appearance and continue to look pressed in after it is selected. A: create xml file using the button image like this <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_pressed="true" android:drawable="@color/transparent" /> <item android:drawable="@drawable/closebutton" /> </selector> add the color folder in values <?xml version="1.0" encoding="utf-8"?> <resources> <color name="transparent">#00000000</color> </resources> A: can use selector <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_focused="true" android:state_pressed="false" android:drawable="@drawable/button_settings" /> <item android:state_focused="true" android:state_pressed="true" android:drawable="@drawable/button_settings" /> <item android:state_focused="false" android:state_pressed="true" android:drawable="@drawable/button_settings_selected" /> <item android:drawable="@drawable/button_settings" /> </selector> now set this drawable on background property of button in XML, now in coding take a boolean flag when button is pressed set the flag and set the bacground of the button(selected image) and on again click reset flag value and change the imageBackground to the selector again, thats it!!! A: Use ImageButton and change the background of the button. you can use this kind of images depends of you need. Like this https://web.archive.org/web/20160429124711/http://www.devahead.com/blog/2011/08/creating-a-custom-android-button-with-a-resizable-skin/
{ "language": "en", "url": "https://stackoverflow.com/questions/7567521", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Painting in Swing, blinking issue I have the following problem in swing. I'm implementing basic drawing operations (lines, shapes). When I'm moving mouse with pressed left button, I need to repaint current shape. So I clear the screen and repaint already drawn shapes and currently being drawn one. Shapes are drawn in paint() method and on mouse move event I call repaint() (paint() is called automatically). The problem is that the screen is blinking strongly on each repaint and it looks really ugly. Please tell me, what I'm doing wrong? Thanks. A: I think what you are looking for is double buffering. A: Shapes are drawn in paint() Custom painting should be done in the paintComponent() method and make sure you invoke super.paintComponent() as the first line. Also custom painting is done on a JPanel (or JComponent), not on the JFrame directly. A: I had flickering or blinking problem. I solved it using the following code. public void update(Graphics g) { paint(g); } @Override public void paint(Graphics g) { //super.repaint(); if (myimg != null) { g.drawImage(myimg, 0, 0, this); } //update(g); } A: You don't need to clear the screen, you just call repaint() then it's enough. If you have to clear the screen, it'll blink if you don't use synchronization, because the painting job is done in a separate thread.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567522", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to use large database (Sqlite more than 100 MB) in android application? i develop one application in which require sqlite database. Database size is very large approx. 100 Mb. so i have not any idea which way use these database in my application. database is some private contents so not installed in sdcard... * *Can android app support or store 100MB database in data directory ? *If app store database in sdcard then , any other way to implement so user can not see or used these database ? *How to encode my sqlite database and store in device so user can not used these database ? Please anyone suggest me if any idea related to large database. A: I think u can store the database file in the data directory. There is no such restriction on the size of file in Android I suppose. At least I have never read about any such restriction.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567526", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can 2 .net executables call functions on eachother? if I have 2 seperate .net executables how would one exe call functions on the other one? A: .NET executables are still assemblies. From VS2008 onwards, it is trivial to add a reference to a .NET exe (in VS2005 you have to use command-line for this). So simply ensure that the target exe exposes some public classes and methods. A: Use it: Assembly ass = Assembly.LoadFile("pathtoYourExe"); Type myType = ass.getType ("Full name of type whose method you need to call"); myTypeName inst = (myTypeName) Activator.CreateInstance(myType); But if you want to call methods of runnning application - use WCF or .NET remoting.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567529", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to script a stored procedure from TSQL I know there's a way to do this as I've seen it done - I just can't remember how. I want to run a SQL command which will return the script to create the stored procedure as a result. How can I do this? A: SELECT OBJECT_DEFINITION(OBJECT_ID('your_schema.your_procname')) or EXEC sp_helptext 'your_schema.your_procname' A: Try using sp_helptext command : sp_helptext 'yourprocname' or using object_definition : SELECT OBJECT_DEFINITION(OBJECT_ID('yourprocname')) A: In SQL Server Management Studio, right-click the proc in the Object Explorer window and choose Script Stored Procedure as ...then choose the operation (Create, Drop, etc.) you want to script.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567530", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to redirect to local html page in phonegap android app? I am trying to create a android app with phonegap, the first page is the login page, it queries to a server for user authentication, the server returns json string: true if the login is successful or false otherwise. I am getting the response but i am not able to redirect to next html page. I am using the below code $('#loginForm').submit(function(){ var uid = $('#login').val(); var pwd = $('#password').val(); $.getJSON('http://example.com/phonegap/login.php', { userid: uid, password: pwd }, function(json) { $.each(json, function(k, v) { if(v == "true" || v == true){ super.loadUrl("file:///android_asset/www/page2.html"); } else { $('#loginError').html("Login failed, username and/or password don't match"); } }); }); return false; }); Please let me know, how can I redirect the user to page2.html after successful login? A: You can call other html pages using window.location and if your second html page present in www folder dont give full path (Please remove your native way path). Please check out following code.$('#loginForm').submit(function(){ var uid = $('#login').val(); var pwd = $('#password').val(); $.getJSON('http://example.com/phonegap/login.php', { userid: uid, password: pwd }, function(json) { $.each(json, function(k, v) { if(v == "true" || v == true){ window.location="page2.html"; } else { $('#loginError').html("Login failed, username and/or password don't match"); } }); }); return false; }); A: from a pure javascript perspective, Will window.location.href = 'something.html'; not work? A: Try the jQuery load method http://api.jquery.com/load/ A: karnyj is right, as the marked solution is bugged for iOS. Using window.location = "url" will sometimes freeze the application in iOS (happens every time I restart the device). //This is the way to go window.location.href = 'something.html'; A: Relative paths should be fine. I have found window.location = './yourPage.html' (and window.location.href = './yourPage.html') don't always work, and have had success using : window.location.replace('./yourPage.html'); A: window.location.replace('xyz.html'); Works always !
{ "language": "en", "url": "https://stackoverflow.com/questions/7567531", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Trouble with strings in C I'm newbie in C world and I have two probably stupid questions. I'm reading about structures in C and here is where I stuck. Let say we have structure like this typedef structs { char model[50]; int yearOfManufacture; int price; } Car; Car Ford; Ford.yearOfManufacture = 1997; Ford.price = 3000; //The line below gives me an error "Array type char[50] is not assignable Ford.model = "Focus" How to pass text into Ford.model in that case ? My second question is also about strings. This code works fine char model[50] = "Focus"; printf("Model is %s", model); But this one doesn't char model[50]; model = "Focus"; Can anyone explain why it doesn't work ? A: That's not how you copy strings in C. Try strcpy(Ford.model, "Focus"); Alternatively (but with very different semantics): typedef structs { char const *model; int yearOfManufacture; int price; } Car; model = "Focus"; These C FAQs explain more about the issue: * *Assign to array *How can an array be an lvalue, if you can't assign to it? A: There are two ways to "put values in objects": * *with initialization, when the object is created *with assignment, after the object is created Though the syntax is similar, they represent different concepts. You can initialize an array, but you cannot assign to it. Also there's a special construct to initialize char arrays based on string literals char arr[] = "foobar"; char arr[] = {'f', 'o', 'o', 'b', 'a', 'r', '\0'}; int arr[] = {1, 2, 3, 4}; // ... but, assignement must be done element by element char arr[4]; arr[0] = arr[1] = arr[2] = 'X'; arr[3] = '\0'; int arr[4]; arr[0] = arr[1] = arr[2] = 42; arr[3] = -1; A "special" way to assign elements of a char arrays one-by-one with a single statement is to use the library function strcpy() with prototype in <string.h> #include <string.h> int main(void) { char arr[10]; strcpy(arr, "foo"); // same as arr[0]='f'; arr[1]=arr[2]='o'; arr[3]='\0'; return 0; } A: This (Ford.model = "Focus") is not possible. You have to copy the string into the array in the struct, best with strcpy: strcpy(Ford.model, "Focus"); If your stdlib supports it, you should also consider an overflow safe version, e.g strncpy: strncpy(Ford.model, "Focus", sizeof Ford.model); At least I think its an extension function and not in the standard... I'm not sure. A: You can't assign to a character array with =, you can only initialize it. When you write char model[50] = "Focus"; that is a initialization. When you write model = ... that is an assignment. And, as I said, assignment to character arrays is not allowed. You need to copy to the character array using strcpy(), e.g. strcpy(model, "Focus"). A: You can assign a string during definition, but anywhere else you have to use a different method, like the strcpy() function: char model[50]; strcpy(model, "Focus");
{ "language": "en", "url": "https://stackoverflow.com/questions/7567541", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Disable Zend Form Element validation if hidden I have a few elements in my zend form that are sometime hidden via javascript. I would like to disable their validations if they are hidden, so the form will be valid. Any way to do it in the server side? or in the element settings? Thanks. A: Depending on the situation, you could at the same time disable the hidden items. Thus they won't be posted and you could then use isValidPartial that only validates the fields that are send in parameter. A: I think you might need to remove the validators for the hidden fields (by calling clearValidators()) before calling isValid(). There is a similar question here: Zend form validation . You might get some inspiration from the answers. Hope it helps,
{ "language": "en", "url": "https://stackoverflow.com/questions/7567542", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Benefit from generated getters and setters in Play! framework The Play! framework generates getters and setters for each public field of a model class at runtime. public class Product { public String name; public Integer price; } will be transformed to public class Product { public String name; public Integer price; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getPrice() { return price; } public void setPrice(Integer price) { this.price = price; } } The manual explains further: Then when you want to access a property you can just write: product.name = "My product"; product.price = 58; Which is translated at load time to: product.setName("My product"); product.setPrice(58); ... and warns: You can’t directly use getter and setter methods to access properties if you rely on automatic generation. These methods are generated at runtime. So if you reference them in code you write, the compiler won’t find the methods and will generate an error. Since I cannot use these getters and setters from outside of the Play! project, I see no benefit in generating them. What is the benefit compared to public fields, refactorings (encapsulate a field and change the callers) of all modern IDEs taken into account? A: Short answer: Beans require them. Longer: Beans specification requires (amongst other things) getter/setter for each internal field. I'm not 100% sure, but I assume both Hibernate and Groovy templates expect Java Beans (the POJO Beans, not the Java EE one!), thus they'll ask for getters/setters. Play just saves you time doing that, so you don't have to worry with boiler-plate code (unless you want to define your own getter/setter for some reason, which you can do). A: Another reason,, is although you don't have to specify the setters and getters, you still can! So, if you have (per your example) product.name = "my product" That's fine, and makes your code quicker and in my opinion easier to read. However, there is a good reason for setters and getters for encapsulation. If you wanted to add some logic when your product.name is changed, you can specify your own setter, but you don't have to change the code above, as it will continue to call the setter behind the scenes. So, this gives you the flexibility and power of good encapsulation, but the neatness and readability of direct field access. I my opinion this is the best of both worlds. A: If you have a private getter/setter method, then this will not work as it is not possible to create a public getter/setter method with same name. So it will fail at run time!
{ "language": "en", "url": "https://stackoverflow.com/questions/7567550", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Solution needed for outputting status of processed files with MVC 3 I have to functions for handling processing of files in a directory. One function reads and counts the files in the directory and foreach file it calls a function that does some action on that file. What i need is how to update a DIV tag everytime a file is processed. The files are done in sync and is startet by calling the first function. Right now i return a partialview, but it first return when alle the files are done. As there can be up to 1000 files, i would like to give the user somekind of progress information. Kind regards \T A: Here is one example of Copying file file with a progress status.. You can modify this as per your requirement. If you wish to show the progress you can use ajax or JSON with a jQuery timer which requests number of files of destination folder.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567551", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Keep the class state in C++ after Returning to C# I have a C++ as the backend and C# as the front end, I use pinvoke interop mechanism to communicate between the native and managed code. The issue now is that there are really two parts of computation done by the C++ backend, the initialization part and the compute-on-the-fly part. The initialization needs to be done only once, but it takes a long time to do, whereas the compute-on-the-fly part takes a very short time to do, but it needs to be done over and over again. And the C++ code as to be kept as it is and can't be rewritten into C# code. I can modify both the C++ and C# code as I have them at my disposal. I know how to do static interop, but I don't know how to do this kind of state-full interop. Any idea? A: You could write a wrapper around your C++ class(es) in C++/CLI thus providing true CLR types. You can than manage their lifecycle in C# seamlessly. * *There is quite some information on the web for it: here or here (just google "C++/CLI wrapper"). *And, naturally, on stackoverflow: here. Unless there is some nifty tool, you would have to write this wrapper yourself. Alternatively, you could write a wrapper function (or a set thereof) around your C++ classes, possibly only exposing the minimum required functionality as "C" functions. You would then passe out a "HANDLE" (Int32, IntPtr, whatever) out of the init-function and requiring it as input for the compute-function. You would have to manage those internally in the wrapper functions (you might also want to provide a cleanup-function).
{ "language": "en", "url": "https://stackoverflow.com/questions/7567556", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Why does my import file not work? I am trying to make my file ClickingButtons.java to work, but I am getting an error that it cant find the symbols playerHasItem & freeSlots. Now I tried importing my ItemAssistant.java file, which has the public ints playerHasItem & freeSlots, but after saving and compiling it is still giving me the same errors! :( This is my import statement in ClickingButtons.java: import server.model.items.ItemAssistant; And these are the public ints in my ItemAssistant: public int freeSlots() { int freeS = 0; for (int i=0; i < c.playerItems.length; i++){ if (c.playerItems[i] <= 0){ freeS++; } } return freeS; } public boolean playerHasItem(int itemID, int amt, int slot) { itemID++; int found = 0; if (c.playerItems[slot] == (itemID)) { for (int i = 0; i < c.playerItems.length; i++) { if (c.playerItems[i] == itemID) { if(c.playerItemsN[i] >= amt) { return true; } else { found++; } } } if(found >= amt) { return true; } return false; } return false; } public boolean playerHasItem(int itemID, int amt) { itemID++; int found = 0; for (int i = 0; i < c.playerItems.length; i++) { if (c.playerItems[i] == itemID) { if(c.playerItemsN[i] >= amt){ return true; } else{ found++; } } } if(found >= amt) { return true; } return false; } The code that calls fo these ints: if (c.dialogueAction == 717) { if (freeSlots() > 0) { if (c.tempRune == 1)//air { if (c.omniQuest == 2) { if (c.getItems().playerHasItems(995,10000) && c.getItems().playerHasItems(556,10)) { c.getItems().deleteItems(995,10000); c.getItems().deleteItems(556,10); c.getItems().addItems(13599, 1); c.getDH().sendDialogues(749,57); } else if (!c.getItems().playerHasItems(995,10000)) { c.getDH().sendDialogues(750, 57); } else if (!c.getItems().playerHasItems(556,10)) { c.getDH().sendDialogues(751, 57); } } else if (c.getItems().playerHasItems(995,20000) && c.getItems().playerHasItems(556,20)) { c.getItems().deleteItems(995,20000); c.getItems().deleteItems(556,20); c.getItems().addItems(13599, 1); c.getDH().sendDialogues(749,57); } else if (!c.getItems().playerHasItems(995,20000)) { c.getDH().sendDialogues(750, 57); } else if (!c.getItems().playerHasItems(556,20)) { c.getDH().sendDialogues(751, 57); } } else if (c.tempRune == 6)//body { if (c.omniQuest == 2) { if (c.getItems().playerHasItems(995,10000) && c.getItems().playerHasItems(559,10)) { c.getItems().deleteItems(995,10000); c.getItems().deleteItems(559,10); c.getItems().addItems(13604, 1); c.getDH().sendDialogues(749,57); } else if (!c.getItems().playerHasItems(995,10000)) { c.getDH().sendDialogues(750, 57); } else if (!c.getItems().playerHasItems(559,10)) { c.getDH().sendDialogues(751, 57); } } else if (c.getItems().playerHasItems(995,20000) && c.getItems().playerHasItems(559,20)) { c.getItems().deleteItems(995,20000); c.getItems().deleteItems(559,20); c.getItems().addItems(13604, 1); c.getDH().sendDialogues(749,57); } else if (!c.getItems().playerHasItems(995,20000)) { c.getDH().sendDialogues(750, 57); } else if (!c.getItems().playerHasItems(559,20)) { c.getDH().sendDialogues(751, 57); } } else if (c.tempRune == 13)//astral { if (c.omniQuest == 2) { if (c.getItems().playerHasItems(995,10000) && c.getItems().playerHasItems(9075,10)) { c.getItems().deleteItems(995,10000); c.getItems().deleteItems(9075,10); c.getItems().addItems(13611, 1); c.getDH().sendDialogues(749,57); } else if (!c.getItems().playerHasItems(995,10000)) { c.getDH().sendDialogues(750, 57); } else if (!c.getItems().playerHasItems(9075,10)) { c.getDH().sendDialogues(751, 57); } } else if (c.getItems().playerHasItems(995,20000) && c.getItems().playerHasItems(9075,20)) { c.getItems().deleteItems(995,20000); c.getItems().deleteItems(9075,20); c.getItems().addItems(13611, 1); c.getDH().sendDialogues(749,57); } else if (!c.getItems().playerHasItems(995,20000)) { c.getDH().sendDialogues(750, 57); } else if (!c.getItems().playerHasItems(9075,20)) { c.getDH().sendDialogues(751, 57); } } } else { c.getDH().sendDialogues(752, 57); c.tempRune = 0; } } Also, the import directory is correct. Why oh why is it not working? A: Your declaration describes method with three int parameters: playerHasItem(int itemID, int amt, int slot) yet you are calling it with two: playerHasItems(995,20000) There is simply no method with two parameters declared.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567558", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jquery to loop through table for text comparison Looping through the table is not a problem. Looping through the table and do comparison at the same time assigning the other td in same row with different value is a problem. How can this be done ??? - going through #tblView tbody tr.class - to find through all row for second td and see whether the .text() is "completed" - if yes - then third td's span's inner text set to "bingo" - else - do nothing - end <table id="tblView"> <tbody> <tr class="class"> <td>completed</td> <td></td> <td></td> </tr> <tr class="class"> <td>not yet</td> <td></td> <td></td> </tr> </tbody> </table> A: Try - $("#tblView tbody tr.class").each(function() { if ($(this).find("td:eq(1)").text() === "completed") $(this).find("td:eq(2)").text('bingo'); }) Demo - http://jsfiddle.net/d45ZQ/1/
{ "language": "en", "url": "https://stackoverflow.com/questions/7567566", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: NSTableView Height resizing I am using NSTableView to display my data. I have to change table data by clicking some buttons. So number of rows are not fix. Sometime it use only 2 rows and sometimes 12. When it takes only 2 rows then table looks not good. What i want is my tableview height can be resize according to number of rows or cell used. I tried this but its not working with me.. Infect i can't even see my table by using that code. I am using NSWindowController. EDIT : - (void)addImageToTableView { [tableView setBackgroundColor:[NSColor clearColor]]; [tableView setHeaderView:nil]; if([title isEqualToString:@"First"]){ if ([[arrayController arrangedObjects] count] != 0) { [arrayController removeObjectsAtArrangedObjectIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, [[arrayController arrangedObjects ] count])]]; } [arrayController addObject:[NSDictionary dictionaryWithObjectsAndKeys:[NSImage imageNamed:@"MS.png"],@"image", nil]]; [arrayController addObject:[NSDictionary dictionaryWithObjectsAndKeys:[NSImage imageNamed:@"CVS.png"],@"image", nil]]; } if ([title isEqualToString:@"Second"]) { if ([[arrayController arrangedObjects] count] != 0) { [arrayController removeObjectsAtArrangedObjectIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, [[arrayController arrangedObjects ] count])]]; } [arrayController addObject:[NSDictionary dictionaryWithObjectsAndKeys:[NSImage imageNamed:@"NS.png"],@"image", nil]]; [arrayController addObject:[NSDictionary dictionaryWithObjectsAndKeys:[NSImage imageNamed:@"EM.png"],@"image", nil]] ; [arrayController addObject:[NSDictionary dictionaryWithObjectsAndKeys:[NSImage imageNamed:@"RES.png"],@"image", nil]]; [arrayController addObject:[NSDictionary dictionaryWithObjectsAndKeys:[NSImage imageNamed:@"ERS.png"],@"image", nil]] ; [arrayController addObject:[NSDictionary dictionaryWithObjectsAndKeys:[NSImage imageNamed:@"RS.png"],@"image", nil]]; [arrayController addObject:[NSDictionary dictionaryWithObjectsAndKeys:[NSImage imageNamed:@"FB.png"],@"image", nil]] ; [arrayController addObject:[NSDictionary dictionaryWithObjectsAndKeys:[NSImage imageNamed:@"SKIN.png"],@"image", nil]]; } [tableView reloadData]; [self windowDidLoad]; } -(void)windowDidLoad{ [super windowDidLoad]; } Any other suggestion?? Thanks in advance..!!
{ "language": "en", "url": "https://stackoverflow.com/questions/7567569", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PySide methods signature in Eclipse/WingIDE/PyCharm? Is there any way to have the signature of the methods of PySide classes in Eclipse, WingIDE, PyCharm or any Python IDE? Currently, it auto-completes the classes and method names, but not the parameters of the methods. All functions are detected as functions without parameters. I know it's a Python binding of a C++ framework so it's not that easy but is there any way to have the method signatures directly in an IDE? A: I use PyDev (Eclipse plugin) and it works like a charm, also with function signatures. EDIT: I'm not 100% sure with C++ extensions, but it should work well if there's a Python wrapper for it. With pure C++ extensions there might be problems, but actually I haven't tried it. A: Try running help(some-qt-method) in a Python console, what do you see? Exactly. As far as I know, the only IDE that handles PyQt / PySide in depth is Eric, and only because it explicitly compiles signatures in its own format for autocompletion.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567572", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: iPhone - Is there any way to cancel a request to the EventKit database? I am trying to figure out if it is possible to cancel a query to the EventKit database. I query the EventKit with a predicate that matches all events in a certain week. This query can take some time depending on how many events are returned. Why do I want this? Well, in my iPhone app the user browses through the weeks of his calendar. Every time a new week is shown to the user, the app has to load all the events for that week. Because this takes a couple of hundred milliseconds, the app isn't as responsive as it should be. The user basically has to browse a little slower because the user interface stalls for a short while every time he browses to another week. I am already running the query in a background thread using "performSelectorInBackground". This still stalls the user interface quite a bit. The solution that I'm thinking of is that whenever the user decides to browse to another week, the current EventKit query is cancelled. The drawback of this is probably that the user sometimes doesn't see the events for that week immediately because the query was cancelled, but the UI will hopefully be highly responsive at all times. So is this at all possible? Does anyone know? Can I cancel an EventKit query? Maybe by stopping the thread it is running in? Any advice is welcome! A: It's not clear how you are performing the query at the moment. Possibly using -[EKEventStore eventsMatchingPredicate:]? An alternative might be to use -[EKEventStore enumerateEventsMatchingPredicate:usingBlock:]. The block you supply is called once for each event found and you can signal that the search should stop. Do something like: [eventStore enumerateEventsMatchingPredicate:predicate usingBlock:^(EKEvent *event, BOOL *stop) { if (event) { ...add event to some collection... } if (shouldStop) { *stop = YES; } }]; This call is synchronous but can be performed on another thread with dispatch_async or NSOperation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567576", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: XULRunner Error: couldn't parse application.ini. I have downloaded XULRunner from http://releases.mozilla.org/pub/mozilla.org/xulrunner/releases/7.0/runtimes/xulrunner-7.0.en-US.win32.zip Unpacked this zip into folder, but when I am issuing a command xulrunner --register-global I am getting a message couldn't parse application.ini I really have no application.ini file because it was no one in zip file. So, how to install XULRunner correctly? A: Support for "registering" XULRunner has been removed in XULRunner 5.0: https://bugzilla.mozilla.org/show_bug.cgi?id=642795 (it actually wasn't exactly useful anyway). So by unpacking XULRunner you already installed it. Now you can go find or create a XULRunner application and run it with xulrunner.exe --app path\to\app\application.ini.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567581", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Auto Branching in svn using teamcity I wonder whether it is possible to do auto branching using Teamcity. As currently I am automatically publishing web applications using web deploy and the only thing left is branching as we usually take a branch in svn and then publish the next version. Can any one please advise if it is possible and how to do it. A: Open TeamCity Version Control Settings for your release build. Set "VCS labeling mode" to "Successful only" and specify an appropriate labeling pattern. E.g. release-build-%system.build.number%. At the top of this page, enter the checkout rule +:/trunk => . then click edit to open the VCS root settings page. Ensure URL points to the root level of the source control tree E.g. https://vcserver/ instead of the trunk https://vcserver/trunk. Also on this page, set the labeling rule to trunk=>branches Each time you run this build, it will be branched automatically using a new system build number.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567589", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: A call to PInvoke function 'Test!DllCall::initDll' has unbalanced the stack Bit of an unusual question. I have worked out that the error is only thrown when running the program via visual studio. If I compile the application and run the compiled program it works fine. Any ideas what would cause this? I have a C# class that calls a method in a Java DLL ( compiled through excelsior jet ) via JNI. When I compile and run the C# class an an executable everything works fine. Now I have built the C# class as a DLL and am trying to call it from another class. At this point I get the followign error message: A call to PInvoke function 'Test!DllCall::initDll' has unbalanced the stack. This is likely because the managed PInvoke signature does not match the unmanaged target signature. Check that the calling convention and parameters of the PInvoke signature match the target unmanaged signature. Could anyone explain why Im getting this and how to fix it? Please let me know if you need anymore code/information Heres the C# code: using System; using System.Runtime.InteropServices; using System.Text; public class DllCall { [DllImport("Stubs")] public static extern int initDll(String userDllName); [DllImport("Stubs")] public static extern void finalizeDll(); [DllImport("Stubs")] public static extern UInt32 newClassInstance(); [DllImport("Stubs")] public static extern int invokeStaticMethod(); [DllImport("Stubs")] public static extern String request(UInt32 hClassInst, String input); [DllImport("Stubs")] public static extern void close(); [DllImport("Stubs")] public static extern void voidtest(UInt32 hClassInst); } public class Test { public UInt32 hClass; public Test() { //when compiled as a DLL this line throws the error. int rc = DllCall.initDll("dllClass.dll"); Console.Write("---> initDll() rc = {0}\n", rc); hClass = DllCall.newClassInstance(); Console.Write("---> hClass = {0}\n", hClass); } // When compiled as an executable this method runs fine. public static void Main(string[] args) { int rc = DllCall.initDll("dllClass.dll"); string rs; Console.Write("---> initDll() rc = {0}\n", rc); UInt32 hClass = DllCall.newClassInstance(); Console.Write("---> hClass = {0}\n", hClass); rs = DllCall.request(hClass, "moo"); Console.Write("---> request() rs = {0}\n", rs); DllCall.close(); DllCall.finalizeDll(); } public string request( string xmlInput ) { string rs; rs = DllCall.request(hClass, xmlInput); Console.Write("---> request() rs = {0}\n", rs); return rs; } public void finalizeDll() { DllCall.finalizeDll(); } public void closeConnection() { DllCall.close(); } } I know this is a lot of code but as requested heres the code in the C Dll..... #include <jni.h> #include <windows.h> JNIEnv *env; JavaVM *jvm; HANDLE hUserDll; jclass jClass; char* dllname; /* * Load dll. */ HANDLE loadDll(char* name) { HANDLE hDll = LoadLibrary (name); if (!hDll) { printf ("Unable to load %s\n", name); exit(1); } printf ("%s loaded\n", name); return hDll; } jint (JNICALL * JNI_GetDefaultJavaVMInitArgs_func) (void *args); jint (JNICALL * JNI_CreateJavaVM_func) (JavaVM **pvm, void **penv, void *args); /* * Initialize JET run-time. */ void initJavaRT(HANDLE myDllHandle, JavaVM** pjvm, JNIEnv** penv) { int result; JavaVMInitArgs args; JNI_GetDefaultJavaVMInitArgs_func = (jint (JNICALL *) (void *args)) GetProcAddress (myDllHandle, "JNI_GetDefaultJavaVMInitArgs"); JNI_CreateJavaVM_func = (jint (JNICALL *) (JavaVM **pvm, void **penv, void *args)) GetProcAddress (myDllHandle, "JNI_CreateJavaVM"); if(!JNI_GetDefaultJavaVMInitArgs_func) { printf ("%s doesn't contain public JNI_GetDefaultJavaVMInitArgs\n", dllname); exit (1); } if(!JNI_CreateJavaVM_func) { printf ("%s doesn't contain public JNI_CreateJavaVM\n", dllname); exit (1); } memset (&args, 0, sizeof(args)); args.version = JNI_VERSION_1_2; result = JNI_GetDefaultJavaVMInitArgs_func(&args); if (result != JNI_OK) { printf ("JNI_GetDefaultJavaVMInitArgs() failed with result %d\n", result); exit(1); } /* * NOTE: no JVM is actually created * this call to JNI_CreateJavaVM is intended for JET RT initialization */ result = JNI_CreateJavaVM_func (pjvm, (void **)penv, &args); if (result != JNI_OK) { printf ("JNI_CreateJavaVM() failed with result %d\n", result); exit(1); } printf ("JET RT initialized\n"); fflush (stdout); } /* * Look for class. */ jclass lookForClass (JNIEnv* env, char* name) { jclass clazz = (*env)->FindClass (env, name); if (!clazz) { printf("Unable to find class %s\n", name); exit(1); } printf ("Class %s found\n", name); fflush (stdout); return clazz; } int initDll(char* userDllName) { jClass = NULL; hUserDll = loadDll(userDllName); dllname = userDllName; initJavaRT(hUserDll, &jvm, &env); jClass = lookForClass(env, "mooMain/mooGeminiX3/mooGeminiX3IFX"); return jClass ? 1 : 0; } /** finalizeDll() - stop Java VM */ void finalizeDll () { (*jvm)->DestroyJavaVM (jvm); FreeLibrary((HMODULE)hUserDll); hUserDll = NULL; jClass = NULL; } jobject newClassInstance() { jmethodID MID_init; jobject obj; jstring name; jobjectArray ret; jclass sclass; jobjectArray arr; MID_init = (*env)->GetMethodID (env, jClass, "<init>", "([Ljava/lang/String;)V"); if (!MID_init) { printf("Error: dllClass.<init>() not found\n"); return NULL; } sclass = (*env)->FindClass(env, "java/lang/String"); arr = (*env)->NewObjectArray(env, 6, sclass, NULL); name = (*env)->NewStringUTF(env,"@C:\\Users\\Ash\\Desktop\\moo-Test\\moo-Test\\mooRoot.cfg"); (*env)->SetObjectArrayElement(env,arr,0,name); name = (*env)->NewStringUTF(env,"-cfg"); (*env)->SetObjectArrayElement(env,arr,1,name); name = (*env)->NewStringUTF(env,"C:\\Users\\Ash\\Desktop\\moo-CVS\\moo-PCB\\Application\\Configuration\\Linear\\Application\\moo.cfg"); (*env)->SetObjectArrayElement(env,arr,2,name); name = (*env)->NewStringUTF(env,"-startupLog"); (*env)->SetObjectArrayElement(env,arr,3,name); name = (*env)->NewStringUTF(env,"C:\\Users\\Ash\\Desktop\\moo-Test\\moo-Test\\Log\\mooStartup.log"); (*env)->SetObjectArrayElement(env,arr,4,name); name = (*env)->NewStringUTF(env,"-geminiX3"); (*env)->SetObjectArrayElement(env,arr,5,name); obj = (*env)->NewObject(env, jClass, MID_init, arr); if (!obj) { printf("Error: failed to allocate an object\n"); return NULL; } return obj; } const char* request(jobject obj, char* input ) { jstring inputString; jstring outputString; const char *nativeString; jmethodID mID = (*env)->GetMethodID (env, jClass, "request", "(Ljava/lang/String;)Ljava/lang/String;"); if (!mID){ printf("\nError: dllClass.request() not found\n"); return 0; } printf("here"); fflush(stdout); inputString = (*env)->NewStringUTF(env, input); printf("here2"); fflush(stdout); outputString = (*env)->CallObjectMethod(env, obj, mID, inputString); nativeString = (*env)->GetStringUTFChars(env, outputString, 0); return nativeString; } void voidtest(jobject obj ) {/* jmethodID mID = (*env)->GetMethodID (env, jClass, "request", "([Ljava/lang/String;)[Ljava/lang/String;"); if (!mID){ printf("\nError: dllClass.request() not found\n"); return 0; } char inputString[] = (*env)->NewStringUTF(env, "Moo"); (*env)->CallVoidMethod(env, obj, mID, inputString);*/ } void close() { jmethodID mID = (*env)->GetMethodID (env, jClass, "close", "()V"); if (!mID){ printf("\nError: dllClass.close() not found\n"); } (*env)->CallVoidMethod(env,jClass, mID); } int invokeStaticMethod() { jmethodID MID_init; jobject obj; jstring name; jobjectArray ret; jclass sclass; jobjectArray arr; jmethodID mID = (*env)->GetStaticMethodID(env, jClass, "start", "([Ljava/lang/String;)V"); if (!mID){ printf("\nError: dllClass.sfstart() not found\n"); return 0; } sclass = (*env)->FindClass(env, "java/lang/String"); arr = (*env)->NewObjectArray(env, 5, sclass, NULL); name = (*env)->NewStringUTF(env,"@C:\\Users\\Ash\\Desktop\\moo-Test\\moo-Test\\mooRoot.cfg"); (*env)->SetObjectArrayElement(env,arr,0,name); name = (*env)->NewStringUTF(env,"-cfg"); (*env)->SetObjectArrayElement(env,arr,1,name); name = (*env)->NewStringUTF(env,"C:\\Users\\Ash\\Desktop\\moo-CVS\\moo-PCB\\Application\\Configuration\\Linear\\Application\\moo.cfg"); (*env)->SetObjectArrayElement(env,arr,2,name); name = (*env)->NewStringUTF(env,"-startupLog"); (*env)->SetObjectArrayElement(env,arr,3,name); name = (*env)->NewStringUTF(env,"C:\\Users\\Ash\\Desktop\\moo-Test\\moo-Test\\Log\\mooStartup.log"); (*env)->SetObjectArrayElement(env,arr,4,name); (*env)->CallStaticVoidMethod(env,jClass, mID, arr); printf("\nGot to here\n"); return 1; } Kind Regards Ash A: This usually happens when you have an incorrect parameter list or mismatching calling convention. You really ought to know what calling convention the other DLL is. If it is cdecl then you change your P/invoke to: [DllImport("Stubs", CallingConvention=CallingConvention.Cdecl)] You need to do this for all imports. The other thing to check is that your parameter lists match. You only showed one side of the boundary so we can't check that for you. If you added the other side then we may be able to spot something. Updated following addition of C code I have the following comments on your code: The parameters for the C# declaration of initDll match the C declaration so I'm pretty confident that the issue is that your C code uses cdecl calling convention. The C# P/invoke defaults to stdcall. Change the calling convention in one or the other, but not both! You are matching jobject with UInt32. I'm not sure about this since I don't know JNI. However, I suspect you should be returning jobject* and matching with IntPtr. It looks to me as though jobject is a class type and not something that you can marshal to C#. Finally, one of your methods returns a string. That just won't work. The C# marshaller will attempt to deallocate it with a call to CoTaskMemFree. That will leak or bomb, dependent on which Windows version you have. You should return an IntPtr and use Marshal.PtrToStringAnsi to marshal it into a C# string. Then you need to deallocate the memory returned by the JNI code. Not sure how you plan to do that. Of course, if your strings are really UTF-8 then you would need to copy to a byte array and then use Encoding.UTF8 to convert to a C# string.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567590", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Monitoring incoming requests on a web hosting server I have a web hosting account with GoDaddy (its a Linux based hosting). Can I install applications like netcat to monitor all incoming requests to my website on a certain port? If not, is there any other way I can do that? I have a page that accepts POST data, and I need to send the POST data from hardware level. I'm sending the data but apparently its not in the correct format. I want to be able to see the exact request being received on the server end in raw HTTP form, and be able to compare it against the request received when sent through another web page to look for discrepancies. A: If you have root access on your server, you can install and run Wireshark. Wireshark will analyze and display the data from the HTTP connection.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567591", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: C#: Windows auto-mail service doesn't work I wanted to create simple service, which would periodically download a list of e-mail adresses and send them e-mails. I started writing the service, and before that I tested, if the e-mail sending works - and yes, it does. The problem is, that whereas I get no timeouts while sending e-mails by simply using the mailing method in Main() I get the timeouts and exceptions, when I try to do the same while executing the code as a service (using InstallUtil.exe, then going to My computer/manage and starting the service) I guess it has to be some permissions/privileges issue, but have completely no idea, how to solve it - I tried to turn the firewalls off with no effect. When I call the mailing method in onStart(), onStop() methods or in the thread that the service starts - I'm unable to "connect to remote server". I tried using different ports and SMTP servers, but it's all the same - it works as long as I run the code in a non-service program. I tried different service settings - LocalSystem, NetworkService itp - all the same. The same goes with any changes to the Windows Registry - I can do the reading/writing while the Main() is being executed or even in the service installer - but it doesn't work when the service wants to use it. Please help! A: Services run under a different account. (Typically SERVICE) You need to make sure that your code accounts for this. When you are running in an interactive mode, you are running with your current credentials. Are you recording all exceptions to a log file? Since a service has no user interface, you will need to record any errors either to a log file or to the event log.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567592", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How can I call a .exe file W/unknown Path? How can I call a .exe file W/unknown Path which installed on the machine in C#? Process.Start(?); A: Process.Start("myExeFileName.exe"); You'll need to hope that the system search path includes the path where the executable lives, or that it has registered an APPPATH.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567594", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to use json_encode to update data in a foreach? i have a foreach looping through messages for the logged in user and displayng them listSuccess.php: $cursor = $pager->getFirstIndice(); foreach ($pager->getResults() as $msg) { $unique_code_from = $msg->getRcProfileTableRelatedByProfileIdFrom()->getUniqueCode(); $block_url = link_to('Block User',"blocklist/block?unqiue_code=$unique_code_from",'class=link_medium_blue'); echo "<tr id='td_id' value='.$cursor.'>"; $date = add_date($msg->getCreatedAt(),$hr=2); echo "<td class='td_show_contact_item' align='left' id='td_date'>".$date."</td>"; $opened_once = $msg->getOpenedOnce(); <td align='left' id='td_subject'> <a href="<?php echo url_for('messagebox/read?cursor=').$cursor ?>" style='color:#ff0000 !important' class='spn_small_red_rbc'><?php echo $msg->getSubject();?></a> </td> <?php echo "<td class='td_show_contact_item' align='left' id='td_from'>".$unique_code_from." </td>"; echo "<td>( ".$block_url." )</td>"; echo "</tr>"; ++$cursor; } i have a tag for date: td_date,subject: td_subject and who the message is from:td_from then i have my actions.class.php public function executeNewMessageDetails(sfWebRequest $request) { $profile_id = $this->getUser()->getAttribute('profile_id','zero'); $new_msgs = RcMessageBoxTablePeer::getNewMessages($profile_id); foreach ($new_msgs as $row) { $date = $row->getCreatedAt(); $subject = $row->getSubject(); $from = $row->getProfileIdFrom(); $id = $row->getId(); $uc_record = RcProfileTablePeer::getById($from); $uc_from = $uc_record->getUniqueCode(); //$block_url = 'Block User',"blocklist/block?unqiue_code=$uc_from",'class=link_medium_blue'); } $output = array("td_date" => $date, "td_subject" => $subject, "td_from" => $uc_from, "td_id" => $id); return $this->renderText(json_encode($output)); } then the JS: function ax_get_new_msg_details() { var mTimer; mTimer = setTimeout('ax_get_new_msg_details();',30000); $.getJSON('/apps_dev.php/messagebox/newMessageDetails', function(data) { var td_id = $('#td_id'); var str='<tr>'; str += "<td class='td_show_contact_item' align='left' id='td_date'>"+data.td_date+'</td>'; str += "<td align='left' id='td_subject'><a href='#' style='color:#ff0000 !important' class='spn_small_red_rbc'>"+data.td_subject+"</a></td>"; str += "<td class='td_show_contact_item' align='left' id='td_from'>"+data.td_from +"</td>"; //str += "<td id='block_url'>"+data.block_url+"</td>"; str +='<tr>'; var tbl = $('#td_date').parents('table'); if (td_id == data.td_id) { } else { $(tbl).append(str); } }); } it runs fine BUT it replaces the first message in the foreach list with the new one, i want my code to add to the end of the list thus displaying the new entry at the end of the list. how can i achieve this? thank you A: function ax_get_new_msg_details() { var mTimer; mTimer = setTimeout('ax_get_new_msg_details();',30000); $.getJSON('/apps_dev.php/messagebox/newMessageDetails', function(data) { var str='<tr>'; str += "<td class='td_show_contact_item' align='left' id='td_date'>"+data.td_date+'</td>'; str += "<td align='left' id='td_subject'> <a href='#' style='color:#ff0000 !important' class='spn_small_red_rbc'> "+data.td_subject+"</a></td>"; str += "<td class='td_show_contact_item' align='left' id='td_from'>"+data.td_from +" </td><td>block url</td>"; str +='<tr>'; var tbl = $('#td_date').parents('table'); $(tbl).append(str); }); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7567595", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to set the links in a text block clickable in wp7 I have a text box contain links .the contents in the text are generated during run time.My problem is that the links inside the text is not clickable,how can make all links inside the text block clickable so that when i tap a link it should open the web browser.In android we can set it by using autolink.Is such option is available in wp7 or in wp7.1 mango? A: There is no built in functionality to do this. If your text (including the links) is HTML you could display it in a WebBrowser control. If not you'll need to parse the text and build the links yourself. (A combination of TextBlocks and HyperlinkButtons inside a WrapPanel is probably the way to go for this.) A: In silverlight RichTextBox contol can help you. <RichTextBox> <Paragraph> <Run Text="This have to navigate me to Google: "/> <Hyperlink NavigateUri="http://google.com" TargetName="_blank">google.com</Hyperlink> </Paragraph> </RichTextBox> A: Use a HyperLink. <TextBlock> <Run>Pure Text</Run> <Hyperlink Command="{Binding HyperLinkTapped}">http://google.com</Hyperlink> <Run>Pure Text Again</Run> </TextBlock> This is supported from Windows Phone 7.1 (Mango). You can create your own FlowDocument from the your data, at runtime, if necessary. Example on how to generate a FlowDocument from a string: private void OnMessageReceived(string message) { var textBlock = new RichTextBox() { TextWrapping = TextWrapping.Wrap, IsReadOnly = true, }; var paragraph = new Paragraph(); var runs = new List<Inline>(); foreach (var word in message.Split(' ')) { Uri uri; if (Uri.TryCreate(word, UriKind.Absolute, out uri) || (word.StartsWith("www.") && Uri.TryCreate("http://" + word, UriKind.Absolute, out uri))) { var link = new Hyperlink(); link.Inlines.Add(new Run() { Text = word }); link.Click += (sender, e) => { var hyperLink = (sender as Hyperlink); new WebBrowserTask() { Uri = uri }.Show(); }; runs.Add(link); } else { runs.Add(new Run() { Text = word }); } runs.Add(new Run() { Text = " "}); } foreach (var run in runs) paragraph.Inlines.Add(run); textBlock.Blocks.Add(paragraph); MessagesListBox.Children.Add(textBlock); MessagesListBox.UpdateLayout(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7567600", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Javascript Error - Can't find variable : google The code I wrote runs absolutely fine on the browser. But when I connect to wifi on the iPhone I get an error in the debugger : Javascript Error - Can't find variable : google This occurs whenever I call any google maps/directions/geoLocation object. The code is as follows : map = new Ext.Map({ mapOptions : { center : center, zoom : 20, // mapTypeId : google.maps.MapTypeId.ROADMAP, navigationControl: true, navigationControlOptions: { style: google.maps.NavigationControlStyle.DEFAULT } }, listeners : { maprender : function(comp, map){ pos = new google.maps.LatLng(lats, longs, true); var marker = new google.maps.Marker({ position: pos, //title : 'Sencha HQ', map: map }); map.setMapTypeId(google.maps.MapTypeId.HYBRID); setTimeout( function(){map.panTo (pos);} , 1000); } }, geo:new Ext.util.GeoLocation({ autoUpdate:true, maximumAge: 0, timeout:2000, listeners:{ locationupdate: function(geo) { pos = new google.maps.LatLng(lats, longs, true); center = new google.maps.LatLng(geo.latitude, geo.longitude); if (map.rendered) map.update(center) else map.on('activate', map.onUpdate, map, {single: true, data: pos}); }, locationerror: function(geo, bTimeout, bPermissionDenied, bLocationUnavailable, message) { if(bLocationUnavailable){ alert('Your Current Location is Unavailable on this device'); } else if (bPermissionDenied){ alert('Location capabilities have been disabled on this device.'); } } } }) }); The error occurs whenever the code encounters the word google. Also for the LatLng object I get the javascript error : "....result of LatLng not a constructor" Note : the variables "lats" and "longs" have been defined n given values before this segment of code A: What worked for me: remove the "https" from the <script src="https://maps.google.com/maps/api/js?sensor=false"></script> so it becomes <script src="http://maps.google.com/maps/api/js?sensor=false"></script> I don't know why Safari doesn't load secure pages on unsecured ones but it just doesn't seem to. And then throws the error. This is the only mobile browser that seems to behave like that. A: So I had posted this earlier as a comment, but since this is the actual solution to the problem, I'm gonna post it once more :D Ok turns out that the reason I was getting all those errors is cos I was behind a proxy. Weirdly enough the proxy lets me access the google libraries and server when I'm connected using the LAN cable, but not when Im using WiFi. Hope some1 else who's stuck wid this kind of error will find this somewhat helpful :) A: Could it be that you're loading the Google JavaScript libraries from the Google server? If so, when you don't have WiFi, that won't work. That's why the "google" object is not defined. You can only use Google Maps and such when you're device is online. EDIT: Nevermind, you said you ARE connected via WiFi. Odd. I guess we need to see your full source code then. A: My solution was to simply make sure the Google Maps js loads before the Touch js. Simply put <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script> before <script id="microloader" type="text/javascript" src="touch/microloader/development.js"</script> A: Check if your config.xml have permission to navigate into Google Api Address that you write in index.html. Double check if you are working with 'https' or 'http'. I did with 'https' In your index.html: `<script src="https://maps.google.com/maps/api/js?key=APIKEY" async defer type="text/javascript"></script>` In your config.xml `<access origin="https://maps.google.com/*" /> <allow-intent href="https://maps.google.com/*" /> <access origin="https://maps.gstatic.com/*" /> <allow-intent href="https://maps.gstatic.com/*" /> <access origin="https://maps.googleapis.com/*" /> <allow-intent href="https://maps.googleapis.com/*" /> <access origin="https://fonts.googleapis.com/*" /> <allow-intent href="https://fonts.googleapis.com/*" />` This worked for me!
{ "language": "en", "url": "https://stackoverflow.com/questions/7567602", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Why the magic method '__get' has been called twice? I have seen some code like below, and it is strange that the __get method has been called twice, why? class Foo { private $bar; function __get($name){ echo "__get is called!"; return $this->$name; } function __unset($name){ unset($this->$name); } } $foo = new Foo; unset($foo->bar); echo $foo->bar; Attention: unset($foo->bar) will not call the __get. A: For me, it looks like a bug. Put some debugging code (the following) and see the result: <?php class Foo { private $bar; function __get($name){ echo "__get(".$name.") is called!\n"; debug_print_backtrace(); $x = $this->$name; return $x; } function __unset($name){ unset($this->$name); echo "Value of ". $name ." After unsetting is \n"; echo $this->$name; echo "\n"; } } echo "Before\n"; $foo = new Foo; echo "After1\n"; unset($foo->bar); echo "After2\n"; echo $foo->bar; echo "After3\n"; echo $foo->not_found; ?> The result is: Before After1 Value of bar After unsetting is __get(bar) is called! #0 Foo->__get(bar) called at [E:\temp\t1.php:17] #1 Foo->__unset(bar) called at [E:\temp\t1.php:24] PHP Notice: Undefined property: Foo::$bar in E:\temp\t1.php on line 9 After2 __get(bar) is called! #0 Foo->__get(bar) called at [E:\temp\t1.php:26] __get(bar) is called! #0 Foo->__get(bar) called at [E:\temp\t1.php:9] #1 Foo->__get(bar) called at [E:\temp\t1.php:26] PHP Notice: Undefined property: Foo::$bar in E:\temp\t1.php on line 9 After3 __get(not_found) is called! #0 Foo->__get(not_found) called at [E:\temp\t1.php:28] PHP Notice: Undefined property: Foo::$not_found in E:\temp\t1.php on line 9 A: invoked in 1) return $this->$name; 2) echo $foo->bar; in the code: class Foo { private $bar; function __get($name){ echo "__get is called!"; return $this->$name; *** here *** } function __unset($name){ unset($this->$name); } } $foo = new Foo; unset($foo->bar); echo $foo->bar; *** and here *** __get() is utilized for reading data from inaccessible properties. so, un-setting the variable, turn $foo->bar and $this->bar inaccessible. However, if unset is removed then $foo->bar is inaccessible but $this->bar is accessible. However, i don't know how PHP avoid to call the function recursively. May be PHP is smart or the variable is self-setting at some point. A: The magic __get function is called everytime you try to access a variable. If you look at your code, you do this exactly 2 times. Once in the unset function and once in the echo function. unset($foo->bar); echo $foo->bar;
{ "language": "en", "url": "https://stackoverflow.com/questions/7567603", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to load data to hive from HDFS without removing the source file? When load data from HDFS to Hive, using LOAD DATA INPATH 'hdfs_file' INTO TABLE tablename; command, it looks like it is moving the hdfs_file to hive/warehouse dir. Is it possible (How?) to copy it instead of moving it, in order, for the file, to be used by another process. A: from your question I assume that you already have your data in hdfs. So you don't need to LOAD DATA, which moves the files to the default hive location /user/hive/warehouse. You can simply define the table using the externalkeyword, which leaves the files in place, but creates the table definition in the hive metastore. See here: Create Table DDL eg.: create external table table_name ( id int, myfields string ) location '/my/location/in/hdfs'; Please note that the format you use might differ from the default (as mentioned by JigneshRawal in the comments). You can use your own delimiter, for example when using Sqoop: row format delimited fields terminated by ',' A: I found that, when you use EXTERNAL TABLE and LOCATION together, Hive creates table and initially no data will present (assuming your data location is different from the Hive 'LOCATION'). When you use 'LOAD DATA INPATH' command, the data get MOVED (instead of copy) from data location to location that you specified while creating Hive table. If location is not given when you create Hive table, it uses internal Hive warehouse location and data will get moved from your source data location to internal Hive data warehouse location (i.e. /user/hive/warehouse/). A: An alternative to 'LOAD DATA' is available in which the data will not be moved from your existing source location to hive data warehouse location. You can use ALTER TABLE command with 'LOCATION' option. Here is below required command ALTER TABLE table_name ADD PARTITION (date_col='2017-02-07') LOCATION 'hdfs/path/to/location/' The only condition here is, the location should be a directory instead of file. Hope this will solve the problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567605", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "54" }
Q: trace 10046 and OEM privileges It would be great if someone would share trace 10046 privileges and Oracle enterprise manager (OEM) privileges so I can ask my DBA to grant the privileges to my role, and by OEM privileges I mean is I can change the threshold on GUI environment. I have read somewhere you need operator's privileges. But correct me if I am wrong. A: Most DBA's wont be granting system trace privs to non-DBA's, especially if this is a production system, since this involves both superuser privileges and access to the trace files that are generated. In my shops we would never let developers have shell access to any server higher than a dev box. If you need to generate traces, work with your DBA team. That's their job.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567607", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Using ruby whois I need to retrieve whois informations for a given site. because the whois content varies with each whois server, i need to parse the whois content what i'm getting. I'm using php to show the content from db and initially tried in php to parse it. now i came to know there is ruby whois package which parses whois content. so the idea is running ruby program in the background to put whois content in db then show using php if requests made. I've installed ruby 1.8.7 and whois and tried examples given in ruby document. But its giving /opt/lampp/htdocs/labs/ruby/ruby-whois.rb:1: uninitialized constant Whois (NameError) is rubywhois different from ruby? can anyone help me in this regard. A: Have you installed the library with gem install whois? After that you have to require it in your code (require 'whois') in order to be able to use it. A: I've found. These are things i've done. * *Installed ruby, using yum install ruby *tried gem install whois, it asked me whether to install gem package and installed. *After installing rubygem, i used gem install whois command Now i created a file with .rb extension with the following content, require 'rubygems' require 'whois' r = Whois.whois("google.com") puts r.created_on I run this file in terminal with this command, ruby /opt/lampp/htdocs/labs/ruby/ruby-whois.rb and the output is, Mon Sep 15 00:00:00 +0530 1997 Thanks for all your efforts.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567608", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: C# using a timer inside a Backgroundworker I couldn't find a solution for this yet...hope someone can help me. I have a backgroundworker that runs until it is cancelled by the user (it reads data from a socket and writes it into a file). Now I want to split the output file after a certain period of time, e.g. every 2 mins create a new file. For this to happen I'd like to use a timer, something like private void bckWrkSocket_DoWork(object sender, DoWorkEventArgs e) { //create timer and set its interval to e.Argument //start timer while(true) { if(timer.finished == true) { //close old file and create new //restart timer } ... } } Any suggestions / ideas? edit: Stopwatch did the trick. Here's my solution Here's my solution: private void bckWrkSocket_DoWork(object sender, DoWorkEventArgs e) { long targettime = (long) e.Argument; Stopwatch watch = new Stopwatch(); if (targettime > 0) watch.Start(); while(true) { if ((targettime > 0) && (watch.ElapsedMilliseconds >= targettime)) { ... watch.Reset(); watch.Start(); } } A: Use a Stopwatch and check within the while loop the Elapsed property. That way you prevent from concurrent writing and closing the same file. A: You could use a Threading.Timer like so private static void bckWrkSocket_DoWork(object sender, DoWorkEventArgs e) { var timer = new Timer(x => { lock (file) { // close old file and open new file } }, null, 0, (int)e.Argument); while(true) { if (bckWrkSocket.CancellationPending) { e.Cancel = true; return; } // check socket etc. } } A: From a design perspective I would separate the concerns of writing and splitting into files. You may want to look into the source code of log4net (NLog?) since they have implementations of rolling file appenders, since you may have to be careful about not messing up by losing some data. A: Define a global variable which store timer tick count. int timerCount = 0; - private void bckWrkSocket_DoWork(object sender, DoWorkEventArgs e) { timer.Tick += new EventHandler(TimerEventProcessor); // Sets the timer interval to 1 minute. timer.Interval = 60000; timer.Start(); } - public void TimerEventProcessor(Object myObject, EventArgs myEventArgs) { if(timerCount % 2 == 0) //Do you works timerCount++; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7567609", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Git - Can't change branch I'm a git newbie, and just started using it the other day. The idea seems good, but I've already run into a problem that makes git seem like much more of a hassle than it's worth. What I'm doing: I started by adding it to one of my projects, and I created 3 branches: * *Master *Stable *Alpha All seemed fine. As of today, Master and Stable were pretty much the same code. I was working on Alpha, which contained the beginnings of some new features. What went wrong: I wanted to finish bug testing the stable branch, so I can release an update to an iOS app. I changed to the master branch accidentally (this is the branch that I plan to use for released versions) and then wanted to change to the stable branch. However, on attempting to change I receive the error: "you need to resolve your current index first" And the branch refuses to change. Apparently, it's something to do with a bad merge... although I can't even remember merging anything, except for maybe a few lines of code when I was setting up git. Here's the output of 'git status': # On branch master # Unmerged paths: # (use "git reset HEAD <file>..." to unstage) # (use "git add/rm <file>..." as appropriate to mark resolution) # # both modified: Schedule.xcodeproj/project.xcworkspace/xcuserdata/Jordan.xcuserdatad/UserInterfaceState.xcuserstate # I'm using Xcode 4, and using the built in repository manager to switch branches/manage git etc. So, what went wrong? Why is git giving me errors, even though I never really merged much (or anything?) in the first place - and how can I fix it, and avoid it happening in the future? A: Fixed with: git reset HEAD <file name of the file stopping merge> Stopped from happening again by adding ignores and attributes to some of the .xcodeproj package files: .gitignore # xcode noise build/* *.pbxuser *.mode1v3 *.xcuserstate # old skool .svn # osx noise .DS_Store profile .gitattributes *.pbxproj -crlf -diff -merge A: The simple approach is to run git stash first, if you're not concerned with Schedule.xcodeproj/project.xcworkspace/xcuserdata/Jordan.xcuserdatad/UserInterfaceState.xcuserstate, which I probably wouldn't be. As Stephen (below) points out, that's not an ideal approach, however. Another approach (which probably won't be liked by some) is to delete the file from the repository and commit that change: git rm -f --cached Schedule.xcodeproj/project.xcworkspace/xcuserdata/Jordan.xcuserdatad/UserInterfaceState.xcuser git commit The --cached flag keeps it from getting deleted off your hard drive, and the -f flag is required because it's been "modified" (even though you think it hasn't). To keep similar problems happening in the future, I'd add this file, as well as all other user specific files, to the .gitignore file. A: It is because you have modified files locally. At this stage, you have to commit these files or you have to reset them. If you want don't want to commit them then : $ git reset HEAD file path After resetting the files you can simply checkout them as : $ git checkout file path CAUTION: By doing this your local changes will be lost.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567624", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: iTunes Allow App Update I've just released a new version of our App. It: * *is live and shows in the App Store *shows in "Updates" on the device *successfully updates via the device However, in iTunes, it says the new version is already downloaded and hence doesn't appear in the list of updates and cannot be updated. If do a sync after the update on the device, the device copy reverts to the old version. I cannot see what I'm doing wrong. Is there a bug in iTunes? I've googled but only found reference to a bug where it keeps saying there's an update, even when you've updated it. That seems to be the opposite problem to the one I have. I'd really appreciate any pointers you may have so I know where to look. Many thanks, Chris. A: Have you checked all the references to the Version metadata in your SDK? It might be that you have forgotten to update a version number somewhere and by coincidence it is the one iTunes uses. A: Have just found what I'm doing wrong. I have two accounts, one personal, one as a developer. I downloaded it originally on the developer account but just now I was signed in on my personal account. As soon as I signed in on the developer account, there it was. Problem solved.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567628", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: inclusion of header files i have a file named functions.h....now i know that it is not wise to define functions in the header files but that is least of my concern as compared to the problem which cropped up... i defined a function in a functions.h named void sayhi() { cout<<"hi"; } now i made a lines.h file whose functions were defined in lines.cpp file...in lines.cpp file i included functions.h...and used sayhi(); in the constructor of lines class...then in mymain.cpp(containing int main) i again included functions.h and in the main i called sayhi(); but when i compiled the program it showed an error in mymain.cpp telling that sayhi() has already been defined in lines.obj...can u point out what am i doing wrong?? A: Well, the solution is to declare the function in functions.h and then define it in functions.cpp, the way nature intended. A: Making your function inline avoids this multiple definition problem. Try, inline void sayhi() { cout<<"hi"; } This link might be helpful to you. In particular, it references section 7.1.2 of the ISO C++ standard: An inline function shall be defined in every translation unit in which it is used and shall have exactly the same definition in every case (3.2). which is why the one-definition-rule is circumvented.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567629", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Swing JComboBox not reloading while switching the Jtabbedpane I am trying to re initialize the JComboBox while tab switches from data updating page to page containing JComboBox my function is like this and it is called as well but doesn't work.... private void jTabbedPane2StateChanged(javax.swing.event.ChangeEvent evt) { System.out.println("State change called"); String[] categories=controller.getCategories(); ComboBoxModel cmbModel1=new DefaultComboBoxModel(categories); jComboBox1.setModel(cmbModel1); jComboBox1.validate(); } A: It seems that controller.getCategories() always returns the same results. Try to rather use the focusGained event for the tab where your combo resides. The stateChanged event occurs with every tab click you make. kingo is right with his comment, since can only guess when the code is incomplete.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567630", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: ZF & ckeditor. Icons are not loading. Got empty blocks instead of office-buttons My directory root is "Public" as default in ZF. The default ZF htaccess also: RewriteEngine On RewriteCond %{REQUEST_FILENAME} -s [OR] RewriteCond %{REQUEST_FILENAME} -l [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^.*$ - [NC,L] RewriteRule ^.*$ index.php [NC,L] So editror works but without any icons. I see editor blocks, seems styles work too. Why icons are not loading? It stored in /public/js/editor/ckeditor.js. Here my init code, its from example: <script type="text/javascript"> if ( window.CKEDITOR ) { (function() { var showCompatibilityMsg = function() { var env = CKEDITOR.env; var html = '<p><strong>Your browser is not compatible with CKEditor.</strong>'; var browsers = { gecko : 'Firefox 2.0', ie : 'Internet Explorer 6.0', opera : 'Opera 9.5', webkit : 'Safari 3.0' }; var alsoBrowsers = ''; for ( var key in env ) { if ( browsers[ key ] ) { if ( env[key] ) html += ' CKEditor is compatible with ' + browsers[ key ] + ' or higher.'; else alsoBrowsers += browsers[ key ] + '+, '; } } alsoBrowsers = alsoBrowsers.replace( /\+,([^,]+), $/, '+ and $1' ); html += ' It is also compatible with ' + alsoBrowsers + '.'; html += '</p><p>With non compatible browsers, you should still be able to see and edit the contents (HTML) in a plain text field.</p>'; var alertsEl = document.getElementById( 'alerts' ); alertsEl && ( alertsEl.innerHTML = html ); }; var onload = function() { // Show a friendly compatibility message as soon as the page is loaded, // for those browsers that are not compatible with CKEditor. if ( !CKEDITOR.env.isCompatible ) showCompatibilityMsg(); }; // Register the onload listener. if ( window.addEventListener ) window.addEventListener( 'load', onload, false ); else if ( window.attachEvent ) window.attachEvent( 'onload', onload ); })(); } </script> A: I would recomend using FireBug (or similar tool) to check why the images aren't loading. If you look under the 'net' panel you can see weather the icons 404 (not found) or 403 (permissions). A: I had the same issue, I found the URL to the icons was ckeditor/plugins/icons.png when I navigated to that image director I got an error "The image cannot be displayed, because it contains errors" I checked locally it worked. For me the issues was in my FTP application I had changed the default file transfer mode from auto - to be ASCII. So it was uploading the png as though it was a text file instead of a Binary. Once I changed the transfer mode back to "Auto" everything worked.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567633", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Tab Apps - signed_request I have 2 FB profiles, one is a dev user that I develop apps with and the other my normal FB account. I created a FB app with the dev user and linked it to a tab. With my dev user when I view the tab and echo out the decoded signed_request i get the following output: Array ( [algorithm] => HMAC-SHA256 [expires] => 1317124800 [issued_at] => 1317118449 [oauth_token] =>xxxxxxxxxxxxxxxxxxxxxxxx [page] => Array ( [id] => xxxxxxxxxxxxxxxxx [liked] => [admin] => 1 ) [user] => Array ( [country] => xxxxxx [locale] => en_US [age] => Array ( [min] => 21 ) ) [user_id] => xxxxxxxxxxxxxxxxxxxx ) However when I setup my main user as an admin and then test the app my output looks like this: Array ( [algorithm] => HMAC-SHA256 [issued_at] => 1317118842 [page] => Array ( [id] => xxxxxxxxxxxxxxx [liked] => [admin] => 1 ) [user] => Array ( [country] => za [locale] => en_US [age] => Array ( [min] => 21 ) ) ) You can see that that my [oauth_token], [expires] have been left out. How can this be and what am I doing wrong? Cheers Phil A: Looks like the second user hasn't authorised the app. The API will only pass UID, tokens & expires for TOS'd users. A: A user MUST interact with a tab before it is given an oauth_token. This is why you have no [user_id] on the second print_r.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567634", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using the Hg Convert Extension, Branchmap Option I've got 2 Mercurial repositories RepoA and RepoB, 2 people have been working independenlty on each of their repos, RepoA only has one branch(Default) but 9 commits, RepoB has 2 branches, Default and Experiment1, each of these branches have approx 30 commits. Now it turns out that RepoB is a subset of RepoA, i.e alot of the stuff in RepoB can be put into RepoA. I'd like to Pull(import) all the contents of RepoB into a branch in RepoA. I do not want the import to go the Default branch of RepoA but rather a named branch in RepoA, called Developer1WIP. I specifically need to know * *How can I create a named branch(Developer1WIP) in RepoA and import ALL of RepoB into the Developer1WIP Branch on RepoA I believe the HgConvert Extension with branch-map is a good way forward. "The branchmap is a file that allows you to rename a branch when it is being brought in from whatever external repository.".... * *what is this file? *where is it to be created & what should be in it? *Can I get some examples of exactly how to use this command in Windows? , A: Everything is documented in the Mercurial wiki, here's an excerpt from the ConvertExtension page: ... --branchmap Since v1.3 The branchmap is a file that allows you to rename a branch when it is being brought in from whatever external repository. When used in conjunction with a splicemap, it allows for a powerful combination to help fix even the most badly mismanaged repositories and turn them into nicely structured Mercurial repositories. The branchmap contains lines of the form original_branch_name new_branch_name "original_branch_name" is the name of the branch in the source repository, and "new_branch_name" is the name of the branch is the destination repository. This can be used to move code in one repository from "default" to a named branch. Remember that "default" identifies the default branch of Mercurial repositories, which is not displayed by default by log, heads or parents commands. To erase named branch markers, convert it to "default" with a branchmap like original_branch_name default The revisions will still be there but no longer attached to the original named branch. ... So basically you'll create a textfile containing this: default Developer1WIP Experiment1 Developer1WIP (do you want both default and Experiment1 on the same branch after conversion? your question was a bit unclear but I assumed you did.) Then issue the convert command: hg convert ORIGINAL_REPO CONVERTED_REPO --branchmap MAP.TXT
{ "language": "en", "url": "https://stackoverflow.com/questions/7567636", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Where to put a configuration file in Python? In development mode, I have the following directory tree : | my_project/ | setup.py | my_project/ | __init__.py | main.py | conf/ | myproject.conf I use ConfigParser to parse the myproject.conf file. In my code, it's easy to load the file with a good path : my_project/conf/myproject.conf The problem is : When I install my project using the setup.py, the configuration file are situated (thanks to setup.py) in the /etc/my_project/myproject.conf and my application in the /usr/lib/python<version>/site-packages/my_project/. How can I refer my my_project/conf/myproject.conf file in my project in "production" mode, and refer to the local file (my_project/conf/myproject.conf) in "devel" mode. In addition, I would like to be portable if possible (Work on windows for example). What's the good practice to do that ? A: Update for S.Lott's answer. Now the method configparser.ConfigParser.readfp() is deprecated。 You can use configparser.ConfigParser.read() method directly for multi files. For example: import configparser config = configparser.ConfigParser() all_config_files = ['/path/to/file1', '/path/to/file2', '/path/to/file3'] config.read(all_config_files) Note: * *The config options in later config file will overwrite the previous. *If the config file not exists, read() will ignore it. *If you have required options need read from a file, use read_file() first. configparser.ConfigParser.read() A: Have you seen how configuration files work? Read up on "rc" files, as they're sometimes called. "bashrc", "vimrc", etc. There's usually a multi-step search for the configuration file. * *Local directory. ./myproject.conf. *User's home directory (~user/myproject.conf) *A standard system-wide directory (/etc/myproject/myproject.conf) *A place named by an environment variable (MYPROJECT_CONF) The Python installation would be the last place to look. config= None for loc in os.curdir, os.path.expanduser("~"), "/etc/myproject", os.environ.get("MYPROJECT_CONF"): try: with open(os.path.join(loc,"myproject.conf")) as source: config.readfp( source ) except IOError: pass A: I don't think there is a clean way to deal with that. You could simply choose to test for the existence of the 'local' file, which would work in dev mode. Otherwise, fall back to the production path: import os.path main_base = os.path.dirname(__file__) config_file = os.path.join(main_base, "conf", "myproject.conf") if not os.path.exists(config_file): config_file = PROD_CONFIG_FILE # this could also be different based on the OS A: The appdirs package does a nice job on finding the standard place for installed apps on various platforms. I wonder if extending it to discover or allow some sort of "uninstalled" status for developers would make sense. A: Another option is to keep all the .cfg and .ini files in the home directory, like 'boto' does. import os.path config_file = os.path.join(os.path.expanduser("~"), '.myproject') A: If you're using setuptools, see the chapter on using non-package data files. Don't try to look for the files yourself. A: The docs for Writing the Setup Script, under section 2.7. Installing Additional Files mention: The data_files option can be used to specify additional files needed by the module distribution: configuration files, message catalogs, data files, anything which doesn’t fit in the previous categories.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567642", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "76" }
Q: how to sort a collection which has strings, integers and alphanumerics in java there are some values like AB, A012B, CD,1,10,01,9 I HAVE TO SORT THE THEM the output shud be 01,1,9,10,A012B,AB,CD can use any collection im trying to use collection.sort function but its considering everything as string and printing like 01,1,10,9,A012B,AB,CD its not my req... Pls help A: //the fishing technique List<String> values = new ArrayList<String>(); values.add("AB"); values.add("A012B"); values.add("CD"); values.add("1"); values.add("10"); values.add("01"); values.add("9"); values.add("I"); Collections.sort(values, new Comparator<String>() { @Override public int compare(String o1, String o2) { // TODO tweak the comparator here try{ Integer integer1 = Integer.valueOf(o1); Integer integer2 = Integer.valueOf(o2); return integer1.compareTo(integer2); }catch (java.lang.NumberFormatException e) { return o1.compareTo(o2); } } }); System.out.println(values); } //not enough??? //here is the fish public static void main(String[] args) throws Exception { List<String> values = new ArrayList<String>(); values.add("AB"); values.add("A012B"); values.add("CD"); values.add("1"); values.add("10"); values.add("01"); values.add("9"); int maxLen = 0; for (String string : values) { if (string.length() > maxLen) { maxLen = string.length(); } } Collections.sort(values, new MyComparator(maxLen)); System.out.println(values); } public static class MyComparator implements Comparator<String> { private int maxLen; private static final String REGEX = "[0-9]+"; public MyComparator(int maxLen) { this.maxLen = maxLen; } @Override public int compare(String obj1, String obj2) { String o1 = obj1; String o2 = obj2; // both numbers if (o1.matches("[1-9]+") && o2.matches("[1-9]+")) { Integer integer1 = Integer.valueOf(o1); Integer integer2 = Integer.valueOf(o2); return integer1.compareTo(integer2); } // both string if (o1.matches("[a-zA-Z]+") && o2.matches("[a-zA-Z]+")) { return o1.compareTo(o2); } Pattern p = Pattern.compile(REGEX); Matcher m1 = p.matcher(o1); Matcher m2 = p.matcher(o2); List<String> list = new ArrayList<String>(); while (m1.find()) { list.add(m1.group()); } for (String string : list) { o1.replaceFirst(string, leftPad(string, "0", maxLen)); } list.clear(); while (m2.find()) { list.add(m2.group()); } for (String string : list) { o2.replaceFirst(string, leftPad(string, "0", maxLen)); } return o1.compareTo(o2); } } public static String leftPad(String stringToPad, String padder, Integer size) { final StringBuilder strb = new StringBuilder(size.intValue()); final StringCharacterIterator sci = new StringCharacterIterator(padder); while (strb.length() < (size.intValue() - stringToPad.length())) { for (char ch = sci.first(); ch != CharacterIterator.DONE; ch = sci.next()) { if (strb.length() < (size.intValue() - stringToPad.length())) { strb.insert(strb.length(), String.valueOf(ch)); } } } return strb.append(stringToPad).toString(); } A: you should implement a comparator: given Object O1 and Object O2: you first try to conver them to numbers and compare numbers. if O1 is numeric and O2 is not, then O2 is to be conisdered greater than O1 if O1 is not numeric and O2 is numeric, then O1 is to be considered greater than O1 if both are not numeric, you compare them as strings. A: You have to implement Comparator. I assume that all your data is in the form of Strings. Therefore by default "10" comes before "9" . You need to fix that by implementing java.util.Comparator yourself. A: First you write your own Comparator and then you call Collections.sort(List, Comparator) A: User952887's answer is great except it still gives 0,01,1,10,11,2,21,3,4,5,...etc (notice 10 comes after 1 and before 2). Look to the following link for a great alphanumeric comparator that will return 0,1,2,3,4,5,10,11,21 http://sanjaal.com/java/tag/sample-alphanumeric-sorting/ The only problem is that it will return 0,1,01-which User952887's fixed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567646", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to display error message in a jsp if(emailVal == '') { $("#email").after('<span class="error"><font color="red">Please enter your email address.</span>'); hasError = true; } when i use above javascript, message displays besides email textbox <form:input path="email" id="email"/> <c:if test="${!empty is_exist_user}"> <span class="error"><font color="red">${is_exist_user}</font></span> </c:if> but when i use above code in jsp file, message displays below email textbox, how can i get this textbox besides email textbox A: Either use CSS to tweak whatever is produced by whatever custom tag that is, modify the html produced by that custom tag, or don't use the custom tag.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567651", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Different row color in gridbag layout How do i set different color for different row in GridBagLayout? P.S : I cannot use swing in my app as client requirement. A: for AWT works setBackground(Color) too A: A GridBagLayout has nothing to do with the color of any row or component added to a panel that uses a GridBadLayout as the layout manager. If you want different color rows, then you need to create a separate panel for every row of components and set the background color of the panel.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567653", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Whats the difference between ContentControl.Template and ContentControl.ContentTemplate What's the difference between ContentControl.Template and ContentControl.ContentTemplate? And when do I use which? For example I could write in a xaml file for WPF: <ContentControl> <ContentControl.Template> <ControlTemplate> <Label Content="This is from the Template"/> </ControlTemplate> </ContentControl.Template> </ContentControl> Notice the ContentControl.Template Tag or I could write this: <ContentControl> <ContentControl.ContentTemplate> <DataTemplate> <Label Content="This is From the ContentTemplate"/> </DataTemplate> </ContentControl.ContentTemplate> </ContentControl> Notice the ContentControl.ContentTemplate Tag The output looks the same and in the first case I use a ControlTemplate and in the other a DataTemplate. However, how should I deceide if I have to use .Template or .ContentTemplate? And what implications does this have (e. g. on DataBinding, Property Inheritance, ...). A: Template property defines the appearence of a Control itself and ContentTemplate defines the template of the Content area of a Control. Interesting point from MSDN: If a Control does not have a ControlTemplate, the Control will not appear in your application. This becomes more clear when we take a look at the data types of both properties: * *Template property type is ControlTemplate *ContentTemplate property type is DataTemplate and you can switch it in runtime using ContentControl.ContentTemplateSelector
{ "language": "en", "url": "https://stackoverflow.com/questions/7567655", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "38" }
Q: update-database error - NuGet Package (EntityFramework.SqlMigrations) i installed EntityFramework.SqlMigrations NuGet Package and i get this error . it worked for me in the past and somehow, now it does not work. PM> update-database The term 'update-database' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:16 + update-database <<<< + CategoryInfo : ObjectNotFound: (update-database:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException A: I just used this command: Update-Package EntityFramework -Reinstall A: Occurs with EF5 RTM, VS2012 RTM. I experienced this problem today. I executed "Update-Package EntityFramework" in the PM Console. No changes were reported by NuGet and the problem persisted. I then restarted VS2012 and re-attempted Update-Database and it worked as expected. It's not clear what caused this problem, it's also not clear whether the Update-Package contributed to correcting it or not. First try restarting Visual Studio, then try Update-Package EntityFramework followed by a restart. A: In my case, helped installing EntityFramework package first: Install-Package EntityFramework and then installing EntityFramework.Migrations again: Install-Package EntityFramework.Migrations A: Not the best solution but to get it to work again I had to re-install the EntityFramework.Migrations package. After it had reapplied the Init.ps1 it remembered all the commands. A: After trying everything else, the only way I could get my EntityFramework Migrations commands back was to run the following from the "Package Manager Console": Import-Module \*PathToSolution*\packages\EntityFramework.5.0.0-beta2\tools\EntityFramework.psd1 After running the above, Add-Migration, Update-Database, etc. was available again. A: Restarting Visual Studio solved the problem for me... A: For me the problem was the Nuget version. * *uninstall Nuget Package Manager. *restart Visual Studio. *installed new version of Nuget Package Manager. *then re-start Visual Studio again
{ "language": "en", "url": "https://stackoverflow.com/questions/7567657", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: Inetgrating iReport(with large no of sub reports) with Spring MVC My current application includes a functionality of displaying a report designed in iReports 4.1.1 from Spring MVC at front and using PostgreSQL at back. Now i am more of concerned about its performance issues. The Main report which will display data has as many as 20 subreports at most. and each subreport has high cost query running for it. So what are the chances of having performance issues when the user count increases (in short when application scales)?? And if there is any such potential problem in coming, what are the remedies?? Also one vary naive doubt: do i need to use jasperserver or just integrate the JRXML directly (what i am just doing now)? does it affect performance anyway?? Thanks in advance.!! A: If you just use the JRXML approach (I'd rather use the pre-compiled .JASPER file, as the report file doesn't need to be compiled at server-runtime), all Jasper-Related stuff is running inside your application. If you are using the Jasper Server then it'll run in it's own webapp, depending on how you configured and started JasperServer. The thing is, I'm not sure if Spring provides a "plug-and-play" solution for integrating JasperServer, but you still can use the approach to write all the Jasper-Code yourself.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567660", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" ... Putting this in .htaccess? I downloaded html5 boilerplate and it wouldnt validate with this in the header. <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" > I was told I can add this to .htaccess for the same effect to avoid validation errors. <IfModule mod_headers.c> Header set X-UA-Compatible "IE=Edge,chrome=1" # mod_headers can't match by content-type, but we don't want to send this header on *everything*... <FilesMatch "\.(js|css|gif|png|jpe?g|pdf|xml|oga|ogg|m4a|ogv|mp4|m4v|webm|svg|svgz|eot|ttf|otf|woff|ico|webp|appcache|manifest|htc|crx|xpi|safariextz|vcf)$" > Header unset X-UA-Compatible </FilesMatch> </IfModule> My question is * *How do i test to make sure this is working properly *What does the filesmatch parameter do? should i be modifying that or is that pretty good as-is? A: The best htaccess configuration that I found is this one below: <IfModule mod_setenvif.c> <IfModule mod_headers.c> BrowserMatch MSIE ie Header set X-UA-Compatible "IE=Edge,chrome=1" env=ie </IfModule> </IfModule> Because it sends the header just for IE browsers. A: http://www.validatethis.co.uk/tag/x-ua-compatible/ Aaron Layton has it all hear :) Just Scroll down to the "The fix" and skip all the above :) Or you could add it to your .htaccess file like this: <FilesMatch "\.(htm|html|php)$"> <IfModule mod_headers.c> BrowserMatch MSIE ie Header set X-UA-Compatible "IE=Edge,chrome=1" env=ie </IfModule> </FilesMatch> A: How do i test to make sure this is working properly Make a request to a URI and look at the response headers. There are plenty of tools to do that, including Charles Proxy, Firebug and Chrome Developer Tools. What does the filesmatch parameter do? It is described in the manual A: Try to pass it through the web.config or htacess file Web.Config <httpProtocol> <customHeaders> <clear /> <add name="X-UA-Compatible" value="IE=Edge,chrome=1" /> </customHeaders> </httpProtocol> your page will be valid after that. Sorry I am not a php guy.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567661", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Set minimum data interval for y axes on Highcharts I need to plot a chart using Highcharts, and I have to sort of round down data not to plot very little variations around small values. Eg. I have yAxis data that moves between 0 and 10, and the plot is ok. Eg. I have yAxis data that moves between 0.0003 and 0.00031 and the plot will show too much detailed info. I need to find a way to make the chart plot data so that I can appreciate variations of +- 0.01, and nothing more, without imposing max and min parameters, so that the chart will auto define its bounds. Also, I do not want to round down each data point, since I want to be able to zoom in the chart freely. Do you know how to achieve this using Highcharts? Thank you! A: The solution is to calculate the tickInterval based on how many ticks you want to see in the y-axis. Say you want to see only 10 ticks (to keep the chart neat) you could do something like this http://jsfiddle.net/W9xKR/9/ The code example also sets a minimum tick interval of 0.01, so you will never see grid lines below this number, which will give you your desired level of detail. If you fiddle with the data array in that example you will see that var data = [ 0.0001, 0.0003, 0.000305, 0.000306, 0.000307, 0.000309, 0.00031, 0.01, 0.035, 0.07, 0.15, 3]; will give you 10 ticks set 0.3 apart. However, if you remove the larger values from the data set: var data = [ 0.0001, 0.0003, 0.000305, 0.000306, 0.000307, 0.000309, 0.00031, 0.01, 0.035]; you will get only 6 ticks set 0.01 apart. Note that you will have to recalculate this on zoom if you want to maintain the same number of ticks at each zoom level. A: See if this helps you: alignTicks: false See here http://jsfiddle.net/highcharts/ebuTs/3735/. Delete the alignTicks from the code to see the difference.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567663", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is it possible to force facebook password entry on adding application I want to ensure that the app I am working on is added to the correct FB account. More specifically, I want to ensure that it is not erroneously added to the account of a user who may have been previously using the browser. A user first comes to my app via an email link. In some cases, the browser they are using may have an active session for a FB user who was previously using the browser. FB will ask if they want to grant access to my app, but it could be for the previous user and the current user might not recognize this. An obvious solution is to only permit a user to add my app if they can correctly enter their FB credentials - is it possible to do this - only allow a user to add an app if the user enters their credentials correctly? A: Yup. You need this: https://developers.facebook.com/docs/reauthentication/ :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7567664", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Searching YouTube with the API for .NET I'm trying to use the YouTube API to search YouTube with a search text. The sample code is as follows. using Google.YouTube; using Google.GData.YouTube; using Google.GData.Client; using Google.GData.Extensions; (..) YouTubeQuery query = new YouTubeQuery(YouTubeQuery.DefaultVideoUri); //order results by the number of views (most viewed first) query.OrderBy = "viewCount"; // search for puppies and include restricted content in the search results // query.SafeSearch could also be set to YouTubeQuery.SafeSearchValues.Moderate query.Query = "puppy"; query.SafeSearch = YouTubeQuery.SafeSearchValues.None; Feed<Video> videoFeed = request.Get<Video>(query); printVideoFeed(videoFeed); My issue is that query.Query, request and printVideoFeed don't exist - how do I use the API to search YouTube? A: While you can use the .NET client library for YouTube, I find that the .NET API lags behind the developments that are being made (for example, I'm not sure if you can even get the like/dislike information from the API yet) in the protocol itself. Instead, I'd recommend that you use the Data API Protocol, it uses HTTP and XML (in ATOM format) which .NET has classes that can easily use/parse. The documentation is also very complete, and composing your queries would be quite easy. In your example, the URL for your query would be: http://gdata.youtube.com/feeds/api/videos?v=2&orderby=viewCount&safeSearch=none&q=puppy Which would subsequently return an XML document structured like this (although the data might be different, as I assume new videos of puppies are being uploaded all the time): <?xml version='1.0' encoding='UTF-8'?> <feed xmlns='http://www.w3.org/2005/Atom' xmlns:app='http://www.w3.org/2007/app' xmlns:media='http://search.yahoo.com/mrss/' xmlns:openSearch='http://a9.com/-/spec/opensearch/1.1/' xmlns:gd='http://schemas.google.com/g/2005' xmlns:gml='http://www.opengis.net/gml' xmlns:yt='http://gdata.youtube.com/schemas/2007' xmlns:georss='http://www.georss.org/georss' gd:etag='W/&quot;C0cBR38zfCp7I2A9WhdUEU4.&quot;'> <id>tag:youtube.com,2008:videos</id> <updated>2011-09-27T13:44:16.184Z</updated> <category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#video'/> <title>YouTube Videos matching query: puppy</title> <logo>http://www.youtube.com/img/pic_youtubelogo_123x63.gif</logo> <link rel='alternate' type='text/html' href='http://www.youtube.com'/> ... <entry gd:etag='W/&quot;CEINR347eCp7I2A9WhdUEEQ.&quot;'> <id>tag:youtube.com,2008:video:vkeETehk8C8</id> <published>2007-05-21T02:02:00.000Z</published> <updated>2011-09-27T03:03:16.000Z</updated> <category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#video'/> ... You can also get the XML and put it into the YouTube .NET client structures for easy access (although not easily, it is possible) if you want to capitalize on the object models that they already have, but drop down to the XML to get values that the API doesn't expose. A: What you're looking for is in the Authentication chapter of their .NET guide. Basically, you need to add this in the beginning: YouTubeRequestSettings settings = new YouTubeRequestSettings("example app", clientID, developerKey); YouTubeRequest request = new YouTubeRequest(settings); The printVideoFeed method is just a demo to print out all the meta-data, but you can find it in the guide too. You probably want to do something else with the Feed you get. query.Query shouldn't be missing though.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567669", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Struts 1 How to set checkbox default checked I'm making some small changes to an existing project, which was built using Struts 1.2. I need to have a check box on the form checked by default. I'm a newbie on Struts. I understand that I can't set a default value for check boxes on form reset method, in fact it is suggested to set the value to false for checkboxes in reset method. The only way I can think of is to check the POST param, but I don't think this is a good solution. Is there a correct Struts way to have a default checked checkbox? A: you have: <html:checkbox property="multiRole" value="Y" /> if you want the page rendered with it checked by default, you need to set the property "multiRole" in your action form to "Y" A: Why can't you set a default value in reset? That's mostly what it's for. You can also set a value in the action that initially displays the form. A: alternatively you can use the ,,normal" html tag to solve this problem. This tag can also interact with the form bean via the name parameter. In the form bean you can use a boolean parameter! <input type="checkbox" name="multiRole" checked="checked" />
{ "language": "en", "url": "https://stackoverflow.com/questions/7567673", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Referencing functions from within functions inside a JavaScript object var Page = { data: null, Load: function () { this.Populate; }, Populate: function () { } }; $(document).ready(Page.Load); * *Why can't I reference Page.Load as a function in ready() eg .ready(Page.Load()) *Why can't I call this.Populate() from the Load function, I just get this.Populate() is not a function. A: Why can't I reference Page.Load as a function in ready() eg .ready(Page.Load()) Sticking () on the end calls a function. You want to pass the function itself, not its return value. (The ready function will call what you pass to it later). Why can't I call this.Populate() from the Load function, I just get this.Populate() is not a function Two reasons. First, you never actually call the Populate function. Change to: this.Populate() Second: because you detach the Load function from the object, so this isn't Page by the time it gets called. Do this instead: $(document).ready(function () { Page.Load() }); A: A function call should be in the format function_name() (parentheses!). A function reference should be function_name (without parentheses). This code will work: var Page = { data: null, Load: function () { Page.Populate(); //PARENTHESES }, Populate: function () { } }; $(document).ready(Page.Load);//NO PARENTHESES $(document).ready is a function which expects a function to be parameter 1. If you use Page.Load(), you will execute function Page.Load() and pass the return value (undefined, in this case) to $(document).ready. A: There are two problems in your code. First, as Rob says, you're not actually calling the Populate() method in Load(). You need to add parenthesis to do that. Second, the this keyword in Populate() does not refer to the Page object. You can use $.proxy() to set the Page object as the context of the method call: var Page = { data: null, Load: function() { this.Populate(); }, Populate: function() { } }; $(document).ready($.proxy(Page.Load, Page)); A: You can get it to work by wrapping your object up in a function like this: var Page = (function () { var that = { data: null, Load: function () { that.Populate(); }, Populate: function () { alert("Test"); } }; return that; })(); // Execute the function immediately to return 'that' $(document).ready(Page.Load); This way you can call between methods as you have a reference to the object (that). JSBin Example A: You're calling the function Page.Load. But more specifically you're calling the function that Page.Load is set to (since that argument to .ready() is just a simple value); you're not calling it on Page, so 'this' is not reset to point to the Page object. This will work better: $(document).ready(function() { Page.Load(); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7567674", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: reading content from a cmd window via python I'm trying to connect to an existing cmd window and read its content. It is an arbitrary cmd window and not a child process. Any ideas how this can be done with python? Thanks in advance, Omer. A: ** Note: the original version of the question asked how to read AND write to a cmd window ** Writing You can write to an existing command window with code such as: from pywinauto import application app = application.Application() app.connect_(path= r"C:\WINDOWS\system32\cmd.exe") dlg = app.top_window_() dlg.TypeKeys('hello world') Notes: * *I installed the latest version of pywinauto into a Python 2.6 installation direct from the Mercurial repository with the command: pip install -e hg+https://code.google.com/p/pywinauto/#egg=pywinauto *I would make this rather more robust than assuming the path to cmd.exe! Documentation on selecting the application is at http://pywinauto.googlecode.com/hg/pywinauto/docs/HowTo.html Reading Reading from an existing command window appears to be somewhat more difficult! Someone on the pywinauto-users mailing list has got it working & is offering to post a working example: http://thread.gmane.org/gmane.comp.python.pywinauto.user/249/focus=252 I suggest you get in touch with him. A: This is possible using pywinauto, pytesseract and PIL, What all you need to do is check for the window existence using pywinauto and take its screenshot. And read the text of the image using tesseract and PIL. Like in below code sample - from pywinauto import Application, Desktop from pytesseract import pytesseract import time from PIL import Image app = Application(backend="uia").start(r'c:\WINDOWS\System32\cmd.exe /k', create_new_console=True, wait_for_idle=False) time.sleep(3) # grab the arbitrary window calc = Desktop(backend="uia").window(title='c:\WINDOWS\System32\cmd.exe') # print the dump tree (control identifiers) of the window calc.dump_tree() # type command and hit enter calc.type_keys("dir") calc.type_keys('{ENTER}') # select the window for taking screenshot textarea = calc.child_window(title='Text Area') textarea.set_focus() textarea.draw_outline() img = textarea.capture_as_image() img.save('CMD_screenshot.png') # Read the image using tesseract path_to_tesseract = r"C:\Users\user-name\AppData\Local\Tesseract-OCR\tesseract.exe" image_path = r"CMD_screenshot.png" img = Image.open(image_path) pytesseract.tesseract_cmd = path_to_tesseract text = pytesseract.image_to_string(img) # Displaying the extracted text print(text[:-1]) sample output - dates of the file created - 08/24/2022 8/11/2022 06/14/2022 7/05/2022 7/06/2022 you will need to install - pip install pillow pip install pytesseract pip install pywinauto
{ "language": "en", "url": "https://stackoverflow.com/questions/7567680", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: access sharepoint documents from J2EE system I have a J2EE online system and I am integrating office365 and sharepoint online to this system. My Goal: access documents that are inside the sharepoint document library through my J2EE system. What I only have now: - My J2EE system - Office 365 account (that includes "Sharepoint Online") What are the steps needed in order to reach my goal ? (for example: installing sharepint server, downloading sharepoint administrator toolkit, how to use contect management interoperability services CMIS, is there any sharepoint development needed...etc ) Thanks a lot. A: This is all what you need. http://msdn.microsoft.com/en-us/library/gg454740.aspx A: The first step you need the integration of you application with sharepoint you might need this : Reading a SharePoint list with Java you can access documents that are inside the sharepoint document library through your J2EE system. You must read the documentation carefully before starting on it here is the link will be help full to you how to get file content from sharepoint list using restapi in java
{ "language": "en", "url": "https://stackoverflow.com/questions/7567684", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: YII CActiveRecord->find() Im now still learning YII on blog tutorial and curious with some code. on this link http://www.yiiframework.com/doc/blog/1.1/en/prototype.auth there is code like this <?php class UserIdentity extends CUserIdentity { private $_id; public function authenticate() { $username=strtolower($this->username); $user=User::model()->find('LOWER(username)=?',array($username)); if($user===null) $this->errorCode=self::ERROR_USERNAME_INVALID; else if(!$user->validatePassword($this->password)) $this->errorCode=self::ERROR_PASSWORD_INVALID; else { $this->_id=$user->id; $this->username=$user->username; $this->errorCode=self::ERROR_NONE; } return $this->errorCode==self::ERROR_NONE; } public function getId() { return $this->_id; } } and i curious with some code. * *Why there is no ?> at the end line of the code? *at this line $user=User::model()->find('LOWER(username)=?',array($username)); why using LOWER(username)=? not LOWER(username)=. WHy there is need ?, is this some query conditional that i didn't know yet maybe? A: * *?> is not really needed, according to this link: The closing tag of a PHP block at the end of a file is optional, and in some cases omitting it is helpful when using include() or require(), so unwanted whitespace will not occur at the end of files, and you will still be able to add headers to the response later. It is also handy if you use output buffering, and would not like to see added unwanted whitespace at the end of the parts generated by the included files. *the ? is related to SQL syntax as seen from here. Also the second answer here says that: The question mark represents a parameter that will later be replaced. Using parameterized queries is more secure than embedding the parameters right into the query.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567686", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: jQuery function (append some text to textarea) I'm trying to make a working JS function which ought to add some text from argument to textarea, without erasing it's content. <textarea id="message" name="message" cols="48" rows="4" accesskey="m"></textarea> So the code above is a code of my textarea. And the script below should add some text to its value but it doesn't work. function appendpostid( postid ) { $('#message').val($('#message').val() + postid); } And, if it's important, here is the code that calls that function: <a href="javascript:void(0)" onclick="appendpostid('."'>>".$rpl["id"]."'".')">'.$rpl["id"].'</a> Code from generated page: <a href="javascript:void(0)" onclick="appendpostid('>>69')">69</a> What am I doing wrong? Thanks in advance! A: Your code works: http://jsfiddle.net/d4pKt. Also make sure that the function is not inside the jquery .ready or it doesn't work A: I'm not sure a textarea has a value attached to it that you can manipulate. Please try: function appendpostid( postid ) { $('#message').append(postid); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7567687", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: does not work I tried to work with today. My starting point was here: https://developers.facebook.com/docs/internationalization. Unfortunately I am not able to register a string with the translation application. I found two threads indicating that is still buggy and not worth working on - last entries on both a few month old: http://forum.developers.facebook.net/viewtopic.php?id=70655 http://bugs.developers.facebook.net/show_bug.cgi?id=11448 Anybody has some more information on this? A working sample would be very helpful. Thanks! A: Registering strings works with intl.uploadNativeStrings. You can enter your strings directly on that page, for exampe: enter in the native_string field: [{text: "some string", desc: "a description"}] Then click Call Method After registering, I can translate the strings in the Translations App. But anyway, the strings in my Iframe App are still not translated. Is use <fb:intl>some string</fb:intl> tags in my app and call FB.init({ appId : '$appid', status : true, // check login status cookie : true, // enable cookies to allow the server to access the session xfbml : true // parse XFBML }); ...on the script //connect.facebook.net/de_DE/all.js but my strings are never translated. Any further help on this?
{ "language": "en", "url": "https://stackoverflow.com/questions/7567688", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to limit the description text to 100-150 words using Razor I want to display a shorter version of description on maine page , I tried something like <div class="newsdetails"> @Html.Raw(item.Short) </div> Although it shorts the news description but i want to customise it to 100 words. Regards A: .Have a free extension method on me. This chops strings by letters, not words. To change it to use words, consider using a method like Tobias's below. public static string Chop(this string text, int chopLength, string postfix = "...") { if (text == null || text.Length < chopLength) return text; else return text.Substring(0, chopLength- postfix.Length) + postfix; } A: You could use string.Split() Methode and use space as seperator. string[] words = item.Text.Split(' '); MSDN: http://msdn.microsoft.com/de-de/library/system.string.split%28v=vs.80%29.aspx Afterwoods concat the words to string.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567689", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Need help in php associative array I have a associative array and i wanted to print out all the column values at once rather by each row Example if i have a array of 1.1, 1.2, 1.3, 1.4 2.1, 2.2, 2.3, 2.4 3.1, 3.2, 3.3, 3.4 Currently is displaying 1.1 1.2 1.3 1.4 then 2.1 2.2 2.3 2.4 ...etc but I wanted to display 1.1 ,2.1, 3.1 then 1.2 2.2 3.2 ... etc In c++ i know you have to use nested for loop in order to achieve this for (int i=0; i< col_size; i++) { for (int j=0; j < row_size; j++) { cout << a[i][j]; } } But how can it be done using associative array in PHP? Thanks so much! A: <?php $array = array(array(1.1, 1.2, 1.3, 1.4), array(2.1, 2.2, 2.3, 2.4), array(3.1, 3.2, 3.3, 3.4)); $_rows = sizeof($array); $_cols = sizeof($array[0]); for ($i=0; $i<=$_cols; $i++) { for($j = 0;$j<=$_rows; $j++) { echo $array[$j][$i]. " "; } echo " \n"; } ?> Outputs 1.1 2.1 3.1 1.2 2.2 3.2 1.3 2.3 3.3 1.4 2.4 3.4 See http://codepad.org/I2AysS5X Note the [$j][$i] instead of [$i][$j] A: Something like this? for ($i=0; $i< col_size; $i++) { for ($j=0; $j < row_size; $j++) { echo $a[$i][$j]; } } ;-) While the above doesn't work for an associative array, you'd have to specify the associations. For example, if the keys for X are in array $foo and the keys for Y are in $bar, you could do it like this: $foo = array('a', 'b', 'c', ...); $bar = array('1', '2', '3', ...); foreach ($foo => $x) { foreach ($bar => $y) { echo a[$x][$y]; } } You can extract the keys using array_keys(). A: for (int $i=0; $i< $col_size; $i++) { for (int $j=0; $j < $row_size; $j++) { echo a[i][j]; } } just noticed that u didnt use $ wich is a syntax error but the php and c++ arrays are too close and every thing u do in c++ can be done the same way in php just don't forget the $ in variable names
{ "language": "en", "url": "https://stackoverflow.com/questions/7567691", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Getting an Error "ORA-06502: PL/SQL: numeric or value error: character string buffer too small" I have a below Package which is giving error ORA-06502: PL/SQL: numeric or value error: character string buffer too small Please let me know what is going wrong here. CREATE OR REPLACE PACKAGE BODY PKG_H IS PROCEDURE PROC_SUBMIT_H ( Pout_Rqst_Id OUT NVARCHAR2, Pout_err_cd OUT VARCHAR2, Pout_err_msg OUT VARCHAR2, Pin_Rqst_Type_Id IN NUMBER, Pin_Attachment IN NVARCHAR2, Pin_Brand_Id IN NVARCHAR2, Pin_Prop_Id IN NVARCHAR2, -- Pin_Htl_Stat_Rqst_Typ_ID IN NUMBER, Pin_Orcl_Acct_Num IN NVARCHAR2, -- NUMBER, /* Changed on 22.09.2011,as stated by FIS Team */ Pin_ORCL_User_Name IN NVARCHAR2, Pin_Rstn_Id IN NUMBER, Pin_Rstn_Name IN NVARCHAR2, Pin_Rstn_Start_Date IN DATE, Pin_Rstn_End_Date IN DATE, -- Pin_Change_Type_Ind IN NVARCHAR2, Pin_Trans_Time_Orcl IN TIMESTAMP, Pin_Fis_Acct_Stat_Prsnt_Id IN NUMBER, Pin_Fis_Acct_Future_Stat IN NUMBER, Pin_Auto_Ind IN NVARCHAR2, -- Pin_Stat_Change_Resn_ID IN NUMBER, /* changed due to ETL requirement as on 17.09.2011 */ Pin_Stat_Change_Resn_Desc IN NVARCHAR2, /* changed due to ETL requirement as on 17.09.2011 */ Pin_Brand_Dot_Com_Ind IN NVARCHAR2, -- Pin_Expdt_Ind IN NVARCHAR2, -- Pin_Expdt_Dt IN DATE, Pin_Rqstr_Id IN NVARCHAR2, Pin_Impn_Id IN NUMBER, -- Pin_Agent_Id IN NVARCHAR2, /* Changed as on 22.09.2011 */ -- Pin_Agent_Name IN NVARCHAR2, /* Changed as on 22.09.2011 */ Pin_File_Name IN NVARCHAR2, Pin_Prov_Date IN DATE -- Pin_Rqst_Stat_ID IN NUMBER -- Pin_Prov_Time IN DATE ) IS -- lv_err_cd VARCHAR2(10); -- lv_err_msg VARCHAR2(4000); Ln_Cnt NUMBER; DUP_VAL EXCEPTION; lv_rqst_id NVARCHAR2(20); Ln_rqst_stat_id_it NUMBER; Ln_rqst_stat_id_Q NUMBER; Ln_rqst_category_id NUMBER; Ln_Stat_Change_Resn_Id NUMBER; -- Ln_Htl_Stat_Rqst_Typ_Id NUMBER; lt_data_01 STRINGTABLETYPE := STRINGTABLETYPE(); lt_data_02 STRINGTABLETYPE := STRINGTABLETYPE(); BEGIN SELECT fnc_gen_request_id INTO Lv_rqst_id FROM dual; SELECT rqst_stat_id INTO Ln_rqst_stat_id_it FROM rqst_stat_mst WHERE rqst_stat_desc = 'In Transmit'; SELECT rqst_stat_id INTO Ln_rqst_stat_id_Q FROM rqst_stat_mst WHERE rqst_stat_desc = 'Pending'; SELECT COUNT(1) INTO Ln_Cnt FROM HOTEL_STAT_RQST WHERE FILE_NAME=Pin_File_Name; IF Ln_Cnt >0 then RAISE DUP_VAL; END IF; IF Pin_Stat_Change_Resn_Desc IS NOT NULL THEN SELECT STAT_CHANGE_RESN_ID INTO Ln_Stat_Change_Resn_Id FROM STAT_CHANGE_RESN_MST WHERE UPPER(STAT_CHANGE_RESN_DESC)=UPPER(TRIM(Pin_Stat_Change_Resn_Desc)); END IF; DELETE FROM HOTEL_STAT_RQST WHERE RQST_ID=lv_rqst_id; INSERT INTO HOTEL_STAT_RQST (RQST_ID ,RQST_TYPE_ID ,RQST_STAT_ID ,BRAND_ID ,PROPERTY_ID ,STAT_CHANGE_RESN_ID -- ,HOTEL_STAT_RQST_TYPE_ID ,ORCL_ACCT_NUM ,ORCL_USER_NAME ,TRANS_TIME_ORCL ,FIS_ACCOUNT_STATUS_PRESENT_ID ,FIS_ACCT_FUTURE_STAT ,RSTCTN_ID ,RSTCTN_NAME ,RSTCTN_STRT_DT ,RSTCTN_END_DT -- ,RSTCTN_PREV_STRT_DT /* SCHEMA CHANGED */ -- ,RSTCTN_PREV_END_DT /* SCHEMA CHANGED */ -- ,PREV_RSTN_ID /* SCHEMA CHANGED */ ,AUTO_IND -- ,CHANGE_TYPE_IND ,BRAND_DOT_COM_IND ,RQSTR_ID ,IMPN_ID ,EXPDT_IND ,EXPDT_DT -- ,PROVSN_STAT /* SCHEMA CHANGED */ -- ,PROVSN_TIME /* SCHEMA CHANGED */ ,CREATED_ON ,UPDATED_BY ,UPDATED_ON ,FILE_NAME ,PROV_DATE ) VALUES ( lv_rqst_id ,Pin_Rqst_Type_Id ,Ln_rqst_stat_id_it ,Pin_Brand_Id ,Pin_Prop_Id ,Ln_Stat_Change_Resn_Id /* changed due to ETL requirement as on 17.09.2011 */ -- ,Pin_Htl_Stat_Rqst_Typ_ID ,Pin_Orcl_Acct_Num ,Pin_ORCL_User_Name ,Pin_Trans_Time_Orcl ,Pin_Fis_Acct_Stat_Prsnt_Id ,Pin_Fis_Acct_Future_Stat ,Pin_Rstn_Id ,Pin_Rstn_Name ,Pin_Rstn_Start_Date ,Pin_Rstn_End_Date -- ,NULL /* SCHEMA CHANGED */ -- ,NULL /* SCHEMA CHANGED */ -- ,NULL /* SCHEMA CHANGED */ ,Pin_Auto_Ind -- ,Pin_Change_Type_Ind ,Pin_Brand_Dot_Com_Ind ,Pin_Rqstr_Id ,Pin_Impn_Id ,NULL ,NULL -- ,NULL /* SCHEMA CHANGED */ -- ,Pin_Prov_Time /* SCHEMA CHANGED */ ,SYSDATE ,Pin_Rqstr_Id ,SYSDATE ,Pin_File_Name ,Pin_Prov_Date ); IF Pin_Attachment IS NOT NULL THEN DELETE FROM attach_ref WHERE rqst_id=lv_rqst_id; SELECT CAST(SPLIT(Pin_Attachment,'|') AS STRINGTABLETYPE) INTO lt_data_01 FROM DUAL; FOR i_outer IN 1..lt_data_01.COUNT LOOP SELECT CAST(SPLIT(lt_data_01(i_outer),'~')AS STRINGTABLETYPE) INTO lt_data_02 FROM DUAL; INSERT INTO attach_ref ( rqst_id, attach_id, -- SEQUENCE attach_ind, attach_file_name, file_path, ord_num ) VALUES( lv_rqst_id, attach_id_seq.NEXTVAL, -- SEQUENCE 'REQUESTOR', lt_data_02(1), lt_data_02(2), i_outer ); END LOOP; END IF; DELETE FROM rqst_queue WHERE rqst_id=lv_rqst_id; INSERT INTO rqst_queue ( rqst_id, prnt_rqst_id, queu_start_time, queu_end_time, agnt_id, agnt_name, property_id, src_sys, tgt_sys, queu_stat_ind ) VALUES ( lv_rqst_id, NULL, SYSDATE, NULL, NULL, NULL, Pin_Prop_Id, 'RQT', 'SFDC', Ln_rqst_stat_id_Q ); IF Pin_Rqst_Type_Id IS NOT NULL THEN SELECT rqst_category_id INTO ln_rqst_category_id FROM rqst_type_mst WHERE rqst_type_id = Pin_Rqst_Type_Id; END IF; DELETE FROM rqst_sumry WHERE rqst_id = lv_rqst_id; INSERT INTO rqst_sumry ( rqst_id, rqst_type_id, prnt_rqst_id, brand_id, property_id, expdt_ind, expdt_dt, rqstr_id, rqst_stat_id, compln_dt, estm_compln_time, rqst_category_id, submission_dt ) VALUES ( lv_rqst_id, Pin_Rqst_Type_Id, NULL, Pin_Brand_Id, Pin_Prop_Id, NULL, NULL, Pin_Rqstr_Id, Ln_rqst_stat_id_it, NULL, NULL, ln_rqst_category_id, SYSDATE ); COMMIT; Pout_Rqst_Id := lv_rqst_id; EXCEPTION WHEN NO_DATA_FOUND THEN ROLLBACK; Pout_err_cd := SQLCODE; Pout_err_msg := 'STAT_CHANGE_RESN_MISMATCH'; WHEN DUP_VAL THEN Pout_err_cd := SQLCODE; Pout_err_msg := 'DUPLICATE'; WHEN OTHERS THEN ROLLBACK; Pout_err_cd := SQLCODE; Pout_err_msg := SUBSTR(SQLERRM, 1 , 4000); END PROC_SUBMIT_H; END PKG_H; / A: You are trying to assign a value to a PL/SQL variable which is not big enough for it. For example, you have ... Lv_rqst_id NVARCHAR2(20); ... And then: ... SELECT fnc_gen_request_id INTO Lv_rqst_id FROM dual; .... I don't know what is fnc_gen_request_id or what is returning, but check it out this kind of assignment in your code and try to testing it or wrap in a BEGIN ... EXCEPTION .. END structure to get a clue. A: As well as the potential fnc_gen_request_id return size problem that @Aitor mentioned, you could also be putting a value into one out of your OUT parameters that the caller can't cope with. For example, when you put up to 4000 chars into Pout_err_msg, though that would only be a problem when an exception is encountered anyway, so Pout_Rqst_Id or Lv_rqst_id might be more likely. You might also want to check that you're using VARCHAR and NVARCHAR consistently. (Incidentally, should Pout_err_cd be declared as a number?) A: You're trying to insert too many characters into a string (buffer) variable. Both blocks below will raise ORA-06502: PL/SQL: numeric or value error: character string buffer too small. Your problem is a variation of these simple cases. declare str varchar2(2); /* Only room for two characters. */ begin select 'foo' into str from dual; /* Three is one too many. */ end; / declare str varchar2(2); /* Only room for two characters. */ begin str := 'foo'; /* Three is one too many. */ end; /
{ "language": "en", "url": "https://stackoverflow.com/questions/7567693", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C# Storing string,int,string in an accessable variable I need to save a class with list of countries in statics for caching. the data is built with string shortName //Primary Key - (IL or UK for example) int ID //Unique - has no meaning, but needs to be saved string longName //(Israel or United Kingdom for example) I thought of saving it in a Dictionary: Dictionary<string , Dictionary<int,string>> list = new Dictionary<string, Dictionary<int,string>>(); this is the API that i need in the class: Countries.getByShortName();// I dont know what to return, I'd love some advise Countries.getById();// I might need that Countries.getAll();// I dont know what to return, I'd love some advise What do you think is the best way of handling this class? thanks A: How about using a struct or class? class Country { string shortName; // Primary Key - (IL or UK for example) int ID; // Unique - has no meaning, but needs to be saved string longName; // (Israel or United Kingdom for example) } You can then store your countries in a generic List, for example: List<Country> countries = new List<Country>(); countries.Add(new Country() { shortName = "UK", ID = 1, longName = "United Kingdom", }); Implementing your given methods then becomes very straightforward: Country getByShortName(string shortName) { foreach (Country country in countries) { if (country.shortName == shortName) { return country; } } return null; } A: I think you need to create your own class incapsulating all three fields and to use own Collection of It. For example: class CountryInfo { string shortName //Primary Key - (IL or UK for example) int ID //Unique - has no meaning, but needs to be saved string longName //(Israel or United Kingdom for example) } class CountryCollection : Collection <CountryInfo> { //Implement methods what you need void getByShortName();// I dont know what to return, I'd love void getById();// I might need that void getAll();// I dont know what to return, I'd l } If you like quick search then to use a pair of dictionaries: class CountryInfo { string shortName //Primary Key - (IL or UK for example) int ID //Unique - has no meaning, but needs to be saved string longName //(Israel or United Kingdom for example) } class CountryCollection { Dictionary <int, string> Ids = new Dictionary <int, string> (); Dictionary <string, string> shortNames = new Dictionary <string, string> (); void Add (CountryInfo info) { Ids.Add (info.ID, info.longName); shortnames.Add(info.ID, info.longName); } //Implement methods what you need void getByShortName();// I dont know what to return, I'd love void getById();// I might need that void getAll();// I dont know what to return, I'd l } A: You should create a custom type: public class Country { public string ShortName {get; set;} public int ID {get; set;} public string LongName {get; set;} } and then store the countries in a Dictionary<string, Country> from which you'll be able to do: var UK = _countries["UK"]; UK.ID... UK.LongName... A: why wont you make your own class? class Country { public string shortName { get; set; } //Primary Key - (IL or UK for example) public int ID { get; set; } //Unique - has no meaning, but needs to be saved public string longName { get; set; } //(Israel or United Kingdom for example) } then just make another class, that will contain methods you need class Countries { List<Country> countries = new List<Country>(); public void Add(Country c) { countries.Add(c); } public List<Country> getByShortName(); public List<Country> getById(); public List<Country> getAll(); } A: I suggest the use of static methods: public class Country { public string ShortName {get;set;} public int ID {get;set;} public string LongName { get; set; } } public class Countries { static Dictionary<string, Country> dict = new Dictionary<string, Country>(); public static void Add(Country country) { if (!dict.ContainsKey(country.ShortName)) dict.Add(country.ShortName, country); } public static Country GetByShortName(string ShortName) { if (dict.ContainsKey(ShortName)) return dict[ShortName]; return null; } public static Country GetById(int id) { var result = from country in dict where country.Value.ID==id select new Country { ID = country.Value.ID, ShortName = country.Value.ShortName, LongName = country.Value.LongName }; return result.SingleOrDefault(); } public static List<Country> GetAll() { var result = from country in dict select new Country { ID = country.Value.ID, ShortName = country.Value.ShortName, LongName = country.Value.LongName }; return result.ToList(); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7567695", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Oracle REGEXP_LIKE and word boundaries I am having a problem with matching word boundaries with REGEXP_LIKE. The following query returns a single row, as expected. select 1 from dual where regexp_like('DOES TEST WORK HERE','TEST'); But I want to match on word boundaries as well. So, adding the "\b" characters gives this query select 1 from dual where regexp_like('DOES TEST WORK HERE','\bTEST\b'); Running this returns zero rows. Any ideas? A: The shortest regex that can check for a whole word in Oracle is (^|\W)test($|\W) See the regex demo. Details * *(^|\W) - a capturing group matching either * *^ - start of string *| - or *\W - a non-word char *test - a word *($|\W) - a capturing group matching either * *$ - end of string *| - or *\W - a non-word char. Note that \W matches any chars but letters, digits and _. If you want to match a word that can appear in between _ (underscores), you need a bit different pattern: (^|[^[:alnum:]])test($|[^[:alnum:]]) The [^[:alnum:]] negated bracket expression matches any char but alphanumeric chars, and matches _, so, _test_ will be matched with this pattern. See this regex demo. A: I believe you want to try select 1 from dual where regexp_like ('does test work here', '(^|\s)test(\s|$)'); because the \b does not appear on this list: Perl-influenced Extensions in Oracle Regular Expressions The \s makes sure that test starts and ends in a whitespace. This is not sufficient, however, since the string test could also appear at the very start or end of the string being matched. Therefore, I use the alternative (indicated by the |) ^ for start of string and $ for end of string. Update (after 3 years+)... As it happens, I needed this functionality today, and it appears to me, that even better a regular expression is (^|\s|\W)test($|\s|\W) (The missing \b regular expression special character in Oracle). A: In general, I would stick with René's solution, the exception being when you need the match to be zero-length. ie You don't want to actually capture the non-word character at the beginning/end. For example, if our string is test test then (\b)test(\b) will match twice but (^|\s|\W)test($|\s|\W) will only match the first occurrence. At least, that's certainly the case if you try to use regexp_substr. Example SELECT regexp_substr('test test', '(^|\s|\W)test($|\s|\W)', 1, 1, 'i'), regexp_substr('test test', '(^|\s|\W)test($|\s|\W)', 1, 2, 'i') FROM dual; Returns test |NULL
{ "language": "en", "url": "https://stackoverflow.com/questions/7567700", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "38" }
Q: System.UnauthorizedAccessException calling UserPrincipal.SetPassword when I run this code PrincipalContext ctx = new PrincipalContext(ContextType.Domain, adHost, adRoot, ContextOptions.SimpleBind, adUsername, adPassword); UserPrincipal user = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, username); user.SetPassword(password); user.Save(); I get this exception System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.UnauthorizedAccessException: One or more input parameters are invalid The code is running from a command line using "runas /user: (domainadminuser is also a local admin) The context is created using the same credentials (domainadminuser) I've checked that all usernames, passwords etc are populated correctly Is it something to do with the way I am creating the PrincipalContext? I'm completely stuck. Does anyone have any ideas? Thanks [UPDATE] Here's the code I used to get it working. I think maybe the ValidateCredentials was the thing that kicked it into life (possibly) PrincipalContext ctx = new PrincipalContext(ContextType.Domain, parameters["adHost"] ); ctx.ValidateCredentials(parameters["adUsername"], parameters["adPassword"], ContextOptions.SimpleBind); UserPrincipal user = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, username); user.SetPassword(password); user.Save(); A: Below is the code that works fine for a password request management system we developed in-house, do try and let me know: PrincipalContext context = new PrincipalContext( ContextType.Domain, null, adAdminLogin, adAdminPassword ); UserPrincipal user = UserPrincipal.FindByIdentity( context, adUserLogin ); user.SetPassword( adUserNewPassword ); A: As far as Active-Directory is concerned with the Standard LDAP protocol the simple bind without SSL not allow to change any password. Clearly here you are using classes that can communicate with your server using non standard protocol, but your SimpleBind context option can switch to standard LDAP. have a look to @CodeCanvas code. A: When the Context is created, make sure to set the ContextOptions to ContextOptions.Negotiate . If you have mentioned ContextOptions.SimpleBind, SetPassword may not work. PrincipalContext oPrincipalContext = new PrincipalContext (ContextType.Domain, "Name", "DefaultOU(if required)", ContextOptions.Negotiate, "Service Account(if required)", "Service password");
{ "language": "en", "url": "https://stackoverflow.com/questions/7567701", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to do JNDI lookup with OracleAQ? Can anybody point me some guide/idea on how to implement JNDI lookup with OracleAQ? ( Creating connectionFacotry, parameters for "java.naming.factory.initial", java.naming.provider.url etc..) A: Here is an example of how to setup a basic JMS (including the lookup of the connection factory) in Oracle WebLogic: http://download.oracle.com/docs/cd/E21764_01/web.1111/e13727/implement.htm#i1317694 Here is another link more specific to Oracle AQ http://download.oracle.com/docs/cd/E21764_01/web.1111/e13738/aq_jms.htm#JMSAD565 It looks like oracle.jms.AQjmsInitialContextFactory might be the correct JNDI Initial Context Factory.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567702", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Binding a jquery autocomplete dynamic textbox to json I have done a heap of searching but can't seem to get anywhere. I have some json that looks like [{"IngredientId":1,"IngredientName":"Butter","CategoryID":1},{"IngredientId":2,"IngredientName":"Sugar","CategoryID":1},{"IngredientId":3,"IngredientName":"Water","CategoryID":1},{"IngredientId":4,"IngredientName":"Salt","CategoryID":1}] Im trying to do 2 things. 1. Somehow store IngredientId from the selected autocomplete textbox and the most important.Bind the autocomplete to the above json. This is my lame attempt of binding the value .autocomplete({ source: ingredients, select: function (item) { console.log(item.IngredientId); return item.IngredientName; } Can someone help out with the right way I should be binding to the autocomplete? Thank you A: source property requires plain array or array of objects (or string). Going with array of objects those should be of the type { 'value': 'some_val', 'label': 'some_label' }. If you don't have control over that ingredients array you should probably map it in order to work with autocomplete. var ingredients_ac = $.map( ingredients, function( obj ) { return { value: obj.IngredientId, label: obj.IngredientName }; } ); then use the new array with autocomplete .autocomplete({ ... source: ingredients_ac, ... } );
{ "language": "en", "url": "https://stackoverflow.com/questions/7567703", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Trouble with imaplib fetch formats: RFC822 unequel utf8? I want to read an email messege which is in utf8 format. And this is not working with the following code: I guess i have to take a different format, but which and how? The output gives sth. like "=C3=96sterreich" for "Österreich". So far I have this...Thanx import imaplib import email imap4 = imaplib.IMAP4(SERVER) imap4.login(USER, PASSWORD) imap4.select() typ, data = imap4.search(None,'(UNSEEN SUBJECT "%s")' % subject) for num in data[0].split(): typ, data = imap4.fetch(num,'(RFC822)') msg = email.message_from_string(data[0][1]) typ, data = imap4.store(num,'-FLAGS','\\Seen') print msg A: Data in MIME containers is usually encoded using “quoted-printable” codec. I don't know the internals of imaplib but I believe what you're looking for is quopri.decodestring().
{ "language": "en", "url": "https://stackoverflow.com/questions/7567704", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Thread Pools using Thread Class and AsyncTask Class my Android app extends a number of Thread and AsyncTask Classes. I used either of these classes when loading an Activity. I am doing this to run an I/O task and show a dialog to the user if the load time is more then a second. It would be safe to say that there will be only one thread or AsynTask running at a time (not including the main UI). Do I need a thread Pool? A: No it would not at all safe to assume that. In all probability there would be multiple threads running (although on a single core) - what you should be bothered about is what you can really control - make sure your user does not have a bad experience - I think you are doing that already by keeping a separate thread for the UI. In fact it is very much possible to run multiple threads (more than 2 excluding the UI thread) from the same activity itself by using the AsyncTask. Android itself has many threads running and it has certain priorities which need to be honored as well. If we break the priority by writing a our own Thread Pool (I'm doubtful if we will have access to all the threads on non-jail broken phones) the system might become unstable and might lead to frequent crashes. Android has an inbuilt algorithm to call the garbage collector and also to kill threads in case they are greedy / starving other threads to death. So while designing a good application, we also need to cover such corner cases otherwise we end up with lots of NPEs at the service.start() and that too pretty randomly. Also, from the latest phones, it looks like newer phones with dual cores have already come out :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7567706", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to quit a pygtk application after last window is closed/destroyed Is there a way I can tell gtk to automatically call gtk.main_quit() when the last open window of the application is closed/destroyed? If there is no direct feature offering this functionality, I could think of the following: In the window's destroy method: get a list of open windows in the process, if its empty quit. Is there a way to get such a list? The obvious solution would be to keep manually track of all open windows, but I would want to avoid this if possible. A: the destroy signal of the main window must be connected to gtk main_quit : window.connect("destroy", gtk.main_quit) A: Use the method gtk.main_level() to get the current nesting level of the main loop. The nesting level is increased by calling the gtk.main() function and reduced by calling the gtk.main_quit() function
{ "language": "en", "url": "https://stackoverflow.com/questions/7567707", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Is ID in XML cause the resource file builder to declare the instance in Android? We mostly in android when working with layout file in XML declare the ID of those views/controls which we want to refer in the code or any else where in XML. I want to know what exactly Andriod performs at back-end * *does mentioned ID in XML cause the resource file builder to declare the instance of the object so that we can use ? *or it just declares instance anyways even if we don't mention the ID ? A: So let me explain here what really happens in the background. We have the standard HashMap which has a key and a value The way the hash map works is by generating a hash-value out of the key which is used for mapping. So, for example, if the strings.xml contains <string name="app_name">Hello, Android</string> The "app_name" is the key, which is hashed using some hash function and using that location the String "Hello, Android" is stored - the way normal Java HashMap works. So lets go over this again When you say map.get("app_name"); the hash function is called this way generatehash("app_name") and this value is used to calculate the position of the value(Hello, Android) So every time we retrieve a value from this HashMap, we end up calling this generatehash() function - Although this is O(1), it is still some amount of processing. To make this little more efficient and spend lesser computing power (mobile devices are designed keeping very low memory foot-print in mind) - this generatehash() function is called only at compile time That's the idea - so the hash-values are calculated at compile time and put up in this file called, R.java ... So at run-time, we have a one-on-one mapping of a key with the hash-value and this hash-value is directly used in finding the actual resource :) So keeping this in mind, the resources are available "in-memory" at some particular location - just like a HashMap, and that location is calculated using the hash-value that is present in the R.java Hope it answers your question.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567708", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Combining two video from ffmpeg I want to combine two mp4 videos to form a single mp4 video using ffmpeg. what i tried so far is ffmpeg -i input1.mp4 -i input2.mp4 output.mp4 But, every time i get the video with video codec of first input and not the other. How can i combine them? Any idea on this will be highly appreciated. A: Please read the FFMPEG FAQ for information about joining files. Unfortunately, since you're using MP4 files, simple concatenation won't work for you because the MP4 format contains a "header" (although it doesn't necessarily have to be at the beginning of the file) section that describes and contains offsets into the media data. You will need to transcode both files to a format that can be concatenated and then generate an MP4 file from that format (which will generate an appropriate header section). A: You can't concatenate .mp4 files but you can concatenate .mpg files. Try converting both videos to .mpg first using ffmpeg. Then, run a simple linux cat command on both .mpg files to create a combined .mpg file. After that, convert the concatenated .mpg file to .mp4 using ffmpeg. This is sort of a roundabout approach but it works. You can use "named pipes" to reduce the number of commands but the result is the same. A: You can do this with ffmpeg, but there's also a little tool out there, called MP4Box (part of GPAC), that can concatenate multiple MP4 files. In your case, the syntax is MP4Box -cat input1.mp4 -cat input2.mp4 output.mp4 A: concat demuxer: fast and preserves quality If all of the inputs have the same attributes, formats, and number of video/audio streams, then you can use the concat demuxer. This can allow you to concatenate without needing to re-encode, so it is fast and preserves quality. * *Make input.txt containing the following: file 'input1.mp4' file 'input2.mp4' *Concatenate ffmpeg -f concat -i input.txt -c copy output.mp4 If you get error Unsafe file name add the -safe 0 concat demuxer input option (before -i). If your inputs do not match If your inputs are different or are arbitrary then either: * *Use the concat filter. See How to concatenate videos in ffmpeg with different attributes? The requires re-encoding, but is the better choice when your inputs are random, mixed, unpredictable, or arbitrary. *Or re-encode the inputs that do not match the majority of inputs, then use the concat demuxer. There are many examples on this site showing how to do this. *Also see FFmpeg Wiki: Concatenate. A: As previous answers show, you need to convert first to an intermediate format. If the mp4 contains h264 bitstream, you can use: ffmpeg -i input1.mp4 -c copy -bsf:v h264_mp4toannexb -f mpegts input1.ts ffmpeg -i input2.mp4 -c copy -bsf:v h264_mp4toannexb -f mpegts input2.ts ffmpeg -i "concat:input1.ts|input2.ts" -c copy output.mp4 A more detailed answer you can find here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567713", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "18" }
Q: Retrieving Longitude and Latitude fron address passed to server I pose an interesting question. What I'm trying to achieve is I have a list of merchants and their address. I want their longitude and latitude so I can determine if the user (using location listener) is within a one kilometre radius of that merchant. I have done the code to determine if they are within that radius. What I need is the merchants longitude and latitude as I said. Is there a soap service that I can use to pass the address of the merchant and it responds with the longitude and latitude? Or can I send that to google places API somehow? A: I think that the Google Maps API does what you need via their GEOCODING support. http://code.google.com/apis/maps/documentation/javascript/v2/services.html#Geocoding A: Since you've tagged the question under Android, I'm going to take a hit and assume that by "how do I use this with java", you actually mean how can I do this on the android platform. Luckily, android provides the Geocoder APIs that you can use for geocoding addresses into lon/lat co-ordinates, by doing the following : gc = new Geocoder(this); //create new geocoder instance btnSearch.setOnClickListener(new OnClickListener() { public void onClick(View v) { String addressInput = adress.getText().toString(); //Get input text try { List<Address> foundAdresses = gc.getFromLocationName(addressInput, 5); //Search addresses } catch (Exception e) { //@todo: Show error message } } }); (above quoted from AndDev tutorial) Once you've got the lon/lats, you can create a GeoPoint and slap them on a map, link here on how to do that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567716", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to run or setup rails3? Have 2 ruby installations 1.8 and 1.9.1, have 2 gems. From "gem1.9.1 install rails" installed rails3 to my system, but don't have "rails" in my "path". How can i get rails to launch from entering rails in terminal? EDIT removed all ruby and ruby-gems from my system (Ubuntu 10.10) and installed ruby1.9.1 - it came with gems1.9.1 and then installed gem1.9.1 install rails How do i make "rails" run the installed gem rails? EDIT 2 Found it! The rails was installed in /var/lib/gems/1.9.1/bin/rails just had to add a alias "rails" to it in system $PATH A: How did you install your rubies? I'd strongly suggest to use a version manager like rvm, otherwise you're asking for trouble. A: You should be specific about your system environment. In windows when you install ruby, you just have RUBY_HOME/bin in your path. Whenever you install rails by gem install rails , it automatically deploy executable files in RUBY_HOME/bin folder. So that you can directly execute that command.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567724", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Fastest way to process php & mysql? I am looking for any kind of way to process php & mysql faster than my MacBook Pro running XAMPP is able to do. I have written an application, that has to process a lot of data for some simulations. On my MB, this takes about half an hour each time I want run a simulation. Not so very handy. Is there a good (and cheap) way to process these simulations a bit faster? I already enabled MySQL-Caches and PHP eAccelerator - but it's just simply too slow. I'd love a service, where I could place some MySQL-DB, some PHP and gain a lot of processing-power. Is there something faster than XAMPP to tun this? A: Generally speaking, performance is difficult to determine without going into details about your implementation so I can't really offer much advice beyond a few tips: As the commenters mention, PHP isn't designed for number crunching; something like Python, Java, or C++ are far better suited to this kind of task. Is 30 minutes a reasonable amount of time for the task to take? Assuming it takes 10 minutes less, will that actually be worth spending money on? Better planning and running jobs overnight is far cheaper :) As far as alternatives go you could try running your jobs on an Amazon EC2 instance, which may give you a bit of a speed boost but you'll still be running on one core; so your simulation will run roughly as quickly, ignoring input/output. If you actually want to optimise it, profile your application. You need to know where the time's being spent so you can figure out which parts you should spend time optimising; once you know which part of the code takes so long you should be able to try different approaches to get it working faster. Make sure you know the quirks of PHP, there are some surprising performance differences you might not be aware of. Optimisation can help, but always make sure your time spent doing it is going to be worth the time it saves. A: You could rent some processing power from a hoster. You should however find the source of the slowness. Analyze the points that take a lot of time. Is it disk access? Try a memory cache. Are the queries slow because they don't hit indexes for examlpe? Analyze and improve your queries. Does your code use massive loops of querying which could be done in a join? Then use a join.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567728", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Managing asp Session I have a code which allows session for my asp pages. However, when i try to use post form which takes me to another asp page, i will be automatically logout. Is there a solution to this? Thanks in advance. <%session("cLoginId") = Request.QueryString("cLoginId") session("Email") = Request.QueryString("Email") session("cPW") = Request.QueryString("cPW") session("UsrId") = csng(Request.QueryString("UsrId")) UsrId = csng(Request.QueryString("UsrId")) Set Con= server.CreateObject("ADODB.Connection") Con.Open "Provider=SQLOLEDB;Initial Catalog="&session("db")&";Data Source="&session("SqlServer")&";UID="&session("uid")&";PWD="&session("pwd")&";" mode = Request.QueryString("mode") UsrId = csng(Request.QueryString("UsrId")) cDesc1=CInt(Request.QueryString("c1")) cStartDte = Request.form("sStartDte") cEndDte = Request.form("sEndDte") p=Request.QueryString("p") 'session("cLoginId") = Request.QueryString("cLoginId") cPW = Request.QueryString("cPW") 'Response.Write "cDesc1=" & cDesc1 & "<br>" 'Response.Write "PW=" & session("cPW") & "<br>" cMsg = Request.QueryString("cMsg") 'Response.Write "<font color=white>db2=" & session("SqlServer") & "</font><br>" session("cLoginId") = Request.QueryString("cLoginId") if cDesc1 <> "" then session("cLoginId") = Request.QueryString("cLoginId") cEmail= "cLoginId"&"Email"&"cPW" end if colorh3 = 1 %> <% sub ChkUsrDetails(NewsRs) set rsUser = Server.CreateObject("ADODB.Recordset") UserSQL="SELECT * FROM Login where loginid='"&trim(NewsRs("UsrName"))&"'" 'Response.Write "UserSQL=" & UserSQL rsUser.Open UserSQL,ObjConn,3 if not rsUser.EOF then cFName = rsUser("FName") cLName = rsUser("LName") cUnit = rsUser("Unit") end if end sub %> A: This is a really bad idea, since you'd be passing login information via a query string which would be visible to anyone. Rather move those variables to constants / pre-set variables which can't be tampered with by the user. As for the user's session when they've logged in, set it in your code once and then just check if it's blank on any pages that need to use it. You could redirect the user back to the login page if it's blank. E.g. on page_requires_session.asp: <% If Session("UserID") = "" Then Redirect("login.asp?expired=1") End If %> <!-- Rest of page --> Then on login.asp: <% If Request.QueryString("expired") = "1" Then Response.Write "Your session has expired; please log in again" End If If Request.Form("submit") = "Login" Then ' check in database if user info. matches valid username and password ' Else ' display error message End If %> <!-- HTML form would be here -->
{ "language": "en", "url": "https://stackoverflow.com/questions/7567735", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: dequeueReusableCellWithIdentifier: always returns 'nil' for visible cells I create a custom table view cell. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ UITextField *editField=nil; ... NSString *CellIdentifier = [NSString stringWithFormat:@"cell:%d",indexPath.row]; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease]; // Configure the cell... switch (indexPath.row) { case 0: { cell.textLabel.text=DEVNAME_TEXT_NDVC; cell.textLabel.font=[UIFont boldSystemFontOfSize:LABEL_TEXTSIZE_NDVC]; editField=[[UITextField alloc] initWithFrame:CGRectMake(158, 9, cell.frame.size.width-183, cell.frame.size.height-15) ]; editField.tag=DEVNAME_TAG_NDVC; ... [cell.contentView addSubview:editField ]; [editField release]; } break; The table has 5 lines only, and each of them is on the screen always. Later, when I try to get access to the cell I always get 'nil' The following code should place cursor to apropriate UITextField when user tap the cell, but it doesn't, since 'cell' is always =0. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { NSString *CellIdentifier = [NSString stringWithFormat:@"cell:%d",indexPath.row]; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; UITextField *tf=nil; [tableView deselectRowAtIndexPath: indexPath animated: YES]; [activeField resignFirstResponder]; // Last used UITextField switch (indexPath.row) { case 0: // tf=(UITextField*)[cell.contentView viewWithTag:DEVNAME_TAG_NDVC]; [tf becomeFirstResponder]; // Show the keyboard //[tf performSelector:@selector(becomeFirstResponder) withObject:nil afterDelay:0.7]; break; Please, could you suggest what is wrong? Why [tableView dequeueReusableCellWithIdentifier:CellIdentifier] always =0, but all of the table cells are always visible. Thanks. A: Maybe I don't understand the question, but don't table cells only become reusable once they are no longer being displayed? If they are still visible, how could you reuse them? A: Change this: NSString *CellIdentifier = [NSString stringWithFormat:@"cell:%d",indexPath.row]; to: static NSString *CellIdentifier = @“XXXX”; A: Yes, dequeueReusableCellWithIdentifier: always return nil EXCEPT using registerNib:forCellReuseIdentifier:.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567737", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: issue with java and environment variables on windows I've got a curious problem. After installing java jdk 6u25 I tested the installation by typing java in the command prompt. Everything worked fine , the console displayed the usage options as expected. This was about 3 weeks ago - I recently reinstalled windows 7 on my machine- Now I would like to get started with the play framework and followed a tutorial. I got a new application with play new but couldn't use play run because of this: play! 1.2.3, http://www.playframework.org Ctrl+C to stop Could not execute the java executable, please make sure the JAVA_HOME environment variable is set properly . The funny thing is that typing java in the console still displays usage options and neither eclipse or netbeans complained about a missing jdk. Nevertheless I checked my environment variables and was surprised to find: No reference to java at all. Seriously I got no idea how the console, eclipse and netbeans found my java. As a first countermeasure I once again reinstalled java hoping that the installer might set the path correctly. It didn't. Now I would like your advise: Should I just create the JAVA_HOME variable ? If I do, will further versions of the jdk override the variable to point to the new version or will I have to change the variable manually everytime? What about eclipse and netbeans. I would guess that they have been downloaded with their "own" jdk. If I want to update java on my machine, will it update their versions, too ? Update: I set the environment variable manually and restarted the pc. Now everything works fine but I would like to know what symbolic link is. Could you just give me a link in a comment or explain briefly ? A: Eclipse and netbeans use a different way of finding your java installation than command line tools likes play, ant, maven, gradle etc. IDEs may search your registry, guess default locations, or even have the JRE prepackaged with the installation. Command-line tools usually rely on JAVA_HOME variable. And you have to set that manually. A: Should I just create the JAVA_HOME variable ? There are several tools that use that environment variable, so I'd recommend creating it. If I do, will further versions of the jdk override the variable to point to the new version or will I have to change the variable manually everytime? If you install your new Java version into the same folder (or if you create symbolic links), then no. What about eclipse and netbeans. I would guess that they have been downloaded with their "own" jdk. If I want to update java on my machine, will it update their versions, too ? That depends on whether the JDK is prebundled and how the configuration is done. I can't speak for Netbeans but in Eclipse, you could add this to your eclipse.ini: -vm C:/Java/jre/bin Note that this is an example path to the bin folder. If you don't add versions there or use symbolic links (see above) then you'd not have to update the path when installing a new version. A: It is possible that you have a (older?) java.exe in C:\windows or other common directory. Make sure that the java you get on the command line is the one you think it is: java -version
{ "language": "en", "url": "https://stackoverflow.com/questions/7567738", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Unicode strings with NHibernate and Oracle I am using the config below for NHibernate to connect to Oracle. In one of the classes, I am storing a unicode string such as 日本語 (日本). The data field for the column is NVARCHAR2() however, when retrieving the data, the value is corrupt showing ??? (??). Somewhere along the line I'm losing my encoding, but am a loss as to where. Any ideas? <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2"> <session-factory> <property name="connection.driver_class">NHibernate.Driver.OracleDataClientDriver</property> <property name="connection.connection_string_name">Oracle</property> <property name="show_sql">true</property> <property name="dialect">NHibernate.Dialect.Oracle10gDialect</property> <property name="query.substitutions">true 1, false 0, yes 'Y', no 'N'</property> <property name="cache.use_second_level_cache">true</property> <property name="adonet.batch_size">30</property> <property name="cache.provider_class">NHibernate.Caches.SysCache.SysCacheProvider, NHibernate.Caches.SysCache</property> <property name="proxyfactory.factory_class">NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu</property> </session-factory> A: NHibernate dose not use NVarChar2. If you want NHibernate to use NVarchar2 than you have to write your own database dialect. A: No need to write a custom dialect, a user type is enough. See my answer to this question: https://stackoverflow.com/a/61792204/5168579
{ "language": "en", "url": "https://stackoverflow.com/questions/7567740", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Show currency in gridview in European Format My gridview in asp.net has a column that shows currency in Euro format which is 89.483,00 I am aware how to format the strings but not sure how to get the currency data in row databound event and modify the same and send back to the gridview. String format that goes for Euro format is as; String.Format("{0:0.0,0}", temp1) // here temp1 would hold the non-Euro format currency data A: Are you aware that you can set the culture for the site e.g. in web.config and not have to worry about doing this for every single string? http://msdn.microsoft.com/en-us/library/bz9tc508.aspx A: I am not sure if this would work for you. You can create your specific number format which would be used for display like decimal currval = 89483.00M; NumberFormatInfo ninfo = CultureInfo.CreateSpecificCulture("en-GB").NumberFormat; // change as you require ninfo.CurrencyDecimalSeparator=","; ninfo.CurrencyGroupSeparator="."; //you can also set the currency symbol string curr = currval.ToString("C", ninfo); This should get you the currency along with the number
{ "language": "en", "url": "https://stackoverflow.com/questions/7567745", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Run a VBA Macro against an Excel sheet with C# Is it possible to write a WPF C# application that can load and read a VBA Macro from a separate text file, open an existing Excel workbook, and process the VBA macro against it? I am NOT trying to convert VBA to C# or generate VBA from C#. The application, VBA Macro text file (the VBA is extracted and saved separately on a text file), and Excel are all written / generated separately by different people. The application load and read a text file that contains VBA, and open an existing excel file and run the Macro against it either by injecting the macro to excel or even better, leave the workbook without a macro in it. I have no idea how or where to start, or if that is even possible. The closet I found on SO is Injecting vba macro code into excel using .net but doesn't seem to help. I'm looking for any suggestion to get me start and I'll share and update my progress here. A: Here is the way to add some VBA from file in VBA (shouldn't be so hard to adapt it to C# but I am not familiar enough to C# syntax): Function Insert_VBACode(ByRef oWB As Workbook) Dim oVBP As VBProject ' VB Project Object Dim oVBC As VBComponent ' VB Component Object On Error GoTo Err_VBP Set oVBP = oWB.VBProject Set oVBC = oVBP.VBComponents.Add(vbext_ct_StdModule) oVBC.CodeModule.AddFromFile "c:\VBADUD\Templates\MSample.bas" oWB.Application.Run "'" & oWB.name & "'!SayHello" oWB.Save End Function [Source] (have a look there if you want to add any error handling I've removed here for more readability). You can also open the workbook instead of taking it as an argument of the function. And then, you can call your imported macro from C# thanks to this walkthrough from MSDN.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567751", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Creatinge a very, very, large Map in Java Using Java I would like to create a Map that can grow and grow and potentially be larger than the size of the memory available. Now obviously using a standard POJO HashMap we're going to run out of memory and the JVM will crash. So I was thinking along the lines of a Map that if it becomes aware of memory running low, it can write the current contents to disk. Has anyone implemented anything like this or knows of any existing solutions out there? What I'm trying to do is read a very large ASCII file (say 50Gb) a line at a time. Each line contains a key and a value. Keys can be duplicated in the file. I'll then store each line in a Map, which is Keys to a List of values. This Map is the object that will just grow and grow. Any advice greatly appreciated. Phil Update: Thanks for all the comments and advice everyone. With the problem that I described, a Database is the correct, scalable, solution. I should have stated that this is a temporary Map that needs to be created and used for a short period of time to aid in the parsing of a file. In this case, Michael's suggestion to "store only the line number instead of the actual value " is the most appropriate. Marking Michael's answer(s) as the recommended solution. A: A NoSQL database will be probably easy to setup and it is more akin a map. Check BerkeleyDB Java edition, now from Oracle. It has a map like interface, can be embeddable so no complex setup is needed A: Sounds like dumping your huge file into DB. Well, I had a same situation like this. But, In my case everything was in TXT file format and the throughout the file has the same formatted lines. So, what I did is I just splitted the files into several pieces (possibly, which my JVM can able to process maximum size). Then I called files one by one, to get processed. Another way, you can directly load your data into database directly. A: Seriously, choose a simple database as advised. It's not overhead — you don't have to use JPA or whatnot, just plain JDBC with native SQL. Derby or HSQL, for example, can run in embedded mode, no need to define users, access rights, start the server separately. The "overhead" will stab you in the back when you've plodden far into the hash map solution and it turns out that you need yet another optimization to avoid the OutOfMemoryException, or the file is not 50 GB, but 75... Really, don't go there. A: I think you are looking for a database. A: If you're just wanting to build up the map for data processing (rather than random access in response to requests), then MapReduce may be what you want, with no need to work with a database. Edit: Note that although many MapReduce introductions focus on the ability to run many nodes, you should still get benefit from sidestepping the requirement to hold all the data in memory on one machine. A: How much memory do you have? Unless you have enough memory to keep most of the data in memory its going to be so slow, it may as well have failed. A program which is heavily paging can be 1000x slower or more. Some PC have 16-24 GB and you might consider getting more memory. Lets assume there is enough duplicates, you can keep most of the data in memory. I suggest you use a byte based String class of your own making, since you have ASCII data and your store your values as another of these "String" types (with a separator) You may find you can keep the working data set in memory. A: I use BerkleyDB for this, though it is more complicated than a Map (though they have a Map wrapper which I don't really recommend for anything but simple applications) http://www.oracle.com/technetwork/database/berkeleydb/overview/index.html It is also available in Maven http://www.oracle.com/technetwork/database/berkeleydb/downloads/maven-087630.html <dependencies> <dependency> <groupId>com.sleepycat</groupId> <artifactId>je</artifactId> <version>3.3.75</version> </dependency> </dependencies> <repositories> <repository> <id>oracleReleases</id> <name>Oracle Released Java Packages</name> <url>http://download.oracle.com/maven</url> <layout>default</layout> </repository> </repositories> It also has one other disadvantage of vendor lock-in (i.e. you are forced to use this tool. though there may be other Map wrappers to some other databases) So just choose according to your needs. A: Most cache-APIs work like maps and support overflow to disk. Ehcache for example supports that. Or follow this tutorial for guave.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567754", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Zend : Setting paths While building a project and linking the pages together within that project, It has come to my attention that to link things together, I have to set the path as follows : /projectname/public/controllername Now when I move this from my local machine across to a live site, I ideally dont need or want the /projectname/public paths to display. Or have to go through and clear them from the application. This is going to be quite an issue, particularly with forms where the action is set to "/projectname/public/controller/action" Does anyone know what is best to replace the first parts of my links with? Or am I looking at .htaccess to cover this Thanks in advance. A: You should be using the Url and BaseUrl helpers for all internal controller URLS and static asset (images, JS, etc) URLs respectively. For example <!-- Link to controller "Foo", action "bar" --> <a href="<?php echo $this->url(array( 'controller' => 'foo', 'action' => 'bar', 'param' => 'value')) ?>">Go to FooController::barAction()</a> <img src="<?php echo $this->baseUrl('images/baz.png') ?>"> Example layout file entry using the headLink helper... <?php echo $this->headLink($this->baseUrl('css/stylesheet.css')) ?> Using these helpers makes your application portable.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567760", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Symfony sfDoctrineGuard insert-sql error 1005 I've fresh isntall of Symfony 1.4 with Doctrine ORM. I'm looking to install the plugin sfDoctrineGuard. I followed the instructions here: http://www.symfony-project.org/plugins/sfDoctrineGuardPlugin all works fine until this step: symfony doctrine:insert-sql when I get an error: SQLSTATE[HY000]: General error: 1005 Can't create table 'kickboxing.#sql-2b5b_a8f' (error 150) Failing Query "ALTER TABLE profile ADD CONSTRAINT profile_sf_guard_user_id_sf_guard_user_id FOREIGN KEY (sf_guard_user_id) REFERENCES sf_guard_user(id) It did seem to create some tables: profile sf_guard_forgot_password sf_guard_group sf_guard_group_permission sf_guard_permission sf_guard_remember_key sf_guard_user sf_guard_user_group sf_guard_user_permission any ideas? UPDATE: I'm after spotting this really has nothign to do with doctrine/symfony. The issue seems to be with mysql I ran the alter command above in MySQL and of course I get same error. For reference on that I've Debian Squeeze installed and mysql 5. UPDATE2 : when i run SHOW INNODB STATUS; I get LATEST FOREIGN KEY ERROR 110927 7:58:35 Error in foreign key constraint of table _kickboxing/#sql-2b5b_a86: FOREIGN KEY (sf_guard_user_id) REFERENCES sf_guard_user(id): Cannot find an index in the referenced table where the referenced columns appear as the first columns, or column types in the table and the referenced table do not match for constraint. Note that the internal storage type of ENUM and SET changed in tables created with >= InnoDB-4.1.12, and such columns in old tables cannot be referenced by such columns in new tables. See http://dev.mysql.com/doc/refman/5.1/en/innodb-foreign-key-constraints.html for correct foreign key definition. A: Looks like a mySql issue. You can get a full (better) description of the error by logging into the mysql console and running show innodb status then look for the LATEST FOREIGN KEY ERROR to get an idea of what went wrong A: I am using Symfony 1.4.16 and to configure sfDoctrineGuardPlugin, I followed prettyscripts.com but the schema.yml should be as follows; Note: user_id is integer(8) thats what the size of sf_guard's id column type is. sfGuardUserProfile: tableName: sf_guard_user_profile actAs: { Timestampable: ~ } options: { collate: utf8_unicode_ci, charset: utf8 } columns: id: { type: integer(8), primary: true, autoincrement: true } user_id: { type: integer(8), notnull: true } fullname: { type: string(80) } email: { type: string(100) } relations: User: class: sfGuardUser foreign: id local: user_id type: one onDelete: cascade foreignType: one foreignAlias: Profile
{ "language": "en", "url": "https://stackoverflow.com/questions/7567764", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: NoSuchMethodError: String.isEmpty Possible Duplicate: Scala on Android: java.lang.NoSuchMethodError: java.lang.String.isEmpty I've just released a new app on Android I've optimized and obfuscated the code with proguard and tested extensively on my Android 2.3.3 phone. It works all right. However, I keep getting really strange crash reports in the developer console, such as java.lang.NoSuchMethodError: java.lang.String.isEmpty Isn't String.isEmpty() a framework function on all Android devices? A: There is TextUtils.isEmpty("your_String");, but haven't seen about your_string.isEmpty() I found that your_string.isEmpty() works after 2.2 as it was added in 2.3 GingerBread. But, before that you can use TextUtils.isEmpty()
{ "language": "en", "url": "https://stackoverflow.com/questions/7567765", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: Delete OneToOne relationship We have the following mapping: @Entity public class A { private B b; @OneToOne public B getB() { return b; } } When we delete an object of class A it must not delete the referenced object B. At the moment we get an exception when we try to delete A because of the existing relationship to B. How is the correct mapping? A: You should disable cascade delete @OneToOne(cascade = {}) or you can try @OneToOne(orphanRemoval=false)
{ "language": "en", "url": "https://stackoverflow.com/questions/7567773", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Saving multiple file types into one potobuf-net'ized file in VB.net I'm writing a program that saves 'map' files to the HD so that I can open them later and display the same data. My maps originally saved only one data type, a set of my own custom objects with the properties: id, layer, x, and y. You can see the code I did for that, here: <ProtoContract()> _ Public Class StrippedElement <ProtoMember(1)> _ Public Property X() As Integer Get Return m_X End Get Set(ByVal value As Integer) m_X = value End Set End Property Private m_X As Integer <ProtoMember(2)> _ Public Property Y() As Integer Get Return m_Y End Get Set(ByVal value As Integer) m_Y = value End Set End Property Private m_Y As Integer <ProtoMember(3)> _ Public Property Id() As Long Get Return m_Id End Get Set(ByVal value As Long) m_Id = value End Set End Property Private m_Id As Long <ProtoMember(4)> _ Public Property Layer() As String Get Return m_Layer End Get Set(ByVal value As String) m_Layer = value End Set End Property Private m_Layer As String End Class Basically, I'm just serializing tons and tons of these classes into one file. Now I've come to find out that I have to save new parts of the map that aren't necessarily the same class type. Is it possible to save multiple types to the same file and still read from it just as simply? Here is my code to write and read to/from the file: Public Shared Sub Save(ByVal File As String, ByVal Map As RedSimEngine.Map) Dim nPBL As New List(Of StrippedElement) For z As Integer = 0 To Grid.LAYERLIMIT For x As Integer = 0 To Grid.GRIDLIMIT For y As Integer = 0 To Grid.GRIDLIMIT Dim currentCell As GridElement = Map.Level.getCell(z, x, y) If currentCell IsNot Nothing Then If currentCell.Archivable Then Dim nStEl As New StrippedElement nStEl.Id = currentCell.getId() nStEl.Layer = currentCell.getLayer() nStEl.X = currentCell.X nStEl.Y = currentCell.Y nPBL.Add(nStEl) End If End If Next Next Next Serializer.Serialize(New FileStream(File, FileMode.Create), nPBL) End Sub Public Shared Function Load(ByVal File As String) As RedSimEngine.Map Dim nMap As New Map Dim nListOfSE As List(Of StrippedElement) = Serializer.Deserialize(Of List(Of StrippedElement))(New FileStream(File, FileMode.Open)) For Each elm As StrippedElement In nListOfSE Dim nElm As GridElement = GridElement.createElementByIdAndLayer(elm.Layer, elm.Id) nElm.X = elm.X nElm.Y = elm.Y nMap.Level.setCell(nElm) Next Return nMap End Function I have to add 3 or more class types to the save file, I'd rather not have it split up because then it would get confusing for my clients. Basically, I have to add things similar to the following: * *A class with X, Y, and Value *A class with Name and Value *A class with Name, ENUMVALUE, X, Y, INTEGERVALUE, and a couple other things (This one will have to contain quite a bit of data). I'm using VB.net so all .net answers are acceptable. Thanks! If you need any clarification, just say so in the comments. A: You have 3 options here: The first option is to write a wrapper class with 3 containers: [ProtoContract] public class MyData { [ProtoMember(1)] public List<Foo> SomeName {get;set;} // x,y,value [ProtoMember(2)] public List<Bar> AnotherName {get;set;} // name,value [ProtoMember(3)] public List<Blap> ThirdName {get;set;} // etc } and serialize an instance of that; note, however, that the order will be lost here - i.e. after deserializing there is no difference between Foo0, Bar0, Foo1 and Foo0, Foo1, Bar0 - either will result in SomeName with Foo0 and Foo1, and AnotherName with Bar0. This option is compatible with your existing data, as internally there is no difference between serializing "a list of Foo" vs "a wrapper class with a list of Foo as field 1". The second option is to mimic the above, but with a manual type-check during deserialization -this involves using the non-generic API and providing a delegate that maps field numbers (1,2,3) to types (Foo,Bar,Blap). This is useful for very large streams, or selectively plucking objects from the stream, as it allows you to process individual objects (or ignore them) individually. With this approach you can also build the file cumulatively rather than building an entire list. The example is a bit more complex, though, so I'd rather not add one unless it is of interest. This approach is compatible with your existing data. The third approach is inheritance, i.e. [ProtoContract, ProtoInclude(1, typeof(Foo))] [ProtoInclude(2, typeof(Bar)), ProtoInclude(3, typeof(Blap))] public class SomeBaseType {} [ProtoContract] public class Foo : SomeBaseType { /* properties etc*/ } [ProtoContract] public class Bar: SomeBaseType { /* properties etc*/ } [ProtoContract] public class Blap: SomeBaseType { /* properties etc*/ } then serialize a List<SomeBaseType> which happens to contain instances that are Foo / Bar / Blap. This is simple and convenient, and preserves order nicely; but it is not quite compatible with data serialized simply as a List<Foo> - if existing serialized data is an issue you will need to migrate between the formats. A: i find "Serializer.Serialize" very unclean in this kind of cases, so here is how i would proceed : i would write variables manually one at time! for example, here is how i would write and read a StrippedElement : Sub WriteStrippedElement(ByVal Stream As IO.Stream, ByVal SE As StrippedElement) Stream.Write(BitConverter.GetBytes(SE.X), 0, 4) 'Write X:integer (4 bytes) Stream.Write(BitConverter.GetBytes(SE.Y), 0, 4) 'Write Y:integer (4 bytes) Stream.Write(BitConverter.GetBytes(SE.Id), 0, 8) 'Write Id:Long (8 bytes) Dim LayerBuffer() As Byte = System.Text.Encoding.Default.GetBytes(SE.Layer) 'Converting String To Bytes Stream.Write(BitConverter.GetBytes(LayerBuffer.Length), 0, 4) 'Write The length of layer, since it can't have a fixed size:integer (4 bytes) Stream.Write(LayerBuffer, 0, LayerBuffer.Length) 'Write The Layer Data Stream.Flush() 'We're Done :) End Sub Sub ReadStrippedElement(ByVal Stream As IO.Stream, ByRef SE As StrippedElement) Dim BinRead As New IO.BinaryReader(Stream) 'Making reading Easier, We can also use a BinaryWriter in the WriteStrippedElement For example SE.X = BinRead.ReadInt32 'Read 4 Bytes SE.Y = BinRead.ReadInt32 'Read 4 Bytes SE.Id = BinRead.ReadInt64 'Read 8 Bytes Dim Length As Integer = BinRead.ReadInt32 'Read 4 Bytes, the length of Layer Dim LayerBuffer() As Byte = BinRead.ReadBytes(Length) 'Read Layer Bytes SE.Layer = System.Text.Encoding.Default.GetString(LayerBuffer) 'Convert Back To String, and done. End Sub So if you like to write alot of those StrippedElement, just write down the number of elements (int32, 4bytes) to know how much to read from the file next time.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567778", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }