text
stringlengths
8
267k
meta
dict
Q: iPhone App- MkMapview get the range of area visible in map view in ipohne app Using mapView how to detect the the range of area visible in mapview (i mean range of longitude and latitude which binds the total area) and also when applying zoomin or zoomout in mapview, how to get notified that the range is changed with gesture controlled (Pinch gesture)? A: Your MapView instance has a .region property that you can use to find the currently displayed visible area (ie. self.mapView.region). The MKMapViewDelegate class has events you can implement for the range change, but it's not tied to the pinch specifically - it's also fired if you double tap on the map (to zoom in). - (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated;
{ "language": "en", "url": "https://stackoverflow.com/questions/7618885", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How is my simple android activity leaking memory? My activity simply displays an image: public class PhotoFrameActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); File externalStorageDir = Environment.getExternalStorageDirectory(); File picturesDir = new File(externalStorageDir, "DCIM/Camera"); File[] files = picturesDir.listFiles(new FilenameFilter(){ public boolean accept(File dir, String name) { return name.toLowerCase().endsWith(".jpg"); }}); List<File> photoFiles = Arrays.asList(files); if (!photoFiles.isEmpty()) { try { Bitmap currentPhoto = BitmapFactory.decodeStream(new FileInputStream(photoFiles.get(3))); ImageView view = (ImageView) findViewById(R.id.photo); view.setImageBitmap(currentPhoto); } catch (FileNotFoundException e) { Log.e("SHOWPIC", "Could not find photo", e); } } } } If the activity is restarted, memory is not reclaimed. i.e. if I turn the phone twice I get the following FC: 10-01 17:29:06.011: ERROR/AndroidRuntime(8446): java.lang.OutOfMemoryError: bitmap size exceeds VM budget 10-01 17:29:06.011: ERROR/AndroidRuntime(8446): at android.graphics.BitmapFactory.nativeDecodeStream(Native Method) 10-01 17:29:06.011: ERROR/AndroidRuntime(8446): at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:470) 10-01 17:29:06.011: ERROR/AndroidRuntime(8446): at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:525) 10-01 17:29:06.011: ERROR/AndroidRuntime(8446): at net.badgerhunt.photoframe.PhotoFrameActivity.onCreate(PhotoFrameActivity.java:34) How am I leaking? A: When your image size is large, this out of memory exception occurs. you have to define the sample size in the options while decoding the stream. like BitmapFactory.Options options=new BitmapFactory.Options(); options.inSampleSize = 8; Bitmap preview_bitmap=BitmapFactory.decodeStream(is,null,options); look at the following link for more info. Strange out of memory issue while loading an image to a Bitmap object A: As Yashwanth Kumar suggested, it's NOT due to your image being too large. Even if you reduce the sample size you will still (eventually) get an OOM. The memory leak you have will not get fixed by reducing sample size. It seems you have a memory leak. Either you can go on a memory leak hunt and try to find the root of your problem, or you could just override the ondestroy method of your activity and do @Override protected void onDestroy() { super.onDestroy(); view.setImageBitmap(null); currentPhoto.recycle(); } This will make sure your bitmap gets recycled and the memory gets freed when you activity is being destroyed(as in the case of orientation switch). I would however advice you to watch this video and eventually finding the root to your leak: http://www.google.com/events/io/2011/sessions/memory-management-for-android-apps.html A: I don't think it is the case (your image has to be incredibly large for an Android device), but why don't you try closing this stream? Bitmap currentPhoto = BitmapFactory.decodeStream(new FileInputStream(photoFiles.get(3)));
{ "language": "en", "url": "https://stackoverflow.com/questions/7618886", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to run any exe with administrator privileges? I am using makecert to create certificate i need to do it though c# program the command doesnot execute as it requires administrator privileges. Please suggest me how to run any exe using administrator privileges in windows 7? If possible than just suggest me the sample code. Does th o.s. really matters in my case? A: Another hint again is using UAC( User Account Control) from the code. Very interestimg source IMHO is this one http://victorhurdugaci.com/using-uac-with-c-part-1/ A: You can use the RunAs: http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/runas.mspx?mfr=true and select an account with the required permissions. A: Use the runas verb when starting the process: ProcessStartInfo info = new ProcessStartInfo(path) { Verb = "runas" }; Process p = Process.Start(info); This assumes that you are running as a user in the administrator group. In that case the UAC dialog will be shown when the process starts. A: Change the manifest of the C# application so that it requires adminstrator privileges. UAC should do the rest to prompt the user and elevate the process.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618887", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: exception handling iterator interface I'm trying to make a watertight interface to a library that I'm designing. The user is to enter two dimensional data and so I thought an iterator interface similar to std::transform would be transparant. However, I am unsure how to exception handle any abuse of the iterators. My interface is like so (I can change the interface if there is a better one): template<typename InputItrX, typename InputItrY> set_data(InputItrX beginX, InputItrX endX, InputItrY beginY) { //What exception handling should I do here? size_t array_size = endX-beginX; //get the size of the xarray. my_xVector.resize(array_size); //resize my internal container my_yVector.resize(array_size); // ..and for the ydata. std::copy(beginX, endX, my_xVector.begin()); //copy X std::copy(beginY, beginY+array_size, my_yVector.begin()); //copy Y } For example, my program becomes undefined if the user get muddled up with the interface and writes set_data(xdata.begin(), ydata.begin(), xdata.end()); or maybe their xdata has 20 elements but their ydata has none. Is it possible to check for such mistakes in my library interface? A: I wouldn't add any checks to the method, but document that the exception specification depends on the used iterators. So the user can use checked iterators if he doesn't care about performance losses or unchecked iterators and get best performance. I think most implementations of STL iterators has asserts that check for iterator incompatibilities. Theses errors don't need check in release mode, because they are programmer mistakes. size_t array_size = endX-beginX; //get the size of the xarray. my_xVector.resize(array_size); //resize my internal container my_yVector.resize(array_size); // ..and for the ydata. This makes your method incompatible with iterators that don't have the -operator! It can be used only with random access iterator. You should extract this to a resize_vectors template which can be implemented for random access iterators, but doesn't make any resize for other iterators. In the std::copy you have to use an inserter iterator that resizes the vector, while inserting if the vectors don't have enough capacity.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618889", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Facebook Connect does nothing have FACEBOOK connect to auto register users on my site - but clicking the "LOG IN WITH FACEBOOK" button does nothing - no pop ups. I've tried various ways of integrating it but still no joy. A: You need to upgrade to oAuth 2.0, Facebook connect has been depreciated. Facebook Integration for WordPress
{ "language": "en", "url": "https://stackoverflow.com/questions/7618892", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Backgrounds look bad in phones? My designer created some good looking designs but the problem is that when I apply them on the app I get a weird outcome... Here is the image he designed: And here it is when I apply it on the phone: Why are there like waves in the phone background? A: Either use gradient in xml or try to increase api level .. It may work.. A: apply draw 9 patch to you image...this might help u.....
{ "language": "en", "url": "https://stackoverflow.com/questions/7618896", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Kohana database select, list of fields In Kohana if I want to select fields 'id', and 'username' I do it this way: $record = DB::select('id', 'username') ->from('users') ->where('id', '=', 1) ->as_object() ->execute(); But how to do it if the list of fields I need to select is in an array, like this: $fields = array('id', 'username'); How to use DB::select in this situation? A: You are looking for DB::select_array(). You can also use $record = call_user_func_array('DB::select', $fields) and then continue building the query; it might be ugly but it also works :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7618898", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Combining common values in SQL Say for Instance I have the following table (full of connections between members) connectionA ConnectionB 887 225 129 887 225 887 887 562 562 887 How am I able to use SQL to find all of the rows where both A is connected to B and vice versa. The query would return (no duplications allowed): connectionA ConnectionB 887 225 887 562 A: SELECT T1.connectionA, T1.connectionB FROM yourtable T1 JOIN yourtable T2 ON T1.connectionA = T2.connectionB AND T2.connectionA = T1.connectionB WHERE T1.connectionA > T1.connectionB
{ "language": "en", "url": "https://stackoverflow.com/questions/7618899", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to make jpeg lossless in java? Is there someone that can tell me how to write 'jpeg' file using lossless compression in java? I read the bytes using the code below to edit the bytes WritableRaster raster = image.getRaster(); DataBufferByte buffer = (DataBufferByte) raster.getDataBuffer(); And I need to write again the bytes as 'jpeg' file without compressing in lossy. A: The JAI package offers the ability to save “lossless JPEG” formats. Set compresion type to JPEG-LS or JPEG-LOSSLESS depending on what variant you want. I'm not sure you really want lossless-JPEG though. It's a separate format that's not really much to do with the normal JPEG format. It is not, in general, very well-supported; for lossless image storage you are typically better off with something like PNG. If you need to do lossless image transcoding (ie the set of cropping and rotation operations you can do without disturbing the boundaries of the DCT matrices), you would generally do it with the jpegtran command, as there's not currently a Java binding to the IJG library as far as I know. ETA: do you know how to do it with JAI. I've not tried it myself (code below is untested), but it should be a straightforward call to setCompressionType. (Of course ‘straightforward’ in Java still means negotiating a maze of twisty little objects to set what would be a simple switch anywhere else:) ImageWriter writer= (ImageWriter) ImageIO.getImageWritersByFormatName("jpeg").next(); ImageWriteParam param= writer.getDefaultWriteParam(); param.setCompressionMode(param.MODE_EXPLICIT); param.setCompressionType("JPEG-LS"); writer.setOutput(ImageIO.createImageOutputStream(new File(path))); writer.write(null, new IIOImage(image, null, null), param); JPEG-LS is the newer lossless JPEG standard. It compresses more than the original JPEG-LOSSLESS standard but support is even worse. Most applications that support JPEG will not be able to do anything with these.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618904", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: ruby on rails javascript_include_tag :defaults What the how the, where the.. <%= javascript_include_tag :defaults %> this little evil line is pulling in 3 additional JavaScript that I could essentially give less then a damn about. In fact I would like to use that to redefine some defaults on a per page basis. However I can't seem to figure out where those defaults are defined. Ive been on google and bing looking for answers but I yield none. I keep coming up with a document or 3 that explain using it, but not how I can use it. A: Use the Rails API documentation for this. If the application is not using the asset pipeline, to include the default JavaScript expansion pass :defaults as source. By default, :defaults loads jQuery, and that can be overridden in config/application.rb: config.action_view.javascript_expansions[:defaults] = %w(foo.js bar.js) When using :defaults, if an application.js file exists in public/javascripts it will be included as well at the end. A: For rails 6 may use javascript_pack_tag 'application', 'data-turbolinks-track': 'reload'
{ "language": "en", "url": "https://stackoverflow.com/questions/7618908", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: jQuery MVC - Basic jQuery if else statement which CANT work? I got an if-else script: $('#favitem').live('click', function () { var fid = $(this).parent().attr('id'); if (isFav(fid)) { alert("Do you want to remove from favorite?"); } else { alert("Add to favorite?"); } }); calling the isFav script function: function isFav(fid) { $.ajax({ url: '/Stock/IsFav', type: 'GET', data: { id: fid }, success: function (result) { return result; } }); } which in turn calling my controller action: public Boolean IsFav(int id) { var food = dbEntities.FOODs.Single(f => f.FoodID == id); if (food.FavFlag == 1) { return true; } else { return false; } } Everything seems works fine, I get a true from firebug, BUT i get the alert message from the else statement. The if statement just never being entered. I cant get what is wrong here. Any idea?? Please help.. A: You're not really returning true from within isFav function. Also ajax is asynchornous, so your code (if statement) actually continues to execute until ajax finishes, so at the moment of execution the result of isFav is undefined. So that's why else is being executed. You're gonna need some remodeling. function isFav(fid) { $.ajax({ url: '/Stock/IsFav', type: 'GET', data: { id: fid }, success: function (result) { if(result == 'favorite') alert("Do you want to remove from favorite?"); else alert("Add to favorite?"); } }); } $('#favitem').live('click', function () { var fid = $(this).parent().attr('id'); isFav(fid); }); A: The ajax request in isFav is async and the isFav method will return before it is completed. This is probably how I would solve it: function isFav(fid, callback) { $.ajax({ url: '/Stock/IsFav', type: 'GET', data: { id: fid }, success: function (result) { callback(result); } }); } $('#favitem').live('click', function () { var fid = $(this).parent().attr('id'); isFav(fid,function(result){ if(result && result.toLowerCase() == "true"){ alert("Do you want to remove from favorite?"); } else { alert("Add to favorite?"); } }); }); You want to make sure that the code in the if-block is run after the ajax request is done. In this snippet this is solved by the callback method that is called when the ajax success function is executed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618912", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Spring integration test does not roll back I'm using Spring + Hibernate + H2. I do database operations in my integration tests (by calling a service class). I want Spring to rollback the changes after each test method, but I can't get it to work. At first I used MySQL (with MyISAM, which doesn't support transaction), but after changing to H2 the problem remains. I tried several DataSource-definitions (after reading that it must be XA-aware), but nothing seems to help. I use http://code.google.com/p/generic-dao/ for my DAO-classes and @Transactional-annotations in my service layer (if I remove them, I get the following error: javax.persistence.TransactionRequiredException: no transaction is in progress). My test classes look like this: @ContextConfiguration("classpath:...spring.xml") @Transactional @TransactionConfiguration(transactionManager="transactionManager", defaultRollback=true) public class DemoServiceTest extends AbstractTestNGSpringContextTests{ @Autowired private DemoService demoService; @Test public void addTest() { int size = demoService.findAll().size(); Test coach = new Test(); test.setName("Test"); testService.save(test); Assert.assertEquals(size+1,testService.findAll().size()); } } Here's my spring-configuration: <!-- <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource"> --> <!-- <property name="driverClassName" value="org.h2.Driver" /> --> <!-- <property name="url" value="jdbc:h2:~/test" /> --> <!-- <property name="username" value="sa" /> --> <!-- <property name="password" value="" /> --> <!-- </bean> --> <!-- <bean id="myDataSource" class=" com.mchange.v2.c3p0.ComboPooledDataSource"> --> <!-- <property name="driverClass" value="org.h2.Driver" /> --> <!-- <property name="jdbcUrl" value="jdbc:h2:~/test" /> --> <!-- <property name="user" value="sa" /> --> <!-- <property name="password" value="" /> --> <!-- </bean> --> <bean id="myDataSource" class="com.atomikos.jdbc.nonxa.AtomikosNonXADataSourceBean"> <property name="uniqueResourceName" value="test" /> <property name="driverClassName" value="org.h2.Driver" /> <property name="url" value="jdbc:h2:~/test" /> <property name="user" value="sa" /> <property name="password" value="" /> <property name="maxPoolSize" value="20" /> <property name="reapTimeout" value="300" /> </bean> <bean id="demoDAO" class="...DemoDAOImpl" /> <bean id="demoService" class="...DemoServiceImpl" /> <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> <property name="persistenceUnitName" value="test" /> <property name="persistenceXmlLocation" value="classpath:persistence.xml" /> <property name="dataSource" ref="myDataSource" /> <property name="loadTimeWeaver"> <bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" /> </property> <property name="jpaVendorAdapter" ref="vendorAdapter" /> </bean> <bean id="vendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"> <property name="database" value="H2" /> <property name="showSql" value="true" /> <property name="generateDdl" value="true" /> </bean> <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> <property name="entityManagerFactory" ref="entityManagerFactory" /> </bean> <bean id="searchProcessor" class="com.googlecode.genericdao.search.jpa.JPASearchProcessor"> <constructor-arg ref="metadataUtil" /> </bean> <bean id="metadataUtil" class="com.googlecode.genericdao.search.jpa.hibernate.HibernateMetadataUtil" factory-method="getInstanceForEntityManagerFactory"> <constructor-arg ref="entityManagerFactory" /> </bean> <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" /> <tx:annotation-driven /> And that's my service implementation: @Transactional public class TestServiceImpl implements TestService { private TestDAO<Test,Long> dao; @Autowired public void setDao(TestDAO<Test,Long> dao) { this.dao = dao; } public void save(Test test) { dao.persist(test); dao.flush(); } public List<Test> findAll() { return dao.findAll(); } public Test findByName(String name) { if (name == null) return null; return dao.searchUnique(new Search().addFilterEqual("name", name)); } } EDIT: The dao.persist()-method basically encapsulates the call to the following method from genericdao (em returns the current EntityManager): /** * <p> * Make a transient instance persistent and add it to the datastore. This * operation cascades to associated instances if the association is mapped * with cascade="persist". Throws an error if the entity already exists. * * <p> * Does not guarantee that the object will be assigned an identifier * immediately. With <code>persist</code> a datastore-generated id may not * be pulled until flush time. */ protected void _persist(Object... entities) { for (Object entity : entities) { if (entity != null) em().persist(entity); } } Everything works fine, but the changes remain in the database. Any ideas? A: I think you need to extend from AbstractTransactionalTestNGSpringContextTests instead of AbstractTestNGSpringContextTests.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618914", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Creating new entity classes from database in Netbeans and Glassfish I am trying to create entity classes from database for my JPA/Hibernate project in Netbeans (7.0) IDE with Glassfish server (3.1) But I get the following error when selecting the datasource from the "New Entity Classes from Database" wizard: Unable to find the driver com.mysql.jdbc.jdbc2.optional.MysqlDataSource. Register this driver in the Databases tab. Please note that the MySQL driver is properly installed in the Glassfish server, IDE and in the project itself. A: The database settings inside Netbeans aren't the same as the ones inside GlassFish. In Netbeans, got to Window and select Services. On that form you'll see a database section. This is where the database you are selecting needs to be configured. Once you have it set up you can test it by right clicking and trying to connect.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618915", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: File names matching "..\ThirdParty\dlls\*.dll" Is there an easy way to get a list of filenames that matach a filename pattern including references to parent directory? What I want is for "..\ThirdParty\dlls\*.dll" to return a collection like ["..\ThirdParty\dlls\one.dll", "..\ThirdParty\dlls\two.dll", ...] I can find several questions relating matching files names including full path, wildcards, but nothing that includes "..\" in the pattern. Directory.GetFiles explicitly disallows it. What I want to do with the names is to include them in a zip archive, so if there is a zip library that can understand relative paths like this I am happier to use that. The pattern(s) are coming from an input file, they are not known at compile time. They can get quite complex, e.g ..\src\..\ThirdParty\win32\*.dll so parsing is probably not feasible. Having to put it in zip is also the reason I am not very keen on converting the pattern to fullpath, I do want the relative paths in zip. EDIT: What I am looking for really is a C# equivalent of /bin/ls. A: static string[] FindFiles(string path) { string directory = Path.GetDirectoryName(path); // seperate directory i.e. ..\ThirdParty\dlls string filePattern = Path.GetFileName(path); // seperate file pattern i.e. *.dll // if path only contains pattern then use current directory if (String.IsNullOrEmpty(directory)) directory = Directory.GetCurrentDirectory(); //uncomment the following line if you need absolute paths //directory = Path.GetFullPath(directory); if (!Directory.Exists(directory)) return new string[0]; var files = Directory.GetFiles(directory, filePattern); return files; } A: There is the Path.GetFullPath() function that will convert from relative to absolute. You could use it on the path part. string pattern = @"..\src\..\ThirdParty\win32\*.dll"; string relativeDir = Path.GetDirectoryName(pattern); string absoluteDir = Path.GetFullPath(relativeDir); string filePattern = Path.GetFileName(pattern); foreach (string file in Directory.GetFiles(absoluteDir, filePattern)) { } A: If I understand you correctly you could use Directory.EnumerateFiles in combination with a regular expression like this (I haven't tested it though): var matcher = new Regex(@"^\.\.\\ThirdParty\\dlls\\[^\\]+.dll$"); foreach (var file in Directory.EnumerateFiles("..", "*.dll", SearchOption.AllDirectories) { if (matcher.IsMatch(file)) yield return file; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7618919", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Customizing rating bar in android I have to design a custon list item including rating bar in it I followed this tutorial([Problem with custom rating bar in android) for customising and resizing rating bar.Rating bar is now appering small bt i am unable to click on it My custom listItem Code is : <TableLayout xmlns:android="http://schemas.android.com/apk/res/android" android:stretchColumns="*" android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/tbl"> <TableRow> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="wrap_content" android:layout_height="wrap_content"> <ImageView xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/icon" /> <TextView android:layout_width="wrap_content" android:id="@+id/txt" android:layout_height="wrap_content" android:text="Item Name" /> </LinearLayout> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="wrap_content" android:layout_height="wrap_content"> <TextView android:layout_width="100dp" android:gravity="center" android:layout_height="wrap_content" android:text="Price" /> <TextView android:layout_width="100dp" android:gravity="center" android:layout_height="wrap_content" android:text="Discount" /> <TextView android:layout_width="100dp" android:gravity="center" android:layout_height="wrap_content" android:text="In Stock" /> </LinearLayout> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="wrap_content" android:layout_height="wrap_content"> <!-- <RatingBar android:id="@+id/ratingBar1" android:fitsSystemWindows="false" android:maxWidth="150dip" android:minHeight="23dip" android:maxHeight="25dip" android:layout_height="40dp" android:layout_width="150dp" /> --> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Shipping days" /> <RatingBar android:id="@+id/ratingBar" style="?android:attr/ratingBarStyleSmall" android:layout_gravity="center_vertical|center_horizontal" android:focusable="true" android:layout_width="wrap_content" android:layout_height="wrap_content"></RatingBar> <Button android:layout_width="60dip" android:layout_height="35dip" android:text="Buy" android:textSize="15dip"/> </LinearLayout> </TableRow> </TableLayout> And the screenShot is : EDIT : i developed the customized rating bar but now whatever i set the rating in landscape and when i look at the application in portrait whole rating bars are deselected..what to do to keep rating bar selected ? A: The smaller RatingBar style ( ratingBarStyleSmall) and the larger indicator-only style (ratingBarStyleIndicator) do not support user interaction and should only be used as indicators. (from RatingBar manual) A: Use drawables with different sizes for HDPI and MDPI, and then give your ratingbar a specific height in dp. Or, put one empty row of pixels in your drawable. but the second way just solves the look of your ratingbars, and the height will be wrong. I suggest the first way.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618920", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Actual precedence for infix operators in Scala The May 24, 2011 Scala Language Specification has a typo in section 6.12.3 as discovered here. This was acknowledged on the mailing list. What is the actual precedence for the infix operators? A: I thought it would be fun figuring it out by testing it, I wrote the following code to be executed in the REPL. Given: val ops = List( "letter", "|", "^", "&", "<", ">", "!", "+", "-", "*", "/", "%", "?", "=?", // add ? to prevent assignment ":?" // add ? to prevent right-association ) First generate an intermediate scala file that use and test the operators. import java.io._ // generate a class with all ops operators defined // where operator combines in a way we can figure out the precedence val methods = ops.map("""def %s(o: Op) = Op("["+o.v+v+"]")""".format(_)) val body = methods.mkString("\n") val out = new PrintWriter(new FileWriter("Op.scala")) out.println("case class Op(v: String) {\n%s\n}".format(body)) // generate tests for all combinations and store in comps // Op(".") op1 Op(".") op2 Op(".") v returns "[[..].]" when op2 > op1 // returns "[.[..]]" when op1 <= op2 def test(op1: String, op2:String) = { """("%s","%s") -> (Op(".") %s Op(".") %s Op(".")).v.startsWith("[[")""". format(op1, op2, op1, op2) } val tests = for (op1 <- ops; op2 <- ops) yield { test(op1, op2) } out.println("val comps = Map[(String, String), Boolean](%s)".format( tests.mkString(",\n"))) out.close Then Load Op class, run tests and load comps :load Op.scala // order operators based on tests val order = ops.sortWith((x,y) => comps(x -> y)) // if op1 or op2 don't have higher precedence, they have the same precedence def samePrecedence(op1: String, op2: String) = !comps(op1 -> op2) && !comps(op2 -> op1) def printPrecedenceGroups(list: List[String]): Unit = { if (list != Nil) { val (same, rest) = list.span(op => samePrecedence(op, list.head)) println(same.mkString(" ")) printPrecedenceGroups(rest) } } printPrecedenceGroups(order) This prints: letter | ^ & ! =? < > :? + - * / % ? So the main difference with the spec is < > needs to be switched with = !.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618923", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Advise how to optimize the solution (LOOP for all records and check for errors) I used the following (check for errors in loop and if they are exists I insert they into the table): FOR rec IN (SELECT MAX(t.s_id) as s_id,t.sdate,t.stype,t.snumber,t.code, SUM(t.amount) as amount, t... (other fields) FROM stable t WHERE t.sdate=p_date AND t.stype=p_type AND t.snumber=p_num GROUP BY t.sdate,t.snumber,t.stype, t... (other fields)) LOOP v_reason := null; BEGIN SELECT d.source_id INTO i_source_id FROM mapping m, source d WHERE TO_NUMBER(m.stage)=rec.snumber AND m.month=EXTRACT(MONTH FROM rec.sdate) AND m.year=EXTRACT(YEAR FROM rec.sdate) AND m.desc=d.source_desc AND m.month=d.month AND m.year=d.year AND m.name='SOURCE'; EXCEPTION WHEN OTHERS THEN e_id := 1; v_reason := 'source_id'; END; IF (v_reason IS NULL) THEN BEGIN SELECT p.product_id INTO i_product_id FROM mapping m, product p WHERE m.stage=rec.code AND m.month=EXTRACT(MONTH FROM rec.sdate) AND m.year=EXTRACT(YEAR FROM rec.sdate) AND m.desc=p.product_name AND m.month=p.month AND m.year=p.year AND m.name='PRODUCT'; EXCEPTION WHEN OTHERS THEN e_id := 2; v_reason := 'product_id'; END; END IF; --- and 5 more checks from other tables --- ---....--- IF (v_reason IS NULL) THEN INSERT INTO tbl_destination(sdate,source_id,product_id,amount, ... and others) VALUES(rec.sdate,i_source_id,i_product_id,NVL(abs(rec.amount),0), ...); ELSE INSERT INTO tbl_errors(rec_id,e_id,desc) VALUES(rec.s_id,e_id,v_reason); END IF; COMMIT; END LOOP; It is too slow for large number of records (about 20000). Please, help me. A: Jumping back and forth between SQL and PLSQL gives a tremendous amount of overhead. In your case, you execute a query, and then execute new queries for each record found in the main query. This slows the lot down because of all those context switches between SQL and PLSQL and because of separate queries are harder to optimize. Write one big query. The optimizer can do all its magic, and you only got a single context switch. Execute the next query: every row it returns is an error. You only need to read sourceCount and productCount to see which one is the problem (or both). To insert the errors: insert into tbl_errors (rec_id, e_id, desc) select s_id, case when sourceCount <> 1 then 1 when productCount <> 1 then 2 when ... end as e_id, case when sourceCount <> 1 then 'source_id' when productCount <> 1 then 'product_id' when ... end as reason from ( SELECT MAX(t.s_id) as s_id, t.sdate,t.stype,t.snumber,t.code, SUM(t.amount) as amount, (SELECT count(*) FROM mapping m, source d WHERE TO_NUMBER(m.stage)=rec.snumber AND m.month=EXTRACT(MONTH FROM rec.sdate) AND m.year=EXTRACT(YEAR FROM rec.sdate) AND m.desc=d.source_desc AND m.month=d.month AND m.year=d.year AND m.name='SOURCE') as sourceCount, (SELECT count(*) FROM mapping m, product p WHERE m.stage=rec.code AND m.month=EXTRACT(MONTH FROM rec.sdate) AND m.year=EXTRACT(YEAR FROM rec.sdate) AND m.desc=p.product_name AND m.month=p.month AND m.year=p.year AND m.name='PRODUCT') as productCount, /* other checks */ FROM stable t WHERE t.sdate=p_date AND t.stype=p_type AND t.snumber=p_num GROUP BY t.sdate, t.snumber, t.stype ) x having sourceCount <> 1 or productCount <> 1 or /* other checks */ To insert the records that are ok. Use the same query for checks, but add extra subqueries to get the right product id and source id. insert into tbl_destination(sdate,source_id,product_id,amount, ...) select sdate, source_id, product_id, amount, ... from ( SELECT MAX(t.s_id) as s_id, t.sdate,t.stype,t.snumber,t.code, SUM(t.amount) as amount, (SELECT count(*) FROM mapping m, source d WHERE TO_NUMBER(m.stage)=rec.snumber AND m.month=EXTRACT(MONTH FROM rec.sdate) AND m.year=EXTRACT(YEAR FROM rec.sdate) AND m.desc=d.source_desc AND m.month=d.month AND m.year=d.year AND m.name='SOURCE') as sourceCount, (SELECT min(source_id) FROM mapping m, source d WHERE TO_NUMBER(m.stage)=rec.snumber AND m.month=EXTRACT(MONTH FROM rec.sdate) AND m.year=EXTRACT(YEAR FROM rec.sdate) AND m.desc=d.source_desc AND m.month=d.month AND m.year=d.year AND m.name='SOURCE') as source_id, (SELECT count(*) FROM mapping m, product p WHERE m.stage=rec.code AND m.month=EXTRACT(MONTH FROM rec.sdate) AND m.year=EXTRACT(YEAR FROM rec.sdate) AND m.desc=p.product_name AND m.month=p.month AND m.year=p.year AND m.name='PRODUCT') as productCount, (SELECT min(product_id) FROM mapping m, product p WHERE m.stage=rec.code AND m.month=EXTRACT(MONTH FROM rec.sdate) AND m.year=EXTRACT(YEAR FROM rec.sdate) AND m.desc=p.product_name AND m.month=p.month AND m.year=p.year AND m.name='PRODUCT') as product_id, /* other checks */ FROM stable t WHERE t.sdate=p_date AND t.stype=p_type AND t.snumber=p_num GROUP BY t.sdate, t.snumber, t.stype ) x having sourceCount = 1 and productCount = 1 and /* other checks */ A: Usually the most performant way is to convert the plsql into set based operations, and get rid of the LOOP, I would start by taking the driving query and embed it into each of the queries (in the loop). Then turn these into inserts. taking care to incorporate any logic in the IF statements into the WHERE clause. e.g: as you are inserting an error where there are no records found you could change the first SELECT INTO....EXCEPTION block into a direct insert where it can't find any rows in the mapping tables INSERT INTO tbl_errors SELECT s_id, 1 as e_id , 'source_id' as reason FROM ( SELECT MAX(t.s_id) as s_id,t.sdate,t.stype,t.snumber,t.code, SUM(t.amount) as amount, t... (other fields) FROM stable t WHERE t.sdate=p_date AND t.stype=p_type AND t.snumber=p_num GROUP BY t.sdate,t.snumber,t.stype, t... (other fields) ) drv LEFT JOIN mapping m ON TO_NUMBER(m.stage) = drv.s_id --etc LEFT JOIN source d ON m.desc=d.source_desc AND m.month=d.month --etc WHERE m.stage IS NULL eventually you will end up with several inserts, it should now be possible to optimise furthur and merge all of the selects into a single statement and do the operation as a single insert. Then to insert the errors just insert the rows from the driving query that have no errors i.e: INSERT INTO tbl_destination SELECT * from drv WHERE NOT EXISTS(SELECT * from tbl_errors WHERE s_id=drv.s_id)
{ "language": "en", "url": "https://stackoverflow.com/questions/7618930", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: emacs gud window use How do I customize which window GUD will use when i issue commands - 'up', 'down', etc ? It seems to use an arbitrary window, sometimes even the window with gdb in it - I want to be able to specify a specific window to be used. A: Have you considered borrowing the key bindings mentioned in the following question? Emacs, switch to previous window This question implies that GUD steps on some things if you don't add a parameter. Maybe your command bindings are being affected similiarly. Using gdb in Emacs 23 I asked a buddy of mine about this issue and here is what he said. Well, we used xemacs and so it's not exactly apples to apples here. I do have gnu-emacs installed on cygwin and I can't replicate his problem. I think he definitely needs to list a version # for emacs and the version # for all his installed packages. When you press up/down it calls 'previous-line' and 'next-line' respectively which both move the cursor in the default buffer. The only thing I can think is that he has something running that switches buffers (lisp 'set-buffer') temporarily and maybe doesn't set it back or errors b/f restoring the buffer? Better to use 'with-current-buffer' (or one of the other with-* forms) that saves the current state of the ui runs your lisp code and restores the ui state.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618933", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Mysql InnoDB Error code #1025 We are using Mysql 5.1 in our production servers and trying to run an alter query to change the datatype of a column from tinytext to varchar(200). On running the alter query we are seeing this error :- #1025 - Error on rename of './msging/#sql-123b_ab7634' to './msging/outboxes' (errno: -1) The MySql forums suggest that this error might be because of foreign key constraints. But our schema does not have any foreign keys. The mysql error logs are showing the below mentioned error.We went through the link mentioned in the error statement but couldn't find anything useful. Any ideas what might be going wrong ? InnoDB: Error: './msging/outboxes.ibd' is already in tablespace memory cache 111001 12:40:18 InnoDB: Error in table rename, cannot rename msging.#sql-123b_ab4828 to msging.outboxes 111001 12:40:18 InnoDB: Error: table msging.outboxes does not exist in the InnoDB internal InnoDB: data dictionary though MySQL is trying to drop it. InnoDB: Have you copied the .frm file of the table to the InnoDB: MySQL database directory from another database? InnoDB: You can look for further help from InnoDB: http://dev.mysql.com/doc/refman/5.1/en/innodb-troubleshooting.html A: When you rename a table using ALTER TABLE, here's what happens: * *The table is copied to a new file with a random filename. *Changes are made to the new file. *The old table is renamed using a random temporary filename. *The new table is renamed to take the place of the old file. *The old table is removed. See this link for more details: http://www.xaprb.com/blog/2006/08/22/mysqls-error-1025-explained/ You can use innotop to get more details on the error: http://code.google.com/p/innotop/
{ "language": "en", "url": "https://stackoverflow.com/questions/7618935", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is it possible to use newer headers on an older version of gcc (g++)? Is it possible to use newer headers with an older version of gcc ? I have gcc 4.2.1 on my ipod (which I learned has a compiler that can be installed with cydia) but I have gcc 4.4.3 on my distro. I was wondering if I need to get the original headers (if thats even possible, I know gnu likes to phase way older versions out) or if I can just use the ones from my distro? In particular, I'm talking about g++. EDIT: just found this going to follow it. jeremyg:Building c/c++ applications using gcc/g++ on iphone NEW EDIT: Found this Trying to compile Hello World example but can't find objc library? antirez iphone-gcc tutorial Edit: Well I'm in one hell of a spot lmao I've got full C support and an almost usable g++ compiler and the open toolchain(torrented a "working version") that needs minor modifications. if i could just get objc working on my ipod I wouldn't mind using objc the whole purpose is to of course is to make apps :D one quick question the toolchain was compiled on an amd64 machine but for i686 so that makes it intel compatible? I'm not sure the whole amd64 thing is throwing me off ;P A: You shouldn't need to, there's no reason for the gcc on your PC and on your iPod to be the same. What are you trying to do?
{ "language": "en", "url": "https://stackoverflow.com/questions/7618938", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Where should the top of stack be in linked list implementation of stack? Here is what a linked list implementing a stack with 3 elements might look like: list | v -------- -------- --------- | C | -+-->| B | -+-->| A | 0 | -------- -------- --------- Where should we consider the top of the stack to be, the beginning or end of the list, and why? Thanks in advance. A: The fastest element to access in a linked list is usually the head (some implementations also keep a reference to the tail element though). Since the stack only ever needs to access the top element, that should be the head element of the linked list. This will avoid having to iterate over the entire list for every operation. A: list.head will be top of the stack. Elements will be add in head like Insert(L,x) 1. x.next = head.next 2. head = x Similarly deletion will be performed in head. Delete(L) 1. x=head 2. head = head.next 3. Free x In this way insertion and deletion will be in performed in LIFO order which is Stack.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618939", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Activity Transition Animation not working from Tab Activity To any other Activity I am trying to use activity transition animaition using OverridePendingTransition The same code works while I move from 1 activity to another everywhere in my App But when I use the same while transitioning from an activity which is a part of tab to any other activity. The animation does not work and the standard animation takes place Intent intent = new Intent(xxx.this, yyy.class); startActivity(intent); overridePendingTransition(R.anim.slide_left_in, R.anim.slide_left_out); here xxx is the class which is one of the tabs activity class and yyy is any activity class I am stuck Any help would be appreciated Thanks Cheers Himanshu A: I reported the same to google issues and the workaround provided was(I have not tried it though) :- I have found a way to work arround this, it is not perfect but it works. I add the overridePendingTransition(R.anim.slide_left_in, R.anim.slide_left_out); before the onPause on the TabActivity. public void onPause() { overridePendingTransition(R.anim.slide_left_in, R.anim.slide_left_out); super.onPause() } A: Better way to make it work: getTabHost().setOnTabChangedListener(new OnTabChangeListener() { public void onTabChanged(String tabId) { View selectedView = getTabHost().getCurrentView(); if (getTabHost().getCurrentTab() > lastTab) { selectedView .setAnimation( R.anim.slide_left_in ); } else { selectedView .setAnimation( R.anim.slide_left_out ); } lastTab = getTabHost().getCurrentTab(); } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7618942", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to access SessionMode in WCF .NET framework 4.0 How do you programatically access SessionMode in WCF on the client side? How do you programatically access SessionMode in WCF on the server side? A: found answer here http://social.msdn.microsoft.com/Forums/en/wcf/thread/bf1ecbec-4eda-4dc5-ba26-c7ad43247b93 ServerSide System.ServiceModel.Description.ContractDescription.GetContract(typeof(IService1)).SessionMode.ToString() ClientSide System.ServiceModel.Description.ContractDescription.GetContract(typeof(ServiceReference1.IService1)).SessionMode
{ "language": "en", "url": "https://stackoverflow.com/questions/7618953", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to create batch file which opens an website e.g. gmail.com and enters user name and password i need to create a batch file which opens a website(gmail) and enters username and password. so can anyone help me please.. Thank you. here is the code i tried.. It opens gmail, now how can i enter username and password. saved as Test.bat @echo off start /d "C:\Program Files\Internet Explorer" IEXPLORE.EXE https://gmail.com A: Won't let me comment, but I agree the batch is the wrong way to do this. You could do this with PowerShell though. add-type -AssemblyName microsoft.VisualBasic add-type -AssemblyName System.Windows.Forms #Loads Website C:\Progra~1\Intern~1\iexplore.exe -k http://www.gmail.com #Enter Credentials [System.Windows.Forms.SendKeys]::SendWait("userid{TAB}password{enter}") A: You cannot do this. You can open a specific url, but you cannot enter values in a form. You can open an e-mail adress from the command prompt, but that will open the default e-mail client, and not some webmail page. So unfortunately, it's not possible. A: I don't think there's a purely-batch way of achieving your goal. You may try to write something up, using, for example, http://jsoup.org/ . But you'll need to change your code every time there's a new specification on the page. A: This can be done with Selenium. You need to write a simple Selenium JUnit test in Java. Of course, this requires that Java be installed on the computer. It would be about 20-30 lines of code. Then, you can execute the JUnit test from a batch file like so: @ECHO off SET username=me SET password=mypassword java -cp MyGmailTest.class MyGmailTest %username% %password% timeout 10 A: Use selenium's firefox WebDriver with java. http://docs.seleniumhq.org/download/ Import all the necessary webDriver librarys, and it will very simple. Something like this: public class checkEmail{ public static void main(String args[]){ WebDriver driver = new FirefoxDriver(); driver.get("www.gmail.com"); driver.findElement(By.id("Email")).sendKeys("your usernamne"); driver.findElement(By.id("Passwd")).sendKeys("your password"); driver.findElement(By.id("signIn")).click(); } } get the .class files, then make a simple batch file @ECHO OFF set CLASSPATH= (wherever your selenium jars are) cd C:\where ever the class file is java checkEmail A: WITH FIREFOX: @echo off set command=C:\Users\%USERNAME%\Desktop\GMAIL.VBS start https://gmail.com echo Set objShell = WScript.CreateObject("WScript.Shell") > %command% echo Set WshShell = WScript.CreateObject("WScript.Shell") >> %command% echo Do Until Success = True >> %command% echo Success = objShell.AppActivate("Mozilla Firefox") >> %command% echo Loop >> %command% echo WshShell.SendKeys "USERNAME HERE" >> %command% echo WshShell.SendKeys "{TAB}" >> %command% echo WshShell.SendKeys "[PASSWORD HERE] >> %command% echo WshShell.SendKeys "{ENTER}" >> %command% ping 192.0.2.2 -n 1 -w 5000 > nul start %command% ping 192.0.2.2 -n 1 -w 1000 > nul del %command% exit chance [USERNAME HERE] AND [PASSWORD] { with the [ ] } WITH GOOGLE CHROME @echo off set command=C:\Users\%USERNAME%\Desktop\GMAIL.VBS start https://gmail.com echo Set objShell = WScript.CreateObject("WScript.Shell") > %command% echo Set WshShell = WScript.CreateObject("WScript.Shell") >> %command% echo Do Until Success = True >> %command% echo Success = objShell.AppActivate("Google Chrome") >> %command% echo Loop >> %command% echo WshShell.SendKeys "USERNAME HERE" >> %command% echo WshShell.SendKeys "{TAB}" >> %command% echo WshShell.SendKeys "[PASSWORD HERE] >> %command% echo WshShell.SendKeys "{ENTER}" >> %command% ping 192.0.2.2 -n 1 -w 5000 > nul start %command% ping 192.0.2.2 -n 1 -w 1000 > nul del %command% exit chance [USERNAME HERE] AND [PASSWORD] { with the [ ] } A: @if (@CodeSection == @Batch) @then @echo off rem Use %SendKeys% to send keys to the keyboard buffer set SendKeys=CScript //nologo //E:JScript "%~F0" %SendKeys% "{ENTER}" goto :EOF @end // JScript section var WshShell = WScript.CreateObject("WScript.Shell"); WshShell.SendKeys(WScript.Arguments(0)); While i myself am still experimenting and testing this batch file program on different applications, i am not sure as to the inner-workings of what this program actually does. All i know is it uses a java script installed on every windows computer to push keyboard commands to be executed. However in my experimentation i found that it could also serve as a means to fill in passwords and usernames. @if (@CodeSection == @Batch) @then @echo off rem Use %SendKeys% to send keys to the keyboard buffer set SendKeys=CScript //nologo //E:JScript "%~F0" START FIREFOX "WWW.EXAMPLE.COM" rem the script only works if the application in question is the active window. Set a timer to wait for it to load! timeout /t 5 rem use the tab key to move the cursor to the login and password inputs. Most htmls interact nicely with the tab key being pressed to access quick links. %SendKeys% "{TAB}" rem now you can have it send the actual username/password to input box %SendKeys% "username{TAB}" %SendKeys% "password{ENTER}" goto :EOF @end // JScript section var WshShell = WScript.CreateObject("WScript.Shell"); WshShell.SendKeys(WScript.Arguments(0)); check this
{ "language": "en", "url": "https://stackoverflow.com/questions/7618954", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Comparing two databases I am using SQL Server 2008, can you recommend me some tool that I will be able to compare two database instances? Also I want to be able to choose what tables and columns should participate in the comparison. I want to add it to our automation testing. Thanks. A: Red Gate's SQL Data Compare can do what you need. It is not particularly expensive, especially if you buy it as part of a bundle (check out some of their other products - they have a lot of useful tools) and you get a free trial so you can see if it works for your situation before you buy it. I have used it and it works well. It allows both comparison and snychronization of data between two databases, even if the schemas are slightly different. For the feature "Command line automation for continuous integration" you will need the Pro edition. A: If you're using Visual Studio 2010 for coding along with SQL Server 2008, you can use the Schema Compare and Data Compare tools that comes along with Visual Studio 2010. Here are some resources: * *Schema Compare *Data Compare
{ "language": "en", "url": "https://stackoverflow.com/questions/7618956", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: PrimeFaces commandButton doesn't call action if ajax enabled Here's my page: <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:cpanel="http://java.sun.com/jsf/composite/components/cpanel" xmlns:f="http://java.sun.com/jsf/core" xmlns:p="http://primefaces.prime.com.tr/ui" xmlns:ui="http://java.sun.com/jsf/facelets"> <h:head> <title></title> </h:head> <h:body> <ui:composition template="/WEB-INF/templates/cpanelLayout.xhtml"> <ui:define name="metadata"> <f:metadata> <f:viewParam name="id" value="#{linkDoctorBean.incomingDoctorId}" required="true"/> <f:event type="preRenderView" listener="#{linkDoctorBean.preRenderView}"/> </f:metadata> </ui:define> <ui:define name="cpanelContent"> <cpanel:adddedClinicDoctor doctor="#{linkDoctorBean.incomingDoctor}" clinic="#{linkDoctorBean.clinic}"/> <h:form id="form"> <div> <h:panelGrid columns="2"> <p:selectOneMenu id="doctor" value="#{linkDoctorBean.doctor}" converter="#{doctorConverter}" effect="fade" var="d" height="180" validator="#{linkDoctorBean.validateDoctor}"> <f:selectItem itemLabel="Select a doctor" itemValue="" noSelectionOption="true"/> <f:selectItems value="#{linkDoctorBean.doctors}" var="doctor" itemLabel="#{stringBean.doctorToString(doctor)}" itemValue="#{doctor}"/> <p:column> <p:graphicImage value="#{applicationBean.baseResourceUrl}/doc-photo/small/#{d.urlDisplayName}"/> </p:column> <p:column> #{stringBean.doctorToString(d)} </p:column> </p:selectOneMenu> <p:message id="doctorMessage" for="doctor"/> </h:panelGrid> </div> <div style="margin-top:20px;"> <p:commandButton value="Link" action="#{linkDoctorBean.submit()}" update="doctorMessage" process="@all"/> <h:link value="Cancel" outcome="/pages/cpanel/manage-doctors" style="margin-left:10px;"/> </div> </h:form> </ui:define> </ui:composition> </h:body> </html> When I add ajax="false" to the <p:commandButton/>, it works just fine - the linkDoctorBean.submit() method is called. With ajax enabled, however, the action method will be called if the form never fails validation in the current view, but if the form fails validation once and is subsequently submitted, the error message is cleared, but the submit() method is never called. Edit: I also tried replacing the p:commandButton with this: <h:commandButton value="Link" action="#{linkDoctorBean.submit()}"> <f:ajax execute="@all" render="doctorMessage"/> </h:commandButton> The behaviour is exactly the same. In both cases, the validation message appears to be cleared when a valid option is submitted. So the update/render is happening, just not the process/execute. All subsequent attempts fail to execute the action, so the form is effectively dead until the next time the page is loaded. Edit: This doesn't seem to be a PrimeFaces issue. Here's the form without PrimeFaces: <h:form id="form"> <div> <h:panelGrid columns="2"> <h:selectOneMenu id="doctor" value="#{linkDoctorBean.doctor}" converter="#{doctorConverter}" style="width:200px;" required="true" requiredMessage="Please select a doctor" validator="#{linkDoctorBean.validateDoctor}"> <f:selectItem itemLabel="Select a doctor" itemValue="#{null}" noSelectionOption="true"/> <f:selectItems value="#{linkDoctorBean.doctors}" var="doctor" itemLabel="#{stringBean.doctorToString(doctor)}" itemValue="#{doctor}"/> </h:selectOneMenu> <h:message id="doctorMessage" for="doctor"/> </h:panelGrid> </div> <div style="margin-top:20px;"> <h:commandButton value="Link" action="#{linkDoctorBean.submit()}"> <f:ajax execute="@form" render="doctorMessage"/> </h:commandButton> <h:link value="Cancel" outcome="/pages/cpanel/manage-doctors" style="margin-left:10px;"/> </div> </h:form> There are some minor differences now, such as required and the place-holder select item's value being null. Perhaps it would be best to focus on what might be going wrong with this latest snippet and forget PrimeFaces for a moment. In case it helps, here's the DoctorConverter class: @Named("doctorConverter") @RequestScoped public class DoctorConverter implements Converter, Serializable { @Override public Object getAsObject(FacesContext context, UIComponent component, String value) { UIInput in = (UIInput) component; String s = in.getSubmittedValue() != null ? in.getSubmittedValue().toString() : ""; try { long doctorId = Long.parseLong(s); Doctor doctor = doctorDao.findByDoctorId(doctorId); if (doctor == null) { throw new Exception("Doctor not found."); } return doctor; } catch (Exception e) { throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Please enter a valid doctor", null), e); } } @Override public String getAsString(FacesContext context, UIComponent component, Object value) { if (value == null || value.toString().length() == 0) { return ""; } Doctor doctor = (Doctor) value; return doctor.getDoctorId().toString(); } @EJB private DoctorDao doctorDao; } Edit: ... and here are a couple of methods from the Doctor entity class: @Override public int hashCode() { int hash = 0; hash += (doctorId != null ? doctorId.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { if (!(object instanceof Doctor)) { return false; } Doctor other = (Doctor) object; if ((this.doctorId == null && other.doctorId != null) || (this.doctorId != null && !this.doctorId.equals(other.doctorId))) { return false; } return true; } Edit: As discussed in comments, DoctorConverter.getAsObject is called three times. Here are the stack traces for the three calls in order: 1 at java.lang.Thread.dumpStack(Thread.java:1342) at com.localgp.jsf.converter.DoctorConverter.getAsObject(DoctorConverter.java:34) at com.localgp.jsf.converter.org$jboss$weld$bean-localgp-server-web-1$0-SNAPSHOT_war-ManagedBean-class_com$localgp$jsf$converter$DoctorConverter_$$_WeldClientProxy.getAsObject(org$jboss$weld$bean-localgp-server-web-1$0-SNAPSHOT_war-ManagedBean-class_com$localgp$jsf$converter$DoctorConverter_$$_WeldClientProxy.java) at com.sun.faces.renderkit.html_basic.HtmlBasicInputRenderer.getConvertedValue(HtmlBasicInputRenderer.java:171) at com.sun.faces.renderkit.html_basic.MenuRenderer.convertSelectOneValue(MenuRenderer.java:202) at com.sun.faces.renderkit.html_basic.MenuRenderer.getConvertedValue(MenuRenderer.java:319) at javax.faces.component.UIInput.getConvertedValue(UIInput.java:1030) at javax.faces.component.UIInput.validate(UIInput.java:960) at javax.faces.component.UIInput.executeValidate(UIInput.java:1233) at javax.faces.component.UIInput.processValidators(UIInput.java:698) at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1214) at javax.faces.component.UIForm.processValidators(UIForm.java:253) at com.sun.faces.context.PartialViewContextImpl$PhaseAwareVisitCallback.visit(PartialViewContextImpl.java:508) at com.sun.faces.component.visit.PartialVisitContext.invokeVisitCallback(PartialVisitContext.java:183) at javax.faces.component.UIComponent.visitTree(UIComponent.java:1589) at javax.faces.component.UIForm.visitTree(UIForm.java:344) at javax.faces.component.UIComponent.visitTree(UIComponent.java:1600) at javax.faces.component.UIComponent.visitTree(UIComponent.java:1600) at com.sun.faces.context.PartialViewContextImpl.processComponents(PartialViewContextImpl.java:376) at com.sun.faces.context.PartialViewContextImpl.processPartial(PartialViewContextImpl.java:252) at javax.faces.context.PartialViewContextWrapper.processPartial(PartialViewContextWrapper.java:183) at javax.faces.component.UIViewRoot.processValidators(UIViewRoot.java:1170) at com.sun.faces.lifecycle.ProcessValidationsPhase.execute(ProcessValidationsPhase.java:76) at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118) at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593) at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1539) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:343) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217) at com.localgp.NoCacheFilter.doFilter(NoCacheFilter.java:36) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217) at org.apache.catalina.core.ApplicationDispatcher.doInvoke(ApplicationDispatcher.java:785) at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:649) at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:483) at org.apache.catalina.core.ApplicationDispatcher.doDispatch(ApplicationDispatcher.java:454) at org.apache.catalina.core.ApplicationDispatcher.dispatch(ApplicationDispatcher.java:350) at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:300) at org.tuckey.web.filters.urlrewrite.NormalRewrittenUrl.doRewrite(NormalRewrittenUrl.java:213) at org.tuckey.web.filters.urlrewrite.RuleChain.handleRewrite(RuleChain.java:171) at org.tuckey.web.filters.urlrewrite.RuleChain.doRules(RuleChain.java:145) at org.tuckey.web.filters.urlrewrite.UrlRewriter.processRequest(UrlRewriter.java:92) at org.tuckey.web.filters.urlrewrite.UrlRewriteFilter.doFilter(UrlRewriteFilter.java:381) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217) at org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:79) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:279) at org.apache.catalina.core.StandardContextValve.__invoke(StandardContextValve.java:175) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java) at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655) at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595) at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:98) at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:91) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:162) at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:330) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231) at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:174) at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:828) at com.sun.grizzly.comet.CometEngine.executeServlet(CometEngine.java:444) at com.sun.grizzly.comet.CometEngine.handle(CometEngine.java:308) at com.sun.grizzly.comet.CometAsyncFilter.doFilter(CometAsyncFilter.java:87) at com.sun.grizzly.arp.DefaultAsyncExecutor.invokeFilters(DefaultAsyncExecutor.java:171) at com.sun.grizzly.arp.DefaultAsyncExecutor.interrupt(DefaultAsyncExecutor.java:143) at com.sun.grizzly.arp.AsyncProcessorTask.doTask(AsyncProcessorTask.java:94) at com.sun.grizzly.http.TaskBase.run(TaskBase.java:193) at com.sun.grizzly.http.TaskBase.execute(TaskBase.java:175) at com.sun.grizzly.arp.DefaultAsyncHandler.handle(DefaultAsyncHandler.java:145) at com.sun.grizzly.arp.AsyncProtocolFilter.execute(AsyncProtocolFilter.java:204) at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137) at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104) at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90) at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79) at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54) at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59) at com.sun.grizzly.ContextTask.run(ContextTask.java:71) at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532) at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513) at java.lang.Thread.run(Thread.java:722) 2 at java.lang.Thread.dumpStack(Thread.java:1342) at com.localgp.jsf.converter.DoctorConverter.getAsObject(DoctorConverter.java:34) at com.localgp.jsf.converter.org$jboss$weld$bean-localgp-server-web-1$0-SNAPSHOT_war-ManagedBean-class_com$localgp$jsf$converter$DoctorConverter_$$_WeldClientProxy.getAsObject(org$jboss$weld$bean-localgp-server-web-1$0-SNAPSHOT_war-ManagedBean-class_com$localgp$jsf$converter$DoctorConverter_$$_WeldClientProxy.java) at javax.faces.component.SelectUtils.doConversion(SelectUtils.java:191) at javax.faces.component.SelectUtils.matchValue(SelectUtils.java:99) at javax.faces.component.UISelectOne.validateValue(UISelectOne.java:153) at javax.faces.component.UIInput.validate(UIInput.java:967) at javax.faces.component.UIInput.executeValidate(UIInput.java:1233) at javax.faces.component.UIInput.processValidators(UIInput.java:698) at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1214) at javax.faces.component.UIForm.processValidators(UIForm.java:253) at com.sun.faces.context.PartialViewContextImpl$PhaseAwareVisitCallback.visit(PartialViewContextImpl.java:508) at com.sun.faces.component.visit.PartialVisitContext.invokeVisitCallback(PartialVisitContext.java:183) at javax.faces.component.UIComponent.visitTree(UIComponent.java:1589) at javax.faces.component.UIForm.visitTree(UIForm.java:344) at javax.faces.component.UIComponent.visitTree(UIComponent.java:1600) at javax.faces.component.UIComponent.visitTree(UIComponent.java:1600) at com.sun.faces.context.PartialViewContextImpl.processComponents(PartialViewContextImpl.java:376) at com.sun.faces.context.PartialViewContextImpl.processPartial(PartialViewContextImpl.java:252) at javax.faces.context.PartialViewContextWrapper.processPartial(PartialViewContextWrapper.java:183) at javax.faces.component.UIViewRoot.processValidators(UIViewRoot.java:1170) at com.sun.faces.lifecycle.ProcessValidationsPhase.execute(ProcessValidationsPhase.java:76) at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118) at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593) at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1539) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:343) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217) at com.localgp.NoCacheFilter.doFilter(NoCacheFilter.java:36) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217) at org.apache.catalina.core.ApplicationDispatcher.doInvoke(ApplicationDispatcher.java:785) at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:649) at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:483) at org.apache.catalina.core.ApplicationDispatcher.doDispatch(ApplicationDispatcher.java:454) at org.apache.catalina.core.ApplicationDispatcher.dispatch(ApplicationDispatcher.java:350) at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:300) at org.tuckey.web.filters.urlrewrite.NormalRewrittenUrl.doRewrite(NormalRewrittenUrl.java:213) at org.tuckey.web.filters.urlrewrite.RuleChain.handleRewrite(RuleChain.java:171) at org.tuckey.web.filters.urlrewrite.RuleChain.doRules(RuleChain.java:145) at org.tuckey.web.filters.urlrewrite.UrlRewriter.processRequest(UrlRewriter.java:92) at org.tuckey.web.filters.urlrewrite.UrlRewriteFilter.doFilter(UrlRewriteFilter.java:381) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217) at org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:79) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:279) at org.apache.catalina.core.StandardContextValve.__invoke(StandardContextValve.java:175) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java) at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655) at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595) at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:98) at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:91) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:162) at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:330) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231) at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:174) at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:828) at com.sun.grizzly.comet.CometEngine.executeServlet(CometEngine.java:444) at com.sun.grizzly.comet.CometEngine.handle(CometEngine.java:308) at com.sun.grizzly.comet.CometAsyncFilter.doFilter(CometAsyncFilter.java:87) at com.sun.grizzly.arp.DefaultAsyncExecutor.invokeFilters(DefaultAsyncExecutor.java:171) at com.sun.grizzly.arp.DefaultAsyncExecutor.interrupt(DefaultAsyncExecutor.java:143) at com.sun.grizzly.arp.AsyncProcessorTask.doTask(AsyncProcessorTask.java:94) at com.sun.grizzly.http.TaskBase.run(TaskBase.java:193) at com.sun.grizzly.http.TaskBase.execute(TaskBase.java:175) at com.sun.grizzly.arp.DefaultAsyncHandler.handle(DefaultAsyncHandler.java:145) at com.sun.grizzly.arp.AsyncProtocolFilter.execute(AsyncProtocolFilter.java:204) at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137) at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104) at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90) at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79) at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54) at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59) at com.sun.grizzly.ContextTask.run(ContextTask.java:71) at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532) at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513) at java.lang.Thread.run(Thread.java:722) 3 at java.lang.Thread.dumpStack(Thread.java:1342) at com.localgp.jsf.converter.DoctorConverter.getAsObject(DoctorConverter.java:34) at com.localgp.jsf.converter.org$jboss$weld$bean-localgp-server-web-1$0-SNAPSHOT_war-ManagedBean-class_com$localgp$jsf$converter$DoctorConverter_$$_WeldClientProxy.getAsObject(org$jboss$weld$bean-localgp-server-web-1$0-SNAPSHOT_war-ManagedBean-class_com$localgp$jsf$converter$DoctorConverter_$$_WeldClientProxy.java) at javax.faces.component.SelectUtils.doConversion(SelectUtils.java:191) at javax.faces.component.SelectUtils.valueIsNoSelectionOption(SelectUtils.java:150) at javax.faces.component.UISelectOne.validateValue(UISelectOne.java:159) at javax.faces.component.UIInput.validate(UIInput.java:967) at javax.faces.component.UIInput.executeValidate(UIInput.java:1233) at javax.faces.component.UIInput.processValidators(UIInput.java:698) at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1214) at javax.faces.component.UIForm.processValidators(UIForm.java:253) at com.sun.faces.context.PartialViewContextImpl$PhaseAwareVisitCallback.visit(PartialViewContextImpl.java:508) at com.sun.faces.component.visit.PartialVisitContext.invokeVisitCallback(PartialVisitContext.java:183) at javax.faces.component.UIComponent.visitTree(UIComponent.java:1589) at javax.faces.component.UIForm.visitTree(UIForm.java:344) at javax.faces.component.UIComponent.visitTree(UIComponent.java:1600) at javax.faces.component.UIComponent.visitTree(UIComponent.java:1600) at com.sun.faces.context.PartialViewContextImpl.processComponents(PartialViewContextImpl.java:376) at com.sun.faces.context.PartialViewContextImpl.processPartial(PartialViewContextImpl.java:252) at javax.faces.context.PartialViewContextWrapper.processPartial(PartialViewContextWrapper.java:183) at javax.faces.component.UIViewRoot.processValidators(UIViewRoot.java:1170) at com.sun.faces.lifecycle.ProcessValidationsPhase.execute(ProcessValidationsPhase.java:76) at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118) at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593) at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1539) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:343) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217) at com.localgp.NoCacheFilter.doFilter(NoCacheFilter.java:36) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217) at org.apache.catalina.core.ApplicationDispatcher.doInvoke(ApplicationDispatcher.java:785) at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:649) at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:483) at org.apache.catalina.core.ApplicationDispatcher.doDispatch(ApplicationDispatcher.java:454) at org.apache.catalina.core.ApplicationDispatcher.dispatch(ApplicationDispatcher.java:350) at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:300) at org.tuckey.web.filters.urlrewrite.NormalRewrittenUrl.doRewrite(NormalRewrittenUrl.java:213) at org.tuckey.web.filters.urlrewrite.RuleChain.handleRewrite(RuleChain.java:171) at org.tuckey.web.filters.urlrewrite.RuleChain.doRules(RuleChain.java:145) at org.tuckey.web.filters.urlrewrite.UrlRewriter.processRequest(UrlRewriter.java:92) at org.tuckey.web.filters.urlrewrite.UrlRewriteFilter.doFilter(UrlRewriteFilter.java:381) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217) at org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:79) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:279) at org.apache.catalina.core.StandardContextValve.__invoke(StandardContextValve.java:175) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java) at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655) at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595) at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:98) at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:91) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:162) at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:330) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231) at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:174) at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:828) at com.sun.grizzly.comet.CometEngine.executeServlet(CometEngine.java:444) at com.sun.grizzly.comet.CometEngine.handle(CometEngine.java:308) at com.sun.grizzly.comet.CometAsyncFilter.doFilter(CometAsyncFilter.java:87) at com.sun.grizzly.arp.DefaultAsyncExecutor.invokeFilters(DefaultAsyncExecutor.java:171) at com.sun.grizzly.arp.DefaultAsyncExecutor.interrupt(DefaultAsyncExecutor.java:143) at com.sun.grizzly.arp.AsyncProcessorTask.doTask(AsyncProcessorTask.java:94) at com.sun.grizzly.http.TaskBase.run(TaskBase.java:193) at com.sun.grizzly.http.TaskBase.execute(TaskBase.java:175) at com.sun.grizzly.arp.DefaultAsyncHandler.handle(DefaultAsyncHandler.java:145) at com.sun.grizzly.arp.AsyncProtocolFilter.execute(AsyncProtocolFilter.java:204) at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137) at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104) at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90) at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79) at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54) at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59) at com.sun.grizzly.ContextTask.run(ContextTask.java:71) at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532) at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513) at java.lang.Thread.run(Thread.java:722) And here's the current form in the JSF page: <h:form id="form"> <!-- Validating here instead of at the selectOneMenu level due to its invalidity not being cleared. --> <div style="clear:both;"> <h:panelGrid columns="2"> <h:selectOneMenu id="doctor" value="#{linkDoctorBean.doctor}" converter="#{doctorConverter}" converterMessage="Please select a doctor" style="width:200px;" required="true"> <f:selectItem itemLabel="Select a doctor" itemValue="" noSelectionOption="true"/> <f:selectItems value="#{linkDoctorBean.doctors}" var="doctor" itemLabel="#{stringBean.doctorToString(doctor)}" itemValue="#{doctor}"/> </h:selectOneMenu> <p:message id="doctorMessage" for="doctor"/> </h:panelGrid> </div> <div style="margin-top:20px;"> <h:commandButton value="Link" action="#{linkDoctorBean.submit()}"> <f:ajax execute="@form" render="doctorMessage"/> </h:commandButton> <h:link value="Cancel" outcome="/pages/cpanel/manage-doctors" style="margin-left:10px;"/> </div> </h:form> Edit: Removed <f:ajax/> and DoctorConverter.getAsObject is still being called three times. A: Your converter is broken. It has to convert the value based on the value argument, not the UIInput#getSubmittedValue(). The noSelectionOption value is namely also passed through the converter (as the 3rd trace hints). If your real submitted value equals the noSelectionOption value, then the value is considered as not valid, hence the validation error. I also suggest other minor rewrites; empty strings should be nulls. @Override public String getAsString(FacesContext context, UIComponent component, Object modelValue) { if (modelValue == null) { return ""; } if (modelValue instanceof Doctor) { Long id = ((Doctor) modelValue).getId(); return (id != null) ? String.valueOf(id) : null; } else { throw new ConverterException(new FacesMessage(modelValue + " is not a valid Doctor")); } } @Override public Object getAsObject(FacesContext context, UIComponent component, String submittedValue) { if (submittedValue == null || submittedValue.isEmpty()) { return null; } try { Long id = Long.valueOf(submittedValue); return doctorService.find(id); } catch (NumberFormatException e) { throw new ConverterException(new FacesMessage(submittedValue + " is not a valid Doctor ID")); } } Note that I have this in my web.xml as well: <context-param> <param-name>javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL</param-name> <param-value>true</param-value> </context-param> Update: as per the comments, thanks to <h:messages/> there turns out to be something else which is been required. Finally it turns out to be a <f:viewParam required="true"> which is been reinvoked on ajax postback. To prevent this, instead use <f:viewParam ... required="#{not facesContext.postback}" /> A: The following: converter="#{doctorConverter}" must be written as: converter="doctorConverter"
{ "language": "en", "url": "https://stackoverflow.com/questions/7618960", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: JBoss Cache Cluster Issue In our production environment we have three JBoss servers loadbalanced for application requests, client applications session has been maintained JBoss-cache with clustered enabled to make sure that all three servers should get the session object. All went fine in production for the past three months and it was very consistent. All of the sudden for the last one week we have an issue with cache replication and buddy backup listing. Following are the issues creeped recently. * *Replication between identified servers stopped suddenly. *Buddy_BACKUP list getting removed automatically. We are running with JBoss Cache and JGroups in UDP mode. We couldnt trace any logs related to this events, please advise what could be the cause. Since this issue is not resolved, we are planning to migrate this to TCP mode will that solve such discrepancy. Please advise. 12:45 please revise the forumn question Jboss Version : 4.2.2 GA JDK : 1.6 JBoss Cache : 1.4.1
{ "language": "en", "url": "https://stackoverflow.com/questions/7618966", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to Hide Video view's Seekbar or Progressbar in android i am doing live streaming and play video in video view. i want to hide default progress bar of video view . so i kindly request for my problem if anybody have good solution for my problem please send me. Thanx in advance....... A: You have to set the media controller as null like this: videoView.setMediaController(null); A: Below is the code which adds the seek bar when using videoview So if you have used the code below please comment it and then check whether you still have a seekbar while viewing the video MediaController mediaController=new MediaController(this); mediaController.setAnchorView(videoView); videoView.setMediaController(mediaController) Cheers!!! A: videoView.setMediaController(null); A: I was able to get the SeekBar hidden with the help of following : public void hidingSeekBar() { final int topContainerId1 = getResources().getIdentifier("mediacontroller_progress", "id", "android"); final SeekBar seekbar = (SeekBar) mediaController.findViewById(topContainerId1); seekbar.setVisibility(View.INVISIBLE); final int topContainerId2 = getResources().getIdentifier("time", "id", "android"); final TextView mEndTime = (TextView) mediaController.findViewById(topContainerId2); mEndTime.setVisibility(View.INVISIBLE); final int topContainerId3 = getResources().getIdentifier("time_current", "id", "android"); final TextView mCurrentTime = (TextView) mediaController.findViewById(topContainerId3); mCurrentTime.setVisibility(View.INVISIBLE); // mEndTime, mCurrentTime; } P.S: I got the reference to the MediaController controls here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618968", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Parsing xml-like data I have a string with xml-like data: <header>Article header</header> <description>This article is about you</description> <text>some <b>html</b> text</text> I need to parse it into variables/object/array "header", "description", "text". What is the best way to do this? I tried $vars = simplexml_load_string($content), but it does not work, because it is not 100% pure xml (no <?xml...). So, should I use preg_match? Is it the only way? A: Your XML string looks like (though may or may not be) an XML document fragment. PHP can work with this using the DOMDocumentFragment class. $doc = new DOMDocument; $frag = $doc->createDocumentFragment(); $frag->appendXML($content); $parsed = array(); foreach ($frag->childNodes as $element) { if ($element->nodeType === XML_ELEMENT_NODE) { $parsed[$element->nodeName] = $element->textContent; } } echo $parsed['description']; // This article is about you A: With a string like that, simlexml_load_string should work. Because of the 3rd tag, if you try to get that it will fail, and not return the correct value (because there is a sub part within the tag. Try something like this, which might work for you: $xml = simplexml_load_string($content) $text = $xml->text->asXML(); You should also take a look at this documentation: http://www.php.net/manual/en/simplexmlelement.asxml.php. They also do the same thing with the string. You might wanna use this option instead of simplexml_load_string too $xml = new SimpleXMLElement($string);
{ "language": "en", "url": "https://stackoverflow.com/questions/7618974", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I create my desired string using a byte array? I have the following byte array: byte[] bytes = new byte[] { (byte) -61, (byte) -61}; At first I convert it to String using the following line: strResult = new String(bytes, "ISO_8859_1"); Then I convert it back to byte array using the following code: byte[] myBytes = strResult.getBytes(); The content of myBytes is [-61, -125, -61, -125] I have tested "US-ASCII" and "UTF-8" charsets. Each one returns a deferent string that none of them is [-61, -61]. How can I create a String containing [-61, -61] bytes? I mean I want to have a string when I use getBytes(); it returns [-61, -61] bytes. How can I create it? A: You should use the same encoding to convert back again: byte[] myBytes = strResult.getBytes("ISO_8859_1"); Basically the string doesn't maintain any record of the encoding originally used to create it - it's always just a sequence of UTF-16 code units. If you don't specify the encoding to use when converting a string to a byte array, it uses the platform default encoding. Note that if you're trying to encode arbitrary binary data as text (i.e. you're not decoding something which is genuinely text in a particular encoding) then you shouldn't use these methods at all - you should use Base64 to encode and decode safely.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618975", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Creating an Interactive map using an Image not google map I want to create a map view using a static image, so I can enlarge the image, minimize it, and if I click on a specific place on the image a message with the clicked place name appear. I'm using titanium for android and iPhone. Is it possible? Note that I create this map but the problem I have that if I click on the image after enlarge it the message that appear will not be correct because the x and y will differ. I need to enlarge the image cause it contain very small building. I hope my Question is clear. A: Introduce a scaling factor so that when you increase the image size you can apply the scaling factor to the clicked x and y coordinates which should give you what they would have been on the original image, and then use those when retrieving your message. if you can pan the image, then you will also need to introduce a panning factor also.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618977", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to create pretty URLs (permalinks) for website on Java? I would like to make pretty URLs for my web projects on Java. For example, I have URLs like these: * *www.mysite.com/web/controller?command=showNews&newsId=1 *www.mysite.com/web/controller?command=showNews&newsId=2 *www.mysite.com/web/controller?command=showNews&newsId=3 or * *www.mysite.com/web/user.do?action=start *www.mysite.com/web/user.do?action=showCategory&category=videoGames&section=AboutGames But it isn't so pretty and userfriendly... I want to make links like these: * *www.mysite.com/web/2011/10/04/Steve-Jobs-iPhone-5/ *www.mysite.com/web/2011/10/23/Facebook-Timeline/ *www.mysite.com/web/2012/05/25/Vladimir-Putin-Russian-President/ Сan you help me with this? How can I get it? It's possible to use any Java frameworks or libs if it's help. Thank you! Update: I found solution - Spring MVC with Controller's @RequestMapping("/Putin") annotation for example. A: Context Framework allows you to do just that. For instance the examples you gave could be mapped like this in a view: @View(url="regex:/web/<year:\\d{4}>/<month:\\d{2}>/<day:\\d{2}>/<specifier>") @PageScoped public class ArticleView extends Component implements ViewComponent { @PathParam private long year; @PathParam private long month; @PathParam private long day; @PathParam private String specifier; @Override public void initialize(ViewContext context) { System.out.println(year+"/"+month+"/"+day+"/"+specifier); // Then do something } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7618978", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: wp7 Display string in webbrowser or otherway? string a="hi <p> how </p> are <Br> you?</Br>"; How can avoid this tags <p> </p><Br> </Br>. In output coming like that : Hi how are you? If anyone know the answer help me. A: You can call NavigateToString to render custom HTML in a WebBrowser control: string html = "<html><body>hi <p> how </p> are <br /> you?</body></html>"; webBrowser.NavigateToString(html);
{ "language": "en", "url": "https://stackoverflow.com/questions/7618979", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Adding UISearchBar as tableHeaderView in xib not works I added UISearchBar as tableHeaderView for UITableView in xib, by just dropping UISearchBar onto UITableView. It is working fine, when the table has more than 6 rows. But when there is less than 6 rows, it UITableView does not scroll. At the same time, if i add the UISearchBar as tableHeaderView for UITableView programatically in .m file using the following statement, EVERYTHING WORKS FINE. tableViewTemp.tableHeaderView = searchBarFriends; Seems very strange to me, What might be the problem? Please advice, Thank you. A: Here is a little trick I did ;) Don't make your SearchBar a subview of your UITableView. Just add instances of them both in your nib file and wire them up as IBOutlets in your UITableViewController. Then what you are going to do is set the SearchBar as the header view for your table, that way you don't have to worry about the frames overlapping and interfering with touch events. Here's how you do it: Create the property in your TableView header file @property ( nonatomic, retain ) IBOutlet UISearchBar *searchBar; Set the header view for your table: - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { return self.searchBar; // The property you wired up in IB } Set the height for your header or (UISearchBar) - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section { return 44; // The height of the search bar } That's all you need. Now this may not be the best solution if you have a grouped tableview or a table with multiple sections but its a clean solution for a simple table. Otherwise, you'd have to adjust the frame of the searchbar AND the tableview in code because they overlap and thats why you have touch issues. Hope this helps! A: if you add search bar like below hierarchy it will work A: I had almost the same problem (for me it wouldn't scroll at all with any number of rows, but it would as soon as I removed the search bar). Fixed it adding this in viewDidLoad: self.tableView.alwaysBounceVertical = YES;
{ "language": "en", "url": "https://stackoverflow.com/questions/7618980", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Let users visit other users (profiles) in my own written social community? The thing I'm asking for is how the users can visit other users profile. The past week I have been scripting a social network I'm doing, and I'm kind of stuck right now. I don't know where to start and read or anything. So I'm asking you guys to kindly help me =) Im thinking of the url to be like user.php?id=123 looking and get user you are visiting to show up instead of "you" wich is at user.php! Live demo: http://social.swipper.org EDIT #2: Here's the current code i got inside user.php : <?php session_start(); if($_SESSION['username']) { include "config.php"; $username = $_SESSION['username']; $fetcher = mysql_query("SELECT * FROM userinfo WHERE username='$username'"); while ($data = mysql_fetch_assoc($fetcher)){ $firstname = $data['firstname']; $lastname = $data['lastname']; $gender = $data['gender']; } // get user's profile image if (file_exists("users/$username/profile.jpg")) { $userPhoto = "<img class='pic' src='users/$username/profile.jpg' width='90%' height='30%' />"; } elseif (!file_exists("users/$username/profile.jpg")) { $userPhoto = "<img class='pic' src='http://www.uavmedia.com/portal/images/no-user.jpg' width='90%' height='30%' />"; } // the user's profile image is fetched // henter profil text $file = "users/$username/bio.txt"; $contents = file($file); $profile_text = implode($contents); // ferdig å hente profil text, vil nå echo ut profil siden. // henter profil stilsett $file2 = "users/$username/style.css"; $contents2 = file($file2); $profile_style = implode($contents2); // ferdig å hente profil stilsett. echo " <!doctype html> <html lang='en'> <head> <title>Social FW</title> <meta name='Description' content='A Social network for everyone. Come join us!' /> <meta name='Keywords' content='Social, Network, Framewerk, Framework, FW, Open-Source, Free' /> <link rel='stylesheet' type='text/css' href='user_files/style.css' media='screen' /> <link rel='stylesheet' type='text/css' href='SFW_files/style2.css' media='screen' /> <style type='text/css'> $profile_style </style> <link rel='icon' href='SFW_files/favicon.ico' media='screen' /> <script type='text/javascript' src='http://code.jquery.com/jquery-latest.js'></script> <script type='text/javascript' src='SFW_files/scripts/login.js'></script> </head> <body> <div id='top'> <h1>Swipper.org</h1> </div> <div id='side-menu'> <ul> <li><a href='user.php'><b>".$username."</b></a></li><br/> <li><a href=''>Inbox</a></li> <li><a href=''>Guestbook</a></li> <li><a href=''>Friends</a></li> <li><a href=''>Pictures</a></li><br /> <div id='showOptions'><li><a href='#'>Edit Profile</a></li></div> <div id='editOptions' style='display:none;'> <pre class='user_info'><b>></b><a href='changeText.php'>Edit Profile Text</a> <b>></b><a href='changeCss.php'>Edit Stylesheet(CSS)</a> <b>></b><a href='changeProfilePic.php'>Change Profile Image</a></pre> </div><br /> <a href='logout.php'><b>Logout</b></a> </ul> </div> <div id='side-left'> <!-- START USER PIC --!> <center> $userPhoto<br /> </center> <!-- END USER PIC --!> <!-- START USER INFO --!> <br /> <h3><pre class='user_info'>User Info</pre></h3> <pre class='user_info'>Name: ".$firstname." ".$lastname."<br />Sex : $gender</pre> <!-- END USER INFO --!> </div> <div id='box_center'> <h2 style='font-size:30px;' align='center'>$username</h2> <hr /> <br /> $profile_text </div> <div id='footer'> <p align='center'>Swipper.org &copy; All rights reserved. 2010-2012</p> </div> </body> </html> "; } else { die("You need to login first or register. You can register/login <a href='index.php'>here</a>!"); } ?> and when the url is like: user.php?id=3 i want to get the user with userid 3 to show up, and get user #3's information instead of the "user" who wants to visit other people. A: Are you listing all the users some where? if you are the href needs to be something like <?php $sql = mysql_query("SLECET * FROM userinfo"); while ($row = mysql_fetch_assoc($sql)){ echo "<a href='users.php?id=" . $row['id'] . "'>" } then in users.php <?php if(isset($_REQUEST['id'])) { if(is_numeric($_REQUEST['id'])){ $uid = $_REQUEST['id']; $sql = mysql_query("SELECT * FROM userinfo WHERE id='" . $uid . "' LIMIT 1"); } } else { $sql = mysql_query("SELECT * FROM userinfo WHERE username='" . $_SESSION['username'] . "' LIMIT 1"); } then later your html can use that with a fetch_assoc($sql) <table> <tr> <td><?php echo $row['username'] ?>'s Profile</td> </tr> </table> simple example. but i think you get the picture, message me on FB for more on this Stian A: Make your query like $userID = $_GET['id']; $fetcher = mysql_query("SELECT * FROM userinfo WHERE userID='$userID'"); and you can accordingly show data for any user with the valid user ID as given in url. if profile can be viewed without login too then there is no need of session and if its compulsory only check if isset or not. if you are passing username in url as user.php?user=test1 then your query will be like $username = $_GET['user']; $fetcher = mysql_query("SELECT * FROM userinfo WHERE username='$username'"); Hope now its more clear to u. A: This should be your answer: if (isset($_GET['username']){ $username = mysql_escape_string($_GET['username']); }else{ $username = $_SESSION['username']; } $fetcher = mysql_query("SELECT * FROM userinfo WHERE username='$username'"); if (mysql_num_rows() == 0){ $username = ''; echo 'Username not found'; die(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7618985", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Openssl asymmetric encryption without salt (in php) I need to encrypt a string data with SSH-2 RSA 1024 bit ( with the public key ) then with RMD-160 algorithm. I do it like this: generate private key: openssl genrsa -des3 -out privatekey.key 1024 public key: openssl rsa -in privatekey.key -pubout -out public.pem encrypt the data: openssl rsautl -encrypt -inkey public.pem -pubin -in file.txt -out encrypted_data.txt But , the request is: need to get the same output with the same input! For example if the input string is "some data" and the encrypted string is "a23c40327a6c5a67a5bb332" then i need to get the "a23c40327a6c5a67a5bb332" output every time when the input is "some data" Can i do it with asymmetric encryption? I know it can be done with symmetric encryption like DES with the -nosalt option openssl des3 -nosalt -in file.txt -out file.des3 but is it possible with asymmetric encryption? A: Probably not. The man page for openssl shows that the rsautl sub-command accepts pkcs1 1.5 padding, oaep padding, backwards-compatible SSL padding or no padding. All of these (except no padding) generate random data to pad the message, so no two encryptions will generate that same ciphertext (this is a good thing). If you can manually pad your data to the right length then you might be able to use no padding but be warned that this will significantly weaken your security. A: Cameron Skinner is right - you should be making use of randomized padding. That said, if you don't want to, you can use phpseclib, a pure PHP RSA implementation, to do so, as follows: $ciphertext = base64_decode('...'); $ciphertext = new Math_BigInteger($ciphertext, 256); echo $rsa->_exponentiate($ciphertext)->toBytes(); It's a hackish solution since phpseclib doesn't natively let you do RSA encryption without randomized padding but it does get the job done.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618991", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Python download all files from internet address? I want to download all files from an internet page, actually all the image files. I found the 'urllib' module to be what I need. There seems to be a method to download a file, if you know the filename, but I don't. urllib.urlretrieve('http://www.example.com/page', 'myfile.jpg') Is there a method to download all the files from the page and maybe return a list? A: Here's a little example to get you started with using BeautifulSoup for this kind of exercise - you give this script a URL, and it will print out the URLs of images that are referenced from that page in the src attribute of img tags that end with jpg or png: import sys, urllib, re, urlparse from BeautifulSoup import BeautifulSoup if not len(sys.argv) == 2: print >> sys.stderr, "Usage: %s <URL>" % (sys.argv[0],) sys.exit(1) url = sys.argv[1] f = urllib.urlopen(url) soup = BeautifulSoup(f) for i in soup.findAll('img', attrs={'src': re.compile('(?i)(jpg|png)$')}): full_url = urlparse.urljoin(url, i['src']) print "image URL: ", full_url Then you can use urllib.urlretrieve to download each of the images pointed to by full_url, but at that stage you have to decide how to name them and what to do with the downloaded images, which isn't specified in your question.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618993", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Errors when using two Asynchronous ASIHTTP Requests in different classes Suppose i have two classes A & B. class A calls the asynchronus method Foo in class B. Foo method fetches data using asynchronous ASIHTTPRequest and send the data from Foo back as the return value to Class A. Class A will use that returned data and do the things I am creating a object of my class URLParser here in another class and calling the function getJsonUrl , it will parse and get the json url for me . I am using that returned URL in another ASIHTTPRequest here . But i am getting EXC_BAD_ACCESS ...help me to figure it out .... ...... URLParser *urlParser = [[URLParser alloc] init]; NSString *JsonString = [urlParser getJsonUrl:@"http://mywebs.com/?q=iphone/news"]; NSLog(@" url returned = %@" ,JsonString); NSURL *JsonUrl = [NSURL URLWithString:JsonString]; newsRequest = [ASIHTTPRequest requestWithURL:JsonUrl]; [newsRequest setDelegate:self]; [newsRequest startAsynchronous]; } - (void)requestFinished:(ASIHTTPRequest *)request { newsDictionary = [[NSMutableDictionary alloc] init]; NSData *responseData = [request responseData]; NSString *response = [[NSString alloc] initWithData:responseData encoding:NSASCIIStringEncoding] ; self.newsDictionary = [response JSONValue]; [response release]; [self getDataNews:self.newsDictionary]; } URL Parser Class @synthesize albumDic; @synthesize GlobalRequest; -(NSString*)getJsonUrl:(NSString *)url{ GlobalRequest = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:url]]; [GlobalRequest setDelegate:self]; [GlobalRequest startAsynchronous]; // when i called the [GlobalRequest startSynchronous] ....both cases m getting the same error return JsonStr; } - (void)requestFinished:(ASIHTTPRequest *)request{ albumDic = [[NSMutableDictionary alloc] init]; NSData *responseData = [request responseData]; NSString *response = [[NSString alloc] initWithData:responseData encoding:NSASCIIStringEncoding] ; self.albumDic = [response JSONValue]; [response release]; [self GetDictionary:self.albumDic]; } - (void)requestFailed:(ASIHTTPRequest *)request{ [request cancel]; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7618999", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Replacing HTML with Javascript in a way that is executable in a browser I have no Javascript experience at all. What I want is to replace a single instance of a block of text in a page's HTML - how can I do this? 30 minutes of reading around has brought me this: javascript:document.body.innerHTML = document.body.innerHTML.replace("this","that"); Am I even close? A: With no experiance at all I recommend you take a look at jQuery. With jQuery you can do: Given: <p>block of text</p> jQuery: $('p').text("some other block of text"); A: javascript:document.body.innerHTML = "that" A: 1) If it is part of a URL, such as <a href="...">, then you need javascript:void(document.body.innerHTML = document.body.innerHTML.replace("this","that")); 2) If it is part of an event, such as <button onClick="...">, then you need document.body.innerHTML = document.body.innerHTML.replace("this","that"); 3) If you are trying to replace ALL instances of "this" with "that", and not just the first, then you need ... .replace(/this/g,"that") A: You cannot just execute that script in the address bar. It needs to operate on a document, but there is nothing to replace there. Executing javascript from the address bar will give you a new empty document on which that code operates. Even if you try to load a document from javascript, the rest of your script gets executed first. Try this: javascript:window.location='http://www.google.com';alert(document.innerHTML); You'll see that the alert pops up before the page is loaded, and it shows 'undefined'. Even when you try binding to the onload event of the document or the window it won't work. Probably because they are reset afterwards. javascript:window.location='http://www.google.com';window.onload=function(){alert(document.innerHTML);}; And it makes sense; if this would work, you could manipulate the next page when jumping to that page, thus making it possible to inject javascript in a page you link to. That would be a big security issue, so it's a good thing this doesn't work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619004", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-4" }
Q: Facebook Canvas JavaScript Links Don't Work We are using ASP.NET for our Canvas Page, however none of the link buttons (JavaScript Post Backs) work when using FireFox. After a bit of investigation it appears that any javascript link i.e. <a href="javascript:..."> will not run. When viewing the iFrame outside of Facebook the links work as expected. Bizarrely javascript on an "onclick" event does work correctly. Facebook Canvas: http://apps.facebook.com/ukflive/test.aspx Any thoughts on why this is happening, and how to resolve this? Other browsers such as Safari and Chrome do not have this issue. Many Thanks,Ady A: In some versions of firefox i've met same problem but i wasn't able to find out reason of problem since i've seen your question. thank you for this :). In my opinion it is a firefox bug working with iframes, and it is related with security concerns. i've changed all <a href="javascript:anyJSFunction()"> codes to <a href="javascript:;" onclick="anyJSFunction"> and it works for my application.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619007", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP Calling A Method Statically; Even Though Its Not Defined As Static How is this working? Shouldn't this throw an error, since I am trying to call a non static method statically? Basically, I've never instantiated an object of type something. class Something { public function helloworld() { echo 'hello world'; } } Something::helloworld(); A: Put this at the top of your script: error_reporting( E_ALL | E_STRICT ); // E_STRICT is important here ini_set( 'display_errors', true ); ... and see what happens then: Strict Standards: Non-static method Something::helloworld() should not be called statically in [...] Admittedly, it more of a notice than an error though. Your script will happily continue to run. A: It would only give you an error, if within helloworld() you'd be using $this. It's a type of PHP "WTF" resulting from missing specs that allows you to statically invoke a function not actually declared static.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619011", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jQuery Modal Window Displayed Under Mask I'm newbie in jQuery and i have a problem creating modal windows. My modal window is displayed under the mask. I want it to be displayed on top of the mask. I'm not being able to figure out the problem so need some assistance on this one. Here's the code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Modal Windows</title> <style type='text/css'> #overlay { display: none; top: 0; right: 0; bottom: 0; left: 0; margin-right: auto; margin-left: auto; position: fixed; width: 100%; height: 100%; background: #000; z-index: 1; } #modal { position: auto; display: none; margin-left: auto; margin-right: auto; color: #F00; z-index: 100; } </style> <script type='text/javascript' src='../javascript/jquery.js'></script> <script type="text/javascript"> $(document).ready(function () { $("#click").click(function() { $('#overlay').css({ 'display' : 'block', opacity : 0}); $('#overlay').fadeTo(500,0.8); $('#modal').show(); }); }); </script> </head> <body> <a href="#" id="click">Click me</a> <div id="modal">This is modal</div> <div id="overlay"> </div> </body> </html> A: This isn't a problem with your jQuery, this is a problem with your CSS. You set the Modal to position:auto which means that it is static positioned (static is the default) and is not affected by z-index. Just change the positioning to anything else and it will work. (relative, absolute, or fixed) Example: http://jsbin.com/unifum Positioning is the backbone of HTML and CSS, you should learn more about it (especially absolute positioning, that can be a very useful tool once you know how to use it correctly)
{ "language": "en", "url": "https://stackoverflow.com/questions/7619012", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Add SuggestBox to CellTable as an editable cell Is there any way to SuggestBox to CellTable? Maybe there is another solution then SuggestBox? I need to get an editable cell with suggestion feature? I'm using GWT 2.4. A: I don't think you can add it directly in. Try using a ClickableTextCell as the cell for that column. Then code your ValueUpdater (which will be called when the cell is clicked) to open up a DialogBox. Put your SuggestBox, and other widgets (OK button, Cancel button, and such), inside that DialogBox. Initialize the SelectionBox with the current contents of the cell. The DialogBox will likely be a DialogBox subclass with extra state data you initialize with the object for that CellTable row as well as the field for that column, so that the OK action knows what field on what object to update with the new contents of the SuggestBox. Essentially it's a popup editor. Not ideal, because users will expect the editor to be embedded in the CellTable, but there are only a few cell editors available (EditTextCell, DatePickerCell, SelectionCell and CheckboxCell, and maybe another variant of text editing), but I've used this technique, and really, it's not too bad. A: I ended up using FlexTable instead of CellTable. With FlexTable you may put any widget inside a table cell. A: I needed this also and found a solution (under testing, but solong it is working): I copied the Code from TextInputCell into a new Class SuggestBoxTextInputCell public class SuggestBoxTextInputCell extends AbstractInputCell<String, SuggestBoxTextInputCell.ViewData> { MySuggestBox suggestBox; and added some lines to the onBrowserEvent method: // Ignore events that don't target the input. InputElement input = getInputElement(parent); String eventType = event.getType(); if (BrowserEvents.FOCUS.equals(eventType)) { TextBox textBox = new MyTextBox(input); suggestBox = new MySuggestBox(getSuggestOracle(), textBox); suggestBox.onAttach(); } Element target = event.getEventTarget().cast(); The classes MySuggestBox and MyTextbox exist only to make the needed constructor and methods public: private class MyTextBox extends TextBox { public MyTextBox(Element element) { super(element); } } private class MySuggestBox extends SuggestBox { public MySuggestBox(SuggestOracle suggestOracle, TextBox textBox) { super(suggestOracle, textBox); } @Override public void onAttach() { super.onAttach(); } } getSuggestOracle() only delivers the needed SuggestOracle. Hope someone can use this solution. A: I needed this as a solution so I play around with the solution provided by Ande Hofer. The exact same issue met by Ankit Singla, when the suggestbox is working fine when I press "Enter" key, but not from the "Mouse Click". I go on further and add-on this onto the solution. if (BrowserEvents.FOCUS.equals(eventType)) { ... ... suggestbox.addSelectionHandler(new SelectionHandler<Suggestion>() { @Override public void onSelection(SelectionEvent<Suggestion> event) { Suggestion selectedSuggestion = event.getSelectedItem(); String selectedValue = selectedSuggestion.getReplacementString(); onSuggestSelected(input, selectedValue, valueUpdater); } }); suggestbox.onAttach(); } and a private function private void onSuggestSelected(Element input, String value, ValueUpdater<String> valueUpdater) { input.blur(); suggestbox.onDetach(); if (suggestbox.getSuggestionDisplay().isSuggestionListShowing()) { ((DefaultSuggestionDisplay) suggestbox.getSuggestionDisplay()).hideSuggestions(); } valueUpdater.update(value); } So far so good.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619015", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: JavaFX when will be available for Linux world? Will Oracle make JavaFX like Flash policy to make Linux developers impossible to get it? I am looking for JavaFX under Linux Ubuntu/Fedora/OpenSuse/Gentoo/TinycoreLinux/MicrocoreLinux But none of the OS have a single JavaFX latest coding emulators, it will be too late as Linux developers to learn it if it arrives after 10 year or even after few years. Because its already available only for Windows users. Not everyone is wiling to switch to Windows because of many other reasons involved.Do we have to force ourselves only to have JavaFX buy Windows PC? (its again Microsoft behind?) So my question is, How can i get the JavaFX under Linux? (latest version) A: It's in the FAQ: What operating systems are supported by JavaFX? JavaFX 2.0 will be fully supported on 32-bit and 64-bit versions of Microsoft Windows XP, Windows Vista, and Windows 7. Early Access versions of JavaFX 2.x for Mac OS and Linux will be made available at a later date, but support for these platforms will not be included as part of the JavaFX 2.0 final release. Updated JavaFX roadmap on oct 13 2011: JavaFX for Linux JavaFX will be officially tested and supported on Ubuntu—the most popular Linux distribution on desktop PCs—but is expected to run 'as is' with other Linux distributions. JavaFX for Linux is planned for release in the end of 2012. JavaFX for Mac OS X JavaFX 2.0 for Mac OS X, which has been available since February 2011 to a limited number of participants, is now available for download as a Developer Preview. While this beta version can be currently tested on Mac OS X Snow Leopard (v 10.6) with Apple's implementation of Java SE 6, the GA1 version will be supported on only Mac OS X Lion (v 10.7) with Oracle's implementation of Java SE 7 for Mac OS X. A: JavaFX 2.1 Developers preview for Linux was released today: http://www.oracle.com/technetwork/java/javafx/downloads/devpreview-1429449.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7619018", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Compare value obtained from textbox in asp(vb) using SQL Server database I am using asp(vb) In SQL Server database I made a table cars which has two columns: * *productid int *name varchar(50) Now I am collecting the value of name attribute from user through a text field: Enter car name <input type="text" name="name" value="" /> and storing it in a variable: name = Request.Form("name") But when I run this query, it gives error: query = "SELECT * FROM cars where name = " & name Unable to figure out why? A: I think u first run a query for INSERT the data A: Using MSSql Server? Try: query = "SELECT * FROM cars where [name] = " & name Note the [] around the name column. A: Because name is defined as a VARCHAR string datatype, this would mean you need to quote the value of name in your SQL query, ie query = "SELECT * FROM cars WHERE name = '" & name & "'" or better still, use a parameterised query via a ADODB.Command object if you're using ADODB
{ "language": "en", "url": "https://stackoverflow.com/questions/7619024", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jquery save multiple cookie for every link I have lots of links in the page, click each one addClass 'voted' to this link. then save the effection into cookies. so that next time refresh web browser, it will save the addClass event. My code here, but it will only save 1 cookie. I mean if I clicked link 1, link 2. it always remember the last click. refresh the web browser. only link 2 addClass 'voted'. link1 missed addClass event. so how to save multiple cookie for every link? Thanks. <script type="text/javascript" src="script/jquery.js"></script> <script type="text/javascript" src="script/cookie.js"></script> <script type="text/javascript"> $(document).ready(function(){ var cookieName = 'up'; var cookieOptions = {expires: 7, path: '/'}; $("#" + $.cookie(cookieName)).addClass('voted'); $(".up").live('click',function(e){ e.preventDefault(); $.cookie(cookieName, $(this).attr("id"), cookieOptions); // save cookie depends on each link id. $("#" + $.cookie(cookieName)).addClass('voted'); }); }); </script> <a href="javascript:void(0)" id="m12345678" class="up">link 1</a> <a href="javascript:void(0)" id="m12345679" class="up">link 2</a> <a href="javascript:void(0)" id="m12345680" class="up">link 3</a> Upload my code in: jsfiddle A: change the cookie-name may resolve the problem. var cn = cookieName + $(this).attr("id"); $.cookie(cn, cookieOptions); // save cookie depends on each link id. $("#" + $.cookie(cn)).addClass('voted'); UPDATE: this update added to answer to your updated question: function checkIfAllClicked(){ var flag = false; $(".up").each(function(){ var f = $(this).data("isClicked"); if(f == true){ flag = true; } else{ flag = false; } }); if(flag){ // refresh the page or call any-other function you want document.location.href = "any-url"; } } $(".up").live('click',function(e){ e.preventDefault(); $.cookie(cookieName, $(this).attr("id"), cookieOptions); // save cookie depends on each link id. $("#" + $.cookie(cookieName)).addClass('voted'); $(this).data("isClicked", true); checkIfAllClicked(); }); A: Solved. refrence here: Jquery - save class state for multiple div #'s to a cookie? share the answer to the all. $(document).ready( function() { $(function() { var cookieName = 'up_'; $('.up').each(function() { var id = $(this).attr('id'), cookie = cookieName + id; if ($.cookie(cookie) !== 'ture') { $(this).addClass('voted'); } }).live('click', function(e) { e.preventDefault(); $.cookie(cookieName + $(this).attr('id'), true); }); }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7619039", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to enable iOS browser to login with facebook from web page (not app)? I have a web site, that uses facebook to login. I would like iOS user of safari, to be able to login into this site. You understand i'm NOT talking about a native iOS app..... just a web site visit. Currently, user can't login from iOS safari, as they can from any desktop environement. Either login link is inactive, or there is an error message instead of the login popup. So what should I implement on website to have facebook login work on iOS browser ?
{ "language": "en", "url": "https://stackoverflow.com/questions/7619043", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Sensor manager not working as expected after Android 2.3.6 update Couple of days back, I made my first app on Android. The basic concept is to monitor the proximity sensor, if there is an obstacle at the sensor I will increment a counter. If the counter crosses the threshold I will trigger an action. I have implemented the sensor monitoring SW in a service, this service is called from an Activity in every 10 Min so as awake the cpu and start the service if it is stopped. Everything was perfect, got few thousands of downloads in market with good ratings. This was fine until Android 2.3.3. Recently my mobile got upgraded to Android 2.3.6 and unfortunately the app is not working as expected. Sensor listener does not trigger when the screen is OFF. Some times it works fine, most of the times it is not working. After giving several inputs at the sensor, after a while if I switch ON the screen, automatically all the triggers at the sensor are called at once and the counter increments and triggers the action. To summarize, sensor listener does not work when screen goes OFF (in Android 2.3.6), this was working fine until Android 2.3.3. If I connect the debugger, phone does not go to sleep and everything works fine so I am not able to find the problem. Please help me . Here is my code . Calling the service at every 10 min .. Thread trd = new Thread(){ public void run(){ int sec = 1000; int min = 60 * sec; Calendar cal = Calendar.getInstance(); alarmMngr.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 10 * min, PendInt); } }; trd.start(); In the service .. // On sensor change public void onSensorChanged(SensorEvent event){ if(event.sensor == SnsrProx){ if(event.values[0] <= 5){ IncProxCntr(1); }else{ IncProxCntr(0); } } } private void IncProxCntr(int x){ if( x == 1){ FakeCall_SnsrCnt++; vibrate(VIBRATE_SHORT); } if(FakeCall_SnsrCnt >= Settings.getMaxSnsrCnts(this)){ Trig_IncominCall(); } } A: Acquire wakelock in the service also
{ "language": "en", "url": "https://stackoverflow.com/questions/7619051", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Prefixing array keys with a string (:) in PHP Quick one; I know a solution, but I'm looking for something more elegant if it exists. I'm using PDO for prepeared statements: $sql = "INSERT INTO my_table (foo, bar, baz) VALUES (:foo, :bar, :baz)"; $source->execute($sql, array( ':foo' => $foo, ':bar' => $bar, ':baz' => $baz, )); This is fine, but I want to pass in a previously created array, however the keys contained aren't prefixed by the colon (:), and I figure there must be an elegant way to take: $array = array( 'foo' => 'some', 'bar' => 'random', 'baz' => 'value', ); And translate it into: $array = array( ':foo' => 'some', ':bar' => 'random', ':baz' => 'value', ); Without doing: $temp = array(); foreach($array as $key => $value){ $temp[':' . $key] = $value; } $array = $temp; I've browsed the PHP docs, but I can't find a function (or sequence of) that suits the purpose. Any ideas? Addendum Leaving the accepted answer, but +1 @chim for his clever 1-liner; solves the X in my XY problem. Reformatted solution: $format = ':%s'; $values = array_flip(array_map(function ($key) use($format) { return sprintf($format, $key); }, array_flip($values))); Wrapped in a function, perhaps array_keys_format(array $array, $format) A: $source->execute($sql, array( 'foo' => $foo, 'bar' => $bar, 'baz' => $baz )); This is presuming the above calls PDOStatement::execute() under the hood, with the above array as its argument.1 :) 1) Tested with version 5.2.17 and 5.3.8 here, and working as expected. A: It has already been answered but this is what I came up with anyway. $arr = array('foo'=>1,'bar'=>2); $arr = array_flip($arr); array_walk($arr,create_function('&$v,$k', '$v = ":$v";')); $arr = array_flip($arr); print_r($arr); A: use the php map-function: http://php.net/manual/en/function.array-map.php function reduce($key) { if(strpos($key,":")===0) return substr($key,1); return $key; } $array = array_map("reduce",$array); A: One liner... $array = array('test'=>'55','yest'=>'66'); $array = array_flip(array_map(function($v){return ':' . $v;},array_flip($array))); // array(':test'=>'55',':yest'=>'66'); However this isn't safe as array_flip relies on all values being unique. So one of the looping solutions is probably the best, or alternatively array_keys with array_combine.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619053", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Unable to access xml files, whose addresses' contain unicode characters I was wondering how to access file addresses containing latin characters, with jquery ajax. I tried to retrieve data in xml files with the script below: $.ajax({ type:'get', url:encodeURI('configuration/'+(value).toLowerCase()+'.xml'), dataType:'xml', contentType:'application/x-www-form-urlencoded;charset=utf-8;', success:function(content){ $('#content').html($('content',content).text().replace('nL','<br/>')); }); }); but the problem surges when I try to access xml files whose addresses' contain unicode characters like intrusão.xml. It keeps loading and nothing happens. Below are are the contents of the xml file example named intrusão.xml: <?xml version="1.0" encoding="utf-8"?> <document> <content>First line.nLSecond line.</content> </document> A: I recomend you to read this They give some solutions , but always modifying encoding: * *Changuing Ajax & php encoding *Convert string encoding (example : $str=iconv("windows-1250","UTF-8",$str);) I would be embarrased to copy solution (not fair) , then , read that thread i have link before A: * *change this may resolve the problem url: 'configuracao/submenus/' + encodeURI((value).toLowerCase()) + '.xml') *It is possible that the server does not support non-ascii chars. check this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619057", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Convert a byte array to integer in Java and vice versa I want to store some data into byte arrays in Java. Basically just numbers which can take up to 2 Bytes per number. I'd like to know how I can convert an integer into a 2 byte long byte array and vice versa. I found a lot of solutions googling but most of them don't explain what happens in the code. There's a lot of shifting stuff I don't really understand so I would appreciate a basic explanation. A: You can also use BigInteger for variable length bytes. You can convert it to long, int or short, whichever suits your needs. new BigInteger(bytes).intValue(); or to denote polarity: new BigInteger(1, bytes).intValue(); To get bytes back just: new BigInteger(bytes).toByteArray() Although simple, I just wanted to point out that if you run this many times in a loop, this could lead to a lot of garbage collection. This may be a concern depending on your use case. A: A basic implementation would be something like this: public class Test { public static void main(String[] args) { int[] input = new int[] { 0x1234, 0x5678, 0x9abc }; byte[] output = new byte[input.length * 2]; for (int i = 0, j = 0; i < input.length; i++, j+=2) { output[j] = (byte)(input[i] & 0xff); output[j+1] = (byte)((input[i] >> 8) & 0xff); } for (int i = 0; i < output.length; i++) System.out.format("%02x\n",output[i]); } } In order to understand things you can read this WP article: http://en.wikipedia.org/wiki/Endianness The above source code will output 34 12 78 56 bc 9a. The first 2 bytes (34 12) represent the first integer, etc. The above source code encodes integers in little endian format. A: /** length should be less than 4 (for int) **/ public long byteToInt(byte[] bytes, int length) { int val = 0; if(length>4) throw new RuntimeException("Too big to fit in int"); for (int i = 0; i < length; i++) { val=val<<8; val=val|(bytes[i] & 0xFF); } return val; } A: As often, guava has what you need. To go from byte array to int: Ints.fromBytesArray, doc here To go from int to byte array: Ints.toByteArray, doc here A: Use the classes found in the java.nio namespace, in particular, the ByteBuffer. It can do all the work for you. byte[] arr = { 0x00, 0x01 }; ByteBuffer wrapped = ByteBuffer.wrap(arr); // big-endian by default short num = wrapped.getShort(); // 1 ByteBuffer dbuf = ByteBuffer.allocate(2); dbuf.putShort(num); byte[] bytes = dbuf.array(); // { 0, 1 } A: byte[] toByteArray(int value) { return ByteBuffer.allocate(4).putInt(value).array(); } byte[] toByteArray(int value) { return new byte[] { (byte)(value >> 24), (byte)(value >> 16), (byte)(value >> 8), (byte)value }; } int fromByteArray(byte[] bytes) { return ByteBuffer.wrap(bytes).getInt(); } // packing an array of 4 bytes to an int, big endian, minimal parentheses // operator precedence: <<, &, | // when operators of equal precedence (here bitwise OR) appear in the same expression, they are evaluated from left to right int fromByteArray(byte[] bytes) { return bytes[0] << 24 | (bytes[1] & 0xFF) << 16 | (bytes[2] & 0xFF) << 8 | (bytes[3] & 0xFF); } // packing an array of 4 bytes to an int, big endian, clean code int fromByteArray(byte[] bytes) { return ((bytes[0] & 0xFF) << 24) | ((bytes[1] & 0xFF) << 16) | ((bytes[2] & 0xFF) << 8 ) | ((bytes[3] & 0xFF) << 0 ); } When packing signed bytes into an int, each byte needs to be masked off because it is sign-extended to 32 bits (rather than zero-extended) due to the arithmetic promotion rule (described in JLS, Conversions and Promotions). There's an interesting puzzle related to this described in Java Puzzlers ("A Big Delight in Every Byte") by Joshua Bloch and Neal Gafter . When comparing a byte value to an int value, the byte is sign-extended to an int and then this value is compared to the other int byte[] bytes = (…) if (bytes[0] == 0xFF) { // dead code, bytes[0] is in the range [-128,127] and thus never equal to 255 } Note that all numeric types are signed in Java with exception to char being a 16-bit unsigned integer type. A: Someone with a requirement where they have to read from bits, lets say you have to read from only 3 bits but you need signed integer then use following: data is of type: java.util.BitSet new BigInteger(data.toByteArray).intValue() << 32 - 3 >> 32 - 3 The magic number 3 can be replaced with the number of bits (not bytes) you are using. A: i think this is a best mode to cast to int public int ByteToint(Byte B){ String comb; int out=0; comb=B+""; salida= Integer.parseInt(comb); out=out+128; return out; } first comvert byte to String comb=B+""; next step is comvert to a int out= Integer.parseInt(comb); but byte is in rage of -128 to 127 for this reasone, i think is better use rage 0 to 255 and you only need to do this: out=out+256;
{ "language": "en", "url": "https://stackoverflow.com/questions/7619058", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "167" }
Q: Start and Reset Button How I could create a Start Button, which start my calculation and repaint in Java(Eclipse)? I try it with if(permission==true) but this do not work. The same is the with the Reset Button. In class space: public void setPermissionTrue() { permission = true; } public void run() { if(permission==true) { MyMoving } } public static void main ( String args[] ) { space.run() } In class GUI //Start-Button private JButton getJButton1() { if(startButton == null) { startButton = new JButton(); startButton.setText("Start"); startButton.setFont(new java.awt.Font("Bodoni MT",0,22)); startButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { space.setPermissionTrue(); System.out.println("startButton.activated, set Permission=True"); } }); } return startButton;
{ "language": "en", "url": "https://stackoverflow.com/questions/7619061", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: adding html tags to selected text in textarea. Why does "if('selectionStart' in textarea)" need to be in there? I found javascript code that allows me to add html tags around text that I have highlighted in the textarea field: <textarea id="myArea" cols="30" spellcheck="false">Select some text within this field.</textarea> <button onclick="ModifySelection ()">Modify the current selection</button> <script> function ModifySelection () { var textarea = document.getElementById("myArea"); if('selectionStart' in textarea){ if (textarea.selectionStart != textarea.selectionEnd) { var newText = textarea.value.substring (0, textarea.selectionStart) + "[start]" + textarea.value.substring (textarea.selectionStart, textarea.selectionEnd) + "[end]" + textarea.value.substring (textarea.selectionEnd); textarea.value = newText; } } } </script> My questions pertain to this line, if('selectionStart' in textarea){: * *What does the line mean exactly? *Why does selectionStart have to be in quotes? *selectionStart is usually appended to an object like "textarea"(textarea.selectionStart), how is it possible to refer to it by itself? *Is If(X in Y){} standard javascript syntax or does it work specifically forselectionStart? note: I'm testing this in jsfiddle A: * *if('selectionStart' in textarea) is feature testing - it checks whether the textarea object has a selectionStart property. *It needs to be in quotes as otherwise it would be interpreted as a variable (which may or may not exist in the current context). *It depends on the browser and what version of HTML is supported and rendered. *Yes it is normal javascript syntax. It is used to test if the specified property is in the object. See in on MDN.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619063", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Converting Java 1.5 compatible code to Java 1.4 Is there any tool that might help in converting the Java code written using 1.5 to 1.4. This is required because i need to reverse engineer my project using STAR UML. and Star UML is Java 1.4 compatible. Please Help A: Maybe you can try with retroweaver, it works on byte code level though, and I don't know if it's enough for your tool. To review the changes between Java 1.4 to Java 1.5, the most important is probably generics, then auto boxing and auto unboxing, annotations, variable number of arguments, the foreach loop, and import static. Generics: At a source code level, while you could probably get rid of generics when used as the collection element type, more difficult will be when a generic type is returned by a method. Auto boxing/unboxing: will need explicit conversions. Annotations: since they enable declarative programming, if used they might be difficult to substitute. With Spring, for instance you can define the same behaviour with XML, but it would be hard to convert by hand and also a bad idea. Variable number of aguments: will have to use arrays. Foreach loop: have to use iterators explicitely. import static: just prepend the class name. It was a pretty good advancement of features from Java 1.4 to 1.5, I wrote this more as a review of the changes, but unless your code is using very little of the new features you'll end losing a lot of time and also you'll reduce the quality of your code, so as sethu advised you probably the easier path is find another tool. A: You can do it with NetBeans by selecting the Java platform you want in the properties folder. Then is going to mark as wrong all the code non compatible with Java 1.4. (But maybe you should follow the @sethu advice)
{ "language": "en", "url": "https://stackoverflow.com/questions/7619065", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Storing an int into NSNumber then calling it in a new class So basically on my ClassA.h I have created a NSNumber called selected. It is also used in @property as well in that .h. Now in ClassA.m I have a table view and when one is selected it goes to another screen. I would like the indexPath.row to save into that NSNumber. (Selected was @synthesized as well in .m) Where it is being called in ClassA.m is in the didSelectRowAtIndexPath and looks like this. selected = [NSNumber numberWithInt:indexPath.row]; In the next view is where I would like to recall this code so that it can load a perticular view by code based on the selection. I import ClassA.h and this is the code I put in for ClassB.m HowTosViewController *h = [[HowTosViewController alloc] init]; if([h.selected intValue] == 0){ content.text = @"0"; } else if ([h.selected intValue] == 1){ content.text = @"1"; } I'm assuming my issue is I didn't store it correctly or it isn't calling it correctly. I would prefer to do this using the global variables so if there is an easier way to do this using them I wouldnt mind. I appreciate any help. Also as a side note. When I go to release selected would it cause any problems or be correct if I did it in ClassB? After it loads the screen from using that number it is no longer needed and another one should be assigned if the person goes back and selects another option. Thanks :) EDIT: Forgot to mention what it is doing currently. Currently when clicking on any of the Cells in ClassA it opens the screen and displays 0. A: selected = [[NSNumber numberWithInt:indexPath.row] retain]; or if the selected has a retain property... then you do self.selected = [NSNumber numberWithInt:indexPath.row]; A: When you do this in ClassB.m HowTosViewController *h = [[HowTosViewController alloc] init]; that is a new instance, not the same instance where you stored your selected value. Consider init'ing your ClassB with selected value as well and use that in classB like doing - (id) initWithSelectedIndex: (NSNumber *) selectedIndex { if(self = [super init]) { receivedSelectedIndex = selectedIndex; } return self; } delcare this receivedSelectedIndex like NSNumber *receivedSelectedIndex; @implementation classB and where you create instance of ClassB you should do like classB *b = [[classB alloc] initWithSelecedIndex:selected]; //using your selected NSNumber
{ "language": "en", "url": "https://stackoverflow.com/questions/7619069", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Which unit test framework for C can be used with Jenkins I am trying to find a unit test framework for C, that would work with Jenkins. from the wikipedia page http://en.wikipedia.org/wiki/List_of_unit_testing_frameworks#C i can see only few that generate results in XML , and gtest needs your code to be compiled with g++ I would appreciate if anyone has good experience using a test framework that worked well with Jenkins. A: Well, in gtest the test classes have to be C++, but nobody prevents you from linking to C code. Therefore, the system under test can be written in C. If it is ok that the test classes are in C++, gtest is a very viable option.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619070", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Make the while loop test all the time I'm working on a simple test that uses a while loop. Here is the code: var ishovered = 0; $('a.hovertest').hover(function(){ ishovered = 1; },function(){ ishovered = 0; }); while(ishovered == 1) { //execute function } How do I make it so that while loop is testing all the time and the function executes as soon as he hovers? (Yes, I know I can put the function in the hover section, I'm asking this for a reason) It doesn't really have to be a loop though, I just need a function to execute as soon as ishovered becomes 1. Is there any way to monitor that? Here is the example: http://jsfiddle.net/9s3zE/ A: Fiddle: http://jsfiddle.net/9s3zE/1/ Use setInterval for this purpose. You're describing the behaviour of a "poller", by the way. A poller checks whether a condition evaluates to true. If true, a function is activated. If false, the default behaviour (possible nothing) occurs. It's not wise to use a while loop for this case, because the browser will freeze when the condition is true. var ishovered = 0; $('a.hovertest').hover(function(){ ishovered = 1; },function(){ ishovered = 0; }); var showresult = $('#showresult'); window.setInterval(function(){ if(ishovered == 1){ showresult.text("You hovered"); } else if(showresult.text() == "You hovered"){ showresult.text("Default text (not hovered)"); } }, 100);
{ "language": "en", "url": "https://stackoverflow.com/questions/7619071", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Factory Girl vs. User.create -- what's the difference? This is an additional note to the question "Factory Girl - what's the purpose?" I'm not sure whether my question is counted as a repetitive one, but I'm simply still not very clear after reading that post, since I think my doubt is still different. Alright, so now that we can always use User.create() in before(:each) block in a Rspec test, why do we still bother using Factory Girl then? This whole confuse occurred to me when I'm reading Michael Hartl's "Rails 3 tutorial", when he suddenly jumped into Factory Girl but used User.create() to build a User instance all the way through before that. I wish someone can clarify this point for me, thx a lot! A: You are correct but gems like factory girl and fabrication allow for significantly less code duplication across clases and within different tests when you need to test large sets of data that require different attribute values due to uniqueness requirements. It mixes in methods to easily "manufacture" many different objects for these types of tests.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619072", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Earliest deadline scheduling I want to implement Earliest deadline scheduling in C but I cant find the algorithm on the net.. I understand the example below that when time is 0, both A1 and B1 arrive. Since A1 has the earliest deadline, it is scheduled first. When A1 completes, B1 is given the processor.when time is 20, A2 arrives. Because A2 has an earlier deadline than B1, B1 is interrupted so that A2 can execute to completion. Then B1 is resumed when time is 30. when time is 40, A3 arrives. However, B1 has an earlier ending deadline and is allowed to execute to completion when time is 45. A3 is then given the processor and finishes when time is 55.. However I cant come up with a solution.. Please help me to find an algorithm. Thanks.. Image of the example http://imageshack.us/photo/my-images/840/scheduling.png/ A: * *when a process finishes (and at the beginning), take the process with the lowest processTimeToDeadline - processTimeToExecute as the new current process *When a new process arrives, replace the current process if and only if newProcessTimeToDeadline - newProcessTimeToExecute < currentProcessTimeToDeadline - currentProcessTimeStillNeededToExecute. Note: if you do this with multiple CPU, you got the Multiprocessor scheduling problem, which is NP complete. A: Previous answer describe "Earliest Feasible Deadline First" (EFDF) scheduler and it fist perfectly to image from qestion. "Earliest Deadline First" (EDF) scheduler is more simple. Scheduler just run task with earliest deadline. And it is all.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619080", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Load json data to autocomplete jquery I am trying to use the jqueryui autocomplete to load services from mysql database on my form but nothing happens?? please help me or tell me where am wrong my html <input type="text" id="actual_service" /> my javascript script $("#actual_service").autocomplete({ source: "http://dev_svr/medportal/search.php?callback=?", dataType: "jsonp", minLength: 1 }); this is search.php $con = mysql_connect('localhost', 'dev', ''); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("medrep", $con); $term = trim(strip_tags($_GET['term'])); $qstring = "select prod_id id,prod_name value FROM product where prod_type='SERVICE' and prod_name LIKE '%".$term."%' ORDER BY prod_name;"; $result = mysql_query($qstring); while ($row = mysql_fetch_array($result,MYSQL_ASSOC)) { $row['value']=htmlentities(stripslashes($row['value'])); $row['id']=(int)$row['id']; $row_set[] = $row; } header("Content-type: application/json"); echo json_encode($row_set); when i load that page nothing happens on that inputbox when i type anything. this is a sample output of http://dev_svr/medportal/search.php?term=ct when i limit the sql to 3 rows [{"id":50,"value":"ABDOMEN SUPINE&amp;ERECT(2VIEWS)"},{"id":142,"value":"CT BRAIN"},{"id":115,"value":"CT CERVICAL SPINE"}] A: 1. Your jQuery code is not correct You are not getting data from a remote domain, therefore you don't need a JSONP request. It should be: $("#actual_service").autocomplete({ source: "http://dev_svr/medportal/search.php", minLength: 1 }); 2. Your JSON object is not correct. Each json object for the autocomplete should have two values: label and value (no ID). If you want the product id to be the value of the selected item, and the product name to be the text that is shown to the user, then the json object should be like: [{"value":50,"label":"ABDOMEN SUPINE&amp;ERECT(2VIEWS)"},{"value":142,"label":"CT BRAIN"},{"value":115,"label":"CT CERVICAL SPINE"}] Edit From what you mentioned in the comments, try this jQuery code: $('#actual_service').autocomplete({ source: function( request, response ) { $.ajax({ url: 'http://dev_svr/medportal/search.php', dataType: 'jsonp', data: { term: request.term }, success: function( data ) { response( data ); } }); }, minLength: 1 });
{ "language": "en", "url": "https://stackoverflow.com/questions/7619082", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to create a Custom Circle? I want to create a custom circle for my application whose all attribute and property i want to define my self. Basically i want to create a myCircle class which should be inherited from NSObject class. How can i do that? Any sample application /example/ code for reference? A: MyCircle.h #import <Foundation/Foundation.h> @interface MyCircle : NSObject { // Declare properties here float radius; } @property (nonatomic) float radius; - (id)initWithRadius:(float)r; @end MyCircle.m #import "MyCircle.h" @implementation MyCircle @synthesize radius; - (id)init { self = [super init]; if (self) { // Initialize [self setRadius:10.0]; // set a default value for radius } return self; } - (id)initWithRadius:(float)r { self = [self init]; if (self) { [self setRadius:r]; } return self; } @end If you want to display a circle on a view based on your MyCircle object, you could subclass a UIView and override the - (void)drawRect:(CGRect)rect method. You can instantiate the circle using the - (id)initWithRadius:(float)r method. If you're not sure how to go about doing any of that, I recommend reading an introductory book on iOS programming. I swear by the Big Nerd Ranch guide.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619086", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MemoryLeak in iphone programming? Can any one help me to understand the problem in this image A: As the analyzer says, you are allocating locs on line 647, using NSMutableArray *locs = [[NSMutableArray alloc] init]; and not releasing it later in the block. You should release it or you can use convenience constructor to get the autoreleased array like this, NSMutableArray *locs = [NSMutableArray array]; I'd suggest you to still simplify your code to this, NSMutableArray *annotations = (NSMutableArray *)[map annotations]; [annotations removeObject:[map userLocation]]; [map removeAnnotations:annotations]; A: You need to release locs at the very end. You have alloc'ed and init'ed it, giving it a reference count of 1, an then you should release it to change the reference count to 0. Refer to http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/MemoryMgmt/ for more info. A: You have initialize the locs array then you have to release that array before closing that function: [locs release];locs=nil;
{ "language": "en", "url": "https://stackoverflow.com/questions/7619088", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Generating one Texture2D from multiple Texture2Ds My problem is the I need to represent a length-changing floor using a Texture2D, which means a floor that the sides has the image of the sides, and in the middle it repeats the same 'middle' image, like so: To achieve this, I get the 'left edge', the 'middle' and the 'right edge' textures, problem is I don't know how to merge them into one single texture2D, It is important to do that at run-time because the floor length is changing (horizontally), I read you can do that using SetData but I have no idea how... It is very important for me that it will act as one texture and not multiple texture parts because I am using Farseer Physics Engine to move the floor and use it. I am using C# and XNA with Visual Studio 2010, I am an almost-experienced C# programmer, Thank you! A: This answer may help you. Either you should use HLSL for repeating your floor or you should draw your floor on a RenderTarget and save it as single Texture. Enjoy. A: First, create a new Texture2D to serve as your floor texture, specifying the appropriate width and height. Then, get the data of the three textures you want to merge, using the GetData method. Finally, use the SetData method to set the data of the new texture as appropriate (check the link, you can specify the start index). Warning: GetData and SetData methods are slow. If you need to create this texture only once per game (at the initialization for example), it's not a problem, though. A: You are using farseer... but it does not prohibit you to use a tiling approach... I don't know farseer, but I suppose that it provide a transform matrix... do: Vector2 pos = Vector2.Zero; spriteBatch.Begin(...,....,...,..., Transform); spriteBatch.Draw(LeftTexture, pos, null, Color.White); pos.X += LeftTexture.Width; for (int i=0; i<floor_repeats; i++) { spriteBatch.Draw(MidleTexture, pos , null, Color.White); pos.X += MiddleTexture.Width; } spriteBatch.Draw(RightTexture, pos , null, Color.White);
{ "language": "en", "url": "https://stackoverflow.com/questions/7619090", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Transform text to vector shape in Adobe Flash Professional CS5 How? Question is simple, hope the answer will be as well. A: * *Use the text tool T and type *Select the text with the Selection tool V *From the menu select Modify then Break Apart or Ctrl+b *Finally use the Subselection tool A and click the text edge (no the inside fill), you'll see the cursor change to an arrow with a black dot. A: If it was imported, as @Dementic says, you'll need to trace it using Modify > Bitmap > Trace Bitmap. If you created it in Flash using the Text Tool, then it is already in a vector format. If you created the file using a newer/older version of Flash that the default/only option is Classic Text whereas for CS5 the default is the TLF format introduced in that version. If you're not sure about the difference between TLF and Classic Text, Andy Anderson can explain. Reading between the lines of your concise question you're probably trying to break apart Classic Text, so here's how.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619092", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to inject CSS into webpage through Chrome extension? I do not know how to inject CSS into a webpage through a Chrome extension. I am trying to inject this into a web page: body { background: #000 !important; } a { color: #777 !important; } Here is my manifest.json: { "update_url":"http://clients2.google.com/service/update2/crx", "name": "Test Extension", "version": "1.0", "description": "This is a test extension for Google Chrome.", "icons": { "16": "icon16.png", "48": "icon48.png", "128": "icon128.png" }, "background_page": "background.html", "browser_action": { "default_icon": "icon19.png" }, "content_scripts": [ { "matches": ["http://test-website.com/*"], "js": ["js/content-script.js"] } ], "permissions": [ "tabs", "http://test-website.com/*" ] } A: You can have to add an extra line in your manifest file: "content_scripts": [ { "matches": ["http://test-website.com/*"], "js": ["js/content-script.js"], "css" : ["yourcss.css"] } ], The CSS file as defined in "css": ["..."]will be added to every page which matches the location as mentioned in matches. If you're developing a Chrome extension, make sure that you have a look at these pages: * *Developer's guide * *Manifest files *Content scripts *Background pages A: You can also inject a css file into one or more tab's content by using the following syntax as detailed on the Chrome Tabs API webpage: chrome.tabs.insertCSS(integer tabId, object details, function callback); You will first need the ID of your target tab, of course. The Chrome Extension documentation doesn't discuss how the injected CSS is interpreted, but the fact is that CSS files that are injected into a webpage, by this method or by including them in the manifest, are interpreted as user stylesheets. In this respect, it is important to note that if you do inject stylesheets by using these methods, they will be limited in one crucial way ( at least, as of Chrome v.19 ): Chrome ignores "!important" directives in user stylesheets. Your injected style rules will be trumped by anything included in the page as it was authored. One work-around, if you want to avoid injecting inline style rules, is the following (I'm using jQuery for the actual insertion, but it could be done with straight Javascript): $(document).ready(function() { var path = chrome.extension.getURL('styles/myExtensionRulz.css'); $('head').append($('<link>') .attr("rel","stylesheet") .attr("type","text/css") .attr("href", path)); }); You can then put the stylesheet in your extension's styles folder, but you won't need to list it anywhere on the manifest. The relevant part above is that you will use the chrome API to get your stylesheet's URL, then plug that in as the link's href value. Now, your stylesheet will be given a higher precedence, and you can use the "!important" directive where needed. This is the only solution that works for me in the latest version of Chrome. A: Looks like chrome.tabs.insertCSS is depreciated you should be using. https://developer.chrome.com/docs/extensions/reference/scripting/ This is what I am doing. let [tab] = await chrome.tabs.query({ active: true, currentWindow: true }); chrome.scripting.insertCSS({ target: { tabId: tab.id }, files: ["button.css"], }, () => { chrome.scripting.executeScript({ target: { tabId: tab.id }, function: doSomething, }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7619095", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "50" }
Q: Can't set image int into webview? Allright so here's my problem. I have an app which contains alot of pictures and i wanted to be able to pinchzoom these, but since the ImageViewer doesnt support this natively I thought I'd use the Webviewer instead, but heres the thing. all my pictures are saved into my "picture" int and its the picture function i want to load into the webviewer. not a specific \drawable\bla.jpg Searched all around but didnt find anything about it. I'll attach some code for reference. public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent=getIntent(); int picture=intent.getIntExtra("picture", 22); setContentView(R.layout.pictureframe); ImageView image = (ImageView) findViewById(R.id.pansarvagn); image.setBackgroundResource(picture); and its here where i want smth like Webview image = (WebView) findViewById(R.id.pansarvagn); image.(setdata bla bla) and this is the picture function public void displayPicture(int pictureresource){ Intent intent = new Intent(); intent.putExtra("picture", pictureresource); intent.setClass(getApplicationContext(), Picture.class); startActivity(intent); called by Button tank = (Button) findViewById(R.id.tank); tank.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { displayPicture(R.drawable.tank); } To further elaborate i want to put an image into a webview which i will be able to zoom into. so some sort of imageview inside the webview to fill up the webview with my picture. and then I want to be able to zoom in on it. A: You need to create you own ContentProvider and override it's opeenFile(..) method. Then you can feed it to WebView: myWebView.loadUrl("content://your.content.provider/someImageName"); Here is an example: http://www.techjini.com/blog/2009/01/10/android-tip-1-contentprovider-accessing-local-file-system-from-webview-showing-image-in-webview-using-content/ Note: with this approach you will need to save your images somewhere. You will not be able to serve them from memory.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619097", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: A bit of assistance with sub and regex This works: 'http://foobar.com/default_profile_images/default_profile_6_normal.png'.sub(/normal\.([a-z]+)$/, 'reasonably_small.\1') This doesn't: "http://foobar.com/profile_images/1550660558/Bathurze_Pics_normal.JPG".sub(/normal\.([a-z]+)$/, 'reasonably_small.\1') I'm trying to substitute normal with reasonably small. Anyone know why it doesnt work? A: It's a case sensitive issue. JPG isn't matched by [a-z]. If you change your regex to be case insensitive it should work. Change /normal\.([a-z]+)$/ to /normal\.([a-z]+)$/i (added the i modifier) A: The second example has uppercase letters at the ending, so you should change your regexpression from /normal\.([a-z]+)$/ to /normal\.([a-zA-Z]+)$/ Edit: Fixed missing + in second regex A: added case handling - "http://foobar.com/profile_images/1550660558/Bathurze_Pics_normal.JPG".sub(/normal\.([a-z]+)$/, 'reasonably_small.\1') Should work. A: The reason is /[a-z]+/ only catch small letters, in other word it is case sensitive. As the file suffix in first example is .png so, the regex match, while the second doesn't. The solution can simply change it from [a-z]+ to [A-Za-z+].
{ "language": "en", "url": "https://stackoverflow.com/questions/7619102", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Creating a 'Table' from divs in CSS/HTML I have content in a 400px wide div that I would like repeated across the width of the screen with 30px spacing in between, similar to the layout of these blog modules. The number of modules per row would depend on the width of the screen, like in the above example. I am new to creating this kind of layout using divs. My biggest problem is getting the divs to lie beside each other with 30px in between and then starting on a new line. Any help would be greatly appreciated. A: you can achive this by give float or display:inline-block CSS: .block { margin-right: 30px; float: left; width: 400px; height:500px } .block:nth-child(3n+3){margin-right:0} HTML: <div class="block">...</div> <div class="block">...</div> <div class="block">...</div> <div class="block">...</div> <div class="block">...</div> <div class="block">...</div> A: CSS: div.block { margin-right: 30px; float: left; width: 400px; } HTML: <div class="block">...</div> <div class="block">...</div> <div class="block">...</div> <div class="block">...</div> A: Try this CSS : .myclass { margin-right: 30px; float: left; width: 400px; } and HTML : <div> <div class="myclass">this is test block</div> <div class="myclass">this is test block</div> <div class="myclass">this is test block</div> <div class="myclass">this is test block</div> </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/7619105", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Noticing strange behavior with strings in c Still in learning mode and may be the following question is a really dumb but I dont have any idea why it is happening.. #include<stdio.h> int main() { /* code to accept string and then a character from stdin */ char str[20], inp; /*take string from stdin */ printf("string:\n"); scanf("%s",str); fflush(stdin); /*input a character */ printf("char:\n"); scanf("%c",&inp);/* code does not reach this point and exits */ } As mentioned in the comment, after I input the string , for eg. 'strng' the code just exits after printing char: but it does not wait for me input the character. As per my understanding, I have given the size of the array large enough to store the string and if the string entered is smaller than the size of the str array, the compiler will automatically add null character at the end of the string and proceed further. Am I missing something or is there a mistake in my code. Please suggest. Thanks. A: Try removing fflush(stdin); and put a space before %c in scanf(" %c",&inp); A: First of all fflush(stdin) is wrong. Many people recommend it but it is plain and simple undefined. The problem is caused by scanf leaving \n in the input buffer because "%s" doesn't read whitespace characters. When scanf("%c"..) is reached, it is immediately "satisfied" and fills inp with \n and calls it a day. The problem is common enough, see these C FAQs: * *Scanf interlace *Scanf problems One (possibly dangerous) solution is to discard \n input: while((c = getchar()) != '\n' && c != EOF) ; Another solution might be to use fgets and parse that, or possibly read one character at a time with getc, or maybe tweak the second scamf to discard whitespace characters. A: Put a space before the %c in the second scanf like this: scanf(" %c",&inp) And as stated by others fflush is defined only for output streams.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619106", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: html_escape seems to be broken after upgrading to Rails 3.1 I have a project that uses the WYSIWYG editor 'wysihat-engine' by Dutch guys from 80beans . It use to work fine with Rails version 3.0.9 , but after upgrading to 3.1.0 the wysihat-engine cannot find 'html_escape' from ERB::Util (ActiveSupport 3.1.0) , giving me this error message : undefined method `html_escape' for #<ActionView::Helpers::InstanceTag:my-wysihat-editor- instance> I've fixed it (verrrry lamely , indeed) by defining the 'html_escape' inside 'wysihat-engine.rb' , but I'm sure , there's a reason not to do it this way :). My questions : 1. Is this a bug of the new version of Rails ? 2. Is there a better choice for WYSIWYG editor for a Rails 3.1 projects ? Thank you in advance . A: The wysihat-engine doesn't seem to be compatible with Rails 3. I've tried to install it in a fresh Rails 3.1 application, but the generator fails when it tries to generate a database migration: $ rails generate wysihat ~/.rvm/gems/ruby-1.9.2-p290@rails31/gems/railties-3.1.0/lib/rails/generators/migration.rb:30:in `next_migration_number': NotImplementedError (NotImplementedError) from ~/.rvm/gems/ruby-1.9.2-p290@rails31/gems/railties-3.1.0/lib/rails/generators/migration.rb:49:in `migration_template' from ~/.rvm/gems/ruby-1.9.2-p290@rails31/gems/wysihat-engine-0.1.13/lib/generators/wysihat_generator.rb:60:in `install_wysihat' I'm surprised you even got as far as the html_escape error you posted. Fixing this would take some poking in the source code. You could ask the developer for info.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619108", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: NLTK Chunking and walking the results tree I'm using NLTK RegexpParser to extract noungroups and verbgroups from tagged tokens. How do I walk the resulting tree to find only the chunks that are NP or V groups? from nltk.chunk import RegexpParser grammar = ''' NP: {<DT>?<JJ>*<NN>*} V: {<V.*>}''' chunker = RegexpParser(grammar) token = [] ## Some tokens from my POS tagger chunked = chunker.parse(tokens) print chunked #How do I walk the tree? #for chunk in chunked: # if chunk.??? == 'NP': # print chunk (S (NP Carrier/NN) for/IN tissue-/JJ and/CC cell-culture/JJ for/IN (NP the/DT preparation/NN) of/IN (NP implants/NNS) and/CC (NP implant/NN) (V containing/VBG) (NP the/DT carrier/NN) ./.) A: This should work: for n in chunked: if isinstance(n, nltk.tree.Tree): if n.label() == 'NP': do_something_with_subtree(n) else: do_something_with_leaf(n) A: Small mistake in token from nltk.chunk import RegexpParser grammar = ''' NP: {<DT>?<JJ>*<NN>*} V: {<V.*>}''' chunker = RegexpParser(grammar) token = [] ## Some tokens from my POS tagger //chunked = chunker.parse(tokens) // token defined in the previous line but used tokens in chunker.parse(tokens) chunked = chunker.parse(token) // Change in this line print chunked A: Savino's answer is great, but it's also worth noting that subtrees can be accessed by index as well, e.g. for n in range(len(chunked)): do_something_with_subtree(chunked[n]) A: def preprocess(sent): sent = nltk.word_tokenize(sent) sent = nltk.pos_tag(sent) return sent pattern = 'NP: {<JJ>*<NNP.*>*}' cp = nltk.RegexpParser(pattern) exp = [] for line in lines: line = preprocess(line) cs = cp.parse(line) for n in cs: if isinstance(n, nltk.tree.Tree): if n.label() == 'NP': if len(n.leaves()) > 1: req = '' for leaf in n.leaves(): req += leaf[0]+' ' exp.append(req) print(exp)
{ "language": "en", "url": "https://stackoverflow.com/questions/7619109", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: PHP replace newlines stored in MySQL DB I have a MySQL table with 2 columns: * *text: stores a multi-line text which could have line breaks as \n, \r, \r\n.... The text is inserted via a webform and could have been inserted by any browser on any OS. *line_break: represents what type of line break this particular text will use (could be \n, <br>, <br />, ...). This is also inserted via a webform by a user. In PHP I then do the replacement: $text = preg_replace ("/(\r\n|\r|\n)/", $row['line_break'], $row['text']); Interestingly, if the line break is stored in the DB as \n I will actually show \n instead of the newline. On the other hand, the following regexp will work correctly: $text = preg_replace ("/(\r\n|\r|\n)/", "\n", $row['text']); How do I need to store the newline in the DB for it to "work" correctly? A: In php, "\n" is a special notation for writing that special character that means 'line break'. But if you store the actual text \n in your database, you have just that text, and not the line break character. You have what you get when you write '\n' or "\\n" in PHP. Make sure you store the actual line break character in your database and not the literal \n text.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619112", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to use answer (from command window) for a code I have random matrix(A) and I find a result I'd like to use later for my code A=randint(5,7,[1,9]) ans A = 8 1 2 2 6 7 7 9 3 9 4 1 7 1 2 5 9 9 8 4 3 9 9 5 8 9 6 1 6 9 8 9 7 2 1 How can I now get: A = [8,1,2,2,6,7,7;9,3,9...7,2,1]; without having to type it myself. A: MATLAB has a function for that: MAT2STR >> A = randi([1,9],[5,7]); >> mat2str(A) ans = [5 5 7 5 3 2 5;5 6 5 3 8 4 1;9 8 8 1 7 9 6;1 5 5 1 8 6 3;3 4 5 8 9 9 5] This is suitable for use with EVAL A: Make the string yourself: Str = ['[' sprintf('%i',A(1)) sprintf(',%i',A(2:end)) ']'] Note this string does not contain any ; as in your example. so when you evaluate it you will get a 1x35 vector (instead of the original 5x7matrix) So easiest way to fix this would be to add after you evaluate the string. A = reshape(A,5,7) It will look like B = [.... B = reshape(B,5,7) A: Just thought of another way. Your goal is to have A in your script - right? You can just paste it as follows: A = [ 8 1 2 2 6 7 7 9 3 9 4 1 7 1 2 5 9 9 8 4 3 9 9 5 8 9 6 1 6 9 8 9 7 2 1 ] (note the square brackets) It will evaluate to your original matrix.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619115", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Sorting groups of data looking at the newest entry I have a table with two columns team and date. The date column has the date that the entry was added to the table. I want to print the last 10 entries of each team sorted by date DESC. I also want to sort these groups of team entries by date DESC. I tried a lot of things, but with no luck. It worked, but with 2 queries which is not acceptable in this case. How can I do this with a single query? I have the feeling that this is a really newbie question. A: SELECT rows.team, rows.date FROM ( SELECT team, date, IF( @prev <> team, @rownum := 1, @rownum := @rownum+1 ) AS rownum, @prev := team FROM my_table JOIN (SELECT @rownum := NULL, @prev := 0) AS init ORDER BY team, date DESC ) AS rows WHERE rownum <= 10 We make a temporary (virtual) table in the sub-query with rows ordered by team, date DESC and we start from the top giving an incrementing row number to each row and whenever team changes we reset the row number, then in the outer query we filter out any row that has row number greater than 10.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619117", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PyQt4: set size of QGridLayout depending on size of QMainWindow I'm writing a little Qt application with Python. I've created QMainWindow, which have a QGridLayout. In each grid I'm adding QTextBrowser Widget. I want left side of my grid to be not bigger than 25% of window. So I'll have two QTextBrowsers: one is 25% of window's width, and another is 75% of window's width. How can I do it? Thanks! A: You can specify relative width by giving each cell a stretch with setStretch(). They will get sizes proportional to the given stretches. Here is a simple example that makes the right widget 3 times greater than the left widget. import sys from PyQt4 import QtGui if __name__ == "__main__": app = QtGui.QApplication(sys.argv) Q = QtGui.QWidget() H = QtGui.QHBoxLayout() H.addWidget(QtGui.QTextBrowser()) H.setStretch(0,1) H.addWidget(QtGui.QTextBrowser()) H.setStretch(1,3) Q.setLayout(H) Q.show() app.exec_() But, bear in mind that widgets have minimum sizes by default. So they can shrink below that. If you want to change that behavior also, consider setting minimum sizes to your liking.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619121", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Executing Scala objects in Eclipse without a main method I have an assignment to code several methods in Scala. The methods will be encapsulated in an object that has no main method. The professor gave us a JAR file that contains an interface (my object implements this interface) as well as a sort of pseudo test object that performs various assert statements against each of my functions. This object also does not contain a main method. Now in Intellij I simply had to declare the dependency on the JAR in the classpath, and it runs fine. Eclipse is giving me trouble though because when I go to define a Scala application run configuration it specifically asks me to name the class that contains a main method, and there is no main method. I am assuming that I might be choosing the wrong project type for this type of set up, but I am inexperienced with this and I would appreciate any advice you might have for running something like this in eclipse. Thanks. A: I would either: * *just write an object with a main method which calls the test object, or *start a Scala interpreter in your project (from context menu, under Scala). Preferring the first approach, because it's faster to repeat tests after a modification.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619129", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How can I spread out randomly located images in js? I am randomly placing images on a canvas in javascript. The problem is that I want to minimize stacking but not prevent it. I would like to see the behavior where if there is enough images to fit on the canvas without overlapping, they wont. However, I want the images to not appear ordered. Any ideas? A: You could place them evenly, then randomly move them a bit... somthing like this: var w = 200, h = 150, leftOffset = 60, topOffset = 30, leftDeviation = 90, topDeviation = 60 for(i=0;i<5;i++) $('<div />').css({ left:(i*w+leftOffset+Math.round(Math.random()*leftDeviation)), top:(topOffset+Math.round(Math.random()*topDeviation)), opacity:.6,width:w,height:h,backgroundColor:'red',position: 'absolute'}).appendTo('body') Demo here: http://jsfiddle.net/y2hdE/ This includes grid layout: http://jsfiddle.net/y2hdE/1/ Once you have placed all the images using a formula similar to mine, you could then randomly select what spot the photo drops into, so all the positions are pre-determined, but the order is random. A: How far are you in your approach? You say that you can, but don't want to prevent stacking. Why don't you use your algorithm, add the prevention and do some exceptions based on a random number? A: I ended up going with an inverted normal distribution which will likely leave space in the center to allow images to be viewed while images on the outside are more likely to be stacked.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619130", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: target and display an object of list control in flex i have made a list control. i want to display the name of the objects in it in a text control box the code i am using here is public function add(event:MouseEvent):void { var str:String; str = mylistcontrol.dataProvider.getItemAt(0).toString(); mytextarea.text += str+ "has been added"; mytextarea.text += "\n"; } The problem with this code is i am using index value of 0. however i want to display the name of object on which i have clicked or which is highlighted. any ideas and thoughts? A: When you say the name of the object do you mean the name of the ItemRenderer? If that's the case one method you could use involves creating a custom event and a custom item renderer... Create a custom ItemRenderer when clicked dispatch your CustomEvent which would a have a data property into which you can put anything you like.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619138", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to close thread when application deactivated? I have some thread in some page (e.g page1) in wp7. I want to close these thread when the application deactivated in this page, not in the global application file.When application deactivated from some other page only this page onNvavigateFrom is called, bit page1 onNavigateFrom isn't called. How can I do that? Or what is the best practice to close such threads? A: If your thread is the result of using BackgroundWorker (the recommended approach), you should be periodically checking CancellationPending as described on the DoWork documentation. If you are creating your own Thread, you can emulate this behavior by setting a boolean flag that is checked periodically (in a loop or whatever) by your thread. What you shouldn't do is call Thread.Abort as that could leave you with corrupted state if you write to the isolated storage or a database.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619140", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: In ruby, why does array append fail on a hash with a default value of empty array? Code example below. Calling append on a hash value returns correctly but the hash itself doesn't behave as I would expect. ruby-1.9.2-p290 :037 > r = {} => {} ruby-1.9.2-p290 :038 > r.default = [] => [] ruby-1.9.2-p290 :039 > r["c"] << 1 => [1] ruby-1.9.2-p290 :040 > r["c"] => [1] ruby-1.9.2-p290 :041 > r => {} ruby-1.9.2-p290 :042 > r.empty? => true A: from the doc on default=: Sets the default value, the value returned for a key that does not exist in the hash. It is not possible to set the default to a Proc that will be executed on each key lookup. So you can use this: irb(main):037:0> h = Hash.new { |hash, key| hash[key] = [] } => {} irb(main):038:0> h[1] << "2" => ["2"] irb(main):039:0> h => {1=>["2"]} also you can use default_proc: irb(main):047:0> h = {} irb(main):047:0> h.default_proc = proc {|hash, key| hash[key] = []} => #<Proc:0x23939a0@(irb):47> irb(main):049:0> h[1] << 3 => [3] irb(main):050:0> h => {1=>[3]} A: It seems ruby hash uses r.default as default value for any r[<unassigned-key>]. So a single value is changed even if you specify different un-assigned keys. Please see below: irb(main):001:0> r = {} => {} irb(main):002:0> r.default = [] => [] irb(main):003:0> r["c"] << 1 => [1] irb(main):004:0> r["c"] => [1] irb(main):005:0> r["b"] << 2 => [1, 2] irb(main):006:0> r["b"] => [1, 2] irb(main):007:0> r["c"] => [1, 2] irb(main):010:0> r.default => [1, 2] irb(main):008:0> r => {} irb(main):009:0> r.empty? => true
{ "language": "en", "url": "https://stackoverflow.com/questions/7619144", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: left outer join by comparing 2 files I have 2 files as shown below: success.txt amar akbar anthony john jill tom fail.txt anthony tom I want to remove the records from sucess.txt those matches with fail.txt Expected output: amar akbar john jill A: I'd use fgrep - if available - as you're using fixed strings it should be more efficient. fgrep -v -x -f fail.txt success.txt You need the -x option to ensure only whole lines are matched, otherwise fails like tom will match successes like tomas. A: awk one-liner: also keep the original order awk 'NR==FNR{a[$0]=1;next;}!($0 in a)' fail.txt success.txt A: There is a Posix-standard join(1) program in all modern Unix systems, see man join. $ join -v1 success.txt fail.txt
{ "language": "en", "url": "https://stackoverflow.com/questions/7619145", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: how to debug PHP/WordPress failure running on WebMatrix (Windows 7) I was able to install and run WordPress via WebMatrix on a VM. I have a WordPress theme though that immediately causes the site to start failing. I receive a 500 error message, there is nothing in my event logs. Where can I find some kind of log for what actually happened? Or is there a way I can have the site show detailed error information? A: Sorry to hear you are having trouble. WebMatrix runs sites in the context of IIS Express, the included lightweight web server. Its logs can be found in: \IISExpress\Logs \IISExpress\TraceLogFiles Hope this helps! A: found this Enable xDebug in WebMatrix. hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619149", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ajax for DB Updation I am updating 100,000 records. So the page looks blank while the update query process runs on the backend. Can someone tell me how to display the text "Please wait blah blah" until the update ends? A: Well depending on your script and the structure, the easiest way would be to change a div's css property called display. When a user clicks on a link that starts the php script, you could add a javascript code like : $(#+THEIDOFYOURDIV).show("slow"); }); and once its done, you can call another js function to close it like : $(#+THEIDOFYOURDIV).hide("slow"); }); *NOTE I am using jquery functions, so you would need to include jquery in your pages. There is another way you could do this using php ONLY, I had the same issue so take a look at this: how to show results while a php script is still running
{ "language": "en", "url": "https://stackoverflow.com/questions/7619151", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: Automatic factory registration i'm just learning java, and i meet some problems. Here we have simple factory pattern: public class SomeFactory { ... public static void registerProduct(String name, Class<? extends IProduct > f) } public SomeProduct implements IProduct { static { SomeFactory.register("some product", SomeProduct.class); } ... } All products should register themselves at factory. But before using this code, all Products classes should be loaded. I can put Class.forName() somewhere, for example in main function. But i want to avoid such sort of manual classes loading. I want just add new IProduct implementations, without updating other parts(such as SomeFactory or Main methods, etc.). But i wonder, is it possible to automatically load some classes(marked with annotation, for example)? P.S I want to notice, that no other classes will be added at run-time, all IProduct implementations are known before compiling. UPD#1 Thank for your answering! But is it possible to make auto-generated property-file with IProduct instances? I mean is it possible to make some build-time script(for maven for example) that generates property-file or loader code? Are there such solutions or frameworks? UPD#2 I finished with using Reflections library that provides run-time information, by scanning classpath at startup. A: This is possible, but not easily. It would need to scan all the classes in the classpath to see if they have an annotation or implement the IProduct interface. See How do you find all subclasses of a given class in Java? for answers to such a problem. I would do keep it simple and just have a list of classes to load, either in the factory itself, or in an external file (properties file, for example). A: * *Have each product register itself, using a static block like this: class MyProduct1{ static{ SomeFactory.register(MyProduct1.getClass()); } .. .. } *An external property file can keep track of all Products. *Your main method can parse this list of Products and do a Class.forName(".."). This way you wouldnt need to code any specific product, just the property file keeps changing. Ah! yes adding security registration would also be a plus point. Note: I'm just proposing an idea, I'vent tried it myself :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7619153", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: PHPExcel : Splitting an Excel document sheet by sheet I'm using PHPExcel library for many Excel manipulations, combined with PHP/MySQL. That helps me well. But I can't figure how to split an Excel document sheet by sheet,where each sheet is created as a new Excel document. I also need, at the same time, to delete the empty lines which are in the original document in the new Excel documents produced (cleaning up the final docs). What's the best way to do it ? All your experiences are greatly appreciated. Best regards. A: I have found the way of what I wanted. Here is a solution (maybe not the best way, but it works fine enough) : $file = $_POST['file']; $filename = pathinfo($file, PATHINFO_FILENAME); require_once 'phpexcel/Classes/PHPExcel.php'; $xls = new PHPExcel(); $xlsReader= new PHPExcel_Reader_Excel5(); $xlsTemplate = $xlsReader->load($file); $sheet1 = $xlsTemplate->getSheetByName('Sheet1'); $xls->addExternalSheet($sheet1,0); $xls->removeSheetByIndex(1); $xlsWriter = new PHPExcel_Writer_Excel5($xls); $xlsWriter->save($filename."_Sheet1.xls"); $sheet2 = $xlsTemplate->getSheetByName('Sheet2'); $xls->addExternalSheet($sheet2,0); $xls->removeSheetByIndex(1); $xlsWriter = new PHPExcel_Writer_Excel5($xls); $xlsWriter->save($filename."_Sheet2.xls"); $sheet3 = $xlsTemplate->getSheetByName('Sheet3'); $xls->addExternalSheet($sheet3,0); $xls->removeSheetByIndex(1); $xlsWriter = new PHPExcel_Writer_Excel5($xls); $xlsWriter->save($filename."_Sheet3.xls"); $sheet4 = $xlsTemplate->getSheetByName('Sheet4'); $xls->addExternalSheet($sheet4,0); $xls->removeSheetByIndex(1); $xlsWriter = new PHPExcel_Writer_Excel5($xls); $xlsWriter->save($filename."_Sheet4.xls"); $sheet5 = $xlsTemplate->getSheetByName('Sheet5'); $xls->addExternalSheet($sheet5,0); $xls->removeSheetByIndex(1); $xlsWriter = new PHPExcel_Writer_Excel5($xls); $xlsWriter->save($filename."_Sheet5.xls"); $sheet6 = $xlsTemplate->getSheetByName('Sheet6'); $xls->addExternalSheet($sheet6,0); $xls->removeSheetByIndex(1); $xlsWriter = new PHPExcel_Writer_Excel5($xls); $xlsWriter->save($filename."_Sheet6.xls"); Then, my original Excel file, containing 6 sheets is now splitted in 6 Excel files, as I wanted. As you can see, it was not so hard to release, but the documentation is so confusing... Hope this can help.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619154", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to upload image with reduced size I am using asp.net fileupload control for uploading image but here i want to automatically re size to 250*200px. please suggest me what to add in my code. I am a novice to asp.net. protected void Button1_Click(object sender, EventArgs e) { string s =@"~\img\"+FileUpload1.FileName; FileUpload1.PostedFile.SaveAs(Server.MapPath(s)); } A: i also find this code useful for resizing using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.IO; using System.Data.SqlClient; using System.Drawing.Imaging; using System.Drawing.Drawing2D; using System.Drawing; public partial class ImageUpload : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void btnUpload_Click(object sender, EventArgs e) { string ImageName = txtName.Text; if (FileUpLoad1.PostedFile != null && FileUpLoad1.PostedFile.FileName != null) { string strExtension = System.IO.Path.GetExtension(FileUpLoad1.FileName); if ((strExtension.ToUpper() == ".JPG") | (strExtension.ToUpper() == ".GIF")) { // Resize Image Before Uploading to DataBase FileUpload fi = new FileUpload(); fi = FileUpLoad1; System.Drawing.Image imageToBeResized = System.Drawing.Image.FromStream( fi.PostedFile.InputStream); int imageHeight = imageToBeResized.Height; int imageWidth = imageToBeResized.Width; int maxHeight = 120; int maxWidth = 160; imageHeight = (imageHeight * maxWidth) / imageWidth; imageWidth = maxWidth; if (imageHeight > maxHeight) { imageWidth = (imageWidth * maxHeight) / imageHeight; imageHeight = maxHeight; } Bitmap bitmap = new Bitmap(imageToBeResized, imageWidth, imageHeight); System.IO.MemoryStream stream = new MemoryStream(); bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg); stream.Position = 0; byte[] image = new byte[stream.Length + 1]; stream.Read(image, 0, image.Length); // Create SQL Connection SqlConnection con = new SqlConnection(); con.ConnectionString = ConfigurationManager.ConnectionStrings["Return_AuthorizationsConnectionString"].ConnectionString; SqlCommand cmd = new SqlCommand(); cmd.CommandText = "INSERT INTO Images(ImageName,Image) VALUES (@ImageName,@Image)"; cmd.CommandType = CommandType.Text; cmd.Connection = con; SqlParameter ImageName1 = new SqlParameter("@ImageName", SqlDbType.VarChar, 50); ImageName1.Value = ImageName.ToString(); cmd.Parameters.Add(ImageName1); SqlParameter UploadedImage = new SqlParameter("@Image", SqlDbType.Image, image.Length); UploadedImage.Value = image; cmd.Parameters.Add(UploadedImage); con.Open(); int result = cmd.ExecuteNonQuery(); con.Close(); if (result > 0) lblMessage.Text = "File Uploaded"; GridView1.DataBind(); } } } } A: After you get the image on the server you can resize it save it, and delete the original one. a sample code only for resize http://weblogs.asp.net/gunnarpeipman/archive/2009/04/02/resizing-images-without-loss-of-quality.aspx and here is a full project with source code to manipulate images, including resize. http://www.codeproject.com/KB/web-image/ASPImaging1.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7619157", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to make certain widgets in scroll view unscrollable or sticky at the top of screen like a header I am creating an android application in which the user can view the channel list and programme list on the same screen. For ex :- The image of the channel will be on left and the programmes scheduled will be on the right and the user can horizontally scroll the programme listing and since there will be many channels the user can also scroll the complete layout vertically. All this has been implemented but what i can not get done is the header should be sticky at the top. The header has 2 parts :- 1. Simple Image View on left side above the channels list of images and should remain sticky at top and not be scrollable 2. Timings list header like 00:00 , 01:00 , 02:00 on the right of the above image view and on the above of the programme list and should not be scrollable vertically but should be scrollable horizontally. The following is the code that i am using to display the layout all i can not get it done are the above two points. They just dont remain sticky they also scroll up and down with the rest of layout <RelativeLayout android:layout_width="wrap_content" android:layout_height="wrap_content"> <RelativeLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:id="@+id/image_layout"> <ImageView android:layout_gravity="center_vertical|center_horizontal" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/tv_guide_channels" android:scaleType="fitCenter" android:id="@+id/channel_img_header" android:layout_alignParentTop="true"/> <LinearLayout android:id="@+id/layout_to_add_channel_image" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical" android:background="@color/White" android:layout_below="@id/channel_img_header" android:layout_alignParentBottom="true"/> </RelativeLayout> <RelativeLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_toRightOf="@id/image_layout" android:id="@+id/programme_layout"> <HorizontalScrollView android:layout_width="fill_parent" android:layout_height="wrap_content"> <RelativeLayout android:layout_width="fill_parent" android:layout_height="wrap_content"> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:id="@+id/table_header" android:layout_alignParentTop="true"> </LinearLayout> <ScrollView android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@id/table_header"> <RelativeLayout android:layout_width="fill_parent" android:layout_height="wrap_content"> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center_vertical" android:background="@color/greyblue" android:orientation="vertical" android:id="@+id/table_programme" android:layout_alignParentBottom="true"> </LinearLayout> </RelativeLayout> </ScrollView> </RelativeLayout> </HorizontalScrollView> </RelativeLayout> </RelativeLayout> <LinearLayout android:layout_height="2dip" android:layout_width="fill_parent" android:background="@color/Black"></LinearLayout> A: I know this is an old question, posting my answer as it would help others who is looking for same. I use StickyScrollViewItems library for the same purpose. Any view inside the scrollView can be tagged as 'Sticky' to make it sticky at top. A: Keep your Header View out of any ScrollView. Edited Hi Abhishek By inspiration of your problem I have tried to solve it. You can check it here A: Well thanks for the link but i found the solution :- One can always use custom widgets and its not that scary also :) In my case i used to custom scroll views and in xml mentioned their packagename+className For ex : <org.vision_asia.utils.MyScrollView1 android:id="@+id/sv1" android:layout_below="@id/channel_img_header" android:layout_height="fill_parent" android:layout_width="wrap_content" android:scrollbars="none"> <LinearLayout android:background="@color/White" android:id="@+id/layout_to_add_channel_image" android:layout_alignParentBottom="true" android:layout_below="@id/channel_img_header" android:layout_height="wrap_content" android:layout_width="wrap_content" android:orientation="vertical" /> and you want to synchronize this ScrollView with other scroll view such that if user scrolls this scroll view then simultaneously the other scroll view must get scrolled as if all the elements are under one scroll view only public class MyScrollView1 extends ScrollView { public MyScrollView2 sv2; public MyScrollView1(Context context) { super(context); // TODO Auto-generated constructor stub } public MyScrollView1(Context context, AttributeSet attrs) { super(context, attrs); // TODO Auto-generated constructor stub } @Override protected void onScrollChanged(int l, int t, int oldl, int oldt) { // TODO Auto-generated method stub sv2.scrollTo(oldt, t); super.onScrollChanged(l, t, oldl, oldt); } } and in your main activity you must call the custom scroll view like this :- sv1 = (MyScrollView1)channelsList.findViewById(R.id.sv1); sv1.sv2 = sv2; where sv2 is the scrollview which should be synchronized For complete synchronization you will need 2 custom scroll views Enjoy
{ "language": "en", "url": "https://stackoverflow.com/questions/7619165", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to create a javascript object like Date()? I wonder how is it possible to create an object for example MyObject() which it can act like javascript Date object when we +(new MyObject()) like: var a = new Date(); alert(+a); A: Your object needs to have a valueOf method like so: var f=new function(){ this.valueOf=function(){ return 5; } }; alert(+f); // Displays 5 If you don't want to define the method on the object but on its prototype as the comments suggested, use the following: function MyObject(value){ this.value = value; } MyObject.prototype.valueOf = function(){ return this.value } var o = new MyObject(17); alert(+o); // Displays 17 A: Create a function, which changes the this property. After defining the function using function(){}, add methods to it using prototype. Normally, an instance of a function created using the new keyword will return an Object, which reprsents the this inside the defined function. When you define a toString method, the function will show a custom string when called from within a string context (default [object Object]. Example: function MyClass(value){ this.value = value this.init_var = 1; } MyClass.prototype.getInitVar = function(){ return this.init_var; } MyClass.prototype.setInitVar = function(arg_var){ this.init_var = arg_var; } MyClass.prototype.toString = function(){ return "This class has the following property: " + this.init_var; } var class_instance = new MyClass(); class_instance.setInitVar(3.1415); alert(class_instance) A: Here is the solution, var MyObject = Date; var b= new MyObject(); alert(+b) //It will display the current date in milliseconds; Hope this helps you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619167", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Register a path via template layer, alt to hook_menu Is there a way to register a path via template layer, like what hook_menu does via a module? I can only work with isset($_GET['some_path']), but I am expecting more like a real registered path. *some_path can be any special page which simply return/print 'print', 'unstyled content, 'xml' pages, etc. Any hint would be very much appreciated. Thanks A: i don't understand what u want exactly but if u want to implement hook_menu inside template file then.. im not sure about this but try to add the file name in the .info file like the following files[] = my_template_file.tpl.php then implement the hook inside your template file dont forget to clear the cache
{ "language": "en", "url": "https://stackoverflow.com/questions/7619170", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java How to mock the object and static method in java? I am writing a junit of CustomerHelper which internally calls the method of AccountHelper object. The CustomerHelper is creating the AccountHelper object with new operator inside one of its method. Now if i want to mock the AccountHelper object.Is there any way i can do it? If this dependency (AccountHelper in this case) would have been injected by some setter or constructor, i could have set my MockAccountHelper.Right? But is there any way we can do mocking when we are creating dependency with New operator? Second question:- Is there anyway we can mock static methods using core java library without going for Power/Easy Mock?Even if i go power mocks , want to understand how it is doing it internally in brief? A: JMockit allows you to easily mock static methods and internally-constructed objects. You'd do something like this: @Test public void testWhatever() { new Expectations() { AccountHelper accountHelper; { new AccountHelper(); accountHelper.someMethod(); }} objectUnderTest.doWhatever(); } I don't believe there is a built-in way to mock static methods in the core Java library. I'm also not sure exactly what happens internally, but I think that JMockit does some kind of bytecode-level tinkering to replace classes on the fly. A: You will need a way to set the desired mock of AccountHelper to your CustomerHelper in your test cases. So your CustomerHelper class will require either a setter for AccountHelper or a constructor that can pass the desired AccountHelper. I guess there is no way for you to set a mock, if AccountHelper is instantiated locally in a method. You don't have access to it from outside(like your junit testcase), it's scope is just local to your method. You cannot mock static methods. I guess that mocking libraries create mocks dynamically using some bytecode generation libraries such as http://asm.ow2.org/index.html or http://cglib.sourceforge.net/ The bytecode framework will generate the mock classes bytecode at runtime. And they do it by overriding methods. But static methods cannot be overridden. Tiberiu A: If this dependency (AccountHelper in this case) would have been injected by some setter or constructor, i could have set my MockAccountHelper.Right? But is there any way we can do mocking when we are creating dependency with New operator? Yes - thats right, but more important that having the object injected is to have the type of object implement an interface which can then be used by mocking type too. The problem with mocking types that dont have any clear interface is that it is not easy to create parallel mocking types that are guarenteed to honor the original contract, while varying the implementation. The only way I see possible in your case is to create a new type AccountHelperMock that extends AccountHelper and overrides all methods ( I hope it can ). Then in your code have the new AccountHelper() replaced by new AccountHelperMock() manually where you want to mock this. A: There is powermockito library available to mock the static method call inside a testing class. The maven repository for powermockito library is: <dependency> <groupId>org.powermock</groupId> <artifactId>powermock-api-mockito</artifactId> <version>1.6.6</version> </dependency> If you want to need more about powermockito, here is a link. A: I use the following code structure when testing static methods. Powermock.mockStatic(Something.class) Something.someMethod(); // Static Method you want to mock EasyMock.expectLastCall().andReturn(/*Whatever you want to return*/); Powermock.replay(Something.class); // Call which makes use of Something.someMethod Powermock.verify(Something.class); Ideally you shouldn't need to test static methods. PowerMock is a Java framework that allows you to unit test code normally regarded as untestable.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619180", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: deploying a new version of a GWT project to GAE doesn't work I have a problem deploying to GAE. I have deployed new versions many times, but now it creates the new staging directory properly, but it uploads 0 files to the server. It is like it doesn't notice the code changes. And when I execute it in the server it doesn't make anything, not even activate an instance. Thanks in advance. Configuration: GWT 2.4 GAE 1.5.4 A: You probably need to rollback a failed update. In the eclipse plugin directory will a folder named appengine-java-sdk-1.3.5. Inside the bin subfolder is a program called appcfg.cmd (I think, there may be a different extension). From the command line run: appcfg.cmd rollback C:/path/to/war_directory
{ "language": "en", "url": "https://stackoverflow.com/questions/7619181", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: stream.publish issue, share is not working Two days ago I started to develop a new application, and I am just copied and pasted my other application, and then change it like how I want. **The problem is that my old application worked perfectly with the share function, but the new one gives an error: An error occurred. Please try again later. I didn't forget to change APP_ID in FB.init. My share function: <script type="text/javascript"> function fb_share() { var publish = { method: 'stream.publish', message: 'Apie tai, kuo gyvena kauniečiai :)', attachment: { name: 'Kas vyksta Kaune tiesioginės transliacijos', caption: '', description: ( 'Kas vyksta Kaune vaizdas gyvai visiems kauniečiams!' ), media: [ { type: 'image', href: 'http://www.facebook.com/Kaunas.gyvai?sk=app_292352984114290', src: 'http://misterp.lt/apps/share/Bambuser_app_icon.jpg' } ] ,href: 'http://www.facebook.com/Kaunas.gyvai?sk=app_292352984114290' }, action_links: [ { text: 'Tinklapis', href: 'http://www.facebook.com/Kaunas.gyvai?sk=app_292352984114290' } ], user_message_prompt: 'Kas vyksta Kaune tiesioginės transliacijos' }; FB.ui(publish, function(response) { console.log(response); }); } </script> A: I found an answer. The problem was that I included the "Facebook live stream" plugin in my application and at the same time used fbAsyncInit to resize the iframe. I just deleted js.src = "//connect.facebook.net/en_US/all.js#appId=292352984114290&xfbml=1"; from the fb-live-stream plugin and the share function started to work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619187", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to keep track of CurrentUser in WPF using ASP.NET Membership I have the following needs. I am using ASP.NET Membership installed into my database. I need to create a WPF application which needs to have login functionality. I have imported the System.Web.Security namespace so I can validate and create users with Membership static methods. My question is if there is something similar to keep track which user is logged (like HttpContext.Current.User.Identity in ASP.NET)? Whats the way to get the userID (guid) other than searching the database for user by username? Thank you in advance A: Try System.Security.Principal.WindowsIdentity.GetCurrent() or Environment.UserName property.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619190", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to get the attribure value of firstnode which is having its attribute value starts with "Heading" and assign to a variable in xslt2.0? This is XML Document. <w:document xmlns:w="w"> <w:body> <w:p> <w:pPr> <w:pStyle w:val="Normal"/> </w:pPr> <w:r> <w:t> Para1 </w:t> </w:r> </w:p> <w:p> <w:pPr> <w:pStyle w:val="Heading1"/> </w:pPr> <w:r> <w:t> Para2 </w:t> </w:r> </w:p> <w:p> <w:pPr> <w:pStyle w:val="Heading2"/> </w:pPr> <w:r> <w:t> Para3 </w:t> </w:r> </w:p> <w:p> <w:pPr> <w:pStyle w:val="Heading1"/> </w:pPr> <w:r> <w:t> Para4 </w:t> </w:r> </w:p> <w:p> <w:pPr> <w:pStyle w:val="Heading2"/> </w:pPr> <w:r> <w:t> Para5 </w:t> </w:r> </w:p> <w:tbl> <w:tr> <w:tc> <w:p> <w:r> <w:t> Para6 </w:t> </w:r> </w:p> </w:tc> <w:tc> <w:p> <w:r> <w:t> Para7 </w:t> </w:r> </w:p> </w:tc> </w:tr> </w:tbl> <w:p> <w:pPr> <w:pStyle w:val="Heading1"/> </w:pPr> <w:r> <w:t> Para8 </w:t> </w:r> </w:p> <w:tbl> <w:tr> <w:tc> <w:p> <w:r> <w:t> Para9 </w:t> </w:r> </w:p> </w:tc> <w:tc> <w:p> <w:r> <w:t> Para10 </w:t> </w:r> </w:p> </w:tc> </w:tr> </w:tbl> <w:p> <w:pPr> <w:pStyle w:val="Heading2"/> </w:pPr> <w:r> <w:t> Para11 </w:t> </w:r> </w:p> </w:body> </w:document> Now , * *i want to search first <w:p><w:pPr><w:pStyle> that having it's w:val attribute value starting with "Heading". *After finding this, assign that attribute value(for example,Heading1 which is in the 2nd <w:p><w:pPr><w:pStyle>) to a variable(for example,variableName in xslt file). *Assign that variable(for example,topLevelHeadings in xslt file) into my specific another variable where i wanted. This is Xslt File for your reference... <xsl:template match="*"> <Document> <xsl:variable name="variableName" select="?"/> <!-- here i want the stuff --> <xsl:variable name="topLevelHeadings" select = "//w:body/w:p[w:pPr[w:pStyle(@w:val,'$variableName')]]"/> <xsl:choose> <xsl:when test="$topLevelHeadings"> <!-- Do things here --> </xsl:when> <xsl:otherwise> <!-- Do things here --> </xsl:otherwise> </xsl:choose> </Document> </xsl:template> Please Guide me to get out of this issue... A: <xsl:variable name="variableName" select="(//w:p/w:pPr/w:pStyle[starts-with(@w:val, 'Heading')])[1]/@w:val" /> <xsl:variable name="topLevelHeadings" select="//w:p[w:pPr/w:pStyle/@w:val = $variableName]" />
{ "language": "uk", "url": "https://stackoverflow.com/questions/7619191", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MCTS 70-515 training kit, wrong on view state? On page 123 of the book - chapter 3, lesson 2. it says: " The Page.ViewState property provides a dictionary object for retaining values between multiple requests for the same page. This object is of the type StateBag. When an ASP.NET page is processed, the current state of the page and its controls is hashed into a string and saved in the page as an HTML hidden field called __ViewState. If the data is too long for a single field (as specified in the Page.MaxPageStateFieldLength property), ASP.NET performs view state chunking to split it across multiple hidden fields." my understanding of the __ViewState hidden field is that it stores the values of controls changed when compared to what they were at design time. Not to mention that if __ViewState was a hash of any amount of data it would never get too large since hashes are fixed in size. Is the book wrong? or am i missing something here... A: Viewstate is encoded with base-64. Book is misleading because hashing is one-way operation and it would make pretty impossible to decode it later on the server side. Your understanding is also wrong, viewstate is not storing values different from design-time values. Basically, it is persisting form data between postbacks. Please refer to msdn (http://msdn.microsoft.com/en-us/library/bb386448.aspx) for detailed info. A: I am also studying for this exam using the same book. That particular line seems similar to the information in the following article http://msdn.microsoft.com/en-us/library/ie/75x4ha6s.aspx When the page is processed, the current state of the page and controls is hashed into a string and saved in the page as a hidden field, or multiple hidden fields if the amount of data stored in the ViewState property exceeds the specified value in the MaxPageStateFieldLength property. When the page is posted back to the server, the page parses the view-state string at page initialization and restores property information in the page. However, if you dig elsewhere on MSDN, one gets following explanation which is accurate. http://msdn.microsoft.com/en-us/library/ie/bb386448.aspx By default, view state data is stored in the page in a hidden field and is encoded using base64 encoding. In addition, a hash of the view state data is created from the data by using a machine authentication code (MAC) key. The hash value is added to the encoded view state data and the resulting string is stored in the page. When the page is posted back to the server, the ASP.NET page framework re-computes the hash value and compares it with the value stored in view state. If the hash values do not match, an exception is raised that indicates that view state data might be invalid. By creating a hash value, the ASP.NET page framework can test whether the view state data has been corrupted or tampered with. However, even if it is not tampered with, view state data can still be intercepted and read by malicious users. So, to answer your questions. * *Hashing is done but for validity purposes only. That paragraph is certainly misleading. *Regarding __ViewState, Dooh has provided the link above
{ "language": "en", "url": "https://stackoverflow.com/questions/7619199", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Strange codeigniter issue When I upload my fully working codeigniter app on live server it did not find any controller and cotroller action. For example: my local url is: localhost/myapp/index.php/testcontroller/testaction Yes, It works fine, But when I upload the same thing and url becomes: livesite.com/index.php/testcontroller/testaction It does not work. Shows error that cant fine the controller. I am wondering why it is happening so while it is working on local server. Kindly help controller code: <?php class Ajaxification extends CI_Controller{ public function __construct() { parent::__construct(); $this->load->database();$this->load->model('MAjaxification'); } public function Index(){ } public function getUserDetail(){ $this->load->model('MAjaxification'); $uid = $_REQUEST['uid']; echo $this->MAjaxification->getUserdetail($uid); // echo "A test response"; } public function getRandomUser(){ $top = $_REQUEST['top']; $left = $_REQUEST['lef']; // $this->load->model('MAjaxification'); // print_r($this->MAjaxification->getRandomDonoers());*/ $this->db->select("users.sno,users.full_name,users.userid,users.email,users.pic"); $this->db->from('users'); $this->db->join('donors','users.userid=donors.userid'); $this->db->order_by('rand()'); $this->db->limit(51); $res= $this->db->get(); foreach ($res->result() as $row) { ?> <div style="border:0px solid black; width: 31px; height: 29px; float: left;"> <a onclick="getUserinfoDetail('<?=$row->userid?>')" href="javascript:void(0)"><img width="40" height="40" src="../profile_pix/<?=$row->pic; ?>" /></a> </div><?php } } private function countUsers(){ $this->db->select("users.sno,users.pic"); $this->db->from('users'); $this->db->join('donors','users.userid=donors.userid'); $res = $this->db->get(); return $res->num_rows(); } function getRandUser($f=1,$t){ $index = rand($f, $t); return $index; } public function testme(){ echo "This is a test"; } } ?> A: I never worked with Codeigniter, but if it is similar to Kohana, you have to setup the base_url. [EDIT] Check this post from CodeIgniter forum: https://github.com/EllisLab/CodeIgniter/wiki/Automatic-configbase-url A: I think this problem may be related to some configs in application config folder routes.php : * *$route['default_controller'] you should be set it to the default controller config.php : *$config['base_url'] should be '' if you used the htaccess rules to remove index.php in the URL and also the .htaccess file in the app directory may be causing this problem Also the controller filename must be the same name of the class which extends the CI_Controller A: In config.php add base_url like this; this will automatically get URL: $base = "http://".$_SERVER['HTTP_HOST']; $base .= str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']); $config['base_url'] = $base;
{ "language": "en", "url": "https://stackoverflow.com/questions/7619204", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to load bitmap from res without resizing? Using this code: Drawable blankDrawable = context.getResources().getDrawable(image); Bitmap blankBitmap=((BitmapDrawable)blankDrawable).getBitmap(); I get a bitmap that is scaled to the density of the context, preserving the physical size of the bitmap (based on its dpi value). So for example, I have a 405x500 bitmap (dpi=96) as a resource. But when I load it on a device, I get a 608x750 image with density=240. I want to load the bitmap without scaling. How do I do that? This question is very similar to: How to create a Drawable from a stream without resizing it? However, that solution cannot be used in my case, because I don't have an input stream. All I have is a resource id, and the getDrawable() method does not have parameters for density. Once the bitmap is loaded, it is too late - it was already resized. Thank you. A: Another good option may be to put the bitmap in the drawable-nodpi resource folder A: use this InputStream is = this.getResources().openRawResource(imageId); Bitmap originalBitmap = BitmapFactory.decodeStream(is); imageview.setImageBitmap(originalBitmap); A: Create a drawable (without hdpi/mdpi etc) folder in res. Keep the drawable in that folder. Now try it. This may help you. A: public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ImageView image = (ImageView) findViewById(R.id.test_image); Bitmap bMap = BitmapFactory.decodeResource(getResources(), R.drawable.icon); image.setImageBitmap(bMap); } First create an ImageView instance containing the ImageView from the layout. Then create a bitmap from the application icon (R.drawable.icon) with BitmapFactory.decodeResource(). Finally set the new bitmap to be the image displayed in the ImageView component of the layout. A: When you're decoding the bitmap with BitmapFactory.decodeResource (Resources res, int id, BitmapFactory.Options opts) Set the flag inScaled in BitmapFactory.Options to false first. Example: /* Set the options */ Options opts = new Options(); opts.inDither = true; opts.inPreferredConfig = Bitmap.Config.RGB_565; opts.inScaled = false; /* Flag for no scalling */ /* Load the bitmap with the options */ bitmapImage = BitmapFactory.decodeResource(context.getResources(), R.drawable.imageName, opts);
{ "language": "en", "url": "https://stackoverflow.com/questions/7619207", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "18" }
Q: How to use DataTemplateSelector with a DataGridBoundColumn? I followed the simple method described here and have a DataGrid with dynamically generated columns which allows DataTemplates to be used and bound dynamically. for (int i = 0; i < testDataGridSourceList.DataList[0].Count; i++) { var binding = new Binding(string.Format("[{0}]", i)); CustomBoundColumn customBoundColumn = new CustomBoundColumn(); customBoundColumn.Header = "Col" + i; customBoundColumn.Binding = binding; customBoundColumn.TemplateName = "CustomTemplate"; TestControlDataGrid.TestDataGrid.Columns.Add(customBoundColumn); } Each column is of type CustomBoundColumn which derives from DataGridBoundColumn public class CustomBoundColumn : DataGridBoundColumn { public string TemplateName { get; set; } protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem) { var binding = new Binding(((Binding)Binding).Path.Path); binding.Source = dataItem; var content = new ContentControl(); content.ContentTemplate = (DataTemplate)cell.FindResource(TemplateName); content.SetBinding(ContentControl.ContentProperty, binding); return content; } protected override FrameworkElement GenerateEditingElement(DataGridCell cell, object dataItem) { return GenerateElement(cell, dataItem); } } I would now like to use a DataTemplateSelector to allow each row to use a different DataTemplate instead of just using the "CustomTemplate" shown in the first snippet. How can I do this? A: Sorry for the late answer. I believe the solution is quite simple, just place a ContentPresenter in your "CustomTemplate" : <DataTemplate x:Key="CustomTemplate"> <ContentPresenter Content="{Binding}" ContentTemplateSelector="{StaticResource myTemplateSelector}"> </ContentPresenter> </DataTemplate> And there you go! You can now use a DataTemplateSelector. A good example here. A: In the end I replaced content.ContentTemplate = (DataTemplate)cell.FindResource(TemplateName); with content.ContentTemplateSelector = (DataTemplateSelector)cell.FindResource("templateSelector"); where 'templateSelector' is the key of a DataTemplateSelector declared as a Static Resource in the XAML code. This works fine. A: I made a custom column class that combines the DataGridBoundColumn with the DataGridTemplateColumn. You can set Binding and Template on that column. Here's the source: gist
{ "language": "en", "url": "https://stackoverflow.com/questions/7619208", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Click closest submit button when any 'enter' key event occurs on any input field I have multiple submit button on the page. What I want is if user presses enter on any input field it should click the related submit button. I tried the way below but it even couldnt catch the key press on the input fields. Thanks in advance, $('* input').keypress(function (e) { if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) { $(this).closest('input[type=submit]').click(); } }); A: Try this. .closest() won't work unless the submit button is located upside in the DOM tree. Instead you could search for it inside the input's parentNode, or just submit the form (but you probably don't have a form element, because otherwise this would be the default behavior for the enter key). $(document).ready(function() { $('input[type="text"], input[type="password"]').keypress(function (event) { if (event.keyCode == '13') { //jquery normalizes the keycode event.preventDefault(); //avoids default action $(this).parent().find('input[type="submit"]').trigger('click'); // or $(this).closest('form').submit(); } }); }); A: It is not require javascript at all ! Enter key will call "implicit submission" by standards. When multiple input[type=submit] in form, the first one will implicitelly "clicked" by Enter. So, you should place default button to the first. If you want to swap some buttons, use CSS rules for it. Some interesting facts about buttons and Enter key is here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619212", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How should I make this box shadow work efficiently? I have a small, fixed position header on my site. It has a shadow at the bottom of it. It is all nice and good, but I think it would look better if the header would have a border originally (when the page loads) and when the user scrolls down the shadow would appear and the border would disappear. Also I would like the process to work backwards as well. So when the user scrolls up to the top the shadow disappears and the border appears. How could I write this? Could you show me a link to a useful resource or could you show the right piece of code for it? Thanks... [The code is here: http://jsfiddle.net/dp8fG/3/] A: Here, I made one that replaces the border with the shadow and back again. I can make it animated too if you want. http://jsfiddle.net/dp8fG/4/ I did this by using the .hover event and modifying the css using jQuery. $("#header").hover(function(){ //Things to happen on mouseover $(this).css({ 'html element':'modifier', }); },function(){ //Things to happen on mouseout $(this).css({ 'html element':'modifier', }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7619215", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }