text
stringlengths
8
267k
meta
dict
Q: Why does Aquatic Prime fail to validate file on second attempt? I have the Objective-C version of Aquatic Prime working in my app. When I swap out the Objective-C class for the CoreFoundation functions, I can validate the license file once, but subsequent validation attempts in other parts of my code (using the same block of code) fails. Why? APSetKey(key); NSString *appSupportFolder = [(MyApp_AppDelegate *)[[NSApplication sharedApplication] delegate] applicationSupportFolder]; NSString *licFile = [appSupportFolder stringByAppendingPathComponent:@"license.myapp-license"]; CFURLRef licURL = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, (CFStringRef)licFile, kCFURLPOSIXPathStyle, false); CFDictionaryRef licenseDictionary = APCreateDictionaryForLicenseFile(licURL); if (licenseDictionary) { // do something CFRelease(licenseDictionary); } CFRelease(key); CFRelease(licURL); I'm using XCode 4.1 on Lion but compiling against 10.6 64 bit.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551018", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Corona SDK Memory Leak I'm writing a game using Corona for a game design class and though I'm still learning, I've got most of the basics down. Right now, I have a situation where the program slows down after about two minutes or so of playing, and I'm not entirely sure why. I've already implemented code to remove all bodies which have served their purpose and I even have it set up to print a notification when each one is removed. http://www.mediafire.com/?5fz7ru0c6euwq1k This is the download link. Any help is greatly appreciated. Thanks! A: First off, have you checked the memory usage? If the problem gradually slows down that certainly sounds like a memory leak, but you need to check the memory usage to be sure. Print out memory usage to the console like so: print("mem "..collectgarbage("count")) Put that in an enterFrame listener so that you can watch the memory usage continuously while your app is running. Now once you are seeing the memory consumed by your app, the most crucial step in any sort of debugging is isolating the problem. That is, zero in on the spot in the code that causes the problem. For some problems you can rely on techniques like printing debug messages to the console, but for a memory leak your best bet is often to selectively comment out sections of the code to see what affect that has on memory. For example, first comment out the event listeners on one screen and then check the memory usage. If the leak is gone, then you know the problem was something to do with those event listeners. If the leak is unaffected, then restore those event listeners and comment out the next possible cause of a memory leak. rinse and repeat Once you know the exact section of code that is causing the leak, you will probably be able to see what you need to fix. If not, ask about that specific code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551020", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: app crashes right after splash screen in xcode 4 / ios 5 beta i am having problems with the new xcode 4.2 and beta ios 5. My app compiles and works in Debug mode both on the simulator and a device. When i build an adhoc build, archive it and install it on the device - the app crashes right after the splash screen giving me the following stack (which may be different at times, but always deriving right from main.m): Thread 0 name: Dispatch queue: com.apple.main-thread Thread 0 Crashed: 0 libsystem_kernel.dylib 0x33b8932c __pthread_kill + 8 1 libsystem_c.dylib 0x33a17f58 pthread_kill + 48 2 libsystem_c.dylib 0x33a10fe8 abort + 88 3 libc++abi.dylib 0x34d0df64 abort_message + 40 4 libc++abi.dylib 0x34d0b346 _ZL17default_terminatev + 18 5 libobjc.A.dylib 0x378452dc _objc_terminate + 140 6 libc++abi.dylib 0x34d0b3be _ZL19safe_handler_callerPFvvE + 70 7 libc++abi.dylib 0x34d0b44a std::terminate() + 14 8 libc++abi.dylib 0x34d0c81e __cxa_rethrow + 82 9 libobjc.A.dylib 0x3784522e objc_exception_rethrow + 6 10 CoreFoundation 0x31538546 CFRunLoopRunSpecific + 398 11 CoreFoundation 0x315383a6 CFRunLoopRunInMode + 98 12 UIKit 0x3462ead8 -[UIApplication _run] + 544 13 UIKit 0x3462bdc0 UIApplicationMain + 1084 14 tflow3 0x001122fe main (main.m:14) 15 tflow3 0x0005ed94 0x5d000 + 7572 Since the app works when debugged on the device i guess (and hope) my adhoc release configuaration has something going wrong. I'd appreciate any help.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551022", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Use uint or int Definitely, I know the basic differences between unsigned integers (uint) and signed integers (int). I noticed that in .NET public classes, a property called Length is always using signed integers. Maybe this is because unsigned integers are not CLS compliant. However, for example, in my static function: public static double GetDistributionDispersion(int tokens, int[] positions) The parameter tokens and all elements in positions cannot be negative. If it's negative, the final result is useless. So if I use int both for tokens and positions, I have to check the values every time this function is called (and return non-sense values or throw exceptions if negative values found???), which is tedious. OK, then we should use uint for both parameters. This really makes sense to me. I found, however, as in a lot of public APIs, they are almost always using int. Does that mean inside their implementation, they always check the negativeness of each value (if it is supposed to be non-negative)? So, in a word, what should I do? I could provide two cases: * *This function will only be called by myself in my own solution; *This function will be used as a library by others in other team. Should we use different schemes for these two cases? Peter P.S.: I did do a lot of research, and there is still no reason to convince me not to use uint :-) A: I see three options. Use uint. The framework doesn't because it's not CLS compliant. But do you have to be CLS compliant? (There are also some not-fun issues with arithmetic that crop up; it's not fun to cast all over the place. I tend to void uint for this reason). Use int but use contracts: Contract.Requires(tokens >= 0); Contract.Requires(Contract.ForAll(positions, position => position >= 0)); Make it explicit it exactly what you require. Create a custom type that encapsulates the requirement: struct Foo { public readonly int foo; public Foo(int foo) { Contract.Requires(foo >= 0); this.foo = foo; } public static implicit operator int(Foo foo) { return this.foo; } public static explicit operator Foo(int foo) { return new Foo(foo); } } Then: public static double GetDistributionDispersion(Foo tokens, Foo[] positions) { } Ah, nice. We don't have to worry about it in our method. If we're getting a Foo, it's valid. You have a reason for requiring non-negativity in your domain. It's modeling some concept. Might as well promote that concept to a bonafide object in your domain model and encapsulate all the concepts that come with it. A: I use uint. Yes, other answers are all correct... But I prefer then uint for one reason: Make interface more clear. If a parameter (or a returned value) is unsigned, it is because it cannot be negative (has you seen a negative collection count?). Otherwise, I need to check parameters, document parameters (and returned value) that cannot be negative; then I need to write additional unit tests for checking parameters and returned values (wow, and someone would complain for doing casts? Are int casts so frequent? No, by my experience). Additionally, users are required to test returned values negativity, which may be worse. I don't mind about CLS compliace, so why I should be? From my point of view, the question should be reversed: why should I use ints when value cannot be negative? For the point of returning negative value for additional information (errors, for example...): I don't like so C-ish design. I think there may be a more modern design to accomplish this (i.e. use of Exceptions, or alterntively use of out values and boolean returned values). A: Yes go for int. I once tried to go uint myself only to refactor everything again as soon as I had my share of annoying casts in my lib. I guess the decision to go for int is for historical reasons where often a result of -1 indicates some sort of error (for example in IndexOf). A: int. it gives more flexibility when you need to do a API change in the near future. such as negative indexes are often used by python to indicate reversed counting from the end of string. values also turns negative when overflows, assertion will catch it. its a trade off for speed vs robustness. A: As you read it violates the Common Language Specification rules, but then how often will the function be used and in case it going to be clubbed up with other method its normal for them to expect int as parameter which would get you into the trouble of casting the values. If you are going to make it available as a library then its better sticking to the conventional int else you need to implicitly take care of conditions wherein you might not get a positive value which would mean littering the checks across the pages. Interesting Read - SO link
{ "language": "en", "url": "https://stackoverflow.com/questions/7551025", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: trigger Android application from Web Application Hello all my problem is : We have to create a system in which we need to create both web(ASP.NET C#) and android application and we have to synchronize data on both interface. So is there any method/Way to trigger Android application from Web Application(ASP.NET C#). A: where you want to trigger? For synchronization of data, you need to create a WebService interface through which you can send/receive data whenever you want from/to mobile.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551026", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Windows explorer get list of selected items and pass it to another process I have to create File/Folder management system. In which user can select multiple files/folder and from context menu execute an command. That command sends list of all selected files/folders list to invoke a process. So that, process can work on file/folder list. If process is running the context menu should not shown or greyed out. I added context menu but can't find the way to disable it. How can I do all this? Any possible study link will help a lot? A: Your IContextMenu::QueryContextMenu handler can apply whatever logic you desire to determine whether to show/hide a menu item, and if shown, whether it is enabled or disabled. Note, however, that in general, shell extensions should not be written in managed code due to CLR injection concerns.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551028", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: why can't install the xdebug? my op system is XP. the PHP Version 5.3.6. the php path is D:/php i downloaded the PHP 5.3 VC6 (32 bit) version from the http://www.xdebug.org/download.php i added the following code to the php.ini: [Xdebug] zend_extension="D:/php/ext/php_xdebug.dll" xdebug.collect_params=On xdebug.collect_return=On xdebug.trace_output_dir="d:\xdebug" xdebug.profiler_enable=On xdebug.profiler_output_dir="d:\xdebug" then restarted the apache, using phpinfo(). it doesn't output the xdebug. what's wrong with my setting? thank you. A: Download http://xdebug.org/files/php_xdebug-2.1.2-5.3-vc6-nts.dll rename it php_xdebug.dll Put it in D:/php/ext/ Restart apache
{ "language": "en", "url": "https://stackoverflow.com/questions/7551029", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: endcoding error my code has a trouble with encoding error: File "test.py", line 1 SyntaxError: encoding problem: with BOM I attached the code below. is there any clear idea to fix it? the input and the output file contain Korean words, numbers, and english charaters. I try to run this code in Mac and windows, it doesn't work at both of OS. please help me out! # coding: uft-8 from __future__ import print_function from __future__ import unicode_literals import os, sys import codecs import re import subprocess, shlex REGEXP = re.compile(r'(\w+)/(\(.*?\))') def main(): words = {} with codecs.open('E:\\mach.txt', 'r', encoding='cp949') as fp: for line in fp: for item, category in REGEXP.findall(line): words.setdefault(category, {}).setdefault(item, 0) words[category][item] += 1 with codecs.open('result.txt', 'w', encoding='cp949') as fp: for category, words in sorted(words.items()): print(category, file=fp) for word, count in words.items(): print(word, count, sep=' ', file=fp) print(file=fp) return 0 if __name__ == '__main__': raise SystemExit(main()) A: You've misspelled UTF-8 on the first line. Since you've only used ASCII characters in you're code, it isn't even required to have a coding line. A: The problem is not with the code, but with the encoding of the script itself. Try saving it with a different editor. Notepad on Windows works for me.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551032", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Set ASP.NET version to 3.5 in the IIS 6 Default Web site properties (ASP.NET tab) How to set ASP.NET version to 3.5 in the IIS 6 Default Web site properties (ASP.NET tab)? From what I can see was version 2 (even though I have install version .NET 3.5) A: There isn't a true "ASP.NET 3.5". "ASP.NET 3.5" is really "ASP.NET 2.0" plus some extra assemblies. A: You cannot specify this in IIS. For websites earlier than Framework 4.0 and greater than 2.0 you need to specify version 2.0 in IIS. However there are configurations in web.config to restrict a website to run or compile under framework version 3.5. Visual Studio by default make these setting in web.config To be sure here are some parts of the web.config
{ "language": "en", "url": "https://stackoverflow.com/questions/7551034", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to get instance of object from XML file? I have XML file of object.I want to get instance of that object.But i dont have class.I must read XML and create dynamically how to say class. How to do? A: See this page, it can help but you need .NET 4. A: I guess you want to read data from an XML into your class. If so, you can use the following way to read the data from a file. var records = from r in XElement.Load(@"YourFile.xml").Elements("NodeName") select r;
{ "language": "en", "url": "https://stackoverflow.com/questions/7551036", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: HashPasswordForStoringInConfigFile - Different Hashes for same password I have recently implemented Hashing for my passwords in a project I am working on, and I cant seem to figure out what is going wrong. It seems that the HashPasswordForStoringInConfigFile() function is returning different values for the same password. I have the following code implemented which actually closely resembles the recommended algorithm to use on the MSDN documentation. I know that SHA1 hashing is not considered very safe, but this is for a research application, and I am not too worried about it at this point. public const int DefaultSaltSize = 5; private static string CreateSalt() { RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); byte[] buffer = new byte[DefaultSaltSize]; rng.GetBytes(buffer); return Convert.ToBase64String(buffer); } public static string CreateHash(string password) { string salt = CreateSalt(); string saltAndPassword = String.Concat(password, salt); string hashedPassword = FormsAuthentication.HashPasswordForStoringInConfigFile(saltAndPassword,"SHA1"); hashedPassword = string.Concat(hashedPassword,salt); return hashedPassword; } public static bool VerifyPassword(string username, string password,AccountDataContext context) { var user = context.UserAccounts.FirstOrDefault(p => p.UserName == username); if (user != null) { string salt = user.Password.Substring(user.Password.Length - DefaultSaltSize); string hashedPassword = CreateHash(password); return hashedPassword.Equals(user.Password); } return false; } Simply put, If I have the following code. string password1 = "password"; string password2 = "password"; var hashedPassword1 = CreateHash(password1); var hashedPassword2 = CreateHash(password2); var match = hashedPassword1.Equals(hashedPassword2); //match should be True, but it is turning out False. It seems that the FormsAuthenticationForStoringInConfigFile() is not returning the same hash for password1 and password2 in the CreateHash() method. I understand with the salt applied they are not the same, but if you see in the code, I am removing the salt before comparing the two hashedPasswords for equality. What could possibly be causing password1 and password2 from being hashed differently? A: Your code has added salt (a random value) to the password before hashing. This is a good thing. It means that if user A and user B use the same password, the password hashes will nevertheless be different. Your VerifyPassword method is not using the original salt to hash the password for comparing - instead it calls CreateHash, which calls CreateSalt and creates new salt. You might try something like: public static string CreateHash(string password) { return CreateHash(password, CreateSalt()); } private static string CreateHash(string password, string salt) { string saltAndPassword = String.Concat(password, salt); string hashedPassword = FormsAuthentication.HashPasswordForStoringInConfigFile( saltAndPassword,"SHA1"); hashedPassword = string.Concat(hashedPassword,salt); return hashedPassword; } public static bool VerifyPassword(string username, string password,AccountDataContext context) { var user = context.UserAccounts.FirstOrDefault(p => p.UserName == username); if (user != null) { string salt = user.Password.Substring(user.Password.Length - DefaultSaltSize); string hashedPassword = CreateHash(password, salt); return hashedPassword.Equals(user.Password); } return false; } A: Even though VerifyPassword looks like it's stripping off the salt portion of the unhashed string, but the code you say should return true doesn't actually call VerifyPassword. Your code simply generates two salted hashes and then uses String.Equals to compare them. What happens when you use VerifyPassword instead of String.Equals? A: This code doesn't work at all either. Why is it marked as being the correct answer? The default length of Salt is set to 5 Create Salt when it takes a 5 byte array to a string it becomes 8 characters not 5 Verify Password then takes only 5 characters off for the salt not 8 so the verify will always fail as it's using 5 characters for the salt and not the 8 that was used to create the hashed password. Below is updated code to make the above code work. private const int DEFAULT_SALT_SIZE = 5; private static string CreateSalt() { RNGCryptoServiceProvider rngCryptoServiceProvider = new RNGCryptoServiceProvider(); byte[] buffer = new byte[DEFAULT_SALT_SIZE]; rngCryptoServiceProvider.GetBytes(buffer); return Convert.ToBase64String(buffer); } public static string CreateHash(string password) { return CreateHash(password, CreateSalt()); } private static string CreateHash(string password, string salt) { string saltAndPassword = String.Concat(password, salt); string hashedPassword = FormsAuthentication.HashPasswordForStoringInConfigFile(saltAndPassword, "SHA1"); hashedPassword = string.Concat(hashedPassword, salt); return hashedPassword; } public static bool VerifyPassword(string userpassword, string password) { byte[] bytePassword = Convert.FromBase64String(userpassword); byte[] byteSalt = new byte[DEFAULT_SALT_SIZE]; Array.Copy(bytePassword, bytePassword.Length - DEFAULT_SALT_SIZE, byteSalt, 0, DEFAULT_SALT_SIZE); string salt = Convert.ToBase64String(byteSalt); string hashedPassword = CreateHash(password, salt); return hashedPassword.Equals(userpassword); } This is how I called it. string hashedPassword = Security.CreateHash("password"); if (Security.VerifyPassword(hashedPassword, "password")) { Response.Write("Valid"); } else { Response.Write("Not Valid"); } As long as the passwords match it returns true otherwise it will return false. This gives you what I think was intended which was not only to include the salt inside of the hash but also add it to the outside of the hash so it all could be stored as 1 column value in a database and then used to recreate the hash on the user entered password using the stored salt value and get a match.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551044", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Different MD5 hashes for .net and java `I want to encode my string using .net and pass it to a java program. I am using the same program for encryption and decryption on both the sides. But the java program and .net programs are returning different MD5 hash codes. Here are the codes for both my programs : VB.net md5Provider = New MD5CryptoServiceProvider() input = UTF8Encoding.UTF8.GetBytes(sSecurityKey) oHash = oMd5CryptoServiceProvider.ComputeHash(input) Java MessageDigest m; m = MessageDigest.getInstance("MD5"); byte[] UTF8bytes = key.getBytes("UTF8"); m.update(UTF8bytes,0,UTF8bytes.length); Edit: The hash computed using vb.net is {170,226,106,33,183,52,99,154,17,225,135,139,170,141,116,108} The m.digest() i get in java is {-44, 29, -116, -39, -113, 0, -78, 4, -23, -128, 9, -104, -20, -8, 66, 126} The problem is that m.digest() from java and oHash from vb.net are different. So i cant go further with DES encryption. Any help appreciated. A: You may want to compare input from both digest methods byte by byte. That is input from VB.net and UTF8bytes from Java. Most likely they will be different (could be some encoding specifics of VB.net, for example). Also, how do you compare results? A: At last I found the answer. I just converted the Md5 hash into BigInteger and then converted into an byte array. Now when i pass it as a key to the DES algorithm, i get my desired output.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551047", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Does Android have a standard Add/Edit/Delete list convention? Similar question, but this one is about Android. On the iPhone, there is a standard convention for editing lists. There is an Edit button and the + button above the list. You click on the Edit button and the list changes slightly notifying the user of change of status. I have a dozen apps on Android that manage lists in some way and they all seem to do it slightly differently. Does Android have some type of a standard convention for editing lists? Perhaps something that's recommended by the Android team? A: I am sure there is no such standard exist but for that you have create custom title bar with Edit/Post options same as Wordpress for Android application, you can also download this code of wordpress application because its open source application. So if you download this code, then it may be helpful to you to understand the Edit functionality for the listview. Update: In short, i just want to say that you have to define custom and efficient adapter for ListView.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551049", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Vector rotation problem I'm working on a program with IK and have run into what I had at first thought was a trivial problem but have since had trouble solving it. Background: Everything is in 3d space. I'm using 3d Vectors and Quaternions to represent transforms. I have a limb which we will call V1. I want to rotate it onto V2. I was getting the angle between V1 and V2. Then the axis for rotation by V1 cross V2. Then making a Quaternion from the axis and angle. I then take the limbs current Orientation and multiply it by the axis angle quaternion. This I believe is my desired local space for the limb. This limb is attached to a series of other links. To get the world space I traverse up to the root combining the parents local space with the child's local space until I reach the root. This seems to work grand if the vector that I am rotating to is contained within the X and Y plane or if the body which the limb is attached to hasn't been modified. If anything has been modified, for example rotating the root node, then on the first iteration the vector will rotate very close to the desired vector. After that point though it will begin to spin all over the place and never reach the goal. I've gone through all the math line by line and it appears to all be correct. I'm not sure if there is something that I do not know about or am simply over looking. Is my logical sound? Or am I unaware of something? Any help is greatly appreciated! Quaternion::Quaternion(const Vector& axis, const float angle) { float sin_half_angle = sinf( angle / 2 ); v.set_x( axis.get_x() * sin_half_angle ); v.set_y( axis.get_y() * sin_half_angle ); v.set_z( axis.get_z() * sin_half_angle ); w = cosf( angle / 2 ); } Quaternion Quaternion::operator* (const Quaternion& quat) const { Quaternion result; Vector v1( this->v ); Vector v2( quat.v ); float s1 = this->w; float s2 = quat.w; result.w = s1 * s2 - v1.Dot(v2); result.v = v2 * s1 + v1 * s2 + v1.Cross(v2); result.Normalize(); return result; } Vector Quaternion::operator* (const Vector& vec) const { Quaternion quat_vec(vec.get_x(), vec.get_y(), vec.get_z(), 0.0f); Quaternion rotation( *this ); Quaternion rotated_vec = rotation * ( quat_vec * rotation.Conjugate() ); return rotated_vec.v; } Quaternion Quaternion::Conjugate() { Quaternion result( *this ); result.v = result.v * -1.0f; return result; } Transform Transform::operator*(const Transform tran) { return Transform( mOrient * transform.getOrient(), mTrans + ( mOrient * tran.getTrans()); } Transform Joint::GetWorldSpace() { Transform world = local_space; Joint* par = GetParent(); while ( par ) { world = par->GetLocalSpace() * world; par = par->GetParent(); } return world; } void RotLimb() { Vector end_effector_worldspace_pos = end_effector->GetWorldSpace().get_Translation(); Vector parent_worldspace_pos = parent->GetWorldSpace().get_Translation(); Vector parent_To_end_effector = ( end_effector_worldspace_pos - parent_worldspace_pos ).Normalize(); Vector parent_To_goal = ( goal_pos - parent_worldspace_pos ).Normalize(); float dot = parent_To_end_effector.Dot( parent_To_goal ); Vector rot_axis(0.0f,0.0f,1.0f); float angle = 0.0f; if (1.0f - fabs(dot) > EPSILON) { //angle = parent_To_end_effector.Angle( parent_To_goal ); rot_axis = parent_To_end_effector.Cross( parent_To_goal ).Normalize(); parent->RotateJoint( rot_axis, acos(dot) ); } } void Joint::Rotate( const Vector& axis, const float rotation ) { mLocalSpace = mlocalSpace * Quaternion( axis, rotation ); } A: You are correct when you write in a comment that the axis should be computed in the local coordinate frame of the joint: I'm wondering if this issue is occuring because I'm doing the calculations to get the axis and angle in the world space for the joint, but then applying it to the local space. The rotation of the axis from the world frame to the joint frame will look something like this: rot_axis = parent->GetWorldSpace().Inverse().get_Rotation() * rot_axis There can be other issues to debug, but it's the only logical error I can see in the code that you have posted.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551052", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: RoR, page can not be redirected if the action contain thread I am trying to put some log from the sever to the browser. Here was what I had done: * *step1. start the websocket server in the action create. *step2. render the view which contain the websocket client to connect with the server. step1 works but the client can not be opened in the browser, since the thread is blocked, redirect_to can not be executed. this is code for detail. def create #some code ... th = Thread.new{ start_server } format.html { redirect_to(@execution, :notice => 'Execution was successfully created.')} th.join end
{ "language": "en", "url": "https://stackoverflow.com/questions/7551054", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Pass httpcontext to WCF via Castle Windsor We are trying to inject the current http context (so we can get authentication info, e.g the forms authentication etc...)from our asp.net mvc web site into our service constructors. Our services are WCF and we are using Castle Windsor at the client and service layers. Is it possible to do this entirely from configuration? Does any one know the best way to go about this? EDIT: our services layer will run on a different physical tier to the web site A: I think you can use something like HttpContextBase/HttpContextWrapper as dicusssed here : Castle.Windsor and HttpContextWrapper
{ "language": "en", "url": "https://stackoverflow.com/questions/7551055", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP, ping a list of IPs? I have a list of IPs which I want to ping via PHP (to save me the trouble of manually doing it via SSH). I can run exec, escapeshellarg, system etc on my server - how would I create a script to ping an IP once and return the response time? Any help would be greatly appreciated. Thank you :) A: Using shell_exec, like this: $output = shell_exec('ping -n 1 127.0.0.1'); print $output; A: If you want to use the shell ping, use shell_exec for this. However...here you can find an excellent example on how to ping via PHP: http://birk-jensen.dk/2010/09/php-ping/ This script can be easily adapted with php timers to return response times.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551059", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Convert timezone name to city name (remove continent part) I was wondering if anyone could help me figure out to to remove part of a string. I am using the java.util.TimeZone to retrieve time zone "ids" but I want to delete the continent/ prefix, basically stripping out the city name. I also have to replace all underscores with spaces which I have done in code already. I just can not seem to find a way to get rid of the backslash and everything before it. Here is my code. Thanks import java.util.*; import java.util.TimeZone; import java.util.Date; import java.text.DateFormat; public class Maps { public static void main(String[] args) { String[] Zone = TimeZone.getAvailableIDs(); int i = 0; for (i =0 ; i< Zone.length; i++) { String zone1 = Zone[i].replaceAll("_"," "); System.out.println(zone1); } } } A: So you want to remove everything before the first slash, and then replace any underscores in the remainder with spaces? That's fairly easy using indexOf, substring and replace (which you're already aware of). You certainly could do this with regular expressions as suggested by Mr_Spock, but personally for just a couple of operations I'd stick with the normal string methods: int slash = text.indexOf('/'); text = text.substring(slash + 1).replace("_", " "); So for a complete example: import java.util.TimeZone; public class Test { public static void main(String[] args) { String[] ids = TimeZone.getAvailableIDs(); for (String id : ids) { int slash = id.indexOf('/'); String stripped = id.substring(slash + 1).replace("_", " "); System.out.println(stripped); } } } Note that this still leaves you with some interesting names such as "North Dakota/Beulah" as the original ID had two slashes in. Just for completeness, another way of handling the slash is to split the string on slash and then take the second part - but as the above example shows, you then probably want to make sure that it splits into at most two parts, keeping "North Dakota/Beulah" as a single token. You'd also need to be careful in case there were any IDs without any slashes (the above code works fine as indexOf will return -1, so the substring will become a no-op). A: I would try to approach this in an unorthodox fashion for the average Java coder (I assume). I'd try to utilize the power of regular expressions. Try exploring the world of java.util.regex It doesn't hurt to learn about RegEx, as it's used in string manipulation solutions across the board. I hope that helps. A: Check this out : public static void main(String[] args) { String[] Zone = TimeZone.getAvailableIDs(); int i = 0; for (i =0 ; i< Zone.length; i++) { String zone1 = Zone[i].replaceAll("_"," "); if(zone1.indexOf('/') != -1) zone1 = zone1.substring(zone1.indexOf('/')+1); System.out.println(zone1); } } A: You can use just split the zone :- String zone1 = Zone[i]; zone1 = (zone1.split("/").length > 1) ? zone1.split("/")[1] : zone1.split("/")[0]; zone1 = zone1.replaceAll("_"," "); A: if(zone1.indexOf("/")!=-1) { zone1=zone1.substring(zone1.indexOf("/")+1,zone1.length()); System.out.println(zone1); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7551064", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Are there another way for replacing except for Replace() function? In c programming language, I can do printf("%d\n", value); But in c#, how can I do it? For example string is "Good %s everybody" I want to replace %s with the variable. Are there any solution except for str.Replace("%s","good morning"); A: string.Format would be your function of choice. You then could write e.g.: const string t = "Thomas"; var s = string.Format("Good morning {0}.", t); With {0} being replaced with the value of t.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551065", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Listview rows order changes randomly on scroll of listview in android I have one ListView and one BaseAdapter.I am downloading Products from webservice and display on listview.It displays properly on listview. But when I scroll ListView displays rows in random position means sometimes third row display in first position, middle position row display on last position and so on. This is my adapter class public class ProductListAdapter extends BaseAdapter implements OnClickListener{ LayoutInflater inflater; ArrayList<Product> arrProducts; Context c; public ProductListAdapter(Context c, ArrayList<Product> arrProducts) { super(); inflater = LayoutInflater.from(c); this.arrProducts = arrProducts; this.c = c; } @Override public int getCount() { return arrProducts.size(); } @Override public Object getItem(int position) { return arrProducts.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View v, ViewGroup parent) { Product product = null; if(v == null) { v = inflater.inflate(R.layout.product_listview_row, null); product = (Product) getItem(position); v.setTag(product); }else { product = (Product)v.getTag(); } v.setOnClickListener(this); TextView tvProductname = (TextView)v.findViewById(R.id.tvProductname); tvProductname.setText(product.getTitle()); String strReviewCount = product.getReviews(); TextView tvReviewsCounts = (TextView)v.findViewById(R.id.tvReviews); if(strReviewCount != null) tvReviewsCounts.setText(strReviewCount +" Reviews"); Button btnPrice = (Button)v.findViewById(R.id.btnPrice); btnPrice.setText(product.getSellingPrice()); return v; } @Override public void onClick(View v) { Product product = (Product) v.getTag(); Intent i = new Intent(c, ProductDetails.class); i.putExtra(Product.PROD_ID, product.getId()); startActivity(i); } @Override public int getItemViewType(int position) { return super.getItemViewType(position); } @Override public int getViewTypeCount() { return super.getViewTypeCount(); } } This is ListView on XML layout <ListView android:id="@+id/lstProducts" style="@style/fill_parent" android:dividerHeight="1dp" android:divider="#dbd3c5" android:scrollbars="vertical" android:layout_below="@id/layLine"></ListView> Also when I change getView() method of BaseAdapter like this it is working fine @Override public View getView(int position, View v, ViewGroup parent) { Product product = null; v = inflater.inflate(R.layout.product_listview_row, null); product = (Product) getItem(position); v.setTag(product); v.setOnClickListener(this); TextView tvProductname = (TextView)v.findViewById(R.id.tvProductname); tvProductname.setText(product.getTitle()); String strReviewCount = product.getReviews(); TextView tvReviewsCounts = (TextView)v.findViewById(R.id.tvReviews); if(strReviewCount != null) tvReviewsCounts.setText(strReviewCount +" Reviews"); Button btnPrice = (Button)v.findViewById(R.id.btnPrice); btnPrice.setText(product.getSellingPrice()); return v; } But problem in this type is I am displaying image of product on listview row which I had not consider here.By using this type of code getView() method always create new View when ever scroll of listView so that I have to download image again and again.I used ImageLoader class which is using cash memory for download images but problem is that when I set image to ImageView many times it giving me out of memory error. Please help me out from this problem. Thanks A: Therefore, according to the recommendations made by Knickedi, the getView() method should look like: public View getView(int position, View v, ViewGroup parent) { TextView tvProductname; TextView tvReviewsCounts; Button btnPrice; // Phase 1... if (v == null) { v = inflater.inflate(R.layout.product_listview_row, null); v.setOnClickListener(this); tvProductname = (TextView)v.findViewById(R.id.tvProductname); tvReviewsCounts = (TextView)v.findViewById(R.id.tvReviews); btnPrice = (Button)v.findViewById(R.id.btnPrice); v.setTag(R.id.tvProductname, tvProductname); v.setTag(R.id.tvReviews, tvReviewsCounts); v.setTag(R.id.btnPrice, btnPrice); } else { tvProductname = (TextView) v.getTag(R.id.tvProductname); tvReviewsCounts = (TextView) v.getTag(R.id.tvReviews); btnPrice = (Button) v.getTag(R.id.btnPrice); } // Phase 2... Product product = (Product) getItem(position); tvProductname.setText(product.getTitle()); btnPrice.setText(product.getSellingPrice()); String strReviewCount = product.getReviews(); if(strReviewCount != null) tvReviewsCounts.setText(strReviewCount +" Reviews"); return v; } A: I landed here because of a link to the right solution. The problem here is that you bind your product once to the view when you create a new view. You should call this on every call of getView: product = (Product) getItem(position); v.setTag(product); But you could call v.setOnClickListener(this) once you create the view (it won't change anyway). This should do the trick. The view type implementation is just misused here. I recommend to read my answer here...
{ "language": "en", "url": "https://stackoverflow.com/questions/7551068", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Update UI using swingworker thread I want to use the swing worker thread to update my GUI in swing. pls any help is appreciated.I need to update only the status of 1 field using the thread i.e setText(). A: I just answer similar question on another forum for a question about SwingWorker: import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.util.List; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.SwingUtilities; import javax.swing.SwingWorker; import javax.swing.Timer; public class Main extends JFrame { private JLabel label; private Executor executor = Executors.newCachedThreadPool(); private Timer timer; private int delay = 1000; // every 1 second public Main() { super("Number Generator"); setDefaultCloseOperation(EXIT_ON_CLOSE); setSize(300, 65); label = new JLabel("0"); setLayout(new FlowLayout()); getContentPane().add(label, "Center"); prepareStartShedule(); setVisible(true); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new Main(); } }); } private void prepareStartShedule() { timer = new Timer(delay, startCycle()); timer.start(); } private Action startCycle() { return new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { executor.execute(new MyTask()); } }; } private class MyTask extends SwingWorker<Void, Integer> { @Override protected Void doInBackground() throws Exception { doTasksInBackground(); return null; } private void doTasksInBackground() { publish(generateRandomNumber()); } private int generateRandomNumber() { return (int) (Math.random() * 101); } @Override protected void process(List<Integer> chunks) { for(Integer chunk : chunks) label.setText("" + chunk); } } } ps: @trashgod helps me a month ago to understand how to deal with SwingWorker (Can't get ArrayIndexOutOfBoundsException from Future<?> and SwingWorker if thread starts Executor), so thanks to him. EDIT: The code is corrected. Thanks @Hovercraft Full Of Eels
{ "language": "en", "url": "https://stackoverflow.com/questions/7551069", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Master pages with Sharepoint 2010 I am new to sharepoint 2010, any one could share steps/links to create and use master pages in share point 2010. A: You need to enable publishing features on your site to change the master page. After that I recommend using http://startermasterpages.codeplex.com/ to customize your master page. Good luck!
{ "language": "en", "url": "https://stackoverflow.com/questions/7551073", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to find anchor tag in a div and push it to an array using jquery how to find anchor tag in a div and push it to an array using jquery. i tried it but my result shows arry=[jquery(a1,a2,a3,a4,a5)] and if i tried to check the array length it shows only one but not 5. please help. Iam getting the anchor tag by $(el).find('a'); A: There is a toArray method for jQuery objects. These method wil convert the jQuery result to a normal array: $(el).find('a').toArray();
{ "language": "en", "url": "https://stackoverflow.com/questions/7551075", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I add a new column to the Documents library upload form? I have added a column to the documents library of my SharePoint site and it appears on the edit form but it does not appear on the upload form. How do I get my new column to appear on the upload form? A: It should appear once the document has been uploaded. It will not appear on the upload form itself.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551076", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why my jquery code works in IE9 but not in IE8? <script> $(document).ready(function() { $("#various2").fancybox({ 'width': 800, 'height': 570, 'type':'iframe' }); }); </script> I'm getting error in IE8 and 7 but not in IE9 Object doesn't support property or method 'fancybox' and error is on this line $("#various2").fancybox({ and my scripts are at bottom before </body> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js" defer="defer"></script> <script>!window.jQuery && document.write(unescape('%3Cscript src="js/libs/jquery-1.5.1.min.js"%3E%3C/script%3E'))</script> <script src="js/plugins.js" defer="defer"></script> <script> $(document).ready(function() { $("#various2").fancybox({ 'width': 800, 'height': 570, 'type':'iframe' }); }); </script> A: You are using defer on the jQuery library, which means it is probably not getting loaded before the jQuery code itself. Since your scripts are at the bottom of the page before </body> there is no need to defer loading them at all since the rest of the page had already loaded. A: I guess, you should debug around defer="defer" part. Different IE versions may be interpreting it different way, causing js libs to be parsed after body script gets parsed. A: Inline script tags don't support defer, and so will always execute as soon as they are encountered. Because your external script has defer, it will load at some arbitrary point in the future. Thus, your inline script will (almost) always execute before your external script has downloaded and run.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551085", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to Create a Global Level Function with UI capability I have a function to find an employee's id number from my sqlite database. The function allows the user to look up by id or name (first and/or last); therefore it creates several dialog boxes and finds the data through an If Else Then tree. Here's the code for those who like that sort of thing: public String getEmployeeID() { final CharSequence[] items = {"By ID", "By Name", "Cancel"}; AlertDialog.Builder builder = new AlertDialog.Builder(LibraryScreen.this); builder.setTitle("Find Employee"); builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { if(items[item].equals("Cancel")) { dialog.cancel(); empid = ""; } else if(items[item].equals("By ID")) { dialog.cancel(); final Dialog dialog2 = new Dialog(LibraryScreen.this); dialog2.setContentView(R.layout.peopledialog); dialog2.setTitle("Employee ID"); dialog2.setCancelable(true); //Set Visibility of the Rows TableRow tblrow1 = (TableRow) dialog2.findViewById(R.id.trGeneral); tblrow1.setVisibility(0); //Set Captions for Rows TextView txtvw1 = (TextView) dialog2.findViewById(R.id.tvGeneral); txtvw1.setText("Employee ID"); //Set Up Edit Text Boxes EditText edttxt1 = (EditText) dialog2.findViewById(R.id.txtGeneral); //Set Input Type edttxt1.setRawInputType(0x00000002);//numbers edttxt1.setText(""); //set max lines edttxt1.setMaxLines(1); //Set MaxLength int maxLength; maxLength = 15; InputFilter[] FilterArray = new InputFilter[1]; FilterArray[0] = new InputFilter.LengthFilter(maxLength); edttxt1.setFilters(FilterArray); Button button = (Button) dialog2.findViewById(R.id.btnTxtDiaSav); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { EditText emplid = (EditText) dialog2.findViewById(R.id.txtGeneral); String newemp = ""; db.open(); Cursor c = db.getEmployee(emplid.getText().toString()); if(c.moveToFirst()) { empid = c.getString(c.getColumnIndex("employeeid")); } else { Toast.makeText(LibraryScreen.this, "No ID Match", Toast.LENGTH_LONG).show(); empid = ""; } c.close(); db.close(); dialog2.dismiss(); } }); Button buttonCan = (Button) dialog2.findViewById(R.id.btnTxtDiaCan); buttonCan.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { dialog2.dismiss(); empid = ""; } }); dialog2.show(); } else if(items[item].equals("By Name")) { dialog.cancel(); final Dialog dialog1 = new Dialog(LibraryScreen.this); dialog1.setContentView(R.layout.peopledialog); dialog1.setTitle("Employee's Name"); dialog1.setCancelable(true); //Set Visibility of the Rows TableRow tblrow1 = (TableRow) dialog1.findViewById(R.id.trGeneral); tblrow1.setVisibility(0); //Set Captions for Rows TextView txtvw1 = (TextView) dialog1.findViewById(R.id.tvGeneral); txtvw1.setText("Employee Name"); //Set Up Edit Text Boxes EditText edttxt1 = (EditText) dialog1.findViewById(R.id.txtGeneral); //Set Input Type edttxt1.setRawInputType(0x00002001);//cap words edttxt1.setText(""); //set max lines edttxt1.setMaxLines(1); //Set MaxLength int maxLength; maxLength = 50; InputFilter[] FilterArray = new InputFilter[1]; FilterArray[0] = new InputFilter.LengthFilter(maxLength); edttxt1.setFilters(FilterArray); Button button = (Button) dialog1.findViewById(R.id.btnTxtDiaSav); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { EditText emplid = (EditText) dialog1.findViewById(R.id.txtGeneral); String firstname = emplid.getText().toString(); String lastname = ""; String matchlist = ""; String temptext = ""; int matchcount = 0; if(firstname.lastIndexOf(" ") <= 0) { lastname = firstname; firstname = "X"; } else { lastname = firstname.substring(firstname.lastIndexOf(" ") + 1); firstname = firstname.substring(0, firstname.lastIndexOf(" ")); } db.open(); Cursor c1, c2; String titletext = ""; if(firstname.length() > 0) { c1 = db.getEmployeeByName(lastname, firstname); if(c1.getCount() == 0) { c1 = db.getRowByFieldTextOrdered("employees", "lastname", lastname, "lastname, firstname"); if(c1.getCount() == 0) { Toast.makeText(LibraryScreen.this, "No matching Employees.", Toast.LENGTH_LONG).show(); empid = ""; } } if(c1.getCount() > 0) { do { c2 = db.getRowByField("orgcodes", "manager", c1.getString(c1.getColumnIndex("employeeid"))); if(c2.moveToFirst()) { if(c2.getString(c2.getColumnIndex("orgcode")).substring(9, 10).equals("0")) { if(c2.getString(c2.getColumnIndex("orgcode")).substring(7, 8).equals("0")) { if(c2.getString(c2.getColumnIndex("orgcode")).substring(5, 6).equals("0")) { if(c2.getString(c2.getColumnIndex("orgcode")).substring(4, 5).equals("0")) { if(c2.getString(c2.getColumnIndex("orgcode")).substring(3, 4).equals("0")) { titletext = "Top Brass"; } else { titletext = "Senior VP"; } } else { titletext = "VP"; } } else { titletext = "Director"; } } else { titletext = "Senior Manager"; } } else { titletext = "Manager"; } } else { titletext = "Employee"; } matchcount++; matchlist = matchlist + c1.getString(c1.getColumnIndex("employeeid")) + ": " + c1.getString(c1.getColumnIndex("firstname")) + " " + c1.getString(c1.getColumnIndex("lastname")) + ": " + titletext + "|"; } while(c1.moveToNext()); } } else { empid = ""; } if(matchcount == 0) { db.close(); Toast.makeText(LibraryScreen.this, "No matching Employees.", Toast.LENGTH_LONG).show(); empid = ""; } else { final CharSequence[] items = new CharSequence[matchcount + 1]; items[0] = "(Cancel)"; for(int i = 1; i <= matchcount; i++) { items[i] = matchlist.substring(0, matchlist.indexOf("|")); matchlist = matchlist.substring(matchlist.indexOf("|") + 1); } db.close(); AlertDialog.Builder builder1 = new AlertDialog.Builder(LibraryScreen.this); builder1.setTitle("Select Employee"); builder1.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { if(items[item].equals("(Cancel)")) { dialog.cancel(); empid = ""; } else { String wasted = items[item].toString(); empid = wasted.substring(0, wasted.indexOf(":")); dialog.cancel(); } } }); AlertDialog alert1 = builder1.create(); alert1.show(); } dialog1.dismiss(); } }); Button buttonCan = (Button) dialog1.findViewById(R.id.btnTxtDiaCan); buttonCan.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { dialog1.dismiss(); empid = ""; } }); dialog1.show(); } } }); AlertDialog alert = builder.create(); alert.show(); return empid; } I use the employee id for a variety of functions through multiple activities in my program. Up to now, I've simply pasted the code under each listener that needs the id, but that is such a waste of space IMHO. My question: Is there a way to put this function somewhere that can be called from many different activities? If so: * *How do I do that? *How do I set the context for the dialog boxes for multiple activities? *How do I get the employee id back to the function that needs it? I'm sure this has been asked before, but I haven't been able to find it online: actually, I'm not even sure how to word the query right. My attempts have come up woefully short. A: A little late to the party - but recorded for posterity: Read up on the Application class: Base class for those who need to maintain global application state. You can provide your own implementation by specifying its name in your AndroidManifest.xml's tag, which will cause that class to be instantiated for you when the process for your application/package is created. Basically, this would give you the ability to obtain a single object that represents your running application (think of it as a singleton that returns an instance of your running app). You first start off by creating a class that extends Application base class and defining any common code that is used throughout your application import android.app.Application; public class MyApplication extends Application { public void myGlobalBusinessLogic() { // } } Then tell your application to use the MyApplication class instead of the default Application class via the <application> node in your app manifest: <application android:icon="@drawable/icon" android:label="@string/app_name" android:name="MyApplication"> Finally, when you need to get to your common function just do something like: MyApplication application = (MyApplication) getApplication(); application.myGlobalBusinessLogic(); If you need to get the context from any part of your application, you can simple return it by calling getApplicationContext() (defined in the base Application class) via a getter method within your custom application class.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551086", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to check if app is in top charts How can I check in iTunes Connect if my app(s) is in any top lists/charts in the App Store? A: I'm using appannie.com : Sales. Reviews. Rankings. 24/7. Global.. You can monitor all your AppStore and Mac AppStore applications. Ranks and reviews all over the world AppStores. And it's free.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551089", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do you use ImageMagick in Perl? I'm trying to get the command line equivalent of "identify image.png" to work in Perl. How do you go about doing this? Thanks. Update: I have the following code use Image::Magick; $image = Image::Magick->new; open(IMAGE, 'image.gif'); $image->Identify(file => \*IMAGE); close(IMAGE); But get the following error: Can't locate Image/Magick.pm in @INC (@INC contains: /etc/perl /usr/local/lib/perl/5.10.1 /usr/local/share/perl/5.10.1 /usr/lib/perl5 /usr/share/perl5 /usr/lib/perl/5.10 /usr/share/perl/5.10 /usr/local/lib/site_perl .) A: There is an Identify method method for PerlMagick as this documentation says. Its parameters are: file=>file, features=>distance, unique=>{True, False} So it could be used like this (tested): use Image::Magick; $image = Image::Magick->new; open(IMAGE, 'image.gif'); $image->Read(file => \*IMAGE); close(IMAGE); $image->Identify(); If you need only the dimensions: use Image::Magick; $image = Image::Magick->new; my ($width, $height, $size, $format) = $image->Ping('image.gif');
{ "language": "en", "url": "https://stackoverflow.com/questions/7551091", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Displaying Bar Chart (and other funky graphics) Any suggestions on freely available libraries to display a bar chart and other "cool" graphics in Visual C++? PS: Please don't say MFC. MFC-based libraries are fine! A: Although not a graphing library, Qt should work pretty nicely for drawing basic graphs, more advanced things can be done using Qwt. Plus you get the advantage of system portability. A: Try Codejock Chart Pro
{ "language": "en", "url": "https://stackoverflow.com/questions/7551093", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to generate a video signal from Android device via USB? Is it possible to create an application for Android, which can generate a video signal (HDMI or VGA) via USB? Any Android device has miniUSB port. Theoretically it's possible to create a small commutator device on microcontroller or microscheme, which will be a USB-host for Android device. You'll connect Android device with commutator and then connect commutator with monitor. For example, the scheme looks like: Android phone -> commutator (USB-host) -> TV/Monitor. Summary, I need to connect android phone with TV via miniUSB port. I found soft which can use miniUSB -> HDMI cable, but those apps only for Motorolla Droid and HTC Evo. I'll glad to get links to existing apps or projects on that theme, to info about software generation HDMI-signal and connecting Android devices with another devices. Thank you and sorry for my bad english! A: Not much chance of that working out: lacking an appropriate converter chip there is no way you will be able to generate an HDMI or DVI signal using only the 4 pins on a standard USB or mini-USB port. You will need to look into building a converter box that does the right thing: something like http://wiki.chumby.com/index.php/What_is_NeTV. A: Those cables are not doing 'HDMI' generation - basically, some phones use the extended standard which has more than just USB in the socket. Specifically, OMAP3/OMAP4 based phones (Droid, Evo) have an onboard HDMI/DVI chip - the cable just breaks out the pins. I'd look at Open Accessory Development Kit for inspirations about what can be done in hardware.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551096", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Creating a WCF webservice with a single standard response object I've been asked to implement a webservice using WCF that will return a single standard response object that indicates whether the webservice call succeeds or fails and an error message if one occurs. It looks to me like this is not how WCF is intended to be used, is that correct? My problem is that I am using IDispatchMessageInspector.AfterReceiveRequest() to validate the request against an XSD prior to WCF deserializing it and calling my operation. If it fails validation how do I return my standard response object? WCF seems to want me to throw a FaultException in this scenario but I want the interface to purely return one standard response object that contains any failure information. So this would mean that you need to define both a custom Fault Exception that you can throw when the request you receive fails validation prior to deserialization etc, and the second standard response to send when the request succeeds. Is that the right approach? To achieve my goal of simply returning the one single response object if something like a validation error occurs, I've been trying to cheat and set the request object to null in AfterReceiveRequest() so it skips processing of the request. object IDispatchMessageInspector.AfterReceiveRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel, System.ServiceModel.InstanceContext instanceContext) { try { validateMessage(ref request); } catch (Exception e) { request = null; return new FaultException<string>(e.Message); } return null; } and then perhaps I can create my own custom response object in BeforeSendReply(). void IDispatchMessageInspector.BeforeSendReply(ref System.ServiceModel.Channels.Message reply, object correlationState) { if (correlationState != null) { reply = CreateMyOwnResponse(((FaultException) correlationState)); } } But I know that this seems silly and is working against how WCF is meant to be used most likely. Is there a way to nicely achieve what I want or do I have to send an exception type when things go bad and a different "normal" response when things succeed? A: WCF does not restrict the return object or force you to throw exceptions to communicate errorenous conditions. It depends on your needs and agreements you make on an overall scale in your architecture. In my applications, I always tend to have an int type return argument that goes negative when an error occurs and is zero when the operation is completed successfully. You can also have more complex return arguments that have error structures in them, like: [DataContract] public class ReturnValue { [DataMember] public int ReturnCode; [DataMember] public string ResultingDescription; // enum listing severities like Critical, Warning, etc. [DataMember] public Severity Severity; } If you need complex returned parameters as returns of your operation you could have the following signature: [OperationContract] ReturnValue MyOperation (int param1, string param2, out MyOperationResult result); My rule of thumb is: * *Only throw an exception over service boundaries for unexpected and unhandled exceptions (things you didn't expect at time of development) *For all other situations, return an error code using the return value of your operation (it is not an exception with that respect)
{ "language": "en", "url": "https://stackoverflow.com/questions/7551102", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Queries based on forms and MS Access development i have 2 questions when i use access: * *i create a form with comboBox and calenders, i want to choose an employee from combobox and from date and to date and when i click ok i will send these parameters to a query to return the result in a query (result is the calculation of it's salary). *i know how to release an access project to be useful to user that can't access tables and queries only forms. is there any way to change the access project from release mode to development one, because supposed that an error occurred, how to solve it without loosing my data. Note: i don't have client/server i develop a program and i release it and give this release to the user, after a specific time this user tell me that an error occurred, and he need data inserted from this program to database. i can solve this problems and release another version of program, but the main problem is how to take all data from the old program to the new one. A: -- You can reference form control in a query: SELECT FROM MyTable WHERE EmployeeID = Forms!MyForm!cboEmployee AND SomeDate BETWEEN Forms!MyForm!txtDateStart And Forms!MyForm!txtDateEnd You could also build an SQL string and use it as the record source for a form or in VBA. -- Access should be split into front-end (forms, reports, etc) and back-end (data). When you make changes to the front-end, you create a new mde or accde and send that to the users. The data stays on a server in the back-end. See: http://msdn.microsoft.com/en-us/library/aa167840(v=office.11).aspx EDIT From your comments, it seems that each application has a single user, if this is the case, splitting is not essential, but it can still be a good idea. The user will get two databases, one for data and one for forms etc and only the one for forms gets replaced. You will need to include a routine to locate and link the back-end tables. However, if this is not possible, an mde or accde does not hide the data, you can send your revised copy and include a routine to import from the previous mde/accde. EDIT 2 There are wizards that will split your database for you and link the tables. Where you find them varies slightly from version to version, but they are under the menu item Database Tools. The only problem with this is that the linked table holds the location for the back-end, which is on your computer, not on your users computer. Linked tables are how you access data in the second database. These act as if there are tables in the first database, except you cannot change them. Unfortunately, linked tables hold the location of the back-end, so this will have to be changed if you are sending it to a users. You can either write code, or show your user how to use the linked table manager. This may lead to confusion and may not be worth the effort for one PC. (See also http://www.alvechurchdata.co.uk/accsplit.htm) Alternatively, you can split the database on your PC and make all the changes to forms etc that you want, then add some code that will import the tables and other data for the user into your new copy. The user will follow the instructions in your code to import the tables. As an aside, you will find that development is a lot safer on a split database. You should also decompile from time to time, which you can find at http://www.granite.ab.ca/access/decompile.htm. If you want to protect your code, you can create a compiled version of this new copy, the extension for a compiled Access database is *.accde, for 2007 onward and *.mde for prior versions. This is what I thought you meant by 'i know how to release an access project'.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551104", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: This XML file does not appear to have any style information associated with it I have deployed my webservice into Tomcat. The WSDL has got some operations like ViewOptions, but when I ran that, I got this error: This XML file does not appear to have any style information associated with it. The document tree is shown below. <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Body> <soap:Fault> <faultcode>soap:Server</faultcode> <faultstring>1</faultstring> </soap:Fault> </soap:Body> </soap:Envelope> Why do we get this error? A: The message isn't an "error" but rather a warning n need not be solved but ignored. An XML document is a data structure but does not contain any presentation/style information internally. Normally an XML document is used in inter-application communication or as a pure data structure that is then used with additional presentation/style information to display to users. XML can be applied style by XSLT just as HTML by CSS and the above warning can be eradicated An eg: of applying xls to xml We don't present xml using xls for RSS, Web Services as they are just used for communication without applying stylesheet rather than meant to be presented to user in browser. So, everything is fine here. A: what worked for my case. I replaced all the links of <a href=".."> ... </a> with window.open("...link", "_self") and changed import { HashRouter as Router, } from 'react-router-dom';
{ "language": "en", "url": "https://stackoverflow.com/questions/7551106", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: PHP Regex Match Troubles I have some data in a string in the format key: value key: value key: value etc... I'm trying to turn it into an array using a regex match. The keys are all uppercase letters directly followed by a colon. Then there is a space and the value starts. This is then followed by a space and then the next key. The value can contain upper/lowercase letters, numbers, space, comma or equals sign. For example, I'd like this input string: NAME: Name of Item COLOR: green SIZE: 40 Turned into this array: newArray[NAME] = Name of Item newArray[COLOR] = green newArray[SIZE] = 40 Any help is much appreciated. Also I don't have access to the formatting of the input, or I'd make this a lot easier on myself. A: A generic solution: $str = 'NAME: Name of Item COLOR: green SIZE: 40'; $split = preg_split('/([A-Z]+):/', $str, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); echo 'Split Array is: ' . var_export($split, true); $newArray = array(); // Stick the key and value together (processing two entries at a time. for ($i = 0; $i < count($split) - 1; $i = $i + 2) { $newArray[$split[$i]] = trim($split[$i + 1]); // Probably trim them. } echo 'New Array is: ' . var_export($newArray, true); A: I'd suggest $str = "NAME: Name of Item COLOR: green SIZE: 40"; preg_match_all('~([A-Z]+):(.+?)(?=[A-Z]+:|$)~', $str, $m, PREG_SET_ORDER); foreach($m as $e) $result[$e[1]] = trim($e[2]); print_r($result);
{ "language": "en", "url": "https://stackoverflow.com/questions/7551108", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is there any CSS file that has the following properties? I am looking for CSS template that has the following properties: * *Website title, menu bar and search box at the top of the page *Tree-based view for the the folders or sub pages on the left *body and the main content on the right I googled about it but I did not get the exact properties. Please help me A: Sounds like you want a CSS layout generator. There are lots of different ones available, but I only linked the first one I found. I suggest that you try them and see what fits your requirements best, since you have not specified if you want a fixed or liquid layout or if any of the sections have a fixed width or height. For the tree view, if you can use jQuery, I highly recommend the excellent Dynatree plugin which is one of the better tree plugins. I like it purely because it's so customizable.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551112", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I set path while saving a cookie value in JavaScript? I am saving some cookie values on an ASP page. I want to set the root path for cookie so that the cookie will be available on all pages. Currently the cookie path is /v/abcfile/frontend/ Please help me. A: document.cookie = "cookiename=Some Name; path=/"; This will do A: See https://developer.mozilla.org/en/DOM/document.cookie for more documentation: setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) { if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/.test(sKey)) { return; } var sExpires = ""; if (vEnd) { switch (typeof vEnd) { case "number": sExpires = "; max-age=" + vEnd; break; case "string": sExpires = "; expires=" + vEnd; break; case "object": if (vEnd.hasOwnProperty("toGMTString")) { sExpires = "; expires=" + vEnd.toGMTString(); } break; } } document.cookie = escape(sKey) + "=" + escape(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : ""); } A: For access cookie in whole app (use path=/): function createCookie(name,value,days) { if (days) { var date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000)); var expires = "; expires="+date.toGMTString(); } else var expires = ""; document.cookie = name+"="+value+expires+"; path=/"; } Note: If you set path=/, Now the cookie is available for whole application/domain. If you not specify the path then current cookie is save just for the current page you can't access it on another page(s). For more info read- http://www.quirksmode.org/js/cookies.html (Domain and path part) If you use cookies in jquery by plugin jquery-cookie: $.cookie('name', 'value', { expires: 7, path: '/' }); //or $.cookie('name', 'value', { path: '/' }); A: This will help.... function setCookie(name,value,days) { var expires = ""; if (days) { var date = new Date(); date.setTime(date.getTime() + (days*24*60*60*1000)); expires = "; expires=" + date.toUTCString(); } document.cookie = name + "=" + (value || "") + expires + "; path=/"; } function getCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null; } A: simply: document.cookie="name=value;path=/"; There is a negative point to it Now, the cookie will be available to all directories on the domain it is set from. If the website is just one of many at that domain, it’s best not to do this because everyone else will also have access to your cookie information.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551113", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "71" }
Q: Is Hudson a mature continuous integration tool now? I have searched the SO site for question about Hudson but some of it are a little dated now say 2 years or more. Some comments link Hudson as 'newbie' ing the CI Field I just would like to know if Hudson is mature right now and is the best option for a CI tool. Thanks P.S. I just would like to hear latest feedback from community. A: I would thoroughly recommend Jenkins, which is a fork of Hudson made in late 2010/early 2011 (wikipedia has more information on the split if you're interested). You'll find more contemporary resources if you do a search for Jenkins - but at the moment most Hudson tutorials are still relevant. As to stability/maturity, we've been using it for many months without any issues that I'd attribute to maturity :) A: We are using Jenkins for our continuous integration and found it quite useful. All the basics are there, regarding starting builds, getting and generating statistics from i.e. build results, unit tests, function tests. It is also very flexible as you can ask Jenkins to execute a script which does pretty much anything you need. Jenkins is the best I've tested so far, and also it is free. A: I think nobody can answer if it is the best option for you. It might be mature and everything, but that doesn't mean it's the best for your particular problem
{ "language": "en", "url": "https://stackoverflow.com/questions/7551118", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Jersey + Oauth 2.0 I'm working on the creation of a REST API using Jersey + Spring 3.0. Jersey is set up and is working correctly however I'm at the point where I need to add authentication to the service. Initially I was asked to look into Oauth however I am considering Oauth 2.0 due to it (apparently) being quite a bit easier for end users to use. So basically: Is it possible to use with Jersey? Does anyone have any guides? Do any libraries exist (if they're even needed)? A: We do support oauth 1.0 (both 2-legged and 3-legged). See com.sun.jersey.contribs.jersey-oauth group id on maven. I am not aware of any library specifically for OAuth 2.0 - OAuth 2.0 is still a work in progress.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551119", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Converting IPad App to Universal App We currently have an app that targets the IPad. We now would like to target the IPhone aswell. Im just wondering how we go about this? UI layout and functionality will be different but under the hood they will be sharing a lot of the same code. Am I best creating a Universal app? or having to seperate apps one for the ipad and one for the iphone? Any help will be greatly appreciated. Thanks A: Use these two macros #define FOR_IPAD (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) #define FOR_IPHONE (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) if(FOR_IPAD) //load view for iPAD else //load view for iPhone
{ "language": "en", "url": "https://stackoverflow.com/questions/7551120", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to set character encoding to a request in Restlet Framework? I am using the Restlet Framework to receive and send the data. //Receiving the Request. Request helpReq = new Request(); Here is my code where I want to send(set) the character encoding along with the response(helpRes).. //Responding to the Request Response helpRes = client.handle(helpReq); A: The encoding applies to representations sent along with request. See the Representation.characterSet property and the Request.entity one.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551122", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: setHorizontallyScrolling causes text to restart in TextView I have added marquee effect in my TextView and appending text to this TextView at run time. After appending I call setHorizontallyScrolling to avoid text overwriting. But this call causes the text to restart again. Is it possible to stop this restart and continue scrolling? Please help A: I don't believe there is a solution that lets you change the value of the horizontallyScrolling attribute without resetting the marquee timer. You may have to set that value in your layout XML to true before you even start appending new text. If you do that then it SHOULDN'T reset when you just append text and should just continue scrolling.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551127", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jquery get call complete function not working I have a web application that gets data with a get call. When it is called, it sets a static variable. After the call is complete I want to get the value, but the complete function that I call is not working, its calling it to fast because its null. $.get('../Controls/myfullcontrol.aspx', {}, function (data) { $('#SiteFullControl').html(data); }).complete(function () { $('#FullControlCount').html('Full Control (<%=GlobalClass.GlobalVariables.User.Count %>)'); $('#LoadingAjax').dialog('close'); }); A: Using Firebug or Chrome's Inspector, look at the XHR and ensure that the script is actually returning something. Are you looking for data returned to the complete function? Then you need a parameter in the function: }).complete(function (data) { A: You don't need the $.complete() method because the $.get() contains allready an success callback. http://api.jquery.com/jQuery.get/ You could work with jQuery the Promise interface (introduced in 1.5).So you can chain multiple callbacks on a single request... Take look: http://api.jquery.com/jQuery.get/#jqxhr-object jQuery.get( url, [data,] [success(data, textStatus, jqXHR),] [dataType] ) $.get('ajax/test.html', function(data) { //STUFF AT SUCCESS });
{ "language": "en", "url": "https://stackoverflow.com/questions/7551129", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I overwrite file contents with new content in PHP? I tried to use fopen, but I only managed to append content to end of file. Is it possible to overwrite all contents with new content in PHP? A: $fname = "database.php"; $fhandle = fopen($fname,"r"); $content = fread($fhandle,filesize($fname)); $content = str_replace("192.168.1.198", "localhost", $content); $fhandle = fopen($fname,"w"); fwrite($fhandle,$content); fclose($fhandle); A: MY PREFERRED METHOD is using fopen,fwrite and fclose [it will cost less CPU] $f=fopen('myfile.txt','w'); fwrite($f,'new content'); fclose($f); Warning for those using file_put_contents It'll affect a lot in performance, for example [on the same class/situation] file_get_contents too: if you have a BIG FILE, it'll read the whole content in one shot and that operation could take a long waiting time A: Use file_put_contents() file_put_contents('file.txt', 'bar'); echo file_get_contents('file.txt'); // bar file_put_contents('file.txt', 'foo'); echo file_get_contents('file.txt'); // foo Alternatively, if you're stuck with fopen() you can use the w or w+ modes: 'w' Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it. 'w+' Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551132", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "73" }
Q: Itransact payment gateway Does itransact allowing to set trial period for individual transactions?
{ "language": "en", "url": "https://stackoverflow.com/questions/7551141", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to calculate correlation of two variables in a huge data set in R? I've got a huge data set with six columns (call them A, B, C, D, E, F), about 450,000 rows. I simply tried to find the correlation between columns A and B: cor(A, B) and I got [1] NA as a result. What can I do to fix this problem? A: You might consider using the rcorr function in the Hmisc package. It is very fast, and only includes pairwise complete observations. The returned object contains a matrix * *of correlation scores *with the number of observation used for each correlation value *of a p-value for each correlation Some example code is available here: A: Try cor(A,B, use = "pairwise.complete.obs"). That will ignore the NAs in your observations. To be statistically rigorous, you should also look at the # of missing entries in your data and look at whether the missing at random assumption holds. Edit 1: Take a look at ?cor to see other options for the use parameter.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551142", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: print preview in wpf with telerik document in rich text box telerik rich text box doesnot support print preview,so im trying to implement print preview but im getting the follwing error Cannot implicitly convert type 'Telerik.Windows.Documents.Model.RadDocument' to 'System.Drawing.Printing.PrintDocument' So how can i convert this or how can i achieve this one...... A: Here is a good example from the official website. For further help, I think you should post this question in the teleric forums itself.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551158", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I implement digit grouping input mask using InputFilter? I am using InputFilter class to make a masked EditText supporting digit grouping. For example when the user inserts" 12345" I want to show "12,345" in EditText. How can I implement it? This is my incomplete code: InputFilter IF = new InputFilter() { @Override public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { for (int i = start; i < end; i++) { if (!Character.isLetterOrDigit(source.charAt(i))) { return ""; } } if (dest.length() > 0 && dest.length() % 3 == 0) { return "," + source; } return null; } }; edtRadius.setFilters(new InputFilter[] { IF }); Is there any other way to implement this kind of input mask? A: This an improvement on the response from @vincent. It adds checks on deleting spaces in a number in the format 1234 5678 9190 so when trying to delete a space it just moves the cursor backon character to the digit before the space. It also keeps the cursor in the same relative place even if spaces are inserted. mTxtCardNumber.addTextChangedListener(new TextWatcher() { private boolean spaceDeleted; public void onTextChanged(CharSequence s, int start, int before, int count) { } public void beforeTextChanged(CharSequence s, int start, int count, int after) { // check if a space was deleted CharSequence charDeleted = s.subSequence(start, start + count); spaceDeleted = " ".equals(charDeleted.toString()); } public void afterTextChanged(Editable editable) { // disable text watcher mTxtCardNumber.removeTextChangedListener(this); // record cursor position as setting the text in the textview // places the cursor at the end int cursorPosition = mTxtCardNumber.getSelectionStart(); String withSpaces = formatText(editable); mTxtCardNumber.setText(withSpaces); // set the cursor at the last position + the spaces added since the // space are always added before the cursor mTxtCardNumber.setSelection(cursorPosition + (withSpaces.length() - editable.length())); // if a space was deleted also deleted just move the cursor // before the space if (spaceDeleted) { mTxtCardNumber.setSelection(mTxtCardNumber.getSelectionStart() - 1); spaceDeleted = false; } // enable text watcher mTxtCardNumber.addTextChangedListener(this); } private String formatText(CharSequence text) { StringBuilder formatted = new StringBuilder(); int count = 0; for (int i = 0; i < text.length(); ++i) { if (Character.isDigit(text.charAt(i))) { if (count % 4 == 0 && count > 0) formatted.append(" "); formatted.append(text.charAt(i)); ++count; } } return formatted.toString(); } }); A: In case you're still searching, I ran into this problem the last day, and found that using a TextWatcher is the best (still not really good) option. I had to group digits of credit card numbers. someEditText.addTextChagedListener(new TextWatcher() { //According to the developer guide, one shall only edit the EditText's //content in this function. @Override public void afterTextChanged(Editable text) { //You somehow need to access the EditText to remove this listener //for the time of the changes made here. This is one way, but you //can create a proper TextWatcher class and pass the EditText to //its constructor, or have the EditText as a member of the class //this code is running in (in the last case, you simply have to //delete this line). EditText someEditText = (EditText) findViewById(R.id.someEditText); //Remove listener to prevent further call due to the changes we're //about to make (TextWatcher is recursive, this function will be //called again for every change you make, and in my experience, //replace generates multiple ones, so a flag is not enough. someEditText.removeTextChangedListener(this); //Replace text with processed the processed string. //FormatText is a function that takes a CharSequence (yes, you can //pass the Editable directly), processes it the way you want, then //returns the result as a String. text.replace(0, text.length(), FormatText(text)); //Place the listener back someEditText.addTextChangedListener(this); } @Override public void beforeTextChaged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } }); My formatting function for the credit card numbers looked like this: String FormatText(CharSequence text) { StringBuilder formatted = new StringBuilder(); int count = 0; for (int i = 0; i < text.length(); ++i) { if (Character.isDigit(text.charAt(i))) { //You have to be careful here, only add extra characters before a //user-typed character, otherwise the user won't be able to delete //with backspace, since you put the extra character back immediately. //However, this way, my solution would put a space at the start of //the string that I don't want, hence the > check. if (count % 4 == 0 && count > 0) formatted.append(' '); formatted.append(text.charAt(i)); ++count; } } return formatted.toString(); } You might have to mind other issues as well, since this solution actually rewrites the EditText's content every time a change is made. For example, you should avoid processing characters you inserted yourself (that is an additional reason for the isDigit check). A: use simple function: public String digit_grouping(String in_digit){ String res = ""; final int input_len = in_digit.length(); for(int i=0 ; i< input_len ; i++) { if( (i % 3 == 0) && i > 0 ) res = "," + res; res = in_digit.charAt(input_len - i - 1) + res; } return res; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7551159", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: ObjectDataSource SelectParameter is an Object? im using C# under Visual studio 2010 i have an object datasource that does performs a certain function taking 2 parameters the first is int, the 2nd in a list how can i pass this list of ints to the object datasource!???? List<int> a = new List<int>(); a=Some Function that populates the list of int by int values; ObjectDataSource1.SelectParameter["Sources"].DefaultValue=a; ?? ? ? A: public WebForm1() { this.Init += (o, e) => { myDS.Selecting += (ds, dsArgs) => { dsArgs.InputParameters["filter"] = new List<int> { 1, 2, 3 }; }; }; } The idea is to set the parameter at the Selecting event.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551162", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Programming languages supported by meego What are the programming languages supported by Meego ? Where Can I get any sample library built in meego for some basic analysis in ubuntu environment... I am going to test libraries built in meego...I am trying to analyse the type of libraries I may be getting.. A: The preferred library for Meego will be Qt. Qt applications can be written in many languages, but the preferred language is C++. Python bindings will probably be available. Security Tools A: C++ - see http://qt.nokia.com/products/platform/meego/
{ "language": "en", "url": "https://stackoverflow.com/questions/7551169", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Navigate on mouse click and change colour on mouse over of div using jquery <c:forEach items="${pagedListHolder.pageList}" var="user"> <div class="dataName" id="userlist" onclick="DoNav('${pageContext.request.contextPath}/secure/user/${user.id}');" > <div class="dataName1">${user.name}</div> <div class="dataName2">${user.email}</div> <div class="dataName3">${user.id}</div> </div> </c:forEach> I have above div defined, now what i want is when user clicks upon any of div , he/she will navigate to a new page which is dynamic(based on userid), and change the div color too on mouse over using jquery. How can i do it, please suggest Thanks Romi A: Basically you have class name to div as - dataName So you just have to attached two event to it - $('.dataName').hover(function(){ // Code to have change css of the div. which will give hover effect. }) and for click event - $('.dataName').click(function(event){ event.preventDefault(); window.location = this.attr('data-url') }) while you have to keep you url to redirect in that div with attribute data-url as - <div class='dataName' data-url='createUrlHere'></div>
{ "language": "en", "url": "https://stackoverflow.com/questions/7551172", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Pushed icon in toolbar I put on bevel button in toolbar, set image for this button and uncheck checkbox bordered. How make pushed icon in toolbar like this? A: Return your item identifiers in the delegate of the toolbar: - (NSArray*)toolbarSelectableItemIdentifiers:(NSToolbar *)toolbar { return _toolbarIdentifiers; } The toolbar will consider them selectable, so the selected item will be displayed the way you need. A: You need to mark your toolbar item as Selectable. Edit your nib file in Xcode, double click the toolbar, click the item in Allowed Toolbar items and, in the Utilities panel, show the Attributes inspector and mark the Selectable checkbox.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551175", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: jquery function undefined for IE9 Iam new @ jquery - Thats working for almost all versions of IE except IE9 it says "Error: 'f' is undefined" i didnt know why ?? and if its not recommended to giving function name like that way then what should i do ? $(document).ready(function f(txtName) { $("#ctl00_Content_chkBox" + txtName).click(function () { var thisCheck = $(this); if (thisCheck.is(':checked')) { var myDate = new Date(); var displayDate = (myDate.getMonth() + 1) + '/' + (myDate.getDate()) + '/' + myDate.getFullYear(); $(this).next(".textbox1").val(displayDate); } }); }); <input type="checkbox" ID="chkBoxName" runat="server" onclick="f('Name');" /> <asp:TextBox CssClass="textbox1" PreValue="" runat="Server" ID="txt_comp_name_date_v" Required="false" Enabled="False" /> A: You're passing a named function expression to $(document).ready. Previous versions of Internet Explorer had a bug which exposed the function into the surrounding scope. It appears Internet Explorer 9 has fixed this bug that you were relying on. Use a function declaration rather than a named function expression by not passing it to $(document).ready: function f(txtName) { $("#ctl00_Content_chkBox" + txtName).click(function () { var thisCheck = $(this); if (thisCheck.is(':checked')) { var myDate = new Date(); var displayDate = (myDate.getMonth() + 1) + '/' + (myDate.getDate()) + '/' + myDate.getFullYear(); $(this).next(".textbox1").val(displayDate); } }); } A: You only use $(document).ready() with code that you want to run at initialization time. You do not use it for named functions that you want to run later. You look like you were trying to do some of both with the same code. I would suggest changing your code like this. I've removed the name on the function and removed the onclick=f() from your HTML that referred to it as you don't need either. Now, there is a click handler that is run in the $(document).ready() that hooks up the click handler function for you (no need for onclick="f()" any more). The code for the click handler then carries out the rest of your work. $(document).ready(function() { $("#chkBoxName").click(function () { var thisCheck = $(this); if (thisCheck.is(':checked')) { var myDate = new Date(); var displayDate = (myDate.getMonth() + 1) + '/' + (myDate.getDate()) + '/' + myDate.getFullYear(); thisCheck.next(".textbox1").val(displayDate); } }); }); <input type="checkbox" ID="chkBoxName" runat="server" /> <asp:TextBox CssClass="textbox1" PreValue="" runat="Server" ID="txt_comp_name_date_v" Required="false" Enabled="False" /> You can see it work here: http://jsfiddle.net/jfriend00/9y7sC/. You should be very careful with this part of the code thisCheck.next(".textbox1") because that is very picky about finding your text field. If you put any intervening HTML tag in between the two, it won't work - it has to be the very next HTML tag and it has to have the right class. If you have a lot of checkboxes next to text fields and you want them all to get this function, then just give them all the same class name and refer to that class in the jQuery code like this: $(document).ready(function() { $(".dateCheckbox").click(function () { var thisCheck = $(this); if (thisCheck.is(':checked')) { var myDate = new Date(); var displayDate = (myDate.getMonth() + 1) + '/' + (myDate.getDate()) + '/' + myDate.getFullYear(); thisCheck.next(".textbox1").val(displayDate); } }); }); <input type="checkbox" class="dateCheckbox" runat="server" /> <asp:TextBox CssClass="textbox1" PreValue="" runat="Server" ID="txt_comp_name_date_v" Required="false" Enabled="False" /> Here's an example of multiple checkboxes working off the one piece of code: http://jsfiddle.net/jfriend00/twu5n/
{ "language": "en", "url": "https://stackoverflow.com/questions/7551177", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I find out if my Open Graph app has already been added to the Timeline programmatically? Assume, that besides using the "Add to Timeline" Social Plugin I want to show a specific message to the user only if she did not yet add my app to her Timeline. Is there any method in the JavaScript SDK that lets me check for that? A: According to what i have read, add to Timeline plugin is available through the Javascript SDK via the XFBML tag. https://developers.facebook.com/docs/reference/plugins/add-to-timeline/ There doesn't seem to be a call that we can subscribe to at the moment. A: There is no coverage of how to read from the timeline via the various APIs [yet]. However you can capture and save the ID of any post made, store that in your local database and use it to reference off of either for determining what to share or to let them delete previous posts. This is a good practice even if the ID doesn't help you as both Facebook and the user want you to be transparent in your posting and the management of said posts.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551180", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is the correct procedure to deploy a Visual studio 2008 Web Application to IIS 6 Currently, I have a Visual Studio 2008 Web Application using .NET Framework 3.5 and I want to deploy to my IIS 6 server. I have try to use the Build > Publish menu to publish my site to IIS 6 but it keep on giving me this error: Visual Web Developer does not support creating Web sites on a SharePoint Web server. See Help for more details. So, may anyone share with me some insight on the correct procedure to deploy my Web application? For your info: MOSS 2007 is also installed. A: Try to use the same publish command but target a local file system folder or a network share and not IIS. Once you have got your binaries and pages in such folder deploy on iis manually with a file copy. A: Thanks Davide, Actually I used another command to perform the deploy. reference: http://msdn.microsoft.com/en-us/library/ms229863%28v=vs.80%29.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7551182", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I keep the selection in ListBox when reloading ItemsSource I am experimenting with WPF and MVVM in our system. However iam having a problem with keeping things selected in lists using only MVVM ( without doing extra CollectionViews ). What i currently have is the list ObservableCollection<ReservationCustomerList> Customers; And then a property storing the selected Customer ReservationCustomerList SelectedCustomer; In my opinion now, when the list reloads (actually from another thread async), the selection should be able to be kept, however this does not happen. Does someone have a nice clean way of achieving this ? A: The way we did it was that we did not replace the collection. We added/removed the entries and updated existing entries if required. This maintains the selection. You can use LINQ methods like Except to identify items that are new or removed. A: In case the reloaded list still contains the last selected item and you want that item to be selected, then you can raise the PropertyChange event for the property SelectedCustomer after your collection gets reloaded. Please make your sure your viewmodel class implements INotifyPropertyChanged interface. A: you can use the ICollectionView to select the entity you want. ICollectionview view = (ICollectionView)CollectionViewSource.GetDefaultView(this.Customers); view.MoveCurrentTo(SelectedCustomer); in your Xaml the itemsControl must have IsSynchronizedWithCurrentItem=true or if the ItemsControl has a SelectedItem property you can simply bind it to your SelectedCustomer Property. A: When you "reload" your collection you basically replace all values in it with new values. Even those that look and feel identical are in fact new items. So how do you want to reference the same item in the list when it is gone? You could certainly use a hack where you determine the item that was selected by its properties and reselect it (i.e. do a LINQ search through the list and return the ID of the matching item, then reselect it). But that would certainly not be using best practices. You should really only update your collection, that is remove invalid entried and add new entries. If you have a view connected to your collection all the sorting and selecting and whatnot will be done automagically behind the scenes again. Edit: var tmp = this.listBox1.SelectedValue; this._customers.Clear(); this._customers.Add(item1); this._customers.Add(item2); this._customers.Add(item3); this._customers.Add(item4); this.listBox1.SelectedValue = tmp; in the method that does the reset/clear works for me. I.e. that is the code I put into the event handling method called when pressing the refresh button in my sample app. That way you dont even need to keep references to the customer objects as long as you make sure that whatever your ID is is consistent. Other things I have tried, like overwriting the collections ´ClearItems()´ method and overwriting ´Equals()´ and ´GetHashCode()´ didn't work - as I expected.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551190", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Groovy Builder support How can i build the above pattern using groovy builder support emp = empFileFactory.root() { emp(id: '3', value: '1') emp(id:'24') { emp(id: '1', value: '2') emp(id: '6', value: '7') emp(id: '7', value: '1') } emp(id: '25') { emp(id: '1', value: '1') emp(id: '6', value: '7') } } i'm trying to build the above strucutre in groovy can some one explain how could i acieve this A: You can do something like this (this has no error handling, and just returns null for methods that I don't expect to be called): // First define our class to hold our created 'Emp' objects @groovy.transform.Canonical class Emp { String id String value List<Emp> children = [] } class EmpBuilder extends BuilderSupport{ def children = [] protected void setParent(Object parent, Object child){ parent.children << child } protected Object createNode(Object name){ if( name == 'root' ) { this } else { null } } protected Object createNode(Object name, Object value){ null } protected Object createNode(Object name, Map attributes){ if( name == 'emp' ) { new Emp( attributes ) } else { null } } protected Object createNode(Object name, Map attributes, Object value){ null } protected void nodeCompleted(Object parent, Object node) { } Iterator iterator() { children.iterator() } } Then, if we call this with your required builder code like so: b = new EmpBuilder().root() { emp(id: '3', value: '1') emp(id:'24') { emp(id: '1', value: '2') emp(id: '6', value: '7') emp(id: '7', value: '1') } emp(id: '25') { emp(id: '1', value: '1') emp(id: '6', value: '7') } } We can print out the 'tree' like so b.each { println it } and see we get the structure we asked for: Emp(3, 1, []) Emp(24, null, [Emp(1, 2, []), Emp(6, 7, []), Emp(7, 1, [])]) Emp(25, null, [Emp(1, 1, []), Emp(6, 7, [])]) A: You want to implement extend the BuilderSupport class, which is pretty easy to do. There's a pretty nice tutorial here. You need to implement a few methods, but the naming should be pretty self-explanatory: * *createNode creates a node (each node has a name and optional attributes and/or a value) *setParent assigns a node as another nodes parent That's pretty much it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551202", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Table with no more than 30k records needs index rebuilding after a handful of inserts I have a table with 20 or so columns. I have approximately 7 non-clustered indexes in that table on the columns that users filter by more often. The active records (those that the users see on their screen) are no more than 700-800. Twice a day a batch job runs and inserts a few records in that table - maybe 30 - 100 - and may update the existing ones as well. I have noticed that the indexes need rebuilding EVERY time that the batch operation completes. Their fragmentation level doesnt go from 0-1% step by step to say 50%. I have noticed that they go from 0-1% to approx. 99% after the batch operation completes. A zillion of selects can happen on this table between batch operations but i dont think that matters. Is this normal? i dont think it is. what do you think its the problem here? The indexed columns are mostly strings and floats. A: A few changes could easily change fragmentation levels. * *An insert on a page can cause a page split *Rows can overflow *Rows can be moved (forward pointers) You'll have quite wide rows too so your data density (rows per page) is lower. DML on existing rows will cause fragmentation quite quickly if the DML is distributed across many pages
{ "language": "en", "url": "https://stackoverflow.com/questions/7551204", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: No module named registro.forms in my own local django server [edited] im setting Django Server in my Ubuntu machine, apache/wsgi, but im getting a error in my view: was No module named registro.forms now after some code in my wsgi is No module name forms #registro.views from registro.forms import ComercioForm In my laptop is running but not in my server machine django is running all database table are syncd WSGI #path /srv/www/project/apache/django.wsgi import is, sys sys.path.insert(0,'/srv/www') sys.path.insert(0,'/srv/www/project') sys.path.insert(0,'/srv/www/') #testing sys.path.insert(0,'/srv/www/project/') #testing os.environ['DJANGO_SETTINGS_MODULE']='project.settings' import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler() httpd.conf #path /srv/www/project/apache/ Alias /media/ "/srv/www/project/public/admin_tools" <Directory "/srv/www/project/public/admin_tools"> Allow from all </Directory> WSGIScriptAlias "/srv/www/project/apache/django.wsgi" <Directory "/srv/www/project/apache"> Allow from all </Directory> project #path /etc/apache2/sites-available <VirtualHost *:80> ServerName project DocumentRoot /srv/www/project <Directory /srv/www/project> Order allow,deny Allow from all </Directory> WSGIDeamonProcess project processes=2 threads=15 display-name=%{GROUP} WSGIProcessGroup project WSGIScriptAlias / /srv/www/project/apache/django.wsgi </VirtualHost> Any idea? thanks A: You probably don't have the "registro"-application in your Django-Path. For an example how to fix it, see here .
{ "language": "en", "url": "https://stackoverflow.com/questions/7551205", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Inheriting from an instance of a template class I have two classes as follows in a header file template<size_t N> class Parent{ protected: char array[N]; size_t i; public: virtual void operator()(int i); }; template<size_t N> void Parent<N>::operator()(int i){ this->i = i; } class Child: public Parent<16>{ public: virtual void operator()(); }; Child has operator()() defined elsewhere in a cpp file. Whenever I include this header file from another cpp file I can access operator()() but operator()(int) is not even defined. Why is this? I thought since I inherit from a specific instance of Parent, all the methods of it should be instanced as well and available. A: Apart from the errors in your code, this is an example of hiding: Your derived class declares a function of the same name but with different signature as a base class. Thus the base function is hidden: class A { virtual void foo(); }; class B : public A { virtual void foo(int); /* hides A::foo() ! */ }; Inheritance only affects functions that have the same signature (with some mild exceptions). Your base class function is declared as void Parent<N>::operator()(int), while in your derived class you declare void Child::operator()(). In C++11 you can explicitly say virtual void foo(int) override to trigger a compiler error if the function isn't overriding anything. If you intentionally want to define a new function with the same name as an existing one but with different signature, and not overriding the base function, then you can make the base function visible with a using directive: class C : public A { using A::foo(); void foo(int); }; // now have both C::foo(int) and C::foo() A: Because the Parent's operator() hides the Child's operator() (they have different signatures). How come you are not getting warnings when you compile your code? This is how it should be : class Child: public Parent<16>{ public: using Parent<16>::operator(); virtual void operator()(); };
{ "language": "en", "url": "https://stackoverflow.com/questions/7551206", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: push an array of references to any number of hashes [ perl ] suppose i have an array: @array = { 'A' => "", 'B' => 0, 'C' => 0, 'D' => 0, }; i can add an element by: $count = 0; $array[$count]->{A} = "abcd"; $array[$count]->{B} = 789; $array[$count]->{C} = 456; $array[$count]->{D} = 123; and another element, $count++; $array[$count]->{A} = "efgh"; $array[$count]->{B} = 111; $array[$count]->{C} = 222; $array[$count]->{D} = 333; how can i add elements to @array using push? A: That first structure you have is a hash reference, not an array. You cannot add values to a Hash via push. push will only operate on an array. If you wish to add a value to a hash reference you will need to either use -> notation or dereference. $hash->{ 'key' } = $val; // -> %{ $hash }{ 'key' } = $val; //dereferencing If you have an array reference inside of a hash reference you can access it in the same manner as above. $hash->{ 'array key' }->[$index] = $val; @{ $hash->{ 'array key' }}[$index] = $val; As for creating an array you use ( and ) like so my @array = ( "One", "Two", "Three" ); Another option is to use the qw() shortcut like so my @array = qw(one two three); Additionally you can create an array by reference using [ and ] my $array_ref = [ 1, 2, 3 ]; Finally to push a value to an array you use push push(@array, $value); Though, push being a list context function can be written sans parens. push @array, $value;
{ "language": "en", "url": "https://stackoverflow.com/questions/7551207", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I read SMS messages from the inbox programmatically in blackberry? I want to read SMS messages from Inbox,Draft,and sent from my blackberry device programmatically. Would any one will help me. A: There is only way to access SMS messages, implement MessageListener and intercept messages when they are sending/receiving. There is no API to access SMS messages already saved in device memory (i.e already received). A: See the BlackBerry Developers Knowledge Base article: What is - Different ways to listen for SMS messages
{ "language": "en", "url": "https://stackoverflow.com/questions/7551210", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Read Users Wall using Facebook Graph API for iPhone I want to retrieve all the feeds in the users wall Posts by my friends, Posts from the Page I Liked, Pictures, Videos Posted basically everything my wall shows. I used this [facebookObj requestWithGraphPath:@"me/feed" andDelegate:delegateObj]; But this results me showing the posts only by me. I cant able to get the feeds by others. How to get all those feeds. I have set the permission as read_stream. Do i have to set anymore permissions to get those feeds A: Use /me/home instead.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551213", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using Getter and Setter for arraylist in java I have a problem that I want to set and get an ArrayList from setter and getter methods of android. But I am new to android and Java and don't know how to do that? Can anyone help me regarding this problem? A: For better Encapsulation / OO design I would do following import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class TestListGetterSetter { List<String> list = new ArrayList<>(); //Return copy of the list public List<String> getList() { return new ArrayList<>(list); } // Copy source list into destination list public void setList(List<String> listToBeSet) { if (listToBeSet != null) this.list.addAll(listToBeSet); } public static void main(String[] args) { TestListGetterSetter testListGetterSetter = new TestListGetterSetter(); List<String> clientList = new ArrayList<>(Arrays.asList("foo", "bar", "HiHa")); testListGetterSetter.setList(clientList); System.out.println("TestListGetterSetter.list before clientList modification = " + testListGetterSetter.getList()); //Now you can change "clientList" without affecting testListGetterSetter object clientList.add("1"); System.out.println("clientList modified List = " + clientList); System.out.println("TestListGetterSetter.list after clientList modification = " + testListGetterSetter.getList()); } } A: ArrayList<String> arrList = new ArrayList<String>(); public ArrayList<String> getArrList() { return arrList; } public void setArrList(ArrayList<String> arrList) { this.arrList = arrList; } A: Example - import java.util.ArrayList; import java.util.List; public class Test { List<String> list = null; public List<String> getList() { return list; } public void setList(List<String> list) { this.list = list; } public static void main(String[] args) { Test test = new Test(); List<String> sample = new ArrayList<String>(); sample.add("element 1"); test.setList(sample); List<String> sample1 = test.getList(); } } A: Generally getter and setter methods are for assign variable and get variables value from that There is not any difference of getter and setter methods for arraylist or for int of a class ArrayList<String> arrList; public ArrayList<String> getArrList() { return arrList; } public void setArrList(ArrayList<String> arrList) { this.arrList = arrList; } Same for Int int id; public int getId() { return id; } public void setId(int id) { this.id = id; } A: I am not familiar with android. But in JAVA, if you want to use set and get method, you need to declare the List first. private List arrayList = new ArrayList(); public List getArrayList() { return arrayList; } public void setArrayList(List arrayList) { this.arrayList = arrayList; } A: please try this public static ArrayList<books> al = new ArrayList<books>(); books book=new books(id,name,type); book1 b1=new book1(id,name,type); al.add(book); al.add(book1); //error at book1 A: Try these public ArrayList getArrayList() { return arraylist; } public void setArrayList(ArrayList arraylist) { this.arraylist = arraylist; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7551214", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Deleting columns from a file with awk or from command line on linux How can I delete some columns from a tab separated fields file with awk? c1 c2 c3 ..... c60 For example, delete columns between 3 and 29 . A: This is what the cut command is for: cut -f1,2,30- inputfile The default is tab. You can change that with the -d switch. A: You can loop over all columns and filter out the ones you don't want: awk '{for (i=1; i<=NF; i++) if (i<3 || i>29) printf $i " "; print""}' input.txt where the NF gives you the total number of fields in a record. For each column that meets the condition we print the column followed by a space " ". EDIT: updated after remark from johnny: awk -F 'FS' 'BEGIN{FS="\t"}{for (i=1; i<=NF-1; i++) if(i<3 || i>5) {printf $i FS};{print $NF}}' input.txt this is improved in 2 ways: * *keeps the original separators *does not append a separator at the end A: awk '{for(z=3;z<=15;z++)$z="";$0=$0;$1=$1}1' Input c1 c2 c3 c4 c5 c6 c7 c8 c9 c10 c11 c12 c13 c14 c15 c16 c17 c18 c19 c20 c21 Output c1 c2 c16 c17 c18 c19 c20 c21 A: Perl 'splice' solution which does not add leading or trailing whitespace: perl -lane 'splice @F,3,27; print join " ",@F' file Produces output: c1 c2 c30 c31
{ "language": "en", "url": "https://stackoverflow.com/questions/7551219", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "26" }
Q: instruments xcode4 not working? Im following Ray Wenderlich tutorial for instruments, but I don't know why the profiling is not showing the leaked object?? - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { NSString * sushiName = [_sushiTypes objectAtIndex:indexPath.row]; NSString * sushiString = [NSString stringWithFormat:@"%d: %@", indexPath.row, sushiName]; NSString * message = [NSString stringWithFormat:@"Last sushi: %@. Cur sushi: %@", _lastSushiSelected, sushiString]; UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Sushi Power!" message:message delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil]; [alertView show]; //_lastSushiSelected = sushiString; //el que jode, pues lo pone en string deallocada, por strinWithFormat que usa autorelease! _lastSushiSelected = [sushiString retain]; //[alertView release]; } Im using the code in the tutorial, and as you can see the alertView is leaking! But I run it trough instruments leaks, and nothing appears! [also is very very very slow to acknowledge the stop button was pressed to stop the profiling!] So what is missing??, thanks a lot! A: Frankly, I think it's a bug. Hopefully it'll be fixed soon (I'm using v4.1) but all is not lost. Under the Allocations instrument you can filter which types are displayed. In this image I've told it to show UIAlertView instances. After clicking in the UITableView a couple of times you can see it tells me that there are 2 instances living, which confirms that there is a leak.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551222", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Find location using Android and keyword search in Google Maps How do I use the Google Maps API to search the destination by some keywords and get a list of options of destination? I'm developing an Android application that uses using Google Maps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551227", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to place a button at a position little above the bottom in android I need to place a button at the bottom of screen, leaving some space below it. In other words I am using these two attributes for my button - android:layout_alignParentBottom="true" android:layout_marginBottom="20dp" but the margin attribute wont work when I use alignParentBottom and the button sticks at the bottom only. Please tell me how to place it a little above the bottom . Here's the xml <RelativeLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center_horizontal" android:background="@drawable/board" android:layout_marginLeft="10dp" android:layout_marginRight="60dp" android:layout_marginTop="15dp" android:layout_marginBottom="10dp"> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center_horizontal" android:text="Type of Lesion" android:textColor="#8B0A50" android:layout_marginTop="40dp" android:id="@+id/disease_listheader_textview" android:drawableBottom="@drawable/underline"/> <ListView android:id="@+id/disease_listview" android:layout_below="@id/disease_listheader_textview" android:layout_width="wrap_content" android:layout_height="wrap_content" android:divider="@drawable/divider" android:layout_marginLeft="40dp" android:layout_marginBottom="50dp" android:cacheColorHint="#00000000"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/disease_search_button" android:layout_centerHorizontal="true" android:background="@drawable/disease_search_btn" android:layout_alignParentBottom="true" android:layout_marginBottom="20dp"/> </RelativeLayout> A: just make change in relative layout height attribute value to fillparent like <RelativeLayout android:layout_width="fill_parent" android:layout_height="fill_parent" .................../> hope this help you A: Can you try this? * *Replace the Button tag with the one mentioned below. I am trying to wrap the button in another dummy layout <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_alignParentBottom="true" android:paddingBottom="20dp"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/disease_search_button" android:background="@drawable/disease_search_btn" android:layout_marginBottom="20dp"/> </LinearLayout> A: This runs just the way you wanted <RelativeLayout android:id="@+id/relativeLayout1" android:layout_width="match_parent" android:layout_height="fill_parent"> <Button android:text="Button" android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_marginBottom="20dip"></Button> </RelativeLayout>
{ "language": "en", "url": "https://stackoverflow.com/questions/7551229", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Which performances better in a query, 'LIKE' or '='? I am using asp.net mvc3. Which of the two '=' or 'LIKE' will perform faster in my SQL query. A: = will be faster than LIKE because testing against exact matches is faster in SQL. The LIKE expression needs to scan the string and search for occurrences of the given expression for each row. Of course that's not a reason not to use LIKE. Databases are pretty optimized and unless you discover that this is a performance bottleneck for your application you should not be afraid of using it. Doing premature optimizations like this is not good. A: As Darin says, searching for equality is likely to be faster - it allows better use of indexes etc. It partly depends on the kind of LIKE operation - leading substring LIKE queries (WHERE Name LIKE 'Fred%') can be optimized in the database with cunning indexes (you'd need to check whether any special work is needed to enable that in your database). Trailing substring matches could potentially be optimized in the same sort of way, but I don't know whether most databases handle this. Arbitrary matches (e.g. WHERE Name LIKE '%Fred%Bill%') would be very hard to optimize. However, you should really be driven by functionality - do you need pattern-based matching, or exact equality? Given that they don't do the same thing, which results do you want? If you have a LIKE pattern which doesn't specify any wildcards, I would hope that the query optimizer could notice that and give you the appropriate optimization anyway - although you'd want to test that. If you're wondering whether or not to include pattern-matching functionality, you'll need to work out whether your users are happy to have that for occasional "power searches" at the cost of speed - without knowing much about your use case, it's hard to say... A: Equal and like are different operators so are not comparable * *Equal is exact match *LIKE is pattern matching That said, LIKE without wildcards should run the same as equal. But you wouldn't run that. And it depends on indexes. Every row will need examined without an index for any operator. Note: LIKE '%something' can never be optimised by an index (edit: see comments) A: * *Equal is fastest *Then LIKE 'something%' *LIKE '%something' is slowest. The last one have to go through the entire column to find a match. Hence it's the slowest one. A: As you are talking about using them interchangeably I assume the desired semantics are equality. i.e. You are talking about queries such as WHERE bar = 'foo' vs WHERE bar LIKE 'foo' This contains no wild cards so the queries are semantically equivalent. However you should probably use the former as * *It is clearer what the expression of the query is *In this case the search term does not contain any characters of particular significance to the LIKE operator but if you wanted to search for bar = '10% off' you would need to escape these characters when using LIKE. *Trailing space is significant in LIKE queries but not = (tested on SQL Server and MySQL not sure what the standard says here) You don't specify RDBMS, in the case of SQL Server just to discuss a few possible scenarios. 1. The bar column is not indexed. In that case both queries will involve a full scan of all rows. There might be some minor difference in CPU time because of the different semantics around how trailing space should be treated. 2. The bar column has a non unique index. In that case the = query will seek into the index where bar = 'foo' and then follow the index along until it finds the first row where bar <> 'foo'. The LIKE query will seek into the index where bar >= 'foo' following the index along until it finds the first row where bar > 'foo' 3. The bar column has a unique index. In that case the = query will seek into the index where bar = 'foo' and return that row if it exists and not scan any more. The LIKE query will still do the range seek on Start: bar >= 'foo' End: bar <= 'foo' so will still examine the next row.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551230", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to fire an event from thickbox without closing it? I'm working with thickbox where i need to use asp controls and have to call the events of the corresponding controls as well. Recently i faced an issue like, asp control's events are not getting fired when used within the thickbox. Following are the step by step procedure on my issue: * *I need to fire an asp button click event from the thickbox without closing the thickbox. *In order to solve #1, i used the following script: function doPostBack(element) { tb_remove(); setTimeout('__doPostBack(\'' + element.name + '\',\'\')', 500); } *#2 fires the event and closes the thickbox window. I need to display a label on the thickbox window and closing the window makes it impossible. I tried the tb_show() method for displaying the thicbox but the window will be displayed while debugging using firebug only and the close button will not work then. Any suggestions will be helpful... A: First, some info on why your original workaround is necessary. Most of these modal dialog plugins, like Thickbox, pull your div that contains the dialog content out of its original place in the DOM, and attach it again under the body tag. This mainly has to do with getting the overlay behind the popup to display properly. One side-effect of this, especially in an ASP.NET page where everything is inside only ONE form tag, is that your form controls are no longer within the <form> tag. So when you click on the button to submit the form, nothing happens (because it's not inside a form that it can submit). The workaround you found above, which is the easiest solution, closes the Thickbox first, so that your form content is now back in its original position in the DOM, inside the <form> tag. Then it initiates the submit of the form. It uses a timeout to make sure the dialog has had a chance to close properly before trying the submit. If you want the Thickbox dialog to stay open during your postback, you have to deal with the real issue above. One way, is to not really do a postback, and instead use AJAX to call a webservice/method with the values from your form fields. Another option is to modify the thickbox.js to keep everything inside the form tag. A third option, is to have another page with your form on it, and then load that inside a Thickbox in an iframe. Whatever the solution, it will either involve keeping the dialog contents inside the form tag in the DOM, or using an alternative way of posting the form data so that it doesn't matter if it's outside the form. Hope this helps you find a solution to your specific situation. Original answer for original question about opening thickbox without a standard link tag Have you tried the following? tb_show('Title for thickbox','WHATEVER-YOU-WOULD-NORMALLY-PUT-IN-THE-HREF'); I don't use Thickbox, but this is the function it uses internally when you click on a link.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551235", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Bind to an exported value by pinvoke I have a dll that exports not only functions, but also values. The dll I'm interested in is from the R Project (http://www.r-project.org/), it's in the R.dll that contains the r language runtime. The declaration in the header file is: LibExtern SEXP R_GlobalEnv; And when when I run dumpbin /exports I can see: 194 C1 00326C08 R_GlobalEnv But I can't seem to find any examples of how to bind such a value from C# or F#. Can anyone enlightenment me to how I might get a reference to it? A: I don't known if there is a way directly from C# or F#. But I think that a C++/CLI wrapper should work. A: After Nick pointed me in the direction of R.NET I was able to look and see how they solved this problem. First they use the win32 api to load the library (or equivalent on other platforms): #if MAC || LINUX private static IntPtr LoadLibrary(string filename) { const int RTLD_LAZY = 0x1; if (filename.StartsWith("/")) { return dlopen(filename, RTLD_LAZY); } string[] searchPaths = (System.Environment.GetEnvironmentVariable(LibraryPath, EnvironmentVariableTarget.Process) ?? "").Split(Path.PathSeparator); foreach (string directory in searchPaths) { string path = Path.Combine(directory, filename); if (File.Exists(path)) { return dlopen(path, RTLD_LAZY); } } return IntPtr.Zero; } [DllImport(DynamicLoadingLibraryName)] private static extern IntPtr dlopen([MarshalAs(UnmanagedType.LPStr)] string filename, int flag); #elif WINDOWS [DllImport("kernel32.dll")] private static extern IntPtr LoadLibrary([MarshalAs(UnmanagedType.LPStr)] string lpFileName); Then they use get GetProcAddress function from kernel32.dll (or equivalent on other platforms) to get the actual address of the variable: #if MAC [DllImport("libdl.dylib", EntryPoint = "dlsym")] #elif LINUX [DllImport("libdl.so", EntryPoint = "dlsym")] #elif WINDOWS [DllImport("kernel32.dll", EntryPoint = "GetProcAddress")] #endif private static extern IntPtr GetSymbolPointer(IntPtr handle, [MarshalAs(UnmanagedType.LPStr)] string symbol);
{ "language": "en", "url": "https://stackoverflow.com/questions/7551237", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Workaround for passing parameter to jQuery ready() I have some code called on jQuery document.ready() which is used in multiple HTML files. Now the difference is each of these HTMLs uses a different div id. I know one option is to just check for hardcode div ids inside $(document).ready() . But I wanted to write a generic code which would take the div Ids based on the currrent/calling HTML page? So is there any way or workaround for passing parameter to jQuery ready() ? A: $(document).ready() just wants a function as an argument so you can write a function that takes your ID as an argument and returns a function for $(document).ready(). For example, instead of this: $(document).ready(function() { $('#some_id').click(/*...*/); }); you could do this: function make_ready(id) { return function() { $('#' + id).click(/*...*/); }; } $(document).ready(make_ready('some_id')); Then you could put your make_ready in some common location and use it to build the functions for your $(document).ready() calls. A: document ready just takes in an handler function as a parameter. You can still define a generic code in you document ready function, by storing the current div id for each html. <input type="hidden" id="current_div" value="div1" /> $(document).ready(function() { var div_id = $('#current_div').val(); // generic code });
{ "language": "en", "url": "https://stackoverflow.com/questions/7551239", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Set the disabled property of the drop down list based on the state of the check boxon loading the page In my application I want to enable a dropdown list box only when the check box is checked and disable it when the check box is unchecked. I am able to achieve this through jquery. The issue I am seeing if I had selected the check box and do a refresh it takes the default value i.e disabled=true for the check box. Is there a way to set the disabled property of the dropdown list based on the state of the check box while loading the page. A: you can check the state of the checkbox when your page loads, instead of hardcoding it to disabled. So when the page loads depending upon the status of the checkbox the dropdown status can be updated. $(document).ready(function() { var is_checked = $('#checkBox').attr('checked'); // handle the drop down });
{ "language": "en", "url": "https://stackoverflow.com/questions/7551240", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to pass two dimensions array to a function and how to call it I've tried many time to pass the array to a function then do some calculation such as getting the total of the columns, the problem is I don't know how to call the result form the function, usually I get errors. this is just one code I'm trying to solve it from yesterday : #include <iostream> using namespace std; //prototype int get_total(int whatever[][2], int row); int main () { const int row=2; const int col=3; int marks[row][col]; // this is prompt the user to input the values for (int i=0; i<row;i++) { for (int p=0; p<col; p++) { cin >> marks[i][p]; } cout << endl; } // this is just display what the user input as a table for (int x=0; x< row ; x++) { for (int y=0; y<col ; y++) { cout << marks[x][y] << " "; } cout << endl; } int sum; // this is the most important thing I want to know, // how to call the function :( sum=get_total(marks,row); return 0; } // to get the total of each columns const int row=3; // not sure if the declaration is correct or not :( int get_total(int whatever[][2], int row) { for (int i=0; i < 2; i++) { for (int p=0; p < 3; p++) int total=0; //this line is completly wrong, How can I calculate the total of columns? total+=get_total[2][p]; } // do we write return total ? // I'm not sure because we need the total for each column return total; } sorry for the mess, and I appreciate any help to explain passing the multidimensions arry to a function as parameter and how to call the function> A: Arrays decay to pointers when calling functions. You can do 2 things: * *Pass the number of lines and columns as arguments to the function. *Use std::vector instead. I suggest you take a look at it, it'll do the trick and you'll learn something new and very useful. Also, your function should do this: int get_total(int** whatever) { //total is 0 at the beginning int total=0; for (int i=0; i < 2; i++) { for (int p=0; p < 3; p++) //go through each element and add it to the total total+=whatever[i][p]; } return total; } This will return the total for the whole matrix, I'm assuming that's what you mean by getting the total of the columns A: int marks[row][col] This means that marks has type int[2][3]. int get_total(int whatever[][2], int row); You've however declared get_total to accept an int(*)[2]. int[2][3] can decay to int(*)[3] but that is not compatible with int(*)[2], hence why you can't pass marks to get_total. You can instead declare get_total to accept an int(*)[3]: int get_total(int whatever[][3], int row); // equivalent to: int get_total(int (*whatever)[3], int row); If you instead decide to declare get_total to accept an int** or an int*, then you can't legally pass marks to it in the former case, and you can't legally iterate over the whole multidimensional array in the latter. Consider not using arrays, it's simpler this way.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551241", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Github multiple machine with single user I am trying to access a github repository from my desktop and laptop with the same user. Could it be possible, if yes then how? I am thankful to you for your cooperation and time. Yours, A: Create a key pair on each machine to push to Github, and you can add as much ssh keys as you wish via https://github.com/account/ssh page. A: Yes. There are to ways : First solution Yes you can shared your ssh public/private keys to access to your github repository. By default, your keys are situated in the ~/.ssh/ folder (id_rsa is your private key, id_rsa.pub is your public key). Second solution (preferable) However, another solution is to create a new pair of keys and put the new public key in your github account. To do that, you can use the ssh-keygen command. After that, you put the new ~/.ssh/id_rsa.pub on your github account as I said above. Don't forget to tape a passphrase when you use the ssh-keygen command to have more security.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551248", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to create navigation bar with navigation back button in a sub view page in iphone Here i developing simple application iphone. I need to create navigation bar with navigation back button in iphone. I'm using view controller page. I want to implement navigation controller. But i could not create back button in next page. I also created navigation bar. In a 2nd sub view page code is -(IBAction)settingspage { Settingscontroller *objec=[[Settingscontroller alloc]initWithNibName:@"Settingscontroller" bundle:nil]; navigationController=[[UINavigationController alloc] initWithRootViewController:objec]; [self presentModalViewController:navigationController animated:YES]; [objec release]; [navigationController release]; } In the using this code it will create navigation bar in 3rd sub view. But i dont knw how to create navigation bar with back button in the 3rd sub view page. How to create navigation bar with back button in 3rd sub view using this code. Can anybody help me pls. A: Back button will appear only in the view that was pushed to previously existing navigation bar using the method below: - (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated If you will use that method and don't overwrite UIBarButtonItem *leftBarButtonItem then back button will be created automatically. A: The whole application should use a single navigation controller. So you shouldn't be creating new controller's if you want to stack the views one above another. However you would need to create new navigation controller only when you need different flow type in the newly presented views. From your question i can infer you are creating new navigation controller's. Hence the solution would be to use the navigation controller already created in the subsequent view controller's. It can be done by accessing the navigationcontroller as follows: self.navigationcontroller
{ "language": "en", "url": "https://stackoverflow.com/questions/7551250", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to convert SQL Server 2005 database file into Excel Possible Duplicate: Can you connect to sql server from Excel? I have my application which I am saving data into SQL Server Express Edition. I want to upload the same data in excel. Please help if any tool available. A: There are quite a few ways to import data from Excel to DB: http://support.microsoft.com/kb/321686 And to export from DB to excel: http://blog.sqlauthority.com/2008/01/08/sql-server-2005-export-data-from-sql-server-2005-to-microsoft-excel-datasheet/
{ "language": "en", "url": "https://stackoverflow.com/questions/7551251", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Problems during generating pdf report because of huge data I have this problem during generating pdf reports. I have some huge data in my database. When I generate the report as HTML, I could use pagination to filter the results so that less data is there to process and show the user. However, in the case of pdf report, I don't think it is nice to make the clients get the pdf page by page. It's better to show the whole data in a single pdf. If I do so, then it will consume a lot of time and memory for the generation. What is the best way to accomplish such feature. Generating such report will result in server timeouts and massive memory consumption. Should I generate them at offline time(say once every day, once every month) and make the users access the pre generated pdfs. I am not sure, what if the users want to generate them themselves in real time What is the best approach? A: You could approach it this way: * *Fetch records from your database, in batches of say 100 records (you could further tune this, based on how many records fit in a single PDF page) *For each batch, generate a separate, single-page, PDF (write to a temporary location on the file system) *Once all records (batches) are processed, combine the PDFs using one of the various PDF assembling/merging tools available on the web, into a single resultant PDF.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551258", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Training data for sentiment analysis Where can I get a corpus of documents that have already been classified as positive/negative for sentiment in the corporate domain? I want a large corpus of documents that provide reviews for companies, like reviews of companies provided by analysts and media. I find corpora that have reviews of products and movies. Is there a corpus for the business domain including reviews of companies, that match the language of business? A: If you have some resources (media channels, blogs, etc) about the domain you want to explore, you can create your own corpus. I do this in python: * *using Beautiful Soup http://www.crummy.com/software/BeautifulSoup/ for parsing the content that I want to classify. *separate those sentences meaning positive/negative opinions about companies. *Use NLTK to process this sentences, tokenize words, POS tagging, etc. *Use NLTK PMI to calculate bigrams or trigrams mos frequent in only one class Creating corpus is a hard work of pre-processing, checking, tagging, etc, but has the benefits of preparing a model for a specific domain many times increasing the accuracy. If you can get already prepared corpus, just go ahead with the sentiment analysis ;) A: http://www.cs.cornell.edu/home/llee/data/ http://mpqa.cs.pitt.edu/corpora/mpqa_corpus You can use twitter, with its smileys, like this: http://web.archive.org/web/20111119181304/http://deepthoughtinc.com/wp-content/uploads/2011/01/Twitter-as-a-Corpus-for-Sentiment-Analysis-and-Opinion-Mining.pdf Hope that gets you started. There's more in the literature, if you're interested in specific subtasks like negation, sentiment scope, etc. To get a focus on companies, you might pair a method with topic detection, or cheaply just a lot of mentions of a given company. Or you could get your data annotated by Mechanical Turkers. A: This is a list I wrote a few weeks ago, from my blog. Some of these datasets have been recently included in the NLTK Python platform. Lexicons * *Opinion Lexicon by Bing Liu * *URL: http://www.cs.uic.edu/~liub/FBS/sentiment-analysis.html#lexicon *PAPERS: Mining and summarizing customer reviews *NOTES: Included in the NLTK Python platform *MPQA Subjectivity Lexicon * *URL: http://mpqa.cs.pitt.edu/#subj_lexicon *PAPERS: Recognizing Contextual Polarity in Phrase-Level Sentiment Analysis (Theresa Wilson, Janyce Wiebe, and Paul Hoffmann, 2005). *SentiWordNet * *URL: http://sentiwordnet.isti.cnr.it *NOTES: Included in the NLTK Python platform *Harvard General Inquirer * *URL: http://www.wjh.harvard.edu/~inquirer *PAPERS: The General Inquirer: A Computer Approach to Content Analysis (Stone, Philip J; Dexter C. Dunphry; Marshall S. Smith; and Daniel M. Ogilvie. 1966) *Linguistic Inquiry and Word Counts (LIWC) * *URL: http://www.liwc.net *Vader Lexicon * *URLs: https://github.com/cjhutto/vaderSentiment, http://comp.social.gatech.edu/papers *PAPERS: Vader: A parsimonious rule-based model for sentiment analysis of social media text (Hutto, Gilbert. 2014) Datasets * *MPQA Datasets * *URL: http://mpqa.cs.pitt.edu *NOTES: GNU Public License. * *Political Debate data *Product Debate data *Subjectivity Sense Annotations *Sentiment140 (Tweets) * *URL: http://help.sentiment140.com/for-students *PAPERS: Twitter Sent classification using Distant Supervision (Go, Alec, Richa Bhayani, and Lei Huang) *URLs: http://help.sentiment140.com, https://groups.google.com/forum/#!forum/sentiment140 *STS-Gold (Tweets) * *URL: http://www.tweenator.com/index.php?page_id=13 *PAPERS: Evaluation datasets for twitter sentiment analysis (Saif, Fernandez, He, Alani) *NOTES: As Sentiment140, but the dataset is smaller and with human annotators. It comes with 3 files: tweets, entities (with their sentiment) and an aggregate set. *Customer Review Dataset (Product reviews) * *URL: http://www.cs.uic.edu/~liub/FBS/sentiment-analysis.html#datasets *PAPERS: Mining and summarizing customer reviews *NOTES: Title of review, product feature, positive/negative label with opinion strength, other info (comparisons, pronoun resolution, etc.) Included in the NLTK Python platform *Pros and Cons Dataset (Pros and cons sentences) * *URL: http://www.cs.uic.edu/~liub/FBS/sentiment-analysis.html#datasets *PAPERS: Mining Opinions in Comparative Sentences (Ganapathibhotla, Liu 2008) *NOTES: A list of sentences tagged <pros> or <cons> Included in the NLTK Python platform *Comparative Sentences (Reviews) * *URL: http://www.cs.uic.edu/~liub/FBS/sentiment-analysis.html#datasets *PAPERS: Identifying Comparative Sentences in Text Documents (Nitin Jindal and Bing Liu), Mining Opinion Features in Customer Reviews (Minqing Hu and Bing Liu) *NOTES: Sentence, POS-tagged sentence, entities, comparison type (non-equal, equative, superlative, non-gradable) Included in the NLTK Python platform *Sanders Analytics Twitter Sentiment Corpus (Tweets) * *URL: http://www.sananalytics.com/lab/twitter-sentiment 5513 hand-classified tweets wrt 4 different topics. Because of Twitter’s ToS, a small Python script is included to download all of the tweets. The sentiment classifications themselves are provided free of charge and without restrictions. They may be used for commercial products. They may be redistributed. They may be modified. *Spanish tweets (Tweets) * *URL: http://www.daedalus.es/TASS2013/corpus.php *SemEval 2014 (Tweets) * *URL: http://alt.qcri.org/semeval2014/task9 You MUST NOT re-distribute the tweets, the annotations or the corpus obtained (from the readme file) *Various Datasets (Reviews) * *URL: https://personalwebs.coloradocollege.edu/~mwhitehead/html/opinion_mining.html *PAPERS: Building a General Purpose Cross-Domain Sentiment Mining Model (Whitehead and Yaeger), Sentiment Mining Using Ensemble Classification Models (Whitehead and Yaeger) *Various Datasets #2 (Reviews) * *URL: http://www.text-analytics101.com/2011/07/user-review-datasets_20.html References: * *Keenformatics - Sentiment Analysis lexicons and datasets (my blog) *Personal experience A: Here are a few more; http://inclass.kaggle.com/c/si650winter11 http://alias-i.com/lingpipe/demos/tutorial/sentiment/read-me.html A: I'm not aware of any such corpus being freely available, but you could try an unsupervised method on an unlabeled dataset. A: You can get a large select of online reviews from Datafiniti. Most of the reviews come with rating data, which would provide more granularity on sentiment than positive / negative. Here's a list of businesses with reviews, and here's a list of products with reviews.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551262", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "57" }
Q: Can anyone explain what is happening in this bit of Javascript? I was looking through a jQuery smooth-scrolling tutorial, and trying to figure out how it worked, when I hit this line of code: $target = $target.length && $target || $('[name=' + this.hash.slice(1) +']'); I can't figure out what it does. It looks like the guy is assigning a string to a variable, but it also kinda looks like he's testing that variable. And I don't understand the use of && and || here. Can anybody explain this? Thanks! EDIT: Wow! What a response! This is taking a bit for me to understand, though - I will have to print this out or something and work on it. Once I understand what's going on, I'll be able to pick the answer that helped me the most. In particular, this bit: if ($target.length && $target) { $target = $target; is stymying me. How does the program know to assign $target to $target? Does the operation assign $target to the first reference to itself (the left side of the equals sign), or to the second reference to itself (the right side, after the &&)? A: It is a cryptic(or elegant?) version of the equivalent ternary operator $target = ($target.length && $target) ? $target : $('[name=' + this.hash.slice(1) +']'); This ternary and the original short circuit expression will return exactly same values if the evaluation of $target does not change the value of $target. But if the evaluation of $target changes the value of $target then SCE and ternary returns different values e.g. var a = 1; b = 2; c = 3; a && ++b || c returns 3; //resetting b b = 2 a && ++b ? ++b : c returns 4; If the evaluation of $target changes the value of $target then the equivalent ternary operator for the SCE $target = $target.length && $target || $('[name=' + this.hash.slice(1) +']'); would be the following $target = ($result= ($target.length && $target)) ? $result : $('[name=' + this.hash.slice(1) +']'); A: It's testing $target (which I assume is a jQuery object) for elements and if empty, assigning a default value. See Logical Operators for a detailed explanation. Update To explain (in case you don't feel like reading the MDN docs), JavaScript logical comparison operators work left-to-right. expr1 && expr2 This will return expr1 if it can be converted to false; otherwise, returns expr2 expr1 || expr2 This will return expr1 if it can be converted to true; otherwise, returns expr2 To break down the line in question, think of it this way $target = ($target.length && $target) || $('[name=' + this.hash.slice(1) +']'); Looking at the first operation... $target.length && $target This will return $target.length if $target.length can be converted to false (ie 0), otherwise it will return $target. The second operation looks like this... (operation1) || $('[name=' + this.hash.slice(1) +']') If the result of the operation1 can be converted to true (ie $target), then it will be returned, otherwise $('[name=' + this.hash.slice(1) +']'). A: This is called Short Circuit evaluation and its not equivalent of ternary operator. and your peace of code equivalent is following: if ($target.length && $target) { $target = $target; } else { $target = $('[name=' + this.hash.slice(1) +']'); } In JavaScript and most of other loosely-typed languages which have more than the two truth-values True and False, the value returned is based on last value. a && b will return a if it false, else will return b. a || b will return a if true, else b. to better understand last value look at the following examples: var a = true; var b = false; var c = 5; var d = 0; return a && b; //returns false return a && c; //returns 5 return b && c; //returns false return c && b; //returns false return c && a; //returns true; return d && b; //returns 0; return b && d; //returns false; return a || b; //returns true return a || c; //returns true return b || c; //returns 5 return c || b; //returns 5 return c || a; //returns 5; return d || b; //returns false; return b || d; //returns 0; Update: Ternary operator: (condition)?(evaluate if condition was true):(evaluate if condition was false) Short Circuit Evaluation: (evaluate this, if true go ahead else return this) && (evaluate this, if true go ahead else return this) You can clearly see that there is a condition for ternary operator while in SCE the evaluation of value itself is the condition. A: $target = $target.length && $target || $('[name=' + this.hash.slice(1) +']'); In javascript you can make inline comparisons when assigning a variable so the example you is the equivalent to if($target.length && $target) $target = $target; else $target = $('[name=' + this.hash.slice(1) +']'); for more examples, see http://www.w3schools.com/JS/js_comparisons.asp for example: var x= y > 4 ?value1:value2 Witch means that if condition is true (y is greater than 4), x will be assigned value1 otherwise it will be assigned value2
{ "language": "en", "url": "https://stackoverflow.com/questions/7551265", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Is there a way to see if two lists are the exact same without looping in python? Say I have: a = [1, 2, 3] b = [1, 2, 3] is there a way to test the lists to see if they are the same, without having to loop through each entry? Here's what I was thinking..I know to check if two variables are the same I could use: id(a) but it doesn't work because the ID's are different so is there some type of checksum or way that python stores values of the table so I can simply compare two variables? A: the == operator should function as expected on lists >>> x = [1, 2] >>> y = [1, 2] >>> x == y True A: Doesn't == work? >>> a = [1, 2, 3] >>> b = [1, 2, 3] >>> a == b True A: the == operator should function works on lists This output is received on certain versions of python, I don't know which. >>> import numpy as np >>> x = [1, 2, 3, 4] >>> y = [1, 2, 3, 4] >>> z = [1, 2, 2, 4] >>> x == y [True, True, True, True] >>> x == z [True, True, False, True] After this, just use numpy to determine the entire list. >>> np.all(x == y) True >>> np.all(x == z) False or if only a single similarity is required: >>> np.any(x == z) True
{ "language": "en", "url": "https://stackoverflow.com/questions/7551268", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Creating a Smudge tool effect in ipad apps How to create a smudge tool effect in ipad apps using core graphics?. A: Andy Finnell wrote a blog post about implementing smudge and stamp tools. Some of the code uses Core Graphics; some of it uses AppKit, which is Mac-specific. Even so, it should be possible for you to port the AppKit bits to UIKit with a bit of work and documentation-checking.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551269", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Instant Alert notification feature using PHP Need to display incoming mails when the user is currently logged in. Can we use socket server programming concept for this requirement. Need help? A: http://code.google.com/p/phpwebsocket/ Avoid using PHP's native socket support. They're an absolute mess, you will end up tearing your eyeballs out. Or you could just poll an ajax script every couple of seconds.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551275", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Extension-less URLs: Url Rerwrite or Routing? I would like to make my ASP.NET web page URLs without .aspx extensions. I can do it in two ways, use IIS7 URL Rewrite module or ASP.NET URL Routing. Which method to choose? A: Use ASP.NET Routing. It's the most up-to-date and right way to do that, since .NET 4.0. Read this thorough article regarding the subject written by the MSDN team (go to Which Option Should You Use?). Routing keeps the request-resource resolution logic within your application, so it's very easy to add application-dependent logic when you need, and it eliminates the need to maintain synchronization between your application and a separate configuration resource. Quote from the article mentioned above: * *If you are developing a new ASP.NET Web application that uses either ASP.NET MVC or ASP.NET Dynamic Data technologies, use ASP.NET routing. Your application will benefit from native support for clean URLs, including generation of clean URLs for the links in your Web pages. Note that ASP.NET routing does not support standard Web Forms applications yet, although there are plans to support it in the future. *If you already have a legacy ASP.NET Web application and do not want to change it, use the URL Rewrite module. The URL Rewrite module lets you translate search engine-friendly URLs into a format that your application currently uses. Also, it lets you create redirect rules that can be used to redirect search engine crawlers to clean URLs. Also read this thorough answer in SO: IIS URL Rewriting vs URL Routing
{ "language": "en", "url": "https://stackoverflow.com/questions/7551279", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Pointer to vector of vectors of ints Hi I am trying to create a pointer to a vector of vectors of int, that is to achieve an effect similar to 2-d arrays. I use the following initialization - vector< vector<int> >* v = new vector< <vector<int> >(10, vector<int>(5, 1)); However, gcc complains- $ c++ test.cpp test.cpp: In member function `int MonochromaticBoard::theMin(std::vector<std::string, std::allocator<std::string> >)': test.cpp:14: error: template argument 1 is invalid test.cpp:14: error: template argument 2 is invalid However, this works - vector< vector<int> > v(10, vector<int>(5, 1)); I tried searching on the web but couldn't find an answer[1], any idea whats wrong in the first syntax? [1] I found that someone at http://www.dreamincode.net/forums/topic/170469-pointer-to-vector-of-vectors/ was successful in initializing like that, but not sure. A: Looks like you just have a typo - one too many <'s after new vector: int main() { vector< vector<int> >* v = new vector< vector<int> >(10, vector<int>(5, 1)); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7551285", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Any source for learning phonegap? I am new to phonegap and I am searching for a source such as websites to learn how to use it. I was searching on http://wiki.phonegap.com but there is only basic information such as installation of eclipse and sdk etc. I need some source code for accessing contacts, camera, accelerometer. Can someone guide me with links or some suggestions? A: * *http://docs.phonegap.com/ : This will give you the insight of PhoneGap APIs with source: *http://drupal.org/project/phonegap : Here you will get the complete source code of Drupal PhoneGap app which runs of Android. iPhone and BlackBerry. This source will help you to understand the PhoneGap development techniques A: There are more books being published in 2012 on PhoneGap. You can browse Amazon for some of the existing titles to date. I agree that it has not been widely documented to date and there there were few in-depth sources of material to reference. PhoneGap Beginner's Guide is a great starting point. It introduces WebKit browsers, cross platform mobile application development and the PhoneGap API in general. There are some pretty basic demos that you can code along with, and the supporting code is downloadable for free. The book was actually written by a member of the PhoneGap development team so it's legit. Another title with a more general intro is Mobile Application Development In The Cloud For Beginners: PhoneGap Build. This book is for a newb and it's newer so it has more references to the cloud version of PhoneGap.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551286", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Keep android alarms alive, even after process killed by a task manager I am writing an alarm program. My problem is task managers, like advanced task manager or Samsung task manager, remove my alarms when clearing memory. Is there any way of preventing task managers from removing my alarms? Or a way to be notified of "clear memory" and forcing app to recreate alarms again. A: In short, no. You can re-register your alarms when the user starts your app again, or when the phone is rebooted.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551287", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Optimize SELECT ... WHERE IN (...) I'm receiving a sequence of product IDs from external system. I have to show the product information preserving the sequence. I'm using the following select to do so: SELECT * FROM products WHERE prodid in (10331,11639,12127..) ORDER BY Field(prodid, 10331,11639,12127...); Sequence can consist of 20 IDs. prodid has b-tree index. It's very frequent query, and I'm trying to find ways to improve performance of that part of the system. Now the average time for this query is 0.14-0.2 sec I would like decrease time to 0.01-0.05 sec. What is the best way to do so? MySQL HASH index, store product id in memcached, or something else? A: SELECT * FROM products <<-- select * is non-optimal WHERE prodid in (10331,11639,12127..) ORDER BY Field(prodid, 10331,11639,12127...); <<-- your problem is here First put an index on prodid see @Anthony's answer. Than change the query to read: SELECT only,the,fields,you,need FROM products WHERE prodid in (10331,11639,12127..) ORDER BY prodid If you make sure your IN list is sorted ascending before offering it to the IN clause, the order by prodid will yield the same result als order by field(... * *Using a function instead of a field kills any chance of using an index, causing slowness. *select * will fetch data you may not need, causing extra disk access, and extra memory usage and extra network traffic. *On InnoDB, if you only select indexed fields, MySQL will never read the table, but only the index saving time (in your case this is probably not an issue though) What is the best way to do so? MySQL HASH index, store product id in memcached, or something else? There are a few tricks you can use. * *If the products table is not too big, you can make it a memory table, which is stored in RAM. Don't do this for big tables, it will slow other things down. You can only use hash indexes on memory tables. *If the prodid's are continuous, you can use BETWEEN 1000 AND 1019 instead of IN (1000, 1001 ..., 1019) A: You may try to create a union of results: SELECT * FROM products WHERE prodid = 10331 UNION ALL SELECT * FROM products WHERE prodid = 11639 UNION ALL . . UNION ALL SELECT * FROM products WHERE prodid = 12127 A: You could try putting an index on the prodid column by using the following query: CREATE INDEX index_name ON products (prodid); For more info, read this post.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551288", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How can I make an position: relative nested in a position: absolute clikable with? I am translating a flash carousel to JavaScript and I am having problems with the position. This is the CSS of the div that contains the images. #tiovivo{ height:382px; width:793px; background-color:#F5F5F5; z-index:-1000; overflow:hidden; position:relative; } If the position is not relative the JavaScript code has to be longer and the images go out of the border The images are in the div like this: <div id="tiovivo"> <img id="tio4" style="cursor:pointer; position:absolute;" onClick="location.href='tio4.php'" height="150px" src="tio4.jpg"> <img id="tio5" style="cursor:pointer; position:absolute;" onClick="location.href='tio5.php'" height="150px" src="tio5.jpg"> </div> The problem is that when #tiovivo is position:relativeI am unable to click the images, the events "onclick" don't work and the cursorpointer is not shown. If #tiovivo is in position:static the "onclick" and the cursor:pointer do work correctly. I need images "position: absolute" so I can put them easily in the JavaScript code. A: Your problem is the z-index: -1000 setting. Compare this (with the z-index on #tiovivo): http://jsfiddle.net/ambiguous/5HZdp/ and this (without the z-index on #tiovivo): http://jsfiddle.net/ambiguous/HLp3Z/ Your negative z-index is pushing #tiovivo and its children under <body> so the images never receive click events. You don't need the z-index to get your absolutely positioned images on top, they'll be on top by default. A: There are several problems with your case * *there is no javascript involved, at least it is has nothing to do with positioning here *you are using position absolute with no other position attributes eg.left,right etc. *remove z-index CSS and it will work. You are placing whole DIV UNDER everything else even if it is transparent A: 1.) Remove z-index:-1000 to make the all elements in the div clickable. 2.) If absolute position for the images, you have to add a vertical and a horizontal position (left or right, top or bottom) to them. Also see my jsfiddle. A: Thank you all, it was the z-index: -1000 I used this index because I was programing a "3D" effect and I want to avoid that the bottom of #tiovivo cover the images. This is the function I use to update the carrousel pos0+=(offx-tempX)/5000;if(pos0> 6.28318531){pos0-=6.28318531} image0.style.left=offx+310*Math.cos(pos0)+"px"; ytilt=Math.sin(pos0); image0.style.top=offy+310*ytilt*((offy+tempY)/1000)+"px"; image0.style.zIndex=Math.round(ytilt*10); pos1+=(offx-tempX)/5000;if(pos1> 6.28318531){pos1-=6.28318531} image1.style.left=offx+310*Math.cos(pos1)+"px"; ytilt=Math.sin(pos1); image1.style.top=offy+310*ytilt((offy+tempY)/1000)+"px"; image1.style.zIndex=Math.round(ytilt*10); I fixed the problem adding an offset to zIndex of the images because sin() function goes from -1 to 1. image0.style.zIndex=100+Math.round(ytilt*10); And removing the z-index: -1000 from #tiovivo
{ "language": "en", "url": "https://stackoverflow.com/questions/7551292", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to use Gmail account to authenticate the app in android? In android how can I authenticate the user by Gmail account. Is their any api or support available for android. Thanks... A: Yes, you can use OAuth in Android. There's a fairly detailed post on this: * *OAuth in Android using the Google APIs Client Library for Java There are also two other Java libraries that you might consider for this purpose: * *Scribe Java API (also supports using several other identity providers) *OAuth Signpost A: Are you asking how to authenticate user in your android app? You can create a gmail client to authenticate user based on their gmail a/c but This is a unsupported in android sdk. A: Take a look at my answer here: https://stackoverflow.com/a/10245999/350691 Hope it helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/7551296", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Connecting to MS SQL Server on Linux in php $server = 'x.x.x.x\SQLEXPRESS'; $link = mssql_connect($server, 'username', 'password'); if (!$link) { die('Something went wrong while connecting to MSSQL'); } else { echo "Connected!"; } It works on windows operating system. but when run linux show "Something went wrong while connecting to MSSQL" please help me A: Be sure to 1.Enable the loading of mssql libraries in php.ini. 2.Check for status of services 3.And also check the php log file to know exactly what is the error. error_reporting(E_ALL); ini_set('display_errors', true); flush(); You can add this piece of code in starting of your .php file, and check what is the exact error. thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/7551299", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why doesn't margin-top using percent work in IE7? IE7 doesn't seem to understand top: 106%: .flex-caption { width: 76%; margin-left: 170px; position: absolute; left: 0; right: 0; top: 106%; color: #b8b8b8; font-size: 14px; line-height: 48px; } http://www.juxt2.com/test/skeleton/index.html What kind of alternatives do I have? I'm making a responsive design so I cannot use px. I'm also open to a JavaScript/jQuery fix that would run in only IE7. A: Trying adding !important next to it. Like :- margin-top !important;
{ "language": "en", "url": "https://stackoverflow.com/questions/7551302", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to decode json in android this is my json data [{"FeedbackId":"1","Phoneid":"9774d56d682e549c","feedbackdate":"2011\/9 \/24","GuestName":"sdf","Address":"sdf","Phone":"456","Email":"sdf","suggestion":"sdf","grievances":"sdf","visitAgain":"0","purposeofvisit":"sdf","flag":"1"},{"FeedbackId":"2","Phoneid":"9774d56d682e549c","feedbackdate":"","GuestName":"sdf","Address":"sdf","Phone":"456","Email":"sdf","suggestion":"sdf","grievances":"sdf","visitAgain":"0","purposeofvisit":"sdf","flag":"1"},{"FeedbackId":"3","Phoneid":"9774d56d682e549c","feedbackdate":"","GuestName":"sdf","Address":"sdf","Phone":"456","Email":"sdf","suggestion":"sdf","grievances":"sdf","visitAgain":"0","purposeofvisit":"sdf","flag":"1"},{"FeedbackId":"4","Phoneid":"9774d56d682e549c","feedbackdate":"2011\/9 \/24","GuestName":"sdf","Address":"dsf","Phone":"456","Email":"sdf","suggestion":"sf","grievances":"sdf","visitAgain":"0","purposeofvisit":"sdf","flag":"1"},{"FeedbackId":"5","Phoneid":"9774d56d682e549c","feedbackdate":"2011\/9 \/24","GuestName":"sdf","Address":"dsf","Phone":"456","Email":"sdf","suggestion":"sf","grievances":"sdf","visitAgain":"0","purposeofvisit":"sdf","flag":"1"},{"FeedbackId":"6","Phoneid":"9774d56d682e549c","feedbackdate":"","GuestName":"xcv","Address":"xcv","Phone":"89","Email":"xcv","suggestion":"xcv","grievances":"xcv","visitAgain":"1","purposeofvisit":"","flag":"1"},{"FeedbackId":"7","Phoneid":"9774d56d682e549c","feedbackdate":"","GuestName":"gfhj","Address":"ghj6678","Phone":"678","Email":"ghjgh","suggestion":"678fgh","grievances":"fgh","visitAgain":"0","purposeofvisit":"sdf","flag":"1"}] how to decode this? A: You should be able to decode using the org.json package. From here: String json = "{" + " \"query\": \"Pizza\", " + " \"locations\": [ 94043, 90210 ] " + "}"; JSONObject object = (JSONObject) new JSONTokener(json).nextValue(); String query = object.getString("query"); JSONArray locations = object.getJSONArray("locations"); Just use your own JSON instead of theirs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551305", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Checkboxes inside dropdown menu php I want to create dropdown menu with multiple checkboxes using framework of cakephp. For example: I have a dropdown having four options respectively-- a b c d Now I want checkboxes before each option. Please help me to solve this problem. A: You can't do this with the default <select> and <option> HTML tags, so I'd recommend using a javascript plugin such as Dropdown Check List (jQuery)
{ "language": "en", "url": "https://stackoverflow.com/questions/7551313", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Problems when assigning values via JavaScript to Asp.net labels and then passing via C# session object I am assigning variables to asp labels via javascript with a simple innerHTML call example: document.getElementById('labelName').innerHTML = parseFloat(var).toFixed(2); It appears in the label fine, and I am able to continue to manipulate it via javascript. I then set it up so that that variable is put into a session object via C# codebehind buttonClick event. example: protected void btnConfirm_Click ( object sender, EventArgs e ) { Session["sessionName"] = labelName.Text; } The buttonConfirm_Click method fires it Response.Redirects to another page and populates asp labels with the session object via the c# codebehind page_load method. example: lblResult.Text = Session["sessionName"].ToString(); When doing this, the label is empty, no errors or 'null'. I have tried to narrow down the issue by trying various things. When I assign the text explicitly in the c# code behind of the first page and the recieve and assign it to the label on the next page, it shows correctly. example: Page 1: Session["sessionName"].ToString() = "Test"; Page 2: lblResult.Test = Session["sessionResult"].ToString(); I have tried several other things, such as casting the variables in javascript and in the codebehind, and checking to make sure I had runat="server" within each applicable label. Anyways, is there something here I am missing? Is asp.net unable to detect the changes that javascript has made to the labels? Are there some incompatibility issues when using innerHTML or anything like this that maybe be causing such a thing to occur? Thanks in advance! A: The problem is that the text in a span tag (that is what asp:Label will render) isn't sent in the post to the server and therefore you can't read your changes server side. You'll need to use a input element (hidden field, textbox etc depending on what your ui should look like).
{ "language": "en", "url": "https://stackoverflow.com/questions/7551315", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C#: Accessing files added to project folder how can i access files I've included in the project folder in Visual C# Windows Application... I've created a folder in the solution and I've added some files. Now, My problem is how to access them? In ASP.NET C# there is ResolveUrl / Url.Content... etc... In Visual C#? what should i do? A: In the properties of those files you could set Copy to Output Directory to Copy if newer and so everytime you run the application they will be copied to the bin/Debug folder alongside with the executable and in your application you could access them as relative files: File.ReadAllText("myfile.txt");: A: You can use Directory.GetCurrentDirectory method to get the current working directory of your application is running in. For more details you can refer to MSDN here A: It depends what kind of files they are, but you may find that a "Resources file" does what you want. Add one of these to your project and then add your existing files to it as resources. You can then access these resources as properties of the resource type. E.g. * *add resources file named Resources.resx) *add a text file to the resources file named "Foo.txt" var foo = Resources.Foo; A: use Server.MapPath sample: string pathToFiles = Server.MapPath("~/ResourceFiles"); string templateFile = pathToFiles + "/MyFileTemplate.xlsx"; using (FileStream fs = File.OpenRead(templateFile)) { }
{ "language": "en", "url": "https://stackoverflow.com/questions/7551319", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: best way to secure sessions (consulting) Ok, yes, I've read the other Qs regarding this topic, but I have several questions more and some Qs were several years old. Anyways, I'm building an admin cp for an insurance company that contains sensitive client info. Such as passwords, social security numbers, and drivers #. First Q: What's more secure, php sessions or cookies? From my understanding of cookies, you can strict them to http only and SSL. Don't know if you can do the same with php sessions. Seems also that php sessions are just quick cookies. Cookies seem more flexible and just as reliable. FYI, I'm using Cookies with http and SSL only. Is there a good reason to use php sessions in MY case? Second Q: My sessions/login work like this: * Passwords are salted and hashed * Sessions are 32 random chars long * Sessions are validated when user enters correct pw and are tied to the user's IP * When a user logs in, the session id and user's password are stored in 2 separate cookies If the sessions are validated via user pw and tied to the user's IP, can I just have the session Cookie and remove the pw cookie? since I think it's kinda redundant since you can only get a session id if you enter the correct PW. I rather have the session id expose in a cookie than the pw (though it's still salted and hashed). Appreciate it if my two Qs can be answered. Additional security advice is welcomed :D Note: Sessions are tied to IP because it increases security greatly. I rather have my users a bit inconvenienced in having to enter their pw when their IP changes when we have SSNs and Driver License #s in our db. Only 3-5 users will have access to the system too. A: * *Do not ever store the user's password in a cookie, in no form of representation. *Regenerate the session ID often *Use strong hashes (no MD5) like SHA512 (consider also stretching the hash) *Sensitive data should be on the server-sided session store: * *Cookies are sent along every request to the cookies domain, hence increasing the chances of being intercepted greatly. Server sided session data is only outputted when needed. *Pass along a session-tied identifier to each sensitive request as an auth token to avoid CSRF *Do not directly bind the session to an IP. Two people using the same AP or private ISP have the same IP and sessions could be mixed up. *SSL is not magical. Don't relay on it too much. A: * *Sessions are stored on server, cookies are stored on the client (browser). Session data that belongs to a user is identified by a cookie (Session ID). I'd say Sessions are safer (you can also apply some encryption for better security). * *Don't store the users password in a cookie. Not a good practice even if it's hashed. You can store an encrypted serialized array containing necessary info to authenticate the user : ip, user agent, username, user id, but not the password. You can also make the site (admin CP) work on SSL only. That way data is not visible in plain text on network. A: Is the password in cookie salted and hashed? Beware - there is no good answer to this question! Tying sessions to IPs really doesn't help much - IPs are cheap, easily spoofed etc. I'd go with SSL, cookies/sessions, perhaps even one-time-cookies, consumed and reset on each pageview. A: Sessions are stored on a server, either in a database, filesystem, memcache, etc. User is tied to the session by session id, which is stored at client either in a cookie or in a URL. Neither is "very very" secure, since session hijacking is possible by stealing session id. But since you've tied session id to an IP, you've done quite enough. Now to password stored in a cookie. Do not do this. Never. Even though they're hashes&salted, it's still better that attackers do not see them. You've got another level of security if they're only stored in a database, since in that case, attacker also has to break into db. It helps if you're regenerating session id using session_regenerate_id() before doing any important action that could compromise the system. Also, take a look at XSS and CSRF attacks and mechanisms to prevent them, like form tokens.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551320", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Problem with selecting a nested last element I have this HTML code with applied CSS. I need all div with cnt-list-box in red but ONLY the LAST div cnt-list-box with different color. Any ideas? <div class="cnt-box-1"> <div class="cnt-list-box">content 1</div> <div class="cnt-list-box">content 2</div> <div class="cnt-list-box">content 3</div> <div class="cnt-list-box">content 4</div> <div class="cnt-list-box">content 5</div> </div> .cnt-list-box { background-color:Red; } A: your example does work in FF and Webkit: http://jsfiddle.net/meo/hwFYT/ As commented by usoban you should check: Changing CSS for last <li> PS: your incode comment is not a valid CSS comment. It produces a parsing error this is why it seams to work, but its no a good practice. A: Fortunately I found by myself a reasonable solution to my problem. .cnt-box-1 > .cnt-list-box:last-child { background-color: Blue; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7551321", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C++: Is it safe to move a jpeg around in memory using a std::string? I have an external_jpeg_func() that takes jpeg data in a char array to do stuff with it. I am unable to modify this function. In order to provide it the char array, I do something like the following: //what the funcs take as inputs std::string my_get_jpeg(); void external_jpeg_func(const char* buf, unsigned int size); int main () { std::string myString = my_get_jpeg(); external_jpeg_func(myString.data(), myString.length() ); } My question is: Is it safe to use a string to transport the char array around? Does jpeg (or perhaps any binary file format) be at risk of running into characters like '\0' and cause data loss? A: std::string does not treat null characters specially, unless you don't give it an explicit string length. So your code will work fine. Although, in C++03, strings are technically not required to be stored in contiguous memory. Just about every std::string implementation you will find will in fact store them that way, but it is not technically required. C++11 rectifies this. So, I would suggest you use a std::vector<char> in this case. std::string doesn't buy you anything over a std::vector<char>, and it's more explicit that this is an array of characters and not a possibly printable string. A: I think it is better to use char array char[] or std::vector<char>. This is standard way to keep images. Of course, binary file may contain 0 characters. A: My recommendation would be to use std::vector<char>, instead of std::string, in this case; the danger with std::string is that it provides a c_str() function and most developers assume that the contents of a std::string are NUL-terminated, even though std::string provides a size() function that can return a different value than what you would get by stopping at NUL. That said, as long as you are careful to always use the constructor that takes a size parameter, and you are careful not to pass the .c_str() to anything, then there is no problem with using a string here. While there is no technical advantage to using a std::vector<char> over a std::string, I feel that it does a better job of communicating to other developers that the content is to be interpreted as an arbitrary byte sequence rather than NUL-terminated textual content. Therefore, I would choose the former for this added readability. That said, I have worked with plenty of code that uses std::string for storing arbitrary bytes. In fact, the C++ proto compiler generates such code (though, I should add, that I don't think this was a good choice for the readability reasons that I mentioned).
{ "language": "en", "url": "https://stackoverflow.com/questions/7551325", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: ASP.net EF Code First - 2 tables (ASP.net MCV 3 Razor View) Hey, my problem is this: I have in the models 2 classes, one called X, one called Y. X has a property for class Y. Now, I seeded them and I have a database with 2 tables for each. I need to use both of them in a single page so I passed them with a 3rd class that contains 2 IQueryables properties for each X and Y. Now, in a page (.cshtml), I made 2 lists, one for X.ToList(), and one for Y.ToList(). I can reach this way both X and Y. The problem is here, the value of Y inside X is null! Why?! it's so frustrating I spent so much time thinking what's wrong but I came up with nothing! A: At a guess, the code that reads X doesn't Include() Y.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551326", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: using VB.net and C#.net in a ASP.net Webapplication I am new to ASP.NET, and I am working on a project which contains two C# and one VB.NET projects. I want to put it all in a single project. How would I do it? A: You can't mix different languages within a same project - but it's simple enough to have a class library written in C# that's called by VB or vice versa. It's possible that you could write your ASP.NET pages in one language and have other code written in another language in the same project - but I would personally try to keep the presentation part of the code in one project and the logic in another, with each project only using a single language. A: Just create a new solution and then add the two projects to it. Set one of them as the startup project and you are done. To create an empty solution, select new project and then under Other Project Types, choose Visual Studio Solutions>>Blank Solution
{ "language": "en", "url": "https://stackoverflow.com/questions/7551329", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }