text
stringlengths
8
267k
meta
dict
Q: Undefined getUserId() function in MVCTable I use atk 4.1.2. I found a problem while I tried to Insert/Update my Model. It seems like because I added two fields in my table, i.e. : created_by and updated_by. I found these lines caused the problem in MVCTable.php: if (isset($this->fields['created_by'])) $this->dsql('modify',false)->set('created_by',$this->api->getUserId()); if (isset($this->fields['updated_by'])) $this->dsql('modify',false)->set('updated_by',$this->api->getUserId()); The method $this->api->getUserId() is not defined anywhere. I don't know whether this same problem occurs for the previous atk versions. A: Yes, it's a bit of legacy code which I haven't cleaned up yet. Please delete those lines manually and they will not be there in further versions. https://github.com/atk4/atk4-addons/commit/e3b2379
{ "language": "en", "url": "https://stackoverflow.com/questions/7610460", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: remove specific html tags using php Since I dont want to use stip_tags function of php instead of I want to replace <script> and </script> to empty string so that output should be alert(1). Input:- <script>alert(1)</script> Output:- alert(1) how to achieve it. A: I guess you want to prevet XSS attacks, you shouldn't merely worry about script tags, someone might exploit it like this: <a href="http://anywhere.com" onClick="alert(1);">test</a> (this is a very basic way though). If you only want the script tag, with no attributes, to be filtered: str_replace(array('<script>', '</script>'), array('', ''), $str); You should improve this using Regex; using preg_match'es and preg_replaces (or only preg_replaces) you can match and/or replace the script tag with its attributes. Or even have more protection against XSS. Edit: or even a regex like /<script>(.+)<\/script>/ then store what between the brackets into a variable then print it. A: Easy way is using StripTags. go to StripTags github and download or install via composer. this class has a method called only that do this for you! use Mimrahe\StripTags\Stripper; $stripper = new Stripper(); $stripper->text('<a href="#">link</a><p>some paragraph</a>'); $stripper->only(['p']); echo $stripper->strip(); // prints '<a href="#">link</a>some paragraph' A: Either use a simple replace: $string = str_replace(array("<script>","</script>"), ""); or a RegEx: $string = preg_replace("/<script.*?>(.*)?<\/script>/im","$1",$string); A: Try this comrade.. $strn = "<script>alert(1)</script>"; $ptrn = "=^<script>(.*)</script>$=i"; echo preg_match( $ptrn, $strn, $mtchs ); // 0 means fail to matche and 1 means matches was found! var_dump( $mtchs ); results in 1array(2) { [0]=> string(25) "" [1]=> string(8) "alert(1)" } A: You can always use strip_tags() with a second parameter containing the allowable tags. Alternativly, use... preg_replace('/<script>(.*)</script>/i', '$1', $input); Note, not tested. A: echo strip_tags($text, '<p><strong><a>'); Just state the ones you dont want removed in the second param
{ "language": "en", "url": "https://stackoverflow.com/questions/7610461", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: view.getId() returning wrong id in OnItemClickListener In my app i have a Gallery with some images in it. When the user selects an image I want to somehow retrieve the id of the selected image. The int that is returned by getId() is -1. Why am I not getting the system id for the image that was selected? gallery.setOnItemClickListener(new OnItemClickListener() { @SuppressWarnings("rawtypes") @Override public void onItemClick(AdapterView parent, View v, int position, long id) { int imageId = v.getId(); } }); Thanks! A: Use OnItemSelectedListener instead of OnItemClickListener gallery.setOnItemSelectedListener(new OnItemSelectedListener(){ @Override public void onItemSelected(AdapterView<?> parent, View view,int pos, long id){ // TODO Auto-generated method stub } @Override public void onNothingSelected(AdapterView<?> arg0) { // TODO Auto-generated method stub } }); A: use this public void onItemClick(AdapterView<?> parent, View v, int position, long id) { int imageId = (( ImageAdapter)parent.getAdapter()).mygetItemId(position); } }); in adapter class add this function public long getItemId(int position) { return imagearray[position]; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7610464", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Multiple Featured Images Wordpress So my aim is to find a method of adding more thumbnails only for displaying on a custom post type, for example I wish to have a large image (not the same image) for a featured post and a different image for the default view. A: In the end i followed this tutorial and it did exactly what i required to a T. http://www.lifeonlars.com/wordpress/how-to-add-multiple-featured-images-in-wordpress A: have you try this add_image_size why don't you use custom post template plugin A: I got a solution from online. I also customized some code. You can check this. Step 1 Download this library from this link and put beside functions.php ( theme root ). Step 2: Copy this code below to functions.php. /* * Code for Multiple Featured Image. * Multiple Featured image is only for your selected post type. */ require_once('library/multi-post-thumbnails.php'); if (class_exists('MultiPostThumbnails')) { new MultiPostThumbnails(array( 'label' => '2nd Feature Image', 'id' => 'feature-image-2', 'post_type' => 'your_post_type_name' ) ); new MultiPostThumbnails(array( 'label' => '3rd Feature Image', 'id' => 'feature-image-3', 'post_type' => 'your_post_type_name' ) ); new MultiPostThumbnails(array( 'label' => '4th Feature Image', 'id' => 'feature-image-4', 'post_type' => 'your_post_type_name' ) ); }; Step 3 Check now. A: I can write entire code here, but clicking on this tutorial link is much easier :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7610476", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to pass variable as a parameter in Execute SQL Task SSIS? I have ssis package in that I'm taking values from flat file and insert it into table. I have taken one Execute SQL Task in that creating one temptable CREATE TABLE [tempdb].dbo.##temptable ( date datetime, companyname nvarchar(50), price decimal(10,0), PortfolioId int, stype nvarchar(50) ) Insert into [tempdb].dbo.##temptable (date,companyname,price,PortfolioId,stype) SELECT date,companyname,price,PortfolioId,stype FROM ProgressNAV WHERE (Date = '2011-09-30') AND (PortfolioId = 5) AND (stype in ('Index')) ORDER BY CompanyName Now in above query I need to pass (Date = '2011-09-30') AND (PortfolioId = 5) AND (stype in ('Index')) these 3 parameter using variable name I have created variables in package so that I become dynamic. A: SELECT, INSERT, UPDATE, and DELETE commands frequently include WHERE clauses to specify filters that define the conditions each row in the source tables must meet to qualify for an SQL command. Parameters provide the filter values in the WHERE clauses. You can use parameter markers to dynamically provide parameter values. The rules for which parameter markers and parameter names can be used in the SQL statement depend on the type of connection manager that the Execute SQL uses. The following table lists examples of the SELECT command by connection manager type. The INSERT, UPDATE, and DELETE statements are similar. The examples use SELECT to return products from the Product table in AdventureWorks2012 that have a ProductID greater than and less than the values specified by two parameters. EXCEL, ODBC, and OLEDB SELECT* FROM Production.Product WHERE ProductId > ? AND ProductID < ? ADO SELECT * FROM Production.Product WHERE ProductId > ? AND ProductID < ? ADO.NET SELECT* FROM Production.Product WHERE ProductId > @parmMinProductID AND ProductID < @parmMaxProductID The examples would require parameters that have the following names: The EXCEL and OLED DB connection managers use the parameter names 0 and 1. The ODBC connection type uses 1 and 2. The ADO connection type could use any two parameter names, such as Param1 and Param2, but the parameters must be mapped by their ordinal position in the parameter list. The ADO.NET connection type uses the parameter names @parmMinProductID and @parmMaxProductID. A: A little late to the party, but this is how I did it for an insert: DECLARE @ManagerID AS Varchar (25) = 'NA' DECLARE @ManagerEmail AS Varchar (50) = 'NA' Declare @RecordCount AS int = 0 SET @ManagerID = ? SET @ManagerEmail = ? SET @RecordCount = ? INSERT INTO... A: The EXCEL and OLED DB connection managers use the parameter names 0 and 1. I was using a oledb connection and wasted couple of hours trying to figure out the reason why the query was not working or taking the parameters. the above explanation helped a lot Thanks a lot. A: Along with @PaulStock's answer, Depending on your connection type, your variable names and SQLStatement/SQLStatementSource Changes https://learn.microsoft.com/en-us/sql/integration-services/control-flow/execute-sql-task A: In your Execute SQL Task, make sure SQLSourceType is set to Direct Input, then your SQL Statement is the name of the stored proc, with questionmarks for each paramter of the proc, like so: Click the parameter mapping in the left column and add each paramter from your stored proc and map it to your SSIS variable: Now when this task runs it will pass the SSIS variables to the stored proc.
{ "language": "en", "url": "https://stackoverflow.com/questions/7610491", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "58" }
Q: Inserting text in teaxtarea cannot recognize new line I am reading from a <td> and inserting the text in a textarea but all texts appearing in one line. I want to keep the formatting in the textarea as the text read from the column. $("#text").text($.trim($(this).closest('tr').next('tr').find('.mytext).text())); The text should be my test is working with spaces but not with new line. <br />This is a new line. But it seems that it not able to interprete the <br/>. How can I make it read the <br/> and display a new line in the textarea. A: Your use of .text() will not get the <br /> since that is not text. From the docs: Get the combined text contents of each element in the set of matched elements, including their descendants. Note it is only the text contents. I don't know what would happen if there were "real" line breaks in the text (as opposed to html ones) but this is where you want to look at your issue. A: Replace the br-elements by a \n character, I think that should work. A: Assuming that you're pulling raw HTML (with <br /> tags intact, rather than just the text), do as JNDPNT suggested, replace all <br /> tags with the \n literal: var input = 'my test is working with spaces but not with new line.<br />This is a new line.'; // This is a simulation of an input string // Create the output (replace all <br /> tags with \n): var output_text = input.replace(new RegExp('<br />', 'g'), '\n'); $('#output').val(output_text); Here's a jsFiddle showing it working: http://jsfiddle.net/xYHjn/
{ "language": "en", "url": "https://stackoverflow.com/questions/7610492", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Get rank of matrix entries? Assume a matrix: > a <- matrix(c(100, 90, 80, 20), 2, 2) > a [,1] [,2] [1,] 100 80 [2,] 90 20 Suppose I want to convert the elements of the matrix to ranks: >rank.a <- rank(a) > rank.a [1] 4 3 2 1 This returns a vector, i.e. the matrix structure is lost. Is it possible to rank a matrix such that the output will be of the form: [,1] [,2] [1,] 4 2 [2,] 3 1 A: An alternative to @EDi's Answer is to copy a and then assign the output of rank(a) directly into the elements of the copy of a: > a <- matrix(c(100, 90, 80, 20), 2, 2) > rank.a <- a > rank.a[] <- rank(a) > rank.a [,1] [,2] [1,] 4 2 [2,] 3 1 That saves you from rebuilding a matrix by interrogating the dimensions of the input matrix. Note that (as @Andrie mentions in the comments) the copying of a is only required if one wants to keep the original a. The main point to note is that because a is already of the appropriate dimensions, we can treat it like a vector and replace the contents of a with the vector of ranks of a. A: why not convert the vector back to a matrix, with the dimensions of the original matrix? > a <- matrix(c(100, 90, 80, 20, 10, 5), 2, 3) > a [,1] [,2] [,3] [1,] 100 80 10 [2,] 90 20 5 > rank(a) [1] 6 5 4 3 2 1 > rmat <- matrix(rank(a), nrow = dim(a)[1], ncol = dim(a)[2]) > rmat [,1] [,2] [,3] [1,] 6 4 2 [2,] 5 3 1 A: @Gavin Simpson has a very nice and elegant solution! But there is one caveat though: The type of the matrix will stay the same or be widened. Mostly you wouldn't notice, but consider the following: a <- matrix( sample(letters, 4), 2, 2) rank.a <- a rank.a[] <- rank(a) typeof(rank.a) # character Since the matrix was character to start with, the rank values (which are doubles) got coerced into character strings! Here's a safer way that simply copies all the attributes: a <- matrix( sample(letters, 4), 2, 2) rank.a <- rank(a) attributes(rank.a) <- attributes(a) typeof(rank.a) # double Or, as a one-liner using structure to copy only the relevant attributes (but more typing): a <- matrix( sample(letters, 4), 2, 2) rank.a <- structure(rank(a), dim=dim(a), dimnames=dimnames(a)) Of course, dimnames could be left out in this particular case.
{ "language": "en", "url": "https://stackoverflow.com/questions/7610495", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Google Maps Apiv3 + Load map on page load + a is NULL First of all: The map is working. The script is in scripts.js, which is included at the bottom of the site. The Google maps script is included in the header (<script src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>). The problem is I am getting this a is NULL error and I would like to fix it, although the map is working fine. I have searched Google and Stackoverflow and tried every possible combination of the answers I found, but either the map is not working, or the map is working, but I get this a is NULL error error. Here is the simple demo script I am using for testing: function init() { var myOptions = { zoom: 8, center: new google.maps.LatLng(-34.397, 150.644), mapTypeId: google.maps.MapTypeId.ROADMAP }; map = new google.maps.Map(document.getElementById('resultsGmap'), myOptions); } window.onload=init(); I have tried to use jQuery too like this: $(function() { init(); }); But than nothing works at all. I have also tried to do it very simple like this: init(); Which works (the map works) but the a is NULL error error appears again. The other thing I tried was: google.maps.event.addDomListener(window, 'load', init); But than again the map doesn't display and the error appears. For various reason I cant do it the way it is in the official example @ Google: <body onload="init()"> Anybody got an idea what I am doing wrong? Regards and have a good day! EDIT: I have just tried to reproduce the error on a blank page and there it doesnt appear - so I guess it is something else in my code (p.s. I am loading the site with the map via ajax and call the script with $.getScript). Sorry that I didnt check that before. I guess the error lies in there somewhere. One more thing: Do you guys think it would be very, very bad to just ignore the error? Since the map and every feature is working correctly. A: I'm suspecting it has to do with the ID you provide. Is there a (for example) DIV with the ID 'resultsGmap'. It might have also got to do with the uppercase. Try using lowercase only, optionally with underscores (_)
{ "language": "en", "url": "https://stackoverflow.com/questions/7610496", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Problems with NauckIT.PostgreSQLProvider I have a problem with AspSQL Provider for PostgreSQL (http://dev.nauck-it.de/projects/aspsqlprovider). When I try to create Roles with the ASP.NET Web Site Administration Tool this message keeps coming up: There is a problem with your selected data store. This can be caused by an invalid server name or credentials, or by insufficient permission. It can also be caused by the role manager feature not being enabled. Click the button below to be redirected to a page where you can choose a new data store. The following message may help in diagnosing the problem: exePath must be specified when not running inside a stand alone exe. (D:\Documents\Programming\Projects\Portal\web.config line 40) Here is the web.config section: <membership defaultProvider="PgMembershipProvider"> <providers> <clear /> <add name="PgMembershipProvider" type="NauckIT.PostgreSQLProvider.PgMembershipProvider" connectionStringName="db" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="bp" /> </providers> </membership> <roleManager enabled="true" defaultProvider="PgRoleProvider" cacheRolesInCookie="true" cookieName=".AspNetRoles" cookiePath="/" cookieProtection="All" cookieRequireSSL="false" cookieSlidingExpiration="true" createPersistentCookie="false" cookieTimeout="30" maxCachedResults="25"> <providers> <clear /> <add name="PgRoleProvider" type="NauckIT.PostgreSQLProvider.PgRoleProvider" connectionStringName="db" applicationName="bp" /> </providers> </roleManager> <profile enabled="true" defaultProvider="PgProfileProvider"> <providers> <clear /> <add name="PgProfileProvider" type="NauckIT.PostgreSQLProvider.PgProfileProvider" connectionStringName="db" applicationName="bp" /> </providers> <properties> <add name="FirstName" /> <add name="LastName" /> </properties> </profile> <sessionState mode="Custom" customProvider="PgSessionStateStoreProvider"> <providers> <clear /> <add name="PgSessionStateStoreProvider" type="NauckIT.PostgreSQLProvider.PgSessionStateStoreProvider" enableExpiredSessionAutoDeletion="true" expiredSessionAutoDeletionInterval="60000" enableSessionExpireCallback="false" connectionStringName="db" applicationName="bp" /> </providers> </sessionState> I followed the instruction Step By Step Thanks in advance A: Seems like HttpContext.Current can be null. The PgMembershipProvider class checks this to see if its hosted or not. Based on the answer, it attempts to either OpenExeConfiguration (for stand-alone) or OpenWebConfiguration for web hosted applications. Since HttpContext.Current can be null sometimes in Asp.Net 4.0, the wrong decision is made and the OpenExeConfiguration is called from within a webapplication (big no-no). The fix is to change PgMembershipProvider.Init to use the following check: Configuration cfg = HostingEnvironment.IsHosted ? WebConfigurationManager.OpenWebConfiguration(HostingEnvironment.ApplicationVirtualPath) : ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); instead of the HttpContext.Current != null check. A: this bug was fixed in the 2.0.0 Version of the Provider. See http://dev.nauck-it.de/issues/131 You can download the latest release via NuGet: https://nuget.org/packages/NauckIT.PostgreSQLProvider/
{ "language": "en", "url": "https://stackoverflow.com/questions/7610501", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: mysql repair threads not spawned In my my.cnf I specify myisam_repair_threads=4 When I add an index to large table in the show processlist I see that mysql outputs: Repair with 2 threads | ALTER TABLE arman.files ADD INDEX (md5sum) Why mysqld does not use more than 2 cores are there more tweaks in configfile to use more cores? thanks Arman. PS I am using mysql 5.5.14
{ "language": "en", "url": "https://stackoverflow.com/questions/7610505", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: "find" and "ls" with GNU parallel I'm trying to use GNU parallel to post a lot of files to a web server. In my directory, I have some files: file1.xml file2.xml and I have a shell script that looks like this: #! /usr/bin/env bash CMD="curl -X POST -d@$1 http://server/path" eval $CMD There's some other stuff in the script, but this was the simplest example. I tried to execute the following command: ls | parallel -j2 script.sh {} Which is what the GNU parallel pages show as the "normal" way to operate on files in a directory. This seems to pass the name of the file into my script, but curl complains that it can't load the data file passed in. However, if I do: find . -name '*.xml' | parallel -j2 script.sh {} it works fine. Is there a difference between how ls and find are passing arguments to my script? Or do I need to do something additional in that script? A: GNU parallel is a variant of xargs. They both have very similar interfaces, and if you're looking for help on parallel, you may have more luck looking up information about xargs. That being said, the way they both operate is fairly simple. With their default behavior, both programs read input from STDIN, then break the input up into tokens based on whitespace. Each of these tokens is then passed to a provided program as an argument. The default for xargs is to pass as many tokens as possible to the program, and then start a new process when the limit is hit. I'm not sure how the default for parallel works. Here is an example: > echo "foo bar \ baz" | xargs echo foo bar baz There are some problems with the default behavior, so it is common to see several variations. The first issue is that because whitespace is used to tokenize, any files with white space in them will cause parallel and xargs to break. One solution is to tokenize around the NULL character instead. find even provides an option to make this easy to do: > echo "Success!" > bad\ filename > find . "bad\ filename" -print0 | xargs -0 cat Success! The -print0 option tells find to seperate files with the NULL character instead of whitespace. The -0 option tells xargs to use the NULL character to tokenize each argument. Note that parallel is a little better than xargs in that its default behavior is the tokenize around only newlines, so there is less of a need to change the default behavior. Another common issue is that you may want to control how the arguments are passed to xargs or parallel. If you need to have a specific placement of the arguments passed to the program, you can use {} to specify where the argument is to be placed. > mkdir new_dir > find -name *.xml | xargs mv {} new_dir This will move all files in the current directory and subdirectories into the new_dir directory. It actually breaks down into the following: > find -name *.xml | xargs echo mv {} new_dir > mv foo.xml new_dir > mv bar.xml new_dir > mv baz.xml new_dir So taking into consideration how xargs and parallel work, you should hopefully be able to see the issue with your command. find . -name '*.xml' will generate a list of xml files to be passed to the script.sh program. > find . -name '*.xml' | parallel -j2 echo script.sh {} > script.sh foo.xml > script.sh bar.xml > script.sh baz.xml However, ls | parallel -j2 script.sh {} will generate a list of ALL files in the current directory to be passed to the script.sh program. > ls | parallel -j2 echo script.sh {} > script.sh some_directory > script.sh some_file > script.sh foo.xml > ... A more correct variant on the ls version would be as follows: > ls *.xml | parallel -j2 script.sh {} However, and important difference between this and the find version is that find will search through all subdirectories for files, while ls will only search the current directory. The equivalent find version of the above ls command would be as follows: > find -maxdepth 1 -name '*.xml' This will only search the current directory. A: Since it works with find you probably want to see what command GNU Parallel is running (using -v or --dryrun) and then try to run the failing commands manually. ls *.xml | parallel --dryrun -j2 script.sh find -maxdepth 1 -name '*.xml' | parallel --dryrun -j2 script.sh A: I have not used parallel but there is a different between ls & find . -name '*.xml'. ls will list all the files and directories where as find . -name '*.xml' will list only the files (and directories) which end with a .xml. As suggested by Paul Rubel, just print the value of $1 in your script to check this. Additionally you may want to consider filtering the input to files only in find with the -type f option. Hope this helps! A: Neat. I had never used parallel before. It appears, though that there are two of them. One is the Gnu Parrallel, and the one that was installed on my system has Tollef Fog Heen listed as the author in the man pages. As Paul mentioned, you should use set -x Also, the paradigm that you mentioned above doesn't seem to work on my parallel, rather, I have to do the following: $ cat ../script.sh + cat ../script.sh #!/bin/bash echo $@ $ parallel -ij2 ../script.sh {} -- $(find -name '*.xml') ++ find -name '*.xml' + parallel -ij2 ../script.sh '{}' -- ./b.xml ./c.xml ./a.xml ./d.xml ./e.xml ./c.xml ./b.xml ./d.xml ./a.xml ./e.xml $ parallel -ij2 ../script.sh {} -- $(ls *.xml) ++ ls --color=auto a.xml b.xml c.xml d.xml e.xml + parallel -ij2 ../script.sh '{}' -- a.xml b.xml c.xml d.xml e.xml b.xml a.xml d.xml c.xml e.xml find does provide a different input, It prepends the relative path to the name. Maybe that is what is messing up your script?
{ "language": "en", "url": "https://stackoverflow.com/questions/7610507", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: How to expose properties of a user control in .NET for the MVP pattern I am implementing a simple UserControl that is actually a fancy TextBox. One of its features is that you can set a formatting specification and this formatting get's applied to its contents automatically. For example, if you set the formatting specification to "000" and the contents are "42", then "042" will appear. I am implementing this UserControl following the MVP pattern. The implementation is similar to this: how Implement usercontrol in winforms mvp pattern?. Also, check this question: passive view and display logic Approach #1 My Title property in the View looks like this: private string title; public string Title { get { return title; } set { title = value; titleTextBox.Text = presenter.Format(title); } } It is my feeling that this implementation adds unnecessary coupling. For example, if I change the Presenter's Format method then I will have to go through all Views and change appropriately the call statement. Approach #2 My Title property in the View looks like this: public string Title { get { return presenter.Title; } set { presenter.Title = value; } } My Title property in the Presenter looks like this: private string title; public string Title { get { return title; } set { _view.SetTitle(this.Format(value); } } Now I have to add the SetTitle method in the View interface and in the View implementation: public void SetTitle(string title) { titleTextBox.Text = title; } So, with this approach I get this ugly SetTitle Java-like method. Approach #3 Instead of calling SetTitle create a new property RealTitle in the View and set that. It remains ugly with this Real prefix. Your approach Can you think of a better way? Use case The UserControl should be used like this: var c = new FancyTextBox(); c.Format = "000"; c.Text = "42"; Controls.Add(c); This snippet should display "042" inside the UserControl. The big picture Form FancyTextBoxView FancyTextBoxPresenter | | | | ftb.Text = "42" | | |-------------------->| | | | | | | A | | |----------------------------->| | | | | | B | | |<-----------------------------| What are the A and B actions? I want the formatted text to appear in the UI. The formatting code is in the Presenter. The View has a titleTextBox that will hold the text in the UI. A: Why don't you just define your View's Title property like this? public string Title { get { return titleTextBox.Text; } set { titleTextBox.Text = value; } } There is absolutely no reason to define an additional SetTitle method. Also, in MVP, your view should never know about your Presenter. Then whenever your Format function gets triggered, you can set the title of your view from there, for example: void OnFormatCalled() { _view.Title = FormatTitle(_view.Title); } A: I normally inject the View interface (and Model interface) into the Presenter. Now you have one place to worry about dependencies and testing. Have your view fire an event when the title is set and have your Presenter subscribe to it. Then the Presenter can format the text and set the title on the view - the Presenter is in charge of the presentation of the view, the view just renders stuff. In this way the view is really dumb with little logic at all. This lends itself to being mocked out during unit testing and makes the presenter really easy to test. Also notice how the formatting logic is also injected into the Presenter through a delegate property, thus decoupling the formatting from the presenter and making it changeable and testable. Just one way of doing it anyway...I like this approach. public class Presenter { private IView _view; private IModel _model; public Func<string, string> TitleFormatter { get; set; } public Presenter(IView view, IModel model) { _model = model; _view = view; _view.OnSetTitle += (s, e) => { _view.Title = TitleFormatter(e.Text); }; } } public View : IView { public event EventHandler<TitleChangedEventArgs> TitleChanged; public SomeUserActionEvent(object sender, SomeUserInterfaceEventArgs e) { TitleChanged(e.Text); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7610511", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: MvcMailer: The context is already tracking a different entity with the same resource Uri i cant seem to figured out why i cant install nuget pakcage ive tried running this in visual studio 2010 package manager Install-Package MvcMailer but i get an error shown below PM> install-package MvcMailer Install-Package : The context is already tracking a different entity with the same resource Uri. At line:1 char:16 + install-package <<<< MvcMailer + CategoryInfo : NotSpecified: (:) [Install-Package], InvalidOperationException + FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PowerShell.Commands.InstallPackageCommand PM> any ideas how to resolve this issue? tnx A: From MSDN: this error will occur if deserialized type dont really match the data Type of the entity being tracked. a fix for this is via using no tracking option. more information can be found here http://msdn.microsoft.com/en-us/library/system.data.services.client.mergeoption.aspx also, it is advisable to use a new, different Data Service Context for every logical operation like insert and queries context.
{ "language": "en", "url": "https://stackoverflow.com/questions/7610513", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get a string instead of an array in PowerShell? I'm trying to do the following: $files = Get-ChildItem c:\temp | Select-Object Name foreach ($i in $files) { Write-Host "Filename is $i" } Sample result: Filename is @{Name=oracle10204.rsp} Filename is @{Name=powershell.txt} How do I get only the following? Filename is oracle10204.rsp Filename is powershell.txt A: With the -Name switch you can get object names only: Get-ChildItem c:\temp -Name A: If you are adamant about getting your original attempt to work, try replacing Select-Object Name with Select-Object -ExpandProperty Name A: I am not sure why you are using Select-Object here, but I would just do: Get-ChildItem c:\temp | % {Write-Host "Filename is $($_.name)"} This pipes the output of Get-ChildItem to a Foreach-Object (abbreviation %), which runs the command for each object in the pipeline. $_ is the universal piped-object variable. A: Here is the answer to get just the name from your example. Surround the $i with $( ) and reference the .Name property. The $() will cause it to evaluate the expression. $files = Get-ChildItem c:\temp | Select-Object Name foreach ($i in $files) { Write-Host "Filename is $($i.Name)" } A: You can get this object as a string with the Get-ChildItem -Name parameter: $variable = Get-ChildItem C:\temp -Name This gives you a: System.String If you use the Name parameter, Get-ChildItem returns the object names as strings. You can read about it in Get-ChildItem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7610521", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Is it possible to store an Array into an EncryptedLocalStore item? AIR I want to save my Array's strucure and load it the next time I open my AIR application. Is there a way to store it to an EncryptedLocalStore item then get it later when I re-open the app? A: EncryptedLocalStore.setItem() method takes a byte array when storing contents. To store an array, just use ByteArray.writeObject() method (as described in http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/utils/ByteArray.html#writeObject()) to convert your Array to a ByteArray - and then persist the same to the ELS. var array:Array = getArray(); var byteArray:ByteArray = new ByteArray(); byteArray.writeObject(array); EncryptedLocalStore.setItem('somekey', byteArray); Hope this helps. Update: Added code to retrieve the array back. var byteArray:ByteArray = EncryptedLocalStore.getItem('somekey'); var array:Array = byteArray.readObject() as Array; Update: For custom classes. In case you want to serialize your own custom classes to the ByteArray, you may have to call registerClassAlias() before writing the object to the ByteArray. For eg. registerClassAlias("com.example.eg", ExampleClass); A: I have found that it is easiest to to serialize the Array to a string and then store that string in the ELS. Then when you pull it out deserialize it back into an Array.
{ "language": "en", "url": "https://stackoverflow.com/questions/7610526", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: putc giving segmentation fault? The following code is giving segmentation fault....Why ????? event tried with fputc I think there might be a silly error i am not able to get..but don't have enogh time. Please help... #include <stdio.h> int main () { // system("sudo openssl enc -base64 -in file.txt -out file.txt.enc"); FILE *fp,*fq; char ch; fp = fopen("file.txt.enc","r"); fq = fopen("output.txt","w"); while( (ch=fgetc(fp)) != EOF) putc(ch,fq); return 0; } A: Probably one of your fopen calls failed. You didn't bother to check whether or not they succeeded. When fopen fails a null pointer is returned. If you try to use that subsequently then your program will likely bomb. You will then have to fix the bug that Blagovest describes, and you should, of course, close your files. A: * *You have to declare ch as int. Otherwise, the processing of the file will stop when the character ÿ appears. char can take only 256 different values, which is not enough for 256 different symbols + the EOF character. EOF is -1, which is equivalent to 4,294,967,295 when treated as an int, but it's equivalent to 255 when treated as a char. If your input file contains the character ÿ (essentially -1 or 255 when treated as signed), the statement ch == EOF will become true and your while loop will break. This has nothing to do with your error, but it's important nonetheless... *If your program crashes, it tries to read from / write to the NULL pointer because the input file couldn't be read (doesn't exist) or the ouput file couldn't be written to (write protected). Try: #include <stdio.h> int main () { FILE *fp,*fq; int ch; if( (fp = fopen("file.txt.enc","r")) == NULL) return 1; if( (fq = fopen("output.txt","w")) == NULL) return 1; while( (ch=fgetc(fp)) != EOF) putc((char) ch, fq); return 0; } A: fgetc returns int, not char. The purpose of that is to be able to return EOF and distinguish that from a character that's read. Just declare ch as an int. A: Check this out and read my answer http://www.cplusplus.com/reference/clibrary/cstdio/fgetc/ Fgetc() \\ returns a signed int value and you have declared ch as char make it as int and try it out. it will work Probably you have to check out what really the fopen is returning to you, may be its because fopen failed . its working fine on my gcc A: ch must be integer. See man fgetc and man putc.
{ "language": "en", "url": "https://stackoverflow.com/questions/7610529", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: emacs standard-/buffer-display-table alterations (transliteration experiment) I adapted cyril-util.el for having transliteration of the Mkhedruli script of Georgian language. A very quick and dirty hack, but it led me to trying to learn about display-tables. The function standard-display-mkhedruli-translit flips (using a buffer-local variable) between Georgian and latin alphabet by altering the buffer-display-table, or creating a new fresh one. I posted it here: https://gist.github.com/1253614 In addition to this, I alter the standard-display-table in .emacs to eliminate line-wrapping eol char, and making split windows on tty use a nicer (unicode) character, like this: (set-display-table-slot standard-display-table 'wrap ?\ ) (set-display-table-slot standard-display-table 'vertical-border ?│) The problem now is that, though transliteration works all right, I end up losing my standard-display-table adjustments. Any ideas how to bring all this together seamlessly? I wouldn't want to have these adjustments also in my mkhedruli-function... (There are certainly a few more flaws, such as the rough (redraw-display), which I for some reason needed to do). A: You can use (set-char-table-parent <newtable> standard-display-table) on the newly created table. While I'm here: you can simplify your code by using define-minor-mode. Other kinds of simplifications: (let ( (mkhedruli-language nil) ) (if (equal mkhedruli-active nil) (setq mkhedruli-language "Georgian") (setq mkhedruli-language nil)) (with-current-buffer (current-buffer) (if (equal mkhedruli-language nil) (setq mkhedruli-active nil) (setq mkhedruli-active t))) turns into (let ( (mkhedruli-language nil) ) (setq mkhedruli-language (if (equal mkhedruli-active nil) "Georgian" nil)) (if (equal mkhedruli-language nil) (setq mkhedruli-active nil) (setq mkhedruli-active t)) which can turn into (let ((mkhedruli-language (if mkhedruli-active nil "Georgian")))) (setq mkhedruli-active (if mkhedruli-language t nil)) tho you may prefer to just switch the two: (setq mkhedruli-active (not mkhedruli-active)) (let ((mkhedruli-language (if mkhedruli-active "Georgian")))) and even get rid of mkhedruli-language altogether since you only test if it's nil, and you can test mkhedruli-active instead to get the same information.
{ "language": "en", "url": "https://stackoverflow.com/questions/7610530", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: python/pygame, pass input from a class to another class there is a way to pass a value or a variable from a class to another class without having to pass through the main function I'm using python A: well, of course you can access other objects attributes in methods of a specific object. e.g: class A(object): def method(self, other): other.somevar = 5 class B(object): pass def main(): a = A() b = B() b.somevar = "Hello World" a.method(b) print(b.somevar) # now prints '5'
{ "language": "en", "url": "https://stackoverflow.com/questions/7610531", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Calling methods with different signatures from a method that receives a delegate type parameter I have a generics method (ParseTo) for parsing strings to other types. This method receives a delegate type parameter that contains a method to execute: public delegate bool ParseToDelegate<T>(string value, out T result); public static T? ParseTo<T>(this string value, ParseToDelegate<T> method) where T : struct { T result; if (String.IsNullOrWhiteSpace(value)) return null; if (method(value, out result)) return result; return null; } That works fine because the signature of TryParse is the same for all the base types. var s = "1234,567"; Console.WriteLine(s.ParseTo<int>(int.TryParse)); //Error. Returns null Console.WriteLine(s.ParseTo<decimal>(decimal.TryParse)); //Ok var d = "14/05/2011 19:45"; Console.WriteLine(d.ParseTo<DateTime>(DateTime.TryParse)); //Ok var g = Guid.NewGuid().ToString(); Console.WriteLine(g.ParseTo<Guid>(Guid.TryParse)); //Ok My issue is: Now I would like to extend this method for supporting different cultures... But the numeric types and date types have different signatures: bool TryParse(string s, NumberStyles style, IFormatProvider provider, out int result); bool TryParse(string s, IFormatProvider provider, DateTimeStyles styles, out DateTime result); Is there a way to ‘map’ the received delegate and call the correct method? Something like this: if (typeof(T) == typeof(DateTime)) { //Call DateTime.TryParse(string s, IFormatProvider provider, //DateTimeStyles styles, out DateTime result) } else { //Call DateTime.TryParse(string s, //NumberStyles style, IFormatProvider provider, out int result); } A: You might be re-inventing the wheel - Convert.ChangeType() does already almost exactly what you want - sample from MSDN: Temperature cool = new Temperature(5); Type[] targetTypes = { typeof(SByte), typeof(Int16), typeof(Int32), typeof(Int64), typeof(Byte), typeof(UInt16), typeof(UInt32), typeof(UInt64), typeof(Decimal), typeof(Single), typeof(Double), typeof(String) }; CultureInfo provider = new CultureInfo("fr-FR"); foreach (Type targetType in targetTypes) { try { object value = Convert.ChangeType(cool, targetType, provider); Console.WriteLine("Converted {0} {1} to {2} {3}.", cool.GetType().Name, cool.ToString(), targetType.Name, value); } catch (InvalidCastException) { Console.WriteLine("Unsupported {0} --> {1} conversion.", cool.GetType().Name, targetType.Name); } catch (OverflowException) { Console.WriteLine("{0} is out of range of the {1} type.", cool, targetType.Name); } } A: It sounds like you're looking for something similar to what you're already doing. At that point, the easiest thing to do would be to make the second and third parameter generic as well. public delegate bool ParseToDelegate<T,U,K>(string value, U secondOption, K thirdOption, out T result); public static T? ParseTo<T, U, K>(this string value, U second, K third, ParseToDelegate<T,U, K> method) where T : struct { T result; if (String.IsNullOrWhiteSpace(value)) return null; if (method(value, second, third, out result)) return result; return null; } An issue with that, though, is that the method callsite signature starts to get pretty nasty and it relies heavily on the caller knowing the delegate structure and what the generic parameters are for in the first place. someDateString.ParseTo<DateTime, IFormatProvider, DateTimeStyles> (CultureInfo.CurrentCulture.DateTimeFormat, DateTimeStyles.AssumeUniversal, DateTime.TryParse); To alleviate that a little, you may want to just wrap those calls in specifically-typed calls and expose those as extension methods instead. public static DateTime? ParseToDateTime(this string value, IFormatProvider provider, DateTimeStyles style) { return ParseTo<DateTime, IFormatProvider, DateTimeStyles>(value, provider, style, DateTime.TryParse); } That will make it easier on the caller, but the underlying guts of the thing may still be a little confusing and should definitely be documented well. someDateString.ParseToDateTime(CultureInfo.CurrentCulture.DateTimeFormat, DateTimeStyles.AssumeUniversal);
{ "language": "en", "url": "https://stackoverflow.com/questions/7610534", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Popup UIPickerView (iphone) I am creating a textField which when clicked UIPickerView comes up. When I run this code there is an error: Thread 1:Profram received signal:"SIGABRT". I am quite new on iPhone development, but the person in charge is away and I am taking on a project. If you could let me know what's wrong with this... This is how the ViewController.h looks like: #import <UIKit/UIKit.h> @interface ViewController : UIViewController { IBOutlet UIPickerView *picker; IBOutlet UITextField *text; } - (IBAction)showPicker:(id)sender; @end and ViewController.m: #import "ViewController.h" @implementation ViewController - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Release any cached data, images, etc that aren't in use. } #pragma mark - View lifecycle - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. } - (void)viewDidUnload { [super viewDidUnload]; // Release any retained subviews of the main view. // e.g. self.myOutlet = nil; } - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; } - (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; } - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; } - (void)viewDidDisappear:(BOOL)animated { [super viewDidDisappear:animated]; } - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { // Return YES for supported orientations if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) { return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown); } else { return YES; } } - (void)showPicker { [UIView beginAnimations:nil context:NULL]; [UIView setAnimationDuration:0.4]; [UIView setAnimationDelegate:self]; picker.center = CGPointMake(160, 240); [UIView commitAnimations]; if (!self.navigationItem.rightBarButtonItem) { UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(done:)]; [self.navigationItem setRightBarButtonItem:doneButton animated:YES]; // [doneButton release]; } } - (void)hidePicker { [UIView beginAnimations:nil context:NULL]; [UIView setAnimationDuration:0.4]; [UIView setAnimationDelegate:self]; picker.center = CGPointMake(160, 240); [UIView commitAnimations]; [self.navigationItem setRightBarButtonItem:nil animated:YES]; } - (void)done:(id)sender { [self hidePicker]; [self.navigationItem setRightBarButtonItem:nil animated:YES]; } - (BOOL)textFieldShouldBeginEditing:(UITextField *)textField { [self showPicker]; return NO; } A: - (IBAction)showPicker:(id)sender; this function is not implemented in your .m file instead of -(void) showPicker use the above one... and what is the use of this... - (void)done:(id)sender A: The picker view must have a data source to get the data to display and a delegate to respond to events. Typically I would define the controller as being both by adopting the corresponding protocols UIPickerViewDelegate and UIPickerViewDataSource. Your controller doesn't, this may mean that the data source and delegate are within another object. You should check in interface builder, tight click on the picker and see what comes up as being he delegate and data source. If you find another class than your controller that's where you should look for the bug. If you find your controller's class then the issue is you didn't implement the methods for the picker view to be populated. For reference the picker is looking at least for the data source methods : - (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView - (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component - (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view Good luck for the hunting.
{ "language": "en", "url": "https://stackoverflow.com/questions/7610535", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Get Include Directories for custom build step I would like to know if there is a possibility to get the list of project's include directories when building files with custom build step. Imagine following situation: my project consists of A.cpp, B.cpp and C.blah. In project properties under the field "C/C++" -> "General" -> "Additional Include Directories" I have specified a list of includes directories to be used for A.cpp and B.cpp. Now for C.blah I do specify a custom build tool and write into "Command Line" -> "mytool.exe C.blah -I*Direcotries?* -o C.obj". How can I now get the list of include directories specified for the C/C++ in this step? When I click on "Macros" there is no such macro giving me the full list of includes. Is anybody aware of a possibility to achieve this goal? A: I think I found an answer, however incomplete. One can specify in the property sheets something like this: <PropertyGroup> <ProjectIncludeDir>@(ClCompile->'%(AdditionalIncludeDirectories)')</ProjectIncludeDir> </PropertyGroup> This will make the macro $(ProjectIncludeDir) available to the custom build steps too containing the list of include directories. The problem with this approach that string operations are not possible on this macro anymore. For example consider following: <ProjectIncludeDirDot>$(ProjectIncludeDir.Replace(';',','))</ProjectIncludeDirDot> This results for the macro $(ProjectIncludeDirDot) in @(ClCompile->'%(AdditionalIncludeDirectories)'). It seems that transforms are get evaluated after the macro evaluation, which breaks that replacement. If somebody knows for a better solution, please...
{ "language": "en", "url": "https://stackoverflow.com/questions/7610538", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Ruby on Rails SMS sending I'm trying to code for an sms server using this tutorial: http://lukeredpath.co.uk/blog/sending-sms-messages-from-your-rails-application.html Here they advice us to use clickatell but i have a gateway that i can use which i would like to use. However i wouldn't know how to write the bits of code that says require clickatel or sudo gem install clickatell. I'm new to ruby and rails hence any help would be appreciated :) A: I have found twilio easy to use and recommend it. They have a tutorial that works (at least in Rails 3.07). http://www.twilio.com/
{ "language": "en", "url": "https://stackoverflow.com/questions/7610541", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to compile the Oracle Instant Client Libraries for PHP PDO - Linux x86_64? I'm currently trying to compile the Oracle Instant Client Libraries for PHP PDO (Linux x86_64) and it's failing on the make step. Note: this is an old experimental plugin. I've followed the steps highlighted on this page: http://lacot.org/blog/2009/11/03/ubuntu-php5-oci8-and-pdo_oci-the-perfect-install.html and it fails on make. Do you have any idea what this error means? or how i can correct it? I think i means that the zend_fcall_info type is not being recognised but as far as i can see the zend.h file is being included ok since i've copied all of the Zend includes into /usr/local/include/php/ext/pdo/ to try and resolve this error. gary@gary-desktop:/tmp/PDO_OCI-1.0$ make /bin/bash /tmp/PDO_OCI-1.0/libtool --mode=compile gcc -I/usr/local/include/php/ext -I. -I/tmp/PDO_OCI-1.0 -DPHP_ATOM_INC -I/tmp/PDO_OCI-1.0/include -I/tmp/PDO_OCI-1.0/main -I/tmp/PDO_OCI-1.0 -I/usr/local/include/php -I/usr/local/include/php/main -I/usr/local/include/php/TSRM -I/usr/local/include/php/Zend -DHAVE_CONFIG_H -g -O2 -c /tmp/PDO_OCI-1.0/pdo_oci.c -o pdo_oci.lo gcc -I/usr/local/include/php/ext -I. -I/tmp/PDO_OCI-1.0 -DPHP_ATOM_INC -I/tmp/PDO_OCI-1.0/include -I/tmp/PDO_OCI-1.0/main -I/tmp/PDO_OCI-1.0 -I/usr/local/include/php -I/usr/local/include/php/main -I/usr/local/include/php/TSRM -I/usr/local/include/php/Zend -DHAVE_CONFIG_H -g -O2 -c /tmp/PDO_OCI-1.0/pdo_oci.c -fPIC -DPIC -o pdo_oci.lo In file included from /tmp/PDO_OCI-1.0/pdo_oci.c:29: /usr/local/include/php/ext/pdo/php_pdo_driver.h:617: error: expected specifier-qualifier-list before 'zend_fcall_info' /usr/local/include/php/ext/pdo/php_pdo_driver.h:624: error: expected specifier-qualifier-list before 'zend_fcall_info' make: *** [pdo_oci.lo] Error 1 gary@gary-desktop:/tmp/PDO_OCI-1.0$ Any help would be appreciated. A: I tried another machine and all worked fine. It was probably a configuration issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/7610542", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Python how to kill threads blocked on queue with signals? I start a bunch of threads working on a queue and I want to kill them when sending the SIGINT (Ctrl+C). What is the best way to handle this? targets = Queue.Queue() threads_num = 10 threads = [] for i in threads_num: t = MyThread() t.setDaemon(True) threads.append(t) t.start() targets.join() A: If you are not interested in letting the other threads shut down gracefully, simply start them in daemon mode and wrap the join of the queue in a terminator thread. That way, you can make use of the join method of the thread -- which supports a timeout and does not block off exceptions -- instead of having to wait on the queue's join method. In other words, do something like this: term = Thread(target=someQueueVar.join) term.daemon = True term.start() while (term.isAlive()): term.join(3600) Now, Ctrl+C will terminate the MainThread whereupon the Python Interpreter hard-kills all threads marked as "daemons". Do note that this means that you have to set "Thread.daemon" for all the other threads or shut them down gracefully by catching the correct exception (KeyboardInterrupt or SystemExit) and doing whatever needs to be done for them to quit. Do also note that you absolutely need to pass a number to term.join(), as otherwise it will, too, ignore all exceptions. You can select an arbitrarily high number, though. A: Isn't Ctrl+C SIGINT? Anyway, you can install a handler for the appropriate signal, and in the handler: * *set a global flag that instructs the workers to exit, and make sure they check it periodically *or put 10 shutdown tokens on the queue, and have the workers exit when they pop this magic token *or set a flag which instructs the main thread to push those tokens, make sure the main thread checks that flag etc. Mostly it depends on the structure of the application you're interrupting. A: One way to do it is to install a signal handler for SIGTERM that directly calls os._exit(signal.SIGTERM). However unless you specify the optional timeout argument to Queue.get the signal handler function will not run until after the get method returns. (That's completely undocumented; I discovered that on my own.) So you can specify sys.maxint as the timeout and put your Queue.get call in a retry loop for purity to get around that. A: Why don't you set timeouts for any operation on the queue? Then your threads can regular check if they have to finish by checking if an Event is raised. A: This is how I tackled this. class Worker(threading.Thread): def __init__(self): self.shutdown_flag = threading.Event() def run(self): logging.info('Worker started') while not self.shutdown_flag.is_set(): try: task = self.get_task_from_queue() except queue.Empty: continue self.process_task(task) def get_task_from_queue(self) -> Task: return self.task_queue.get(block=True, timeout=10) def shutdown(self): logging.info('Shutdown received') self.shutdown_flag.set() Upon receiving a signal the main thread sets the shutdown event on workers. The workers wait on a blocking queue, but keep checking every 10 seconds if they have received a shutdown signal. A: I managed to solve the problem by emptying the queue on KeyboardInterrupt and letting threads to gracefully stop themselves. I don't know if it's the best way to handle this but is simple and quite clean. targets = Queue.Queue() threads_num = 10 threads = [] for i in threads_num: t = MyThread() t.setDaemon(True) threads.append(t) t.start() while True: try: # If the queue is empty exit loop if self.targets.empty() is True: break # KeyboardInterrupt handler except KeyboardInterrupt: print "[X] Interrupt! Killing threads..." # Substitute the old queue with a new empty one and exit loop targets = Queue.Queue() break # Join every thread on the queue normally targets.join()
{ "language": "en", "url": "https://stackoverflow.com/questions/7610545", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Debugging on Android hardware not in OEM list I've got a PendoPad Android device that's not on the OEM list that I want to debug an app on. I've taken the time to read the Android development site, but my device isn't listed on the OEM list. I've got Eclipse on Windows 7 installed, and I've run my application on an emulator. I run the adb.exe devices, and though I can see my "phone" and its files in Windows Explorer, the adb list is empty. Has anyone encountered and surmounted this issue? A: I encountered this with an Archos device. You need to add device ID into list of ADB supported devices. The file to modify is this: %USERPROFILE%.android\adb_usb.ini Here's Archos advice about this. Now you just need to determine your device's vendor ID. And this seems to be written in Device manager, when you click details of your Android device, Details tab, Hardware Ids property. There's something like USB\VID_0E79&PID_1411&REV_0216&MI_01, where 0E79 is vendor id of Archos. Find our your ID and append it to the adb_usb.ini file. Restart adb and it should work. Hope this helps. A: On Linux: Write lsusb Sample output for Nexus4: Bus 002 Device 002: ID 8087:8000 Intel Corp. Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub Bus 001 Device 002: ID 8087:8008 Intel Corp. Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub Bus 004 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub Bus 003 Device 002: ID 046d:c52f Logitech, Inc. Unifying Receiver Bus 003 Device 007: ID 18d1:XXXX Google Inc. Nexus 4 (debug) <------ 18d1 here it is! Bus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub Not listed OEM device aka tablet no_name: Bus 002 Device 002: ID 8087:8000 Intel Corp. Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub Bus 001 Device 002: ID 8087:8008 Intel Corp. Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub Bus 004 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub Bus 003 Device 002: ID 046d:c52f Logitech, Inc. Unifying Receiver Bus 003 Device 008: ID 2207:0010 <------------------------------ here it is 2207 Bus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub So next you should edit /etc/udev/rules.d/51-android.rules as they say here So in my example i must add something like this: #FunTab8 SUBSYSTEM=="usb", ATTR{idVendor}=="2207", MODE="0666", GROUP="plugdev" For me it works now ADB after using adb devices List of devices attached NCGS6FX7U5 device If you want here is my full list: #FunTab8 SUBSYSTEM=="usb", ATTR{idVendor}=="2207", MODE="0666", GROUP="plugdev" #Acer 0502 SUBSYSTEM=="usb", ATTR{idVendor}=="0502", MODE="0666", GROUP="plugdev" #ASUS 0b05 SUBSYSTEM=="usb", ATTR{idVendor}=="0b05", MODE="0666", GROUP="plugdev" #Dell 413c SUBSYSTEM=="usb", ATTR{idVendor}=="413c", MODE="0666", GROUP="plugdev" #Foxconn 0489 SUBSYSTEM=="usb", ATTR{idVendor}=="0489", MODE="0666", GROUP="plugdev" #Fujitsu 04c5 SUBSYSTEM=="usb", ATTR{idVendor}=="04c5", MODE="0666", GROUP="plugdev" #Fujitsu Toshiba 04c5 SUBSYSTEM=="usb", ATTR{idVendor}=="04c5", MODE="0666", GROUP="plugdev" #Garmin-Asus 091e SUBSYSTEM=="usb", ATTR{idVendor}=="091e", MODE="0666", GROUP="plugdev" #Google 18d1 SUBSYSTEM=="usb", ATTR{idVendor}=="18d1", MODE="0666", GROUP="plugdev" #Haier 201E SUBSYSTEM=="usb", ATTR{idVendor}=="201E", MODE="0666", GROUP="plugdev" #Hisense 109b SUBSYSTEM=="usb", ATTR{idVendor}=="109b", MODE="0666", GROUP="plugdev" #HTC 0bb4 SUBSYSTEM=="usb", ATTR{idVendor}=="0bb4", MODE="0666", GROUP="plugdev" #Huawei 12d1 SUBSYSTEM=="usb", ATTR{idVendor}=="12d1", MODE="0666", GROUP="plugdev" #Intel 8087 SUBSYSTEM=="usb", ATTR{idVendor}=="8087", MODE="0666", GROUP="plugdev" #K-Touch 24e3 SUBSYSTEM=="usb", ATTR{idVendor}=="24e3", MODE="0666", GROUP="plugdev" #KT Tech 2116 SUBSYSTEM=="usb", ATTR{idVendor}=="2116", MODE="0666", GROUP="plugdev" #Kyocera 0482 SUBSYSTEM=="usb", ATTR{idVendor}=="0482", MODE="0666", GROUP="plugdev" #Lenovo 17ef SUBSYSTEM=="usb", ATTR{idVendor}=="17ef", MODE="0666", GROUP="plugdev" #LG 1004 SUBSYSTEM=="usb", ATTR{idVendor}=="1004", MODE="0666", GROUP="plugdev" #Motorola 22b8 SUBSYSTEM=="usb", ATTR{idVendor}=="22b8", MODE="0666", GROUP="plugdev" #MTK 0e8d SUBSYSTEM=="usb", ATTR{idVendor}=="0e8d", MODE="0666", GROUP="plugdev" #NEC 0409 SUBSYSTEM=="usb", ATTR{idVendor}=="0409", MODE="0666", GROUP="plugdev" #Nook 2080 SUBSYSTEM=="usb", ATTR{idVendor}=="2080", MODE="0666", GROUP="plugdev" #Nvidia 0955 SUBSYSTEM=="usb", ATTR{idVendor}=="0955", MODE="0666", GROUP="plugdev" #OTGV 2257 SUBSYSTEM=="usb", ATTR{idVendor}=="2257", MODE="0666", GROUP="plugdev" #Pantech 10a9 SUBSYSTEM=="usb", ATTR{idVendor}=="10a9", MODE="0666", GROUP="plugdev" #Pegatron 1d4d SUBSYSTEM=="usb", ATTR{idVendor}=="1d4d", MODE="0666", GROUP="plugdev" #Philips 0471 SUBSYSTEM=="usb", ATTR{idVendor}=="0471", MODE="0666", GROUP="plugdev" #PMC-Sierra 04da SUBSYSTEM=="usb", ATTR{idVendor}=="04da", MODE="0666", GROUP="plugdev" #Qualcomm 05c6 SUBSYSTEM=="usb", ATTR{idVendor}=="05c6", MODE="0666", GROUP="plugdev" #SK Telesys 1f53 SUBSYSTEM=="usb", ATTR{idVendor}=="1f53", MODE="0666", GROUP="plugdev" #Samsung 04e8 SUBSYSTEM=="usb", ATTR{idVendor}=="04e8", MODE="0666", GROUP="plugdev" #Sharp 04dd SUBSYSTEM=="usb", ATTR{idVendor}=="04dd", MODE="0666", GROUP="plugdev" #Sony 054c SUBSYSTEM=="usb", ATTR{idVendor}=="054c", MODE="0666", GROUP="plugdev" #Sony Ericsson 0fce SUBSYSTEM=="usb", ATTR{idVendor}=="0fce", MODE="0666", GROUP="plugdev" #Sony Mobile Communications 0fce SUBSYSTEM=="usb", ATTR{idVendor}=="0fce", MODE="0666", GROUP="plugdev" #Teleepoch 2340 SUBSYSTEM=="usb", ATTR{idVendor}=="2340", MODE="0666", GROUP="plugdev" #Toshiba 0930 SUBSYSTEM=="usb", ATTR{idVendor}=="0930", MODE="0666", GROUP="plugdev" #ZTE 19d2 SUBSYSTEM=="usb", ATTR{idVendor}=="19d2", MODE="0666", GROUP="plugdev"
{ "language": "en", "url": "https://stackoverflow.com/questions/7610547", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android: DigitalClock remove seconds I used this code for adding a clock to my app: <DigitalClock android:id="@+id/digitalclock" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:textSize = "30sp" /> The problem is that it shows also seconds..there is a simple and fast way for hide those? I need just hours and minutes in hh:mm format instead of hh:mm:ss! any suggestions? Thanks! A: Found the answer here, for anyone else looking for a working answer, here it is: * *Clone/copy DigitalClock.java from android source *Change format strings within new CustomDigitalClock package com.example; import android.content.Context; import android.content.res.Resources; import android.database.ContentObserver; import android.os.Handler; import android.os.SystemClock; import android.provider.Settings; import android.text.format.DateFormat; import android.util.AttributeSet; import android.widget.TextView; import java.util.Calendar; /** * You have to make a clone of the file DigitalClock.java to use in your application, modify in the following manner:- * private final static String m12 = "h:mm aa"; * private final static String m24 = "k:mm"; */ public class CustomDigitalClock extends TextView { Calendar mCalendar; private final static String m12 = "h:mm aa"; private final static String m24 = "k:mm"; private FormatChangeObserver mFormatChangeObserver; private Runnable mTicker; private Handler mHandler; private boolean mTickerStopped = false; String mFormat; public CustomDigitalClock(Context context) { super(context); initClock(context); } public CustomDigitalClock(Context context, AttributeSet attrs) { super(context, attrs); initClock(context); } private void initClock(Context context) { Resources r = context.getResources(); if (mCalendar == null) { mCalendar = Calendar.getInstance(); } mFormatChangeObserver = new FormatChangeObserver(); getContext().getContentResolver().registerContentObserver( Settings.System.CONTENT_URI, true, mFormatChangeObserver); setFormat(); } @Override protected void onAttachedToWindow() { mTickerStopped = false; super.onAttachedToWindow(); mHandler = new Handler(); /** * requests a tick on the next hard-second boundary */ mTicker = new Runnable() { public void run() { if (mTickerStopped) return; mCalendar.setTimeInMillis(System.currentTimeMillis()); setText(DateFormat.format(mFormat, mCalendar)); invalidate(); long now = SystemClock.uptimeMillis(); long next = now + (1000 - now % 1000); mHandler.postAtTime(mTicker, next); } }; mTicker.run(); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); mTickerStopped = true; } /** * Pulls 12/24 mode from system settings */ private boolean get24HourMode() { return android.text.format.DateFormat.is24HourFormat(getContext()); } private void setFormat() { if (get24HourMode()) { mFormat = m24; } else { mFormat = m12; } } private class FormatChangeObserver extends ContentObserver { public FormatChangeObserver() { super(new Handler()); } @Override public void onChange(boolean selfChange) { setFormat(); } } } *Reference custom class within in layout xml <com.example.CustomDigitalClock android:id="@+id/fragment_clock_digital" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="DigitalClock" /> *Load CustomDigitalClock within activity/fragment CustomDigitalClock dc = (CustomDigitalClock) mFragmentView.findViewById(R.id.fragment_clock_digital); A: The DigitalClock Javadoc states: Class Overview Like AnalogClock, but digital. Shows seconds. FIXME: implement separate views for hours/minutes/seconds, so proportional fonts don't shake rendering Judging by the FIXME, the ability to hide portions of DigitalClock might be implemented eventually. I didn't find anything currently in the Javadoc or source code that would do what you want it to. Unless you want to write your own class that extends DigitalClock (or your own clock implementation altogether), you could just cover the seconds portion of the DigitalClock with another element if it would serve your purpose.
{ "language": "en", "url": "https://stackoverflow.com/questions/7610549", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Dump postgres data with indexes I've got a Postgres 9.0 database which frequently I took data dumps of it. This database has a lot of indexes and everytime I restore a dump postgres starts background task vacuum cleaner (is that right?). That task consumes much processing time and memory to recreate indexes of the restored dump. My question is: * *Is there a way to dump the database data and the indexes of that database? *If there is a way, will worth the effort (I meant dumping the data with the indexes will perform better than vacuum cleaner)? *Oracle has some the "data pump" command a faster way to imp and exp. Does postgres have something similar? Thanks in advance, Andre A: Best Practice is probably to * *restore the schema without indexes *and possibly without constraints, *load the data, *then create the constraints, *and create the indexes. If an index exists, a bulk load will make PostgreSQL write to the database and to the index. And a bulk load will make your table statistics useless. But if you load data first, then create the index, the stats are automatically up to date. We store scripts that create indexes and scripts that create tables in different files under version control. This is why. In your case, changing autovacuum settings might help you. You might also consider disabling autovacuum for some tables or for all tables, but that might be a little extreme. A: If you use pg_dump twice, once with --schema-only, and once with --data-only, you can cut the schema-only output in two parts: the first with the bare table definitions and the final part with the constraints and indexes. Something similar can probably be done with pg_restore.
{ "language": "en", "url": "https://stackoverflow.com/questions/7610550", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Emulate mobile Safari in OS X app WebView I am trying to make an OS X app that displays a WebView of a mobile website using basic webview code, problem is I want this WebView to automatically load the mobile versions of whatever website it's on. WebFrame *mainFrame = [web1 mainFrame]; NSURL *url = [NSURL URLWithString:@"http://www.website.com"]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; [mainFrame loadRequest:request]; So my question is, is there anything that I can add to the above code to make this web view identify itself to the server of what ever website it is on as a mobile browser, thus automatically loading the mobile version of any website it is on? I have already tried looking for the answer to this for myself online and haven't had the least bit of luck finding the answer. Thank you in advance for any and all help! A: Yes Use an NSMutableURLRequest instead of a simple NSURLRequest, so you can alter it and use its setValue:forHTTPHeaderField: method to set the "User-Agent" HTML Header field to the User-Agent of MobileSafari. // You may adapt the UserAgent string depending on what device and Safari version you want to represent static NSString* const kMobileSafariUserAgent = @"Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_0 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8A293 Safari/6531.22.7"; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; [request setValue:kMobileSafariUserAgent forHTTPHeaderField:@"User-Agent"]; [mainFrame loadRequest:request]; For the User-Agent String to use, it depends on the version of MobileSafari you want to "emulate" (which version/device you want to make the server belives you are). See here for some of the UA strings possible A: A simpler way would be to just set that in the WebView.
{ "language": "en", "url": "https://stackoverflow.com/questions/7610552", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: To stop the EC2 instance after the execution of a script I configured a ubuntu server(AWS ec2 instance) system as a cronserver, 9 cronjobs run between 4:15-7:15 & 21:00-23:00. I wrote a cron job on other system(ec2 intance) to stop this cronserver after 7:15 and start again @ 21:00. I want the cronserver to stop by itself after the execution of the last script. Is it possible to write such script. A: When you start the temporary instance, specify --instance-initiated-shutdown-behavior terminate Then, when the instance has completed all its tasks, simply run the equivalent of sudo halt or sudo shutdown -h now With the above flag, this will tell the instance that shutting down from inside the instance should terminate the instance (instead of just stopping it). A: Yes, you can add an ec2stop command to the end of the last script. You'll need to: * *install the ec2 api tools *put your AWS credentials on the intance, or create IAM credentials that have authority to stop instances *get the instance id, perhaps from the inIstance-data Another option is to run the cron jobs as commands from the controlling instance. The main cron job might look like this: * *run processing instance -wait for sshd to accept connections *ssh to processing instance, running each processing script *stop processing instance This approach gets all the processing jobs done back to back, leaving your instance up for the least amount of time., and you don't have to put the credentials on thee instance. If your use case allows for the instance to be terminated instead of stopped, then you might be able to replace the start/stop cron jobs with EC2 autoscaling. It now sports schedules for running instances. http://docs.amazonwebservices.com/AutoScaling/latest/DeveloperGuide/index.html?scaling_plan.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7610557", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to automate firefox with powershell? I am currently doing the automation with power shell and I am stuck in the following problem , I have automated internet explorer with scripting in power shell, But now i need to automate Firefox using this , i have searched and not able to track down , Is there any way or is it possible to automate FF with power shell ....suggestions are required. A: Have a look at http://watin.org/ You can work with the watin.dll wich supports multiple browsers.. I started to use it because i needed a File Upload which comobject InternetExplorer.Application can't do... Little snippet to get you started: $watin = [Reflection.Assembly]::LoadFrom( "c:\WatiN.Core.dll" ) $ie = new-object WatiN.Core.IE("http://xyz.com") #Here you could load also Firefox with watin $ie.TextField([watin.core.Find]::ByName("HF_Text1")).TypeText("Text1") $ie.FileUpload([watin.core.Find]::ByName("HF_file")).Set("C:\text.txt") $ie.Button([watin.core.Find]::ByName("HF_Button")).Click() $ie.WaitForComplete() $ie.quit() Note that you have to run Powershell in STA Mode when using WatiN (powershell.exe -sta)
{ "language": "en", "url": "https://stackoverflow.com/questions/7610558", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: The usefulness of AS operator in C# Possible Duplicate: Direct casting vs 'as' operator? Where could this operator be useful? Instead of writing this: Asset a = new Asset(); Stock s = a as Stock; // s is null; no exception thrown if (s != null) Console.WriteLine (s.SharesOwned); You'd better write something that throws. I saw tons of (s != null) in production code and it really becomes ugly. Exceptions are more descriptive and natural in that way. Even conceptually: how can you get no asset if it is not a stock? It should an exception if it is not a stock. A: You often have the case where you don’t want an exception to be thrown because, well, the situation isn’t exceptional. You have a frob object which you know can be a Foo, but could also be a Bar. So you want to perform some action only if it’s a Foo. You try to avoid these situations in designs, and use virtual methods instead. But sometimes there’s just no good way around that. So rather than taking the roundabout way, if (frob is Foo) { ((Foo) frob).Frobnicate(); } you do it directly: var asFoo = frob as Foo; if (asFoo != null) { asFoo.Frobnicate(); } If nothing else, this is at least more efficient since you only need to test for type equality once (inside the as cast) instead of twice (in the is and in the cast). As a concrete example, this is very useful when you want to clear all the input boxes in a form. You could use the following code: foreach (Control c in this.Controls) { var tb = c As TextBox; if (tb != null) tb.Clear(); } Using an exception here would make no sense. A: You'd better write something that throws Not necessarily. Users don't like seeing things throwing. You should write code that works. And if it doesn't you'd better handle it appropriately by apologizing to the user. The as operator can be useful in situations where for example you would attempt a cast and if this cast doesn't work assign a default value to the variable so that the code continues to work with this default value. It would really depend on the context. A: as does an is and if the is returns false assigns null. sounds like a song but it's the answer and I use it a lot, like in the FindControl methods of ASP.NET: Button myButton = e.item.FindControl("myControlId") as Button; this kind of assignment does not crash or throw simply assigns null if FindControl finds something different than a Button. I like this so much.... A: If Asset is inherited from Stock, then this should be fine. That's the only sort of case where I've seen that work, although you could prolly also use it in the case of interfaces. A: Yes, the as operator is useful, and yes, it can be misused. If you are sure that some variable x is of type T, you should use a regular cast. T y = (T)x; If both T1 and T2 are valid types for variable x, you cau use as to check the type and perform the cast in one operation. A: What are your requirements? If the asset is a stock print the number of shares owned. The as operator is very useful in that case but you will have to check stock != null. That is implied by the requirement. Print the number of shares owned of a stock. It is an error if another asset is supplied. Then you should write code that throws an exception. A: Exceptions are not designed for flow control, they are, by definition, exceptions to the normal train of events. If it's acceptable for the conversion to fail, use as. If, rather, not being able to cast "a" as a Stock should never happen, you can use simple s=(Stock)a; which will throw it's own exception. You have no control of the exception at this point, though. The following lets the developer handle the exceptional case much cleaner: Asset a= new Asset(); Stock s= a as Stock(); if(s == null) { // Safely exit from call if possible, maybe make calls to logging mechanism or // other ways of determining why an exception occurred. Also, could throw custom // Exception if needed with much more detailed info. } else { // Continue normal flow } You could do: Asset a= new Asset(); try { Stock s= (Stock); // Continue normal flow } catch (InvalidCastException exc) { // Safely exit from call if possible, maybe make calls to logging mechanism or // other ways of determining why an exception occurred. Also, could throw custom // Exception if needed with much more detailed info. } However, that is using the exception as flow control and is costly and bad design. A: It depends on your Error Handling policy. I work on code base where we always use casting than using as operator. However, there are some cases where AS operator is very much useful and faster than exception. For example, In following case what do you What do you prefer? public bool Process(int choice) { try { Thing thing = GetRequiredThing(choice); SubThing subThing = (SubThing)thing; } catch (InvalidCastException ex) { // report ex. return false; } } or public bool Process(int choice) { Thing thing = GetRequiredThing(choice); SubThing subThing = thing as SubThing; if (subThing == null) { //report error; return false; } } If is not necessary that you should always use as operator. Take your call.
{ "language": "en", "url": "https://stackoverflow.com/questions/7610560", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: div positioning adjusting the height and width I have one div positioned inside my popup and it contains the content to be displayed inside the popup . Now , I am implementing it to have the property overflow:auto but I have one problem here. Here is my div : <div style="max-height:500px;max-width:500px;overflow:auto;"> <strong>Ad Tag for "sdk call test - greystripe"</strong><br><br> <pre> &lt;sdkcall network="greystripe" appid="4ca44ca5-621d-4c13-b035-4c694868253e" slotname="interstitial" slottype="kGSAdSizeIPhoneFullScreen" /&gt; </pre> </div> in case where my content is small the horizontal scroll gets displayed immidiately after the content . Given below are two such scenarios : Again in case where the content is large : I need to align the scroller at the very bottom of the outer div i.e. the popup-block div . I have tried with height,width=100% but it didn't solve my problem. A: If you give your outer div a height 100% than your inner element should be able to use height 100%. Else if it is a fixed height you can set the height in pixels.
{ "language": "en", "url": "https://stackoverflow.com/questions/7610561", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Center page in IE I am trying to center page on IE. If I force quirk-mode by adding <!-- some comment --> before DOCTYPE declaration margin: auto; doesn't work properly and page is adjusted to the left. If I remove the comment page is centered, but some other elements are in mess. Could you give me some hints how to solve this? A: Setting margin-left: auto and margin-right: auto for the body using CSS usually does the trick. Forcing quirks mode probably isn't a great idea, though. A: Of course, being in quirks mode is not where you want to be so quit doing that. The problem will lie with the rest of the markup but, unless you give us a link or a jsfiddle with the complete markup, anything we say will just be a wild guess. Does the page work in a modern browser (anything but IE)? A: You can use a 50% margin, and a negative left position with half of your element size: position: relative; width: 600px; margin-left: 50%; left: -300px;
{ "language": "en", "url": "https://stackoverflow.com/questions/7610562", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: I am developping a maven project using spring mvc. I have a problem with accessing properties () using @value. when i start tomcat 6, I get the following exception : 09:21:21.703 ERROR o.s.web.context.ContextLoader - Context initialization failed org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'resultsDisplayController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private int foo.ResultsDisplayController.PAGE_SIZE; nested exception is org.springframework.beans.factory.BeanExpressionException: Expression parsing failed; nested exception is org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 0): Field or property 'appProperties' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext' at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:285) ~[spring-beans-3.0.5.RELEASE.jar:3.0.5.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1074) ~[spring-beans-3.0.5.RELEASE.jar:3.0.5.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517) ~[spring-beans-3.0.5.RELEASE.jar:3.0.5.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456) ~[spring-beans-3.0.5.RELEASE.jar:3.0.5.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291) ~[spring-beans-3.0.5.RELEASE.jar:3.0.5.RELEASE] at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-3.0.5.RELEASE.jar:3.0.5.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288) ~[spring-beans-3.0.5.RELEASE.jar:3.0.5.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190) ~[spring-beans-3.0.5.RELEASE.jar:3.0.5.RELEASE] at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:580) ~[spring-beans-3.0.5.RELEASE.jar:3.0.5.RELEASE] at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895) ~[spring-context-3.0.5.RELEASE.jar:3.0.5.RELEASE] at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425) ~[spring-context-3.0.5.RELEASE.jar:3.0.5.RELEASE] at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:276) ~[spring-web-3.0.5.RELEASE.jar:3.0.5.RELEASE] at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:197) ~[spring-web-3.0.5.RELEASE.jar:3.0.5.RELEASE] at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:47) [spring-web-3.0.5.RELEASE.jar:3.0.5.RELEASE] at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3830) [catalina.jar:na] at org.apache.catalina.core.StandardContext.start(StandardContext.java:4337) [catalina.jar:na] at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045) [catalina.jar:na] at org.apache.catalina.core.StandardHost.start(StandardHost.java:719) [catalina.jar:na] at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045) [catalina.jar:na] at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443) [catalina.jar:na] at org.apache.catalina.core.StandardService.start(StandardService.java:516) [catalina.jar:na] at org.apache.catalina.core.StandardServer.start(StandardServer.java:710) [catalina.jar:na] at org.apache.catalina.startup.Catalina.start(Catalina.java:566) [catalina.jar:na] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.6.0_21] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) ~[na:1.6.0_21] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) ~[na:1.6.0_21] at java.lang.reflect.Method.invoke(Method.java:597) ~[na:1.6.0_21] at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288) [bootstrap.jar:na] at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413) [bootstrap.jar:na] Here is my foo.resultsDisplayController @Controller @Transactional(readOnly = true) public class ResultsDisplayController { private static final Logger LOG = LoggerFactory.getLogger(ResultsDisplayController.class); @Value("#{appProperties.page_default_size}") private int PAGE_SIZE; @RequestMapping(value = "/show-results", method = RequestMethod.GET) public String displayVariousreults(Model model) { ... } } the content of servlet-context.xml <?xml version="1.0" encoding="UTF-8"?> <beans:beans xmlns="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:spring-configured /> <context:component-scan base-package="foo" /> <annotation-driven /> <tx:annotation-driven /> <!-- properties --> <util:properties id="appProperties" location="classpath:app.properties" /> <resources mapping="/resources/**" location="/resources/" /> <beans:bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver" /> <interceptors> <beans:bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"> <beans:property name="paramName" value="language" /> </beans:bean> </interceptors> <beans:bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> <beans:property name="basenames"> <beans:list> <beans:value>classpath:labels</beans:value> </beans:list> </beans:property> <beans:property name="cacheSeconds" value="5" /> <beans:property name="defaultEncoding" value="UTF-8" /> <beans:property name="fallbackToSystemLocale" value="false" /> </beans:bean> <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <beans:property name="prefix" value="/WEB-INF/views/" /> <beans:property name="suffix" value=".jsp" /> </beans:bean> <beans:bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver"> <beans:property name="order" value="0" /> <beans:property name="mediaTypes"> <beans:map> <beans:entry key="json" value="application/json" /> <beans:entry key="xml" value="text/xml" /> </beans:map> </beans:property> <beans:property name="defaultContentType" value="application/json" /> </beans:bean> <beans:bean id="authenticationListener" class="foo.AuthenticationListener" /> </beans:beans> the content of app.properties : page_default_size=10 EDIT: I doscovered that the problem is related to eclipse wtp. When I deploy the webapp on tomcat using eclipse the problem occurs. However, when I deployed the war ganarated by maven on another tomcat server independently from eclipse, I don't get the problem and the application works fine. The question is how to fix this eclipse wtp bug? A: I'd use <context:property-placeholder location=".." /> and then @Value("${property}") A: "NumberFormatException" i think it reads the value as string.Maybe you can change the type of PAGE_SIZE to String,and then convert it to int.
{ "language": "en", "url": "https://stackoverflow.com/questions/7610565", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: creating hash table using perl I am trying to create hash table using perl. I have XML file as input and it contains information about diognostic tests and test description. Test number as a key and Test description as a value to the key. Then test number and string have the key -value relation.Help me to write perl script that stores description in one string and create hash table.please can help me because i am begginer to perl and i am reading but i am not able to implement. <DATA> <number>1</number> <age>24</age> <place>india</place> <description></description> </data> A: That's pretty much what XML::Simple does. So just use that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7610567", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-6" }
Q: Rendering Color Data to a Window, Win32 So I am able to create an array of color data (projecting 3d models in case you are wondering), but I need to display them in a Win32 window. I know I could draw it pixel by pixel, but that is really slow. I know that I probably need BitBlt(); I would need it anyway if I am to use double buffering. I have seen how to render a .bmp to the window, but I don't have a .bmp. I guess I could MAKE a .bmp, but I'm going for speed here. Is there any way to directly (probably not directly, but still quickly) access the pixel data of the hDC? How do graphics libraries do it so quickly? A: To copy your buffer to the DC, you should construct a BITMAPINFO, then use SetDIBitsToDevice() with the screen hDC, the pointer to your buffer and the constructed BITMAPINFO. You can find a good starting-point for double buffering here. A: Render to a MemoryDC (which is quicker for pixel-by-pixel access), then copy that to your window DC.
{ "language": "en", "url": "https://stackoverflow.com/questions/7610569", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: why aren't my JLabels and JTextFields showing up in the JPanel? I have a JDialog and inside it I have a JPanel that uses FlowLayout now I've created 3 labels and text fields using the Netbeans GUI Builder, and I want to add 2 more text fields using code I've adjusted the size of the panel so that when I add a new label and a textfield with a preferred size the new set of label - textfield will be under the previous set somewhere in the JDialog I do something like this JLabel cores = new JLabel("Cores"); cores.setPreferredSize(new Dimension(70,15)); first = new JTextField(); first.setPreferredSize(new Dimension(140,20)); JLabel power = new JLabel("Power"); power.setPreferredSize(new Dimension(70,15)); second = new JTextField(); second.setPreferredSize(new Dimension(140,20)); panel2.add(cores);panel2.add(first);panel2.add(power);panel2.add(second); when I compile the program, the labels don't show up and neither do the textfields when I go down and click I have the following result http://img684.imageshack.us/img684/13/unledlpy.png if I type something, the text field appears http://img5.imageshack.us/img5/6796/unledhig.png the labels don't appear though, I don't think I made any changes to the properties, any help would be appreciated thanks A: Define the no of columns while creating object. like this JTextField jt=new JTextField(20);
{ "language": "en", "url": "https://stackoverflow.com/questions/7610572", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Symfony 1.4 Doctrine fixtures load individual file? I've got a working app and I want to add some fixtures but really all I want to do is load in the new fixture file. When i run the php symfony doctrine:data-load Does it re-enter data that is already in the database. If not I assume I can just call this and it will only add new fixtures since last time. If it does enter all data again then is there a way to isolate data load on a specific fixture file? A: With the string "help" befor the command you become a detailed description: php symfony help doctrine:data-load ... If you want to load data from specific files or directories, you can append them as arguments: ./symfony doctrine:data-load data/fixtures/dev data/fixtures/users.yml A: You can do both of the things you want - you will need to create a new task to do it though ... This will load in an individual fixtures file : Doctrine_Core::loadData('/path/to/data.yml'); This will append the fixtures file to the current data : Doctrine_Core::loadData('/path/to/data.yml', true); So just create a new task - access the database connection and run one of these commands depending on what you want to do Apologies ... perhaps I should read the manual properly ... You can indeed use the current command to append and/or use a specific file. Usage: symfony doctrine:data-load [--application[="..."]] [--env="..."] [--append] [dir_or_file1] ... [dir_or_fileN] Arguments: dir_or_file Directory or file to load Options: --application The application name (default: 1) --env The environment (default: dev) --append Don't delete current data in the database Description: The doctrine:data-load task loads data fixtures into the database: ./symfony doctrine:data-load The task loads data from all the files found in data/fixtures/. If you want to load data from specific files or directories, you can append them as arguments: ./symfony doctrine:data-load data/fixtures/dev data/fixtures/users.yml If you don't want the task to remove existing data in the database, use the --append option: ./symfony doctrine:data-load --append Once again apologies for misleading you ... but just think - you have learned how to write tasks now :-)
{ "language": "en", "url": "https://stackoverflow.com/questions/7610573", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Add a widget (button) to HTML5 canvas in GWT In smartGWT it is possible to add another widget (seems to use an interface) to an HTML5-canvas, as you can see in this example. Now I'm trying to figure out, if this is possible in (raw) GWT2.4 too. Has anybody of you a working example using GWT without any additional projects (like smartGWT, gwtExt, extGWT, ...)? Thanks for all your answers. A: HTML5 canvas is not in the scope of GWT yet, but maybe you can just build que equivalent elements in your dom with GWT dom API and draw in it throught JSNI calls A: Thanks to Erik, i noticed the recent release of canvas in GWT 2.4 http://google-web-toolkit.googlecode.com/svn/javadoc/2.4/com/google/gwt/canvas/client/Canvas.html A: As far as I know, you can not put arbitrary widget in a canvas. What you can do is draw images. So I guess the smartGWT widgets you refere to are nothing else but images. If you have a GWT image object, this is how you get it to be drawn in a canvas: import com.google.gwt.canvas.client.Canvas; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.dom.client.ImageElement; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.RootLayoutPanel; public class ImageCanvasTest implements EntryPoint { public void onModuleLoad() { Image image = new Image( "http://upload.wikimedia.org/wikipedia/en/f/f6/Gwt-logo.png"); Canvas canvas = Canvas.createIfSupported(); canvas.getContext2d().drawImage( ImageElement.as(image.getElement()), 0, 0); RootLayoutPanel.get().add(canvas); } } A: What you need is a CSS style for your buttons. A style like this: button { position:absolute; z-index:2; } button.zoomOut { top:200px; left:265px; font-size: 30px; margin-left:auto; margin-right:auto; } button.zoomIn { top:200px; left:400px; font-size: 30px; margin-left:auto; margin-right:auto; } With absolute position you're able to put them anywhere on the screen. Cheers
{ "language": "en", "url": "https://stackoverflow.com/questions/7610574", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How to improve my performance in filling gaps in time series and data lists with Python I'm having a time series data sets comprising of 10 Hz data over several years. For one year my data has around 3.1*10^8 rows of data (each row has a time stamp and 8 float values). My data has gaps which I need to identify and fill with 'NaN'. My python code below is capable of doing so but the performance is by far too bad for my kind of problem. I cannot get though my data set in anything even close to a reasonable time. Below an minimal working example. I have for example series (time-seris-data) and data as lits with same lengths: series = [1.1, 2.1, 3.1, 7.1, 8.1, 9.1, 10.1, 14.1, 15.1, 16.1, 20.1] data_a = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] data_b = [1.2, 1.2, 1.2, 2.2, 2.2, 2.2, 2.2, 3.2, 3.2, 3.2, 4.2] I would like series to advance in intervals of 1, hence the gaps of series are 4.1, 5.1, 6.1, 11.1, 12.1, 13.1, 17.1, 18.1, 19.1. The data_a and data_b lists shall be filled with float(nan)'s. so data_a for example should become: [1.2, 1.2, 1.2, nan, nan, nan, 2.2, 2.2, 2.2, 2.2, nan, nan, nan, 3.2, 3.2, 3.2, nan, nan, nan, 4.2] I archived this using: d_max = 1.0 # Normal increment in series where no gaps shall be filled shift = 0 for i in range(len(series)-1): diff = series[i+1] - series[i] if diff > d_max: num_fills = round(diff/d_max)-1 # Number of fills within one gap for it in range(num_fills): data_a.insert(i+1+it+shift, float(nan)) data_b.insert(i+1+it+shift, float(nan)) shift = int(shift + num_fills) # Shift the index by the number of inserts from the previous gap filling I searched for other solutions to this problems but only came across the use of the find() function yielding the indices of the gaps. Is the function find() faster than my solution? But then how would I insert NaN's in data_a and data_b in a more efficient way? A: First, realize that your innermost loop is not necessary: for it in range(num_fills): data_a.insert(i+1+it+shift, float(nan)) is the same as data_a[i+1+shift:i+1+shift] = [float(nan)] * int(num_fills) That might make it slightly faster because there's less allocation and less moving items going on. Then, for large numerical problems, always use NumPy. It may take some effort to learn, but the performance is likely to go up orders of magnitude. Start with something like: import numpy as np series = np.array([1.1, 2.1, 3.1, 7.1, 8.1, 9.1, 10.1, 14.1, 15.1, 16.1, 20.1]) data_a = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] data_b = [1.2, 1.2, 1.2, 2.2, 2.2, 2.2, 2.2, 3.2, 3.2, 3.2, 4.2] d_max = 1.0 # Normal increment in series where no gaps shall be filled shift = 0 # the following two statements use NumPy's broadcasting # to implicit run some loop at the C level diff = series[1:] - series[:-1] num_fills = np.round(diff / d_max) - 1 for i in np.where(diff > d_max)[0]: nf = num_fills[i] nans = [np.nan] * nf data_a[i+1+shift:i+1+shift] = nans data_b[i+1+shift:i+1+shift] = nans shift = int(shift + nf) A: IIRC, inserts into python lists are expensive, with the size of the list. I'd recommend not loading your huge data sets into memory, but to iterate through them with a generator function something like: from itertools import izip series = [1.1, 2.1, 3.1, 7.1, 8.1, 9.1, 10.1, 14.1, 15.1, 16.1, 20.1] data_a = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] data_b = [1.2, 1.2, 1.2, 2.2, 2.2, 2.2, 2.2, 3.2, 3.2, 3.2, 4.2] def fillGaps(series,data_a,data_b,d_max=1.0): prev = None for s, a, b in izip(series,data_a,data_b): if prev is not None: diff = s - prev if s - prev > d_max: for x in xrange(int(round(diff/d_max))-1): yield (float('nan'),float('nan')) prev = s yield (a,b) newA = [] newB = [] for a,b in fillGaps(series,data_a,data_b): newA.append(a) newB.append(b) E.g. read the data into the izip and write it out instead of list appends.
{ "language": "en", "url": "https://stackoverflow.com/questions/7610576", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: UILabel to automatic line break when line is too long My UILabel can do a line break according to the current \n . But if the line itself is too long, it won't be able to automatically do a line break. Can I do more configurations to my UILabel to achieve that? And I've already used: aLabel.lineBreakMode = UILineBreakModeWordWrap; aLabel.numberOfLines = 0; [aLabel setFont:[UIFont fontWithName:@"MarkerFelt-Wide" size:24]]; aLabel.textAlignment = UITextAlignmentCenter; CGRect labelFrame = aLabel.bounds; labelFrame.size = [words sizeWithFont:aLabel.font constrainedToSize:CGSizeMake(LABEL_WIDTH, 100000) lineBreakMode:aLabel.lineBreakMode]; aLabel.frame = CGRectMake(0, 0, aLabel.frame.size.width-10, labelFrame.size.height); words is a NSString A: Set Number of line as you want to set. aLabel.numberOfLines = 2; A: if you are having text in a paragraph and want to place it in a lable with differ lines no need to use UILineBreakModeWordWrap.. simply write one line code as in how many lines you want to place the text as labobj.numberOfLines = 90;
{ "language": "en", "url": "https://stackoverflow.com/questions/7610589", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Storing Loggedin User details from UI and use that in BL methods I am working in a DocumentManagement System. The users defined in the database can create/manipulate his own documents based on their access rights defined. The owner of a document can let other user access/modify the document (stored as XML Contetnt). I need to autorize the LoggedIn User Whenever a document is opened for editing. The document has alredy a CreatedBy,EditingUser properties. There is chance that a document owned by User "A" can be edited by user "B" if he has the Write Access for that document. Now I need to check the authorization of the LoggedIn user for the document which is opened for editing (inside the Save() BL method of the DocumentManager object). Here I need to access the LoggedIn User details inside the BL method which is filled after Login process (which should not be changed after that). My application is WPF application. So what is the best approach to handle the situation like this. I need to often check the rightst of the Loggedin user aganist the Document in my application (particularly inside the BL methods). A: I would rather suggest a decouple mechanism to authorize users. So the actual application need not to worry about the authorization. You can define the authorization logic a policy - XACML. XACML is the de-facto standard for authorization. Once you have the authorization logic defined in XACML PDP - before executing the user actions, your application will call the XACML PDP - and ask whether the logged in user is eligible to perform this action against the given resource. Using XACML will give you flexibility to change the logic of authorization, with out even touching the application logic. Also - you can define very fine-grained rules with XACML. A: You need to take session approach. You need to maintain a static class as below. When ever user is logged in, you need to add them to the list on BLL public static class Session{ public static Dictionary<User, DateTime> loggedInUser; public static Add(User user){ loggedInUser.Add(user, DateTime.Now); // raise event user arrival } public static GetUser(int Id){ // fetch user; } public static Remove(User user){ loggedInUser.Removed(user); // raise event user left } // TODO: add timer to check itself. If not activity done in past n minutes, //log him out }
{ "language": "en", "url": "https://stackoverflow.com/questions/7610591", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jquery ajax call returns error on successful call to a servlet I have a servlet that adds a user to a file on the server side. I invoke it with a jqueries ajax call. I can see on the server that the method is being called correctly and my user is added, but the error callback is being invoked on the jquery call. All the status text says is error. Using firebug the response seems to be empty. Why can I not get a success jquery callback? //Servlet Code protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String action = request.getParameter("action"); String responseStr = ""; if(action.equals("addUser")) { responseStr = addUser(request); } System.out.println("Reponse:" + responseStr); response.setContentType("application/json"); response.setCharacterEncoding("utf-8"); response.getWriter().println(responseStr); } private String addUser(HttpServletRequest request) throws IOException { Storage s; s = Storage.load(); String name = request.getParameter("name"); String imageUrl = request.getParameter("imageUrl"); User u = new User(); u.setName(name); u.setImageUrl(imageUrl); s.addUser(u); s.save(); return "success"; } . //javascript code function addUser() { var name = $('#name').val(); var imageUrl = $('#imageUrl').val(); var url = "http://ws06525:8080/QCHounds/QCHoundServlet?action=addUser&name=${name}&imageUrl=${imageUrl}"; url = url.replace("${name}", name); url = url.replace("${imageUrl}", imageUrl); $('#result').html(url); $.ajax({ url: url, success: function( data ) { $('#result').html(data); }, error: function(jqXHR, textStatus, errorThrown) { alert("error: " + textStatus); alert("error: " + errorThrown); } }); } A: Aaargh! Feel like an idiot. It's a cross site scripting issue. I was testing the call to the server from the html file on disk so my browser address was file://projects/myproject/content/Users.html <<< Fail instead of: http://myboxname:8080/appname/Users.html <<< Works The actual code is fine... A: use this for learn what is the problem, it will be better for get solution i think error: function(e){ alert(JSON.stringify(e)) } A: For one thing the string "success" isn't valid json. If your ajax query is expecting json, that would fail it. What if you returned "{ \"success\": true }" ? EDIT It looks like from your ajax call that the response shouldn't be json, why is your return content type json? If it is true that firebug shows no response, your problem must be in the java code that writes the response.
{ "language": "en", "url": "https://stackoverflow.com/questions/7610593", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Why didn't the dialog in the class execute? Dialog::Dialog(QWidget *parent) : QDialog(parent), ui(new Ui::Dialog) { ui->setupUi(this); connect(ui->addButton , SIGNAL(clicked()) , this , SLOT(addItem())); connect(ui->editButton , SIGNAL(clicked()) , this , SLOT(editItem())); connect(ui->deleteButton , SIGNAL(clicked()) , this , SLOT(deleteItem())); } void Dialog::addItem() { EditDialog dlg(this); dlg.show(); if(dlg.exec() == EditDialog::Accepted) { ui->list->addItem(dlg.name() + "--" + dlg.number()); } } That a class Dialog to Add Items. When I run the program and click the Button to execute the Dialog it doesn't do anything so What is the solution? A: You need to use QDialog::Accepted If you look at the docs for QDialog::exec, you will see that it returns a value from the QDialog::DialogCode enum - the values for which are QDialog::Accepted and QDialog::Rejected.
{ "language": "en", "url": "https://stackoverflow.com/questions/7610595", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-5" }
Q: OnRender Method does not work with more than 144 controls I have a custom TextBox which overrides the OnRender method. Unfortunately, OnRender does not work properly when I add more than 143-145 TextBoxes to the grid. This is what a windows with 160 TextBoxes looks like in the wpf designer. Each TextBox sets the border brush to red in the OnRender Method. For the last column of textboxes, OnRender does not work anymore. render test example http://s3.postimage.org/id6jvq09n/render_Test_Example.png The problem is not bound to the wpf designer, the same happens at runtime. Funnilly enough, if you delete one component inside the designer or at runtime once it has been rendered, then all the other controls suddenly work. example code: MytextBox.cs RenderTestPanel.xaml RenderTestPanel.xaml.cs A: Your approach should be the one suggested by chibacity. This type of behavior is standard and is even used by the DataGridTextColumn that ships with WPF. From the MSDN: DataGridTextColumn creates a TextBlock element in the non-editing mode and a TextBox element in the editing mode. Also, as suggested by many other users in comments, you should not override OnRender to adjust the visual appearance of a control. In WPF, changes to a control's visual appearance can be accomplished by adjusting the control's Style and/or Template. The following style results in the exact same appearance change as your OnRender override: <Style TargetType="TextBox"> <Setter Property="BorderBrush" Value="Red" /> </Style> You should only "derive and override" when you're extending the functionality and/or purpose of a control and there's nothing in your example that suggests that's what you're doing. Additionally, your RenderTestPanel.xaml implies that all you're doing is creating a data grid which is provided by WPF. I would strongly suggest using the out-of-the-box DataGrid, styling the DataGridTextColumn and you'll (probably) accomplish your goals with less code and entirely in XAML. A: I was able to work around a very similar problem to this. I posted the resolution here: https://stackoverflow.com/a/40605635/5823234
{ "language": "en", "url": "https://stackoverflow.com/questions/7610608", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: kth order Fibonacci numbers series I am reading an article on Fibonacci numbers at following link http://xlinux.nist.gov/dads/HTML/kthOrderFibonacci.html F(k)n = 0 for 0 ≤ n ≤ k-2 i am not getting what about above statement. For example when k = 3 and n =2, 0 <= 2 < 1 which is not making sense? can any one please elaborate and pls give an example first 10 numbers 3rd order Fibonacci numbers A: The statement you quoted indicates that the first k-1 numbers in the sequence are zero. if f(k,n) is zero for all n such that 0 <= n < k-2, then f(3, n) is zero for all n such that 0 <= n <= 1. So f(3,0) and f(3,1) are both zero. Second Order: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34... Third Order: 0, 0, 1, 1, 2, 4, 7, 13, 24, 44... Fourth Order: 0, 0, 0, 1, 1, 2, 4, 8, 15, 29... A: For k=3 and n=2, you are looking at the wrong part of the definition. In your case, n = k-1, so you would you the second part of the definition or, F(k)k-1 = 1, so when k=3 and n=2, f(k) = 1. For 3rd order, n=0 to n=10, you would have 0, 0, 1, 1, 2, 4, 7, 13, 24, 44, 81 edit for not being able to add =) A: Basically you can't sum the k values preceding n if n < k - 1, simply because there aren't enough numbers. :) as for your example, since n = k - 1 then f(n = 2) = 1. n f reason -------------------------------------------------- 0 0 by definition (because n <= k - 2 = 1) 1 0 see above 2 1 by definition (because n = k - 1 = 2) 3 1 1 + 0 + 0 4 2 1 + 1 + 0 5 4 2 + 1 + 1 6 7 4 + 2 + 1 7 13 7 + 4 + 2 8 24 14+ 7 + 4
{ "language": "en", "url": "https://stackoverflow.com/questions/7610612", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What is the correct ASP.NET Control event/method in which to add nested controls? What is the correct event/method in the ASP.NET life cycle to dynamically add Child Controls ? My objective is to ensure that all the input controls on a User Control have the correct associated Validator and Label controls, based on configuration from an external file. It seems like the correct place should be either OnInit(EventArgs e) or CreateChildControls(). Both of them are behaving a little bit unexpected, and rather than try to debug each of them, I figured I'd first ask you guys which one (or other) to use. A: Its OnInit, and you need to do it on first load and on post back. A: Since this is a Web User Control (ASCX) create the dynamic controls during OnInit. By creating them during OnInit they will be created on the first page load and on every postback. The CreateChildControls method is typically used for rendering in custom server controls.
{ "language": "en", "url": "https://stackoverflow.com/questions/7610623", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: why webform (asp.net-3.5)appears excluded after copying it to local system from the production server? I have jsut copied one web apllication (web project) developed in asp.net 3.5 with c# and working fine now, from the live server to my local host. My question is The form which is avialble in live server is not avialble when executed from local host. then i found that form was excluded from project, viewed in solution explorer. i got erros after including that form in project and compiled, those errors are Error 1 :frmUpdateNCR.aspx.cs 'EAudit.AUDIT_BAL.AuditRoleSubmit' does not contain a definition for 'Afpf_Editedby' and no extension method 'Afpf_Editedby' accepting a first argument of type 'EAudit.AUDIT_BAL.AuditRoleSubmit' could be found (are you missing a using directive or an assembly reference?) 142 26 EAudit Error 2:frmUpdateNCR.aspx.cs 'EAudit.AUDIT_BAL.AuditRoleSubmit' does not contain a definition for 'UpdateNCRAfterEditing' and no extension method 'UpdateNCRAfterEditing' accepting a first argument of type 'EAudit.AUDIT_BAL.AuditRoleSubmit' could be found (are you missing a using directive or an assembly reference?) 146 35 EAudit. The parameter and function are already added in class file when uploaded into production server but same are not available in the applicaiton which is in local host. I am sure i copied correct file but i dont know why this happened, could any one give me solution. sorry if this question is not to be here.. A: If you're copying it down from the production server it's probably been compiled. If you can't find the [webform].aspx.cs or [webform].aspx.designer.cs file, then the code has been compiled into a DLL in the BIN folder, and you won't be able to include it in your project. If there is a code file, then go to the solution explorer and click the "Show All Files" icon at the top. Find the web form (should be greyed out if it's excluded), right click on it and then click "Include In Project", and you should be all set.
{ "language": "en", "url": "https://stackoverflow.com/questions/7610626", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CXF - JAX-WS server side Schema Validation does not find element definition I have a web service that defines severals schemas in the webTypes section. I define a read operation which type is define in this schema: <xs:schema version="1.0" targetNamespace="http://example.com/webservice/service" xmlns:ns0="http://example.com/webservice/parameter" xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:import namespace="http://example.com/webservice/parameter"/> <xs:complexType name="read"> <xs:sequence> <xs:element name="name" type="xs:string" minOccurs="1" maxOccurs="1" /> <xs:element name="filter" type="ns0:filter" minOccurs="0" maxOccurs="1"/> <xs:element name="startIndex" type="xs:int" minOccurs="1" maxOccurs="1" /> <xs:element name="noOfResults" type="xs:int" minOccurs="1" maxOccurs="1" /> </xs:sequence> </xs:complexType> <xs:element name="read" type="tns:read"/> </xs:schema> Then I activate the schema validation in the CXF config file like this: <jaxws:endpoint id="dataService" implementor="com.example.webservice.jaxws.endpoint.SIB" address="/DataService" wsdlLocation="classpath:DataService.wsdl"> <jaxws:properties> <entry key="schema-validation-enabled" value="true" /> </jaxws:properties> </jaxws:endpoint> I tested my schema validating some of my request with the SOAPUI validator, and it works perfectly. But in the server side, when a request is received I'm getting this error: Caused by: javax.xml.bind.UnmarshalException - with linked exception: [org.xml.sax.SAXParseException: cvc-elt.1: Cannot find the declaration of element 'name'.] at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.handleStreamException(UnmarshallerImpl.java:425) at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:362) at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:339) at org.apache.cxf.jaxb.JAXBEncoderDecoder.unmarshall(JAXBEncoderDecoder.java:768) ... 287 more Caused by: org.xml.sax.SAXParseException: cvc-elt.1: Cannot find the declaration of element 'name'. at org.apache.xerces.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source) at org.apache.xerces.util.ErrorHandlerWrapper.error(Unknown Source) at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source) at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source) at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source) at org.apache.xerces.impl.xs.XMLSchemaValidator.handleStartElement(Unknown Source) at org.apache.xerces.impl.xs.XMLSchemaValidator.startElement(Unknown Source) at org.apache.xerces.jaxp.validation.ValidatorHandlerImpl.startElement(Unknown Source) at com.sun.xml.bind.v2.runtime.unmarshaller.ValidatingUnmarshaller.startElement(ValidatingUnmarshaller.java:96) at com.sun.xml.bind.v2.runtime.unmarshaller.StAXStreamConnector.handleStartElement(StAXStreamConnector.java:242) at com.sun.xml.bind.v2.runtime.unmarshaller.StAXStreamConnector.bridge(StAXStreamConnector.java:176) at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:360) ... 289 more Any Clue? It seems that the validator can access the "read" operation definition. I don't know what to do because actually the webservices works correctly without the schema validation, but I want to avoid param validation in the web services implementation. Thanks in advance, NOTE I'm Using CXF 2.3.3 with JAXWS 2.2 and JAXB 2.2.1 in a non endorsed tomcat 6 with java 1.6.0.
{ "language": "en", "url": "https://stackoverflow.com/questions/7610629", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Glsl mod vs Hlsl fmod I've implemented the spiral GLSL shader described in this question in HLSL, but the results are not the same. I think it's because of the mod function in GLSL that I've translated to fmod in HLSL. I suspect that this problem only happens when we have negative numbers in the input of the fmod function. I've tried replacing the call to mod by a call to a function that I've made which does what is described in the GLSL documentation and it works: mod returns the value of x modulo y. This is computed as x - y * floor(x/y). The working code I use instead of fmod is: float mod(float x, float y) { return x - y * floor(x/y) } By contrast to GLSL mod, MSDN says the HLSL fmod function does this: The floating-point remainder is calculated such that x = i * y + f, where i is an integer, f has the same sign as x, and the absolute value of f is less than the absolute value of y. I've used an HLSL to GLSL converter, and the fmod function is translated as mod. However, I don't know if I can assume that mod translates to fmod. Questions * *What are the differences between GLSL mod and HLSLfmod? *How can I translate MSDN's cryptic description of fmod to a pseudo-code implementation? GLSL Shader uniform float time; uniform vec2 resolution; uniform vec2 aspect; void main( void ) { vec2 position = -aspect.xy + 2.0 * gl_FragCoord.xy / resolution.xy * aspect.xy; float angle = 0.0 ; float radius = length(position) ; if (position.x != 0.0 && position.y != 0.0){ angle = degrees(atan(position.y,position.x)) ; } float amod = mod(angle+30.0*time-120.0*log(radius), 30.0) ; if (amod<15.0){ gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 ); } else{ gl_FragColor = vec4( 1.0, 1.0, 1.0, 1.0 ); } } HLSL Shader struct Psl_VertexShaderInput { float3 pos : POSITION; }; struct Psl_VertexShaderOutput { float4 pos : POSITION; }; struct Psl_PixelShaderOutput { float4 Output0 : COLOR0; }; float3 psl_positionOffset; float2 psl_dimension; Psl_VertexShaderOutput Psl_VertexShaderFunction(Psl_VertexShaderInput psl_input) { Psl_VertexShaderOutput psl_output = (Psl_VertexShaderOutput)0; psl_output.pos = float4(psl_input.pos + psl_positionOffset, 1); return psl_output; } float time : TIME; float2 resolution : DIMENSION; Psl_PixelShaderOutput Psl_PixelShaderFunction(float2 pos : VPOS) { Psl_PixelShaderOutput psl_output = (Psl_PixelShaderOutput)0; float2 aspect = float2(resolution.x / resolution.y, 1.0); float2 position = -aspect.xy + 2.0 * pos.xy / resolution.xy * aspect.xy; float angle = 0.0; float radius = length(position); if (position.x != 0.0 && position.y != 0.0) { angle = degrees(atan2(position.y, position.x)); } float amod = fmod((angle + 30.0 * time - 120.0 * log(radius)), 30.0); if (amod < 15.0) { psl_output.Output0 = float4(0.0, 0.0, 0.0, 1.0); return psl_output; } else { psl_output.Output0 = float4(1.0, 1.0, 1.0, 1.0); return psl_output; } } technique Default { pass P0 { VertexShader = compile vs_3_0 Psl_VertexShaderFunction(); PixelShader = compile ps_3_0 Psl_PixelShaderFunction(); } } A: As you've noted, they're different. The GLSL mod will always have the same sign as y rather than x. Otherwise it's the same -- a value f such that x = i*y + f where i is an integer and |f| < |y|. If you're trying to make a repeating pattern of some kind, the GLSL mod is generally what you want. For comparison, the HLSL fmod is equivalent to x - y * trunc(x/y). They're the same when x/y is positive, different when x/y is negative.
{ "language": "en", "url": "https://stackoverflow.com/questions/7610631", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: How do you append your sub-views in Backbone? I have a Backbone app that renders several related views on each page they you navigate to. For example, one page renders the following views: * *Context bar * *Drop-down menus *Pagination *Main table * *Table rows The main table view here is the first to be appended to the DOM by my router - within this view reset is bound to an appendRows function within it - which addes in each table row: // Instantiate the view, render and append it to the DOM var tableView = new TableView({ collection: blahCollection }); $("main").append(tableView.render().el); // Fetch the latest data for the collection (triggers a reset which appends rows) blahCollection.fetch(); This seems logical to me, however when it comes to adding in a pagination sub-view for example, I ask myself the question, "should a view really be controlling what is appended to the screen"? Therefore, given the pagination example: * *Should a view (in this case the main table view) control how/when pagination is appended to the DOM? *Should the router? If so, should it call a function on the parent view to do this - or should the logic be kept completely outside of the main view? A: I like letting my router do a lot of the high-level stuff for me. For instance, I will set up a basic layout... something like this: <body> <div id="contextBar"> <div id="menus"></div> <div id="pagination"></div> </div> <div id="mainTable"></div> </body> Then, in my router handler, I'd hook up the views that are unrelated to each other: var contextView = new ContextView({el: $("#contextBar")}); var menusView = new MenusView({el: $("#menus")}); var paginationView = new PaginationView({el: $("#pagination")}); var tableView = new MainTableView({el: $("#mainTable")}); As far as the main table goes, I see the table view and the rows view being tightly coupled as they are directly related to each other, so I usually have the collection view (your table view) create and manage the individual item views (your table row view). At least, that is how I organize my code with Backbone.
{ "language": "en", "url": "https://stackoverflow.com/questions/7610632", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Facebook, send sk and app_data in send Dialog I have an app that has a function to send app_data as part of the URL. When the link is clicked the dialog pops up to select friends and the link at this stage is correct. However when friend receives the message the link is to the business page no the original link. When you first open the dialog you get a link like: e.g http://www.facebook.com/pages/Autofficina/136519656411435?sk=app_175456335854933&app_data=carID%3D110&ref=nf but the friend receives: http://www.facebook.com/pages/Autofficina/136519656411435 Is there anyway to link to the app? My Code: function send(carId, vname, image) { var theUrl = dealersPageURL + '?sk=app_' + appID + '&app_data=' + encodeURIComponent('carID=' + carId); vname += ' on ' + branchName; FB.ui({ method: 'send', name: vname, link: theUrl, picture: image, redirect_uri: null, display: 'popup' }); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7610635", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to handle a custom protocol on Blackberry I'm trying to integrate my application with the web browser on Blackberry platform: the application should be registered as the default handler for a custom protocol (something like "myapp://link-to-resource") How do I implement it? Is it possible in the first place?
{ "language": "en", "url": "https://stackoverflow.com/questions/7610640", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Open any image through my app I have image on my email and I have to open it through my application just like when I press on image it gives the action sheet. I want to show my app option on it. A: <key>CFBundleDocumentTypes</key> <array> <dict> <key>CFBundleTypeName</key> <string>PDF</string> <key>LSHandlerRank</key> <string>Alternate</string> <key>LSItemContentTypes</key> <array> <string>com.adobe.pdf</string> </array> </dict> </array> <key>CFBundleExecutable</key> this is for adding pdf file. update the code appropriately and paste in into your .plist file. A: You need to tell the system which file types your appe handles: http://developer.apple.com/library/ios/#documentation/FileManagement/Conceptual/DocumentInteraction_TopicsForIOS/Articles/RegisteringtheFileTypesYourAppSupports.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7610644", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to convert .exe setup file to .scr file? I am doing screen saver project so i want to convert project .exe file to scr file. A: Just rename the file. A .scr file is identical in format to a .exe but by convention has the .scr extension. I expect that you can configure a WPF project to output a target with .scr extension which would save the renaming step..
{ "language": "en", "url": "https://stackoverflow.com/questions/7610647", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to resolve memory crash I'm creating an application which features having multiple animations. There are 50 pages and on each page there is a different animation and each animation uses many images. I'm using UIPresentModelViewController for presenting the views and am changing images using NSTimer. When I swipe continuously the application crashes with this message:- Program received signal: “0”. Data Formatters temporarily unavailable, will re-try after a 'continue'. (Unknown error loading shared library "/Developer/usr/lib/libXcodeDebuggerSupport.dylib") I searched a lot but couldn't find any proper solutions to this issue. A: Just check within your code that you are making some mistake by adding new view every time but forgot to release it... A: You need to look at (and perhaps post) the stack trace when you crash. And the code that changes the image. This sounds like memory bloat (not a true leak in that someone is still referring to memory). The Analyze menu item might catch something (and you should definitely run it), but you may need to run the Allocation instrument and look at heap checks. See http://www.friday.com/bbum/2010/10/17/when-is-a-leak-not-a-leak-using-heapshot-analysis-to-find-undesirable-memory-growth/ for more. A: This sounds like a stack overflow to me. In the "Other C Flags" section of the project's C/C++ language settings add a flag for "-fstack-check" and see if that turns up any unwanted recursion. A: Signal 0 is usually due to memory low as the app using too much memory. Check whether memory warning method is called or not. The data formatter thingy failed to load might be due to there's not enough memory to load it.. A: 50 views like you describe sounds like a big memory hog. So I suspect memory management is unloading some views. Then when your program needs the views, they are not there and your program crashes. The error message doesn't quite fit this, but it may not be accurately telling you what the problem is. Consider the following possible scenario, and see if it fits how you coded this program. In order for the OS to manage memory, it can unload views and reload them as needed. When this is done, the methods viewDidUnload, loadView, and viewDidLoad are called. viewDidUnload: This method is called as a counterpart to the viewDidLoad method. It is called during low-memory conditions when the view controller needs to release its view and any objects associated with that view to free up memory. Because view controllers often store references to views and other view-related objects, you should use this method to relinquish ownership in those objects so that the memory for them can be reclaimed. You should do this only for objects that you can easily recreate later, either in your viewDidLoad method or from other parts of your application. You should not use this method to release user data or any other information that cannot be easily recreated. loadView: The view controller calls this method when the view property is requested but is currently nil. If you create your views manually, you must override this method and use it to create your views. If you use Interface Builder to create your views and initialize the view controller—that is, you initialize the view using the initWithNibName:bundle: method, set the nibName and nibBundle properties directly, or create both your views and view controller in Interface Builder—then you must not override this method. Check the UIView Class Reference -- viewDidLoad: This method is called after the view controller has loaded its associated views into memory. This method is called regardless of whether the views were stored in a nib file or created programmatically in the loadView method. This method is most commonly used to perform additional initialization steps on views that are loaded from nib files. You may have inadvertently initialized these views in your init methods rather than in your loadView methods. If you did this, then when the OS unloads a view (you will see viewDidUnload is called) the memory associated with the view and all subviews (all of the images and animations) will be unloaded. This saves memory, but when you need one of those unloaded views to reappear, loadView will be called first if the view had been previously unloaded. If your view setup is done in the init methods rather than in loadView, then the view will not be setup again. But if the view setup is done in loadView method, it can be recovered after memory management unloads it. A: There is one and easy way to find out leaks that is hard to find via leaks instruments and so on - Zombies analyser. It shows every unlinked memory in your program, and you can easily detect leaks and optimize code in minutes. A: If you're using lots of images for a single animation you're doing it wrong. You should have one, or several very large images and then just show a portion of that image. This way you can load very few images, but have the same affect of having many images. Look into cocos2d or other frameworks that are popular for making games, as they will be much more efficient for animations than just UIKit. A: Find out the reason for memory crash using instrument tool and then refactor the code with best practises with recommended design pattern. There is no unique solution for this. Thanks.
{ "language": "en", "url": "https://stackoverflow.com/questions/7610651", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Integrate html form with jQuery plugin I have a HTML form which submits the data to a cgi-bin script which in turns provides some output. I have seen this example that show a modal box with jQuery. This would be perfect for showing the output of the cgi-bin! The problem is that this example works with a <a href> and I can't replace the submit button with a link. How should I do? A: $('#your-form').submit(function(e){ e.preventDefault(); // make sure form is NOT submitted by the browser as this would make us navigate away from the current page and therefor render our modal window useless $this = $(this); // cache $(this) for better performance $.post( // submit the form via POST ... $this.attr('action'), // ... to the action URL of our form $this.serialize(), // ... with all the form fields as data function(data) { // ... and with the server response ... $(data).appendTo('body').paulund_modal_box().click(); // ... open the modal. // note that the click() is only required for the rather quirky "plugin" that you linked to. I suggest using easybox or the like } ); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7610653", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Reference to current object in constructor I'm trying to define a class that, in its constructor, instantiates other objects and passes them a reference to itself: var Child = function(m) { var mother = m; return { mother: mother } } var Mother = function() { var children = makeChildren(); return { children: children } function makeChildren() { var children = []; for (var i = 0; i < 10; i++) { var c = new Child(this); // <--- 'this' is an empty object here children.push(c) } return children; } } This doesn't work, and the Child instances end up with an empty object in their mother property. What is the proper way to do this? A: Javascript's this is not lexical. This means that makeChildren gets its own this instead of getting the Mother's this you want. Set a normal variable to this and use it instead. var that = this; function makeChildren(){ blabla = that; } I don't think doing this is just enough though. By returning an object from the constructor you ignore the this. Set things into it: this.children = children; instead of returning a new object. A: You could try passing a reference to the mother object when you call makeChildren() from within the mother object, something like this maybe: var Mother = function() { var children = makeChildren(this); } The makeChildren() function can then accept as an argument the reference, which you can use: function makeChildren(ref) var c = new Child(ref); No idea whether or not that will work, but it might be worth a try. A: A nested function does not inherit this from its parent, so the this within makeChildren() is not the same as the this within the Mother constructor unless you explicitly set it when calling makeChildren(): var children = makeChildren.call(this); That should work without any further changes to your code. Have a look at MDN for more detail about .call(). Alternatively you can save a reference to this and pass that into the function: var Mother = function() { var self = this; // <-- new variable var children = makeChildren(); return { children: children } function makeChildren() { var children = []; for (var i = 0; i < 10; i++) { var c = new Child(self); // <--- change 'this' to 'self' children.push(c) } return children; } } Local variables within a function are accessible to nested functions. A: var Child = function(m) { var mother = m; return { mother: mother } }; var Mother = function() { if (!(this instanceof Mother)) { return new Mother(); } var that = this; var makeChildren = function() { var children = []; for (var i = 0; i < 10; i++) { var c = new Child(that); // <--- 'that' is the reference to Mother children.push(c) } return children; }; var children = makeChildren(); return { children: children } }; then do: var m = Mother(); The first three lines in the Mother object ensure that the value of that is the Mother instance and not the global object. Without them, you would always have to write: var m = new Mother();
{ "language": "en", "url": "https://stackoverflow.com/questions/7610656", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to store absolute and relative date ranges in SQL database? I'm trying to model a DateRange concept for a reporting application. Some date ranges need to be absolute, March 1, 2011 - March 31, 2011. Others are relative to current date, Last 30 Days, Next Week, etc. What's the best way to store that data in SQL table? Obviously for absolute ranges, I can have a BeginDate and EndDate. For relative ranges, having an InceptionDate and an integer RelativeDays column makes sense. How do I incorporate both of these ideas into a single table without implementing context into it, ie have all four columns mentioned and use XOR logic to populate 2 of the 4. Two possible schemas I rejected due to having context-driven columns: CREATE TABLE DateRange ( BeginDate DATETIME NULL, EndDate DATETIME NULL, InceptionDate DATETIME NULL, RelativeDays INT NULL ) OR CREATE TABLE DateRange ( InceptionDate DATETIME NULL, BeginDaysRelative INT NULL, EndDaysRelative INT NULL ) Thanks for any advice! A: I don't see why your second design doesn't meet your needs unless you're in the "no NULLs never" camp. Just leave InceptionDate NULL for "relative to current date" choices so that your application can tell them apart from fixed date ranges. (Note: not knowing your DB engine, I've left date math and current date issues in pseudocode. Also, as in your question, I've left out any text description and primary key columns). Then, either create a view like this: CREATE VIEW DateRangesSolved (Inception, BeginDays, EndDays) AS SELECT CASE WHEN Inception IS NULL THEN Date() ELSE Inception END, BeginDays, EndDays, FROM DateRanges or just use that logic when you SELECT from the table directly. You can even take it one step further: CREATE VIEW DateRangesSolved (BeginDate, EndDate) AS SELECT (CASE WHEN Inception IS NULL THEN Date() ELSE Inception END + BeginDays), (CASE WHEN Inception IS NULL THEN Date() ELSE Inception END + EndDays) FROM DateRanges A: Others are relative to current date, Last 30 Days, Next Week, etc. What's the best way to store that data in SQL table? If you store those ranges in a table, you have to update them every day. In this case, you have to update each row differently every day. That might be a big problem; it might not. There usually aren't many rows in that kind of table, often less than 50. The table structure is obvious. Updating should be driven by a cron job (or its equivalent), and you should run very picky exception reports every day to make sure things have been updated correctly. Normally, these kinds of reports should produce no output if things are fine. You have the added complication that driving such a report from cron will produce no output if cron isn't running. And that's not fine. You can also create a view, which doesn't require any maintenance. With a few dozen rows, it might be slower than a physical table, but it might still fast enough. And it eliminates all maintenance and administrative work for these ranges. (Check for off-by-one errors, because I didn't.) create view relative_date_ranges as select 'Last 30 days' as range_name, (current_date - interval '30' day)::date as range_start, current_date as range_end union all select 'Last week' as range_name, (current_date - interval '7' day)::date as range_start, current_date as range_end union all select 'Next week' as range_name, (current_date + interval '7' day)::date as range_start, current_date as range_end Depending on the app, you might be able to treat your "absolute" ranges the same way. ... union all select 'March this year' as range_name, (extract(year from current_date) || '-03-01')::date as range_start, (extract(year from current_date) || '-03-31')::date as range_end A: Put them in separate tables. There is absolutely no reason to have them in a single table. For the relative dates, I would go so far as to simply make the table the parameters you need for the date functions, i.e. CREATE TABLE RelativeDate ( Id INT Identity, Date_Part varchar(25), DatePart_Count int ) Then you can know that it is -2 WEEK or 30 DAY variance and use that in your logic. If you need to see them both at the same time, you can combine them LOGICALLY in a query or view without needing to mess up your data structure by cramming different data elements into the same table. A: Create a table containing the begindate and the offset. The precision of the offset is up to you to decide. CREATE TABLE DateRange( BeginDate DATETIME NOT NULL, Offset int NOT NULL, OffsetLabel varchar(100) ) to insert into it: INSERT INTO DateRange (BeginDate, Offset, OffsetLabel) select '20110301', DATEDIFF(sec, '20110301', '20110331'), 'March 1, 2011 - March 31, 2011' Last 30 days INSERT INTO DateRange (BeginDate, Duration, OffsetLabel) select '20110301', DATEDIFF(sec, current_timestamp, DATEADD(day, -30, current_timestamp)), 'Last 30 Days' To display the values later: select BeginDate, EndDate = DATEADD(sec, Offset, BeginDate), OffsetLabel from DateRange If you want to be able to parse the "original" vague descriptions you will have to look for a "Fuzzy Date" or "Approxidate" function. (There exists something like this in the git source code. )
{ "language": "en", "url": "https://stackoverflow.com/questions/7610663", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Should autoboxing be avoided in Java? There are instances where a method expects a primitive type double and you pass a Double object as a parameter. Since the compiler unboxes the passed object will this increase memory usage or decrease performance? A: This is what Java Notes says on autoboxing: Prefer primitive types Use the primitive types where there is no need for objects for two reasons. * *Primitive types may be a lot faster than the corresponding wrapper types, and are never slower. *The immutability (can't be changed after creation) of the wrapper types may make their use impossible. *There can be some unexpected behavior involving == (compare references) and .equals() (compare values). See the reference below for examples. A: The rule of thumb is: always use primitives if possible. There are cases where this is not possible, like collections, so use wrappers only then. A: It's a design-choice and not trivially answered for every case. There are several items that could influence your decision: Advantages: * *Auto-boxing and auto-unboxing can make your code easier to read: Leaving out all the unnecessary .doubleValue() and Double.valueOf() reduces the visual noise and can make your code easier to read. *Auto-boxing allows you to easily use collections of primitive values (such as a List<Double>, ...) Disadvantages: * *excessive, unnecessary auto-boxing and auto-unboxing can hinder your performance. For example, if you have an API that returns a double and another API that expects a double, but you handle the value as a Double in between, then you're doing useless auto-boxing. *auto-unboxing can introduce a NullPointerException where you don't expect it: public void frobnicate(Double d) { double result = d / 2; // ... } *using collections of auto-boxed values uses a lot more memory than a comparable double[] for example. A: You don't have to avoid autoboxing if talking about performance, JVM should handle that. The only thing you should consider is a readability of your code. A: Autoboxing should be avoided. It can lead to errors because of overloading and it has some performance impact. Nonetheless it may not be an issue in your application. But be aware of the impact.
{ "language": "en", "url": "https://stackoverflow.com/questions/7610664", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Compact SQL Remote Access I'm kind of newbie to the compact SQL edition and willing to use it in a new project which need to store local data but I would like to access to it from a remote computer also. Is this possible? or is it meant only to be accessed from the local application ? To be clear, I have an application running in computer A with a local DB file accessed with the embedded compact SQL in the app, and I need to access the data from computer B also. Thanks in advance! Nach A: For situations like that, you should use SQL Server (Express), or you must expose the data on computer A via a WCF Data Service (for example)
{ "language": "en", "url": "https://stackoverflow.com/questions/7610665", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: .NET app doesn't want to run Okay, so, here's my problem: I have developed a .NET 4.0 (Client Profile) + SQL Server Compact application for someone and that someone reported the following issue: the application doesn't start at all. No errors, no exceptions, no messages, no nothing. The loading cursor shows up for 5 seconds, and then nothing happens. The application doesn't show up in the process tree either. This is not the first .NET app I develop for him, so I am 100% confident that all required software has been installed on his machine (.NET 4.0 CP). I have asked him to install the runtime for SQL Server Compact 4.0, which he did, so I don't think the problem is coming from here. I have tried sending a build with UI initialization only (no other stuff within the main form's constructor/load method). It has the same issue. I have no idea where to look for the problem's source. Anyone here who could help me with some hints, to point me to the right direction? My guess is that the application 'tries' to start during those 5 seconds, but fails. If you need some more info, please ask. A: The Event Viewer generally has good information when there is no other good information. When one of the applications I work on fail to start, this is where I look. Under the "Windows Logs", I review the" Application" and "System" Logs. Most of the time there is an error that will point me in the right direction. A: Try looking in Windows "Event Viewer" for some clues and send him a simple console-app (Hello World will do - maybe with simple Sql Compact test) to make really sure he got everything he needs. And if everything else fails go and check for yourself - it's sometimes the simplest things your user just don't mention. And yes: add loging (into a simple text file will do) A: * *First of all check that app framework is installed on PC. If you build your app using 4.5 -- 4.5 must be installed on the machine. *If your app doesn't show any error -- you need to go to Event Viewer, and find last error from the Source ".NET Runtime". Look at that error message as it will contain the Exception info.
{ "language": "en", "url": "https://stackoverflow.com/questions/7610667", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Are there any advantages to making a free static function? I have a .cpp file which has some static free functions. I know how that would help in a header file, but since the cpp is not included anywhere, what's the point? Are there any advantages to it? A: Declaring free functions as static gives them internal linkage, which allows the compiler more aggressive optimizations, as it is now guaranteed that nobody outside the TU can see that function. For example, the function might disappear entirely from the assembly and get inlined everywhere, as there is no need to provide a linkable version. Note of course that this also changes the semantics slightly, since you are allowed to have different static functions of the same name in different TUs, while having multiple definitions of non-static functions is an error. A: Since comment boxes are too small to explain why you have a serious error in your reasoning, I'm putting this as a community wiki answer. For header-only functions, static is pretty much useless because anyone who includes their header will get a different function. That means you will duplicate code the compiler creates for each of the functions (unless the linker can merge the code, but by all I know, that's very unlikely), and worse, if the function would have local statics, each of those locals would be different, resulting in potentially multiple initializations for each call to a definition from a different inclusion. Not good. What you need for header-only functions is inline (non-static inline), which means each header inclusion will define the same function and modern linkers are capable of not duplicating the code of each definition like done for static (for many cases, the C++ Standard even requires them to do so), but emitting only one copy of the code out of all definitions created by all inclusions. A: A bit out of order response because the first item addressed raises some huge questions in my head. but since the cpp is not included anywhere I strongly hope that you never #include a source file anywhere. The preprocessor doesn't care about the distinction between source versus header. This is distinction exists largely to benefit humans, not the compilers. There are many reasons you should never #include a source file anywhere. I have a .cpp file which has some static free functions. I know how that would help in a header file ... How would that help? You declare non-static free functions in a header if those free functions have external linkage. Declaring (but not defining) static free functions in a header doesn't help. It is a hindrance. You want to put stuff in a header that helps you and other programmers understand the exported content of something. Those static free functions are not exported content. You can define free functions in a header and thus make them exported content, but the standard practice is to use the inline keyword rather than static. As far as your static free functions in your source file, you might want to consider putting the declarations of those functions near the top of the source file (but not in a header). This can help improve understandability. Without those declarations, the organization of the source file will look Pascalish, with the low-level functions defined first. Most people like a top-down presentation. By declaring the functions first you can employ a top-down strategy. Or an inside out strategy, or whatever strategy makes the functionality easiest to understand.
{ "language": "en", "url": "https://stackoverflow.com/questions/7610668", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "39" }
Q: WatIn test innerText contains a whitespace at the end. HTML does not I'm using WatIn to automate IE9 testing of table. Text of cell contains a trailing whitespace that is not in the HTML. I have stepped through the WatIn code and found it is asking for innerText attribute. The value of innerText also have the trailing whitespace Run the same test on different machine with same IE version and testing the same web site and the whitespace is gone How can I avoid the trailing whitespace on my machine? A: I haven't seen your specific issue, but I have seen slight differences of HTML output due to different versions of IE and IIS. Trailing whitespace can be removed with the string.TrimEnd method. Example C# code string extraspaces = " spaces before and after "; Console.WriteLine("None a" + extraspaces + "a"); Console.WriteLine("Trim a" + extraspaces.Trim() + "a"); Console.WriteLine("TrimStart a" + extraspaces.TrimStart(' ') + "a"); Console.WriteLine("TrimEnd a" + extraspaces.TrimEnd(' ') + "a");
{ "language": "en", "url": "https://stackoverflow.com/questions/7610669", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: object rotation is not proper - iPhone application I am facing a typical problem in rotating an object. Description is as given below I have taken two CGPoint let say point1 and point2 point1 = (50,50) point2 = (150, 50) this point will draw a horizontal line. Now i am drawing a rectangle with that point on it. Width is 100 and height is 10. Angle is 0.see screen shot works fine now i change the point let say point1 = (50,50) point2 = (50,150) this point will draw a vertical line. For rectangle Angle is 90. With this point rectangle is not drawing properlysee screen shot My code for drawing rectangle is : CGPoint mid = CGPointMake((point1.x+point2.x)/2, (point1.y+point2.y)/2) CGPoint UL = CGPointMake(mid.x + ( Width / 2 ) * cos (A) - ( Height / 2 ) * sin (A) , mid.y + ( Height / 2 ) * cos (A) + ( Width / 2 ) * sin (A)); CGContextMoveToPoint(context, UL.x,routeView.frame.size.height - UL.y); CGPoint UR = CGPointMake(mid.x - ( Width / 2 ) * cos (A) - ( Height / 2 ) * sin (A) , mid.y + ( Height / 2 ) * cos (A) - ( Width / 2 ) * sin (A)); CGContextAddLineToPoint(context, UR.x,routeView.frame.size.height - UR.y); CGPoint BR = CGPointMake(mid.x - ( Width / 2 ) * cos (A) + ( Height / 2 ) * sin (A) , mid.y - ( Height / 2 ) * cos (A) - ( Width / 2 ) * sin (A)); CGContextAddLineToPoint(context, BR.x,routeView.frame.size.height - BR.y); CGPoint BL = CGPointMake(mid.x + ( Width / 2 ) * cos (A) + ( Height / 2 ) * sin (A) , mid.y - ( Height / 2 ) * cos (A) + ( Width / 2 ) * sin (A)); CGContextAddLineToPoint(context, BL.x,routeView.frame.size.height - BL.y); CGContextAddLineToPoint(context, UL.x,routeView.frame.size.height - UL.y); CGContextStrokePath(context); Here A is Angle and it is not static, mid is middle point of point1 and point2 for more ref see this Am I missing something? Please help me if you have any idea....... Thanks, A: Let me guess, it's actually rotated about 26 degrees too far, right? (90 x 180) / Pi ~= 5156.62 = (360 x 14) + 90 + 26.62 You rotated it 90 radians by mistake.
{ "language": "en", "url": "https://stackoverflow.com/questions/7610672", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What is the best way to create map in parallel with scala? Suppose I have a collection which should be converted to Map, but not in one to one fashion like map method. var map = collection.mutable.HashMap() for (p <- dataList.par) { if(cond1(p)) { map += (p, true) } else { // do nothing } } I've come up with several solutions and want to know what is best. * *map.synchronize { map += (p, true) } *use actor to update map. But I dont know how to wait till all actors task are completed *yield Some(p) or None and then run foreach { case Some(p) => map += (p, true)}. But I don't know how to make it sequential if first iterator is from parallel collections. A: Not sure that will actually perform best, but that should make evaluation of conditions parallel: import scala.collection._ val map: mutable.Map[Int, Boolean] = dataList.par.collect{case p if cond1(p) => (p, true)}(breakOut) (with a mutable Map as it is what your code did, but this is not required). Context must give the type of the expected result (hence the : mutable.Map[Int, Boolean]) for breakOut to work. Edit: breakOut is scala.collection.breakOut. Collections operation returning a collection (here collect) takes an implicit argument bf: CanBuildFrom[SourceCollectionType, ElementType, ResultType]. Implicit CanBuildFroms made available by the library are arranged so that the best possible ResultType will be returned, and best means closest to the source collection type. breakOut is passed in place of this implicit argument, so that another CanBuildFrom, hence result type, can be selected. What breakOut does is select the CanBuildFrom irrespective of the source collection type. But then there are many implicits available and no priority rule. That is why the result type must be given by the context, so that one of the implicits can be selected. To sum up, when breakOut is passed in place of the implicit argument, the result will be built to the type expected in the context. A: The breakOut mentioned in the other answer resolves to a builder factory for the collection of the expected type of map. The expected type of map is mutable.Map[Int, Boolean]. Since the builder factory is provided by a sequential collection, the collect will not proceed in parallel: scala> val cond1: Int => Boolean = _ % 2 == 0 cond1: Int => Boolean = <function1> scala> val dataList = 1 to 10 dataList: scala.collection.immutable.Range.Inclusive = Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) scala> val map: mutable.Map[Int,Boolean] = dataList.par.collect{case p if cond1(p) => println(Thread.currentThread); (p, true)}(breakOut) Thread[Thread-8,5,main] Thread[Thread-8,5,main] Thread[Thread-8,5,main] Thread[Thread-8,5,main] Thread[Thread-8,5,main] map: scala.collection.mutable.Map[Int,Boolean] = Map(10 -> true, 8 -> true, 4 -> true, 6 -> true, 2 -> true) You can see that from the thread name - the thread should contain a name ForkJoin-something. The Correct Way The correct way to do it should be to first use the breakOut with the expected type being a parallel map, so that the collect proceeds in parallel: scala> val map: parallel.mutable.ParMap[Int,Boolean] = dataList.par.collect{case p if cond1(p) => println(Thread.currentThread);(p, true)}(breakOut) Thread[Thread-9,5,main] Thread[Thread-9,5,main] Thread[Thread-9,5,main] Thread[Thread-9,5,main] Thread[Thread-9,5,main] map: scala.collection.parallel.mutable.ParMap[Int,Boolean] = ParHashMap(10 -> true, 8 -> true, 4 -> true, 6 -> true, 2 -> true) and then call seq on the result of collect, since seq is always O(1). UPDATE: just checked - this seems to work correctly with trunk, but not with 2.9.1.final. The Patch But, as you can see, this doesn't work either because it is a bug, and will be fixed in the next version of Scala. A workaround: scala> val map: parallel.mutable.ParMap[Int, Boolean] = dataList.par.collect{case p if cond1(p) => println(Thread.currentThread);(p, true)}.map(x => x)(breakOut) Thread[ForkJoinPool-1-worker-7,5,main] Thread[ForkJoinPool-1-worker-3,5,main] Thread[ForkJoinPool-1-worker-0,5,main] Thread[ForkJoinPool-1-worker-8,5,main] Thread[ForkJoinPool-1-worker-1,5,main] map: scala.collection.parallel.mutable.ParMap[Int,Boolean] = ParHashMap(10 -> true, 8 -> true, 4 -> true, 6 -> true, 2 -> true) scala> val sqmap = map.seq sqmap: scala.collection.mutable.Map[Int,Boolean] = Map(10 -> true, 8 -> true, 4 -> true, 6 -> true, 2 -> true) With a note that the final map will currently be done sequentially. Alternatively, if just a parallel.ParMap is ok with you, you can do: scala> val map: Map[Int, Boolean] = dataList.par.collect{case p if cond1(p) => println(Thread.currentThread);(p, true)}.toMap.seq Thread[ForkJoinPool-1-worker-2,5,main] Thread[ForkJoinPool-1-worker-3,5,main] Thread[ForkJoinPool-1-worker-7,5,main] Thread[ForkJoinPool-1-worker-1,5,main] Thread[ForkJoinPool-1-worker-8,5,main] map: scala.collection.Map[Int,Boolean] = Map(10 -> true, 6 -> true, 2 -> true, 8 -> true, 4 -> true)
{ "language": "en", "url": "https://stackoverflow.com/questions/7610677", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Passing vector of Class> objects to other activity - in Android I'd like to ask what I'm doing wrong if I want to pass such data to other class: String [] codes = {"code"}; Class<?> [] classes = { TestActivity.class }; Intent i = new Intent(); Pack p = new Pack(); p.eat(classes,codes); i.putExtra("com.mbar", p); i.setClass(this, CaptureActivity.class); startActivity(i); } } Later in other activity I try it to unpack like that: Bundle b = getIntent().getExtras(); Pack p = (Pack)b.getParcelable("com.mbar"); if(p!=null){ classes = p.getClasses(); codes = p.getNames(); The Pack class which is Parcelable looks like: package com.mbar; import android.os.Parcel; import android.os.Parcelable; public class Pack implements Parcelable { Class<?>[] classes; String [] codes; public void eat(Class<?>[] classes,String [] codes){ this.classes = classes; this.codes = codes; } public Class<?>[] getClasses(){ return this.classes; } public String [] getNames(){ return this.codes; } @Override public int describeContents() { // TODO Auto-generated method stub return 0; } @Override public void writeToParcel(Parcel dest, int flags) { } } A: String [] codes = {"code"}; Class<?> [] classes = { TestActivity.class }; Intent i = new Intent(); Pack p = new Pack(classes,codes); i.putExtra("com.mbar", p); i.setClass(this, CaptureActivity.class); startActivity(i) Pack p = (Pack)getIntent().getParcelableExtra("com.mbar"); if(p!=null){ classes = p.getClasses(); codes = p.getNames(); public static class Pack implements Parcelable { Class<?>[] classes; String[] codes; public Pack(Class<?>[] classes, String[] codes) { this.classes = classes; this.codes = codes; } public Pack(Parcel in) { int len = in.readInt(); String[] classnames = new String[len]; in.readStringArray(classnames); classes = new Class<?>[classnames.length]; for (int i = 0; i < classnames.length; i++) { try { classes[i] = Class.forName(classnames[i]); } catch (ClassNotFoundException e) { } } len = in.readInt(); codes = new String[len]; in.readStringArray(codes); } public Class<?>[] getClasses() { return this.classes; } public String[] getNames() { return this.codes; } @Override public int describeContents() { return 0; } public static final Parcelable.Creator<Pack> CREATOR = new Parcelable.Creator<Pack>() { public Pack createFromParcel(Parcel in) { return new Pack(in); } public Pack[] newArray(int size) { return new Pack[size]; } }; @Override public void writeToParcel(Parcel dest, int flags) { String[] classnames = new String[classes.length]; for (int i = 0; i < classes.length; i++) { classnames[i] = classes[i].getName(); } dest.writeInt(classnames.length); dest.writeStringArray(classnames); dest.writeInt(codes.length); dest.writeStringArray(codes); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7610679", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Returning a list of wildcard matches from a HashMap in java I have a Hashmap which may contain wildcards (*) in the String. For instance, HashMap<String, Student> students_; can have John* as one key. I want to know if JohnSmith matches any elements in students_. There could be several matches for my string (John*, Jo*Smith, etc). Is there any way I can get a list of these matches from my HashMap? Is there another object I could be using that does not require me to iterate through every element in my collection, or do I have to suck it up and use a List object? FYI, my collection will have less than 200 elements in it, and ultimately I will want to find the pair that matches with the least amount of wildcards. A: It's not possible to achieve with a hasmap, because of the hashing function. It would have to assign the hash of "John*" and the hash of "John Smith" et al. the same value. You could make it with a TreeMap, if you write your own custom class WildcardString wrapping String, and implement compareTo in such a way that "John*".compareTo("John Smith") returns 0. You could do this with regular expressions like other answers have already pointed out. Seeing that you want the list of widlcard matchings you could always remove entries as you find them, and iterate TreeMap.get()'s. Remember to put the keys back once finished with a name. This is just a possible way to achieve it. With less than 200 elements you'll be fine iterating. UPDATE: To impose order correctly on the TreeSet, you could differentiate the case of comparing two WildcardStrings (meaning it's a comparation between keys) and comparing a WildcardString to a String (comparing a key with a search value). A: You can use regex to match, but you must first turn "John*" into the regex equivalent "John.*", although you can do that on-the-fly. Here's some code that will work: String name = "John Smith"; // For example Map<String, Student> students_ = new HashMap<String, Sandbox.Student>(); for (Map.Entry<String, Student> entry : students_.entrySet()) { // If the entry key is "John*", this code will match if name = "John Smith" if (name.matches("^.*" + entry.getKey().replace("*", ".*") + ".*$")) { // do something with the matching map entry System.out.println("Student " + entry.getValue() + " matched " + entry.getKey()); } } A: You can just iterate your Map without converting it into a list, and use the String matches function, wih uses a regexp. If you want to avoid the loop, you can use guava like this @Test public void hashsetContainsWithWildcards() throws Exception { Set<String> students = new HashSet<String>(); students.add("John*"); students.add("Jo*Smith"); students.add("Bill"); Set<String> filteredStudents = Sets.filter(students, new Predicate<String>() { public boolean apply(String string) { return "JohnSmith".matches(string.replace("*", ".*")); } }); assertEquals(2, filteredStudents.size()); assertTrue(filteredStudents.contains("John*")); assertTrue(filteredStudents.contains("Jo*Smith")); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7610689", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: How to invoke "{Model.Foo} updated" after model update? I have a javascriptMVC Model /** * @class Hzfrontend.Models.Warmwasser * @parent index * @inherits jQuery.Model * Wraps backend warmwasser services. */ $.Model('Hzfrontend.Models.Warmwasser', /* @Static */ { findAll: "/api/warmwasser", findOne : "/api/warmwasser/{id}", update : "/api/warmwasser/{id}" }, /* @Prototype */ { update : function(attrs, success, error){ $.ajax({ type: 'PUT', url:"/api/warmwasser/"+this.id, data: $.toJSON(this), success: success, error: error, dataType: "json"}); } }); and a Controller: $.Controller('Hzfrontend.Warmwasser.List', /** @Static */ { defaults : {} }, /** @Prototype */ { init : function(){ this.element.append(this.view('init',Hzfrontend.Models.Warmwasser.findAll()) ) }, '.waterTemperature change': function( el ){ var mod = el.closest('.warmwasser').model(); mod.attr('waterTemperature', el.val()); mod.update(); steal.dev.log("update waterTemperature"); }, "{Hzfrontend.Models.Warmwasser} updated" : function(Warmwasser, ev, warmwasser){ warmwasser.elements(this.element) .html(this.view('warmwasser', warmwasser) ); steal.dev.log("updated"); } }); after the update completed I want to invoke the updated callback in the controller. How to do this? If I use the ./fixtures/fixtures.js' to test the app without a server backend, it works without any problems. Thanks. A: That code should work. What do you return as a response from your server? You should return an JSON response with the object that you updated. A: You shouldn't have a prototype update method.
{ "language": "en", "url": "https://stackoverflow.com/questions/7610691", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Python: how to keep only first 50 char of a string I have a string which x = "very_long_string_more_than_50_char_long" I want to keep only first 50 char and delete the rest. how would i do that? thanks A: use the powerful slicing mechanism: x = x[:50] A: You could use slicing x = "very_long_string_more_than_50_char_long" print x[0:50] A: >>> x = "fooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo" >>> len(x) 70 >>> y = x[:50] >>> len(y) 50 >>> y 'fooooooooooooooooooooooooooooooooooooooooooooooooo' A: x = x[:50] For details on slices like this, refer to the documentation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7610694", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How to send the mouse event to the ajaxSetup beforeSend? I have few buttons that call Ajax functions (submit contact form, submit newsletter, check if user is valid/already registered, check user status etc...) I use the ajaxSetup to show a Loading Dialog every time someone click on a button in order to tell him to wait. Here's my code: $('#submit').click(function(e) { // easily done but it's repetitive $('#loadingDiablog').css({'top':e.pageY+'px','left':e.pageX+'px'}); }); $.ajaxSetup({ beforeSend: function(jqXHR, settings) { $('#loadingDiablog').css({'top':e.pageY+'px','left':e.pageX+'px'}); // e is not defined here } }); So in order to not repeat the same code, How can I pass the mouse even ( passed on .click(function(e) ) to the beforeSend in the AjaxSetup? Thanks A: One quick way of doing it would be to add a class to all your submit buttons that you want to show the loader for and just fire it when any of them are clicked. $('#submit .ajaxButton').click(function(e) { $('#loadingDiablog').css({'top':e.pageY+'px','left':e.pageX+'px'}); }); UPDATE: var myEvent; $(document).ready(function() { $('#submit').click(function(e) { myEvent = e; }); $.ajaxSetup({ beforeSend: function(jqXHR, settings) { if (myEvent != null) { $('#loadingDiablog').css({'top':myEvent.pageY+'px','left':myEvent.pageX+'px'}); } }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7610701", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Wordpress - Remove submenu from custom post type I created a custom post type named portfolio with tag taxonomy support. Since WP does not make a difference between post tags and custom post type tags, I created a menu item Taxonomy under which I want to put categories and post tags. I managed to create the the menu and submenus, and also remove category and post tags from the Post menu, but i didn't manage to remove Post Tags from the custom post type menu. I tried: remove_submenu_page( 'edit.php?post_type=portfolio', 'edit-tags.php?taxonomy=post_tag&post_type=portfolio' ); A: This is a bit dirty, but it works: add_action('admin_menu', 'remove_niggly_bits'); function remove_niggly_bits() { global $submenu; unset($submenu['edit.php?post_type=portfolio'][11]); } I'm not sure exactly which key number you'll want to remove. Best way to find that is to do: add_action('admin_menu', 'remove_niggly_bits'); function remove_niggly_bits() { global $submenu; //unset($submenu['edit.php?post_type=portfolio'][11]); print_r($submenu); exit; } Everything will break when you load the admin area until you remove that line, but it'll show you the structure and which key you need. A: You can use remove_submenu_page() - the trick however is to get the slug exactly right, to do this the easiest way is to dump the global $submenu and check for the menu_slug and submenu_slug. global $submenu; var_dump($submenu); This will give you the array of menus, the top level key is the menu_slug and then the correct submenu_slug can be found in the element 2 of the nested arrays. So if I had a custom post type called "my_events" and I wanted to remove the tags menu from it, my original menu structure would look like this ... 'edit.php?post_type=my_events' => array 5 => array 0 => string 'All Events' (length=10) 1 => string 'edit_posts' (length=10) 2 => string 'edit.php?post_type=my_events' (length=28) 10 => array 0 => string 'Add New' (length=7) 1 => string 'edit_posts' (length=10) 2 => string 'post-new.php?post_type=my_events' (length=32) 15 => array 0 => string 'Tags' (length=4) 1 => string 'manage_categories' (length=17) 2 => string 'edit-tags.php?taxonomy=post_tag&amp;post_type=my_events' (length=55) ... From this you can see that the menu_slug is 'edit.php?post_type=my_events' and the submenu slug for the tags menu is 'edit-tags.php?taxonomy=post_tag&amp;post_type=my_events'. So the remove function call would be: remove_submenu_page('edit.php?post_type=my_events', 'edit-tags.php?taxonomy=post_tag&amp;post_type=my_events'); Note that the submenu slug is html encoded so the ampersand is now &amp; - this is probably that thing that has made it hard for people to work out from first principles what the slug name should be. A: It might be better to just use the 'show_ui' => false. function car_brand_init() { // new taxonomy named merk register_taxonomy( 'merk', 'lease_fop', array( 'label' => __( 'Merken' ), 'rewrite' => array( 'slug' => 'merken' ), 'update_count_callback' => '_update_post_term_count', // use this to hide from menu 'show_ui' => false, 'capabilities' => array( 'assign_terms' => 'edit_guides', 'edit_terms' => 'publish_guides' ) ) ); } add_action( 'init', 'car_brand_init' ); A: To build on the answer from benz001: No need to do the var dump to get the slug right. This worked for me. remove_submenu_page('edit.php?post_type=POST_TYPE', 'edit-tags.php?taxonomy=TAXONOMY_SLUG&amp;post_type=POST_TYPE') First argument, replace POST_TYPE with what you see in your URL field at the top of the browser when viewing archive in back end. Second Argument: Left click on the submenu you want to remove, copy the link, remove the last forward slash and everything to the left of it. Replace the & with &amp; Second arg example below. 1 Copy and paste submenu link http://yourwebsite.com/wp-admin/edit-tags.php?taxonomy=your_custom_taxonomy&post_type=your_custom_post 2 Remove last forward slash and everything left of it. edit-tags.php?taxonomy=your_custom_taxonomy&post_type=your_custom_post 3 Replace the & with the HTML entity &amp; /edit-tags.php?taxonomy=your_custom_taxonomy&amp;post_type=your_custom_post
{ "language": "en", "url": "https://stackoverflow.com/questions/7610702", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Ria services how to query with Nolock - Read uncommited functionality Is there a way to implement a nolock - read uncommited functionality in specific queries in RIA Services (silverlight 4)? In Linq To Sql i can achieve the same result by setting the isolation level of the transaction to IsolationLevel.ReadUncommitted. Any way to do that in RIA? A: RIA Services doesn't query the database on its on, you have to provide it a context. If you use a LinqToSql context then you should be able to use the same methods to read uncommitted data. Just have your service context inherit from LinqToSqlDomainService.
{ "language": "en", "url": "https://stackoverflow.com/questions/7610703", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Seeing a ViewController behind the displayed one Is it possible to view the viewcontroller behind the displayed one? I have a viewcontroller with a scrollview, which has imageviews added as subviews and would like the view that presented this viewcontroller to be visible behind the presented view controller. I have set all the views, the viewcontroller view too to have a clear color background, but still there is a black background. when I dismiss the viewcontroller, I see 2 layers being dismissed. one has alpha dropped, the other not. Is there an easy way to make this effect possible? A: Its not possible. When a new view controller is pushed or presented as modal view, the previous view controller will be removed from the display(may be UINavigationController/iOS hides it). The rule is only one view controller would be visible at a time. So you will see the color of your window(the black color you've mentioned) in the background. A: What you could do is make a screenshot before displaying the other controller. and send this image to new controller to be displayed as background. This will only work for static content, but you could do something like the curl display. A: You can do this but the truth is what EmptyStack says. You can use setFrame of the subView and add it on the viewController. Also use below method to set the index of the added View. By default currentView has Index 0. [self.view insertSubview:myView atIndex:0]; or you can try below methods as per your logic insertSubview:aboveSubview: insertSubview:atIndex: insertSubview:belowSubview: addSubViews: bringSubviewToFront: removeFromSuperview:
{ "language": "en", "url": "https://stackoverflow.com/questions/7610720", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Hiding a specific no of div on page load Lets say i have following html structure- <div>blah</div> <div>blah</div> <div>blah</div> <div>blah</div> <div>blah</div> <div>blah</div> <div>blah</div> <div>blah</div> <div>blah</div> <div>blah</div> <div>blah</div> <div>blah</div> <div>blah</div> <div>blah</div> <div>blah</div> <div>blah</div> <a>more..</a> I want to hide all except the first 5 div on page load, then on click of more link I want to show further 5 div and so on till last div. How can I do this using jquery? A: I guess what you wanted to do is hide all divs and then clicking on more show the 5 next divs each time. You can try it on jsfiddle. HTML: <div>blah</div> <div>blah</div> <div>blah</div> <div>blah</div> <div>blah</div> <div>blah</div> <div>blah</div> <div>blah</div> <div>blah</div> <div>blah</div> <div>blah</div> <div>blah</div> <div>blah</div> <div>blah</div> <div>blah</div> <div>blah</div> <a id="more">more..</a> JS using jQuery: $(function() { $('div').hide(); $('#more').click(function() { $('div:hidden').slice(0,5).show(); }); }); A: Try - $(document).ready(function() { $("div:gt(4)").hide(); $("a").click(function() { if ($("div:hidden").length > 5) $("div:hidden:lt(5)").show(); else $("div:hidden").show(); }) }) Demo - http://jsfiddle.net/ipr101/dfL8q/1/ A: I'm assuming what you want to do is, on page load, hide all but the first 5 divs. Then when the "more" link is clicked, show 5 more divs until all are visible Here's how I would do it: (Demo: http://jsfiddle.net/HC4KW/2/) * *By default, have all you divs visible and the "more" link hidden using CSS. This allows non-js browsers to still see your content *On document ready, hide all but the first 5 divs $("div:gt(4)", container).hide(); *Show your "more" link which, on click: * *Displays the first 5 hidden divs *hides the "more" link if there are no more hidden divs $('#more').show().click(function() { var hidden_divs = $("div:hidden", container); /* list of hidden divs */ if (hidden_divs.size() <= 5) { /* No hidden divs left after we show 5 more*/ $(this).hide(); /* hide "more" link */ } hidden_divs.slice(0, 5).slideDown(); /* reveal first 5 hidden divs */ }); A: $(document).ready(function() { $("div").hide() $("div:lt(5)").show() $("a").click(function() { $("div:hidden:lt(5)").show() }) }) http://jsfiddle.net/KaPNa/1/ A: I'm not sure if I get the question right. $(function() { $("div:gt(4)").hide(); $("a").click(function(event) { $("div:hidden:lt(5)").show(); event.preventDefault(); }); }); Demo: http://jsbin.com/uzovug/6 A: To hide five elements you could do: $('button').click(function(){ var div = $('div:visible').filter(function(i){ if (i <5) return this; }).hide(); }); fiddle here http://jsfiddle.net/sbpkR/ EDIT - of course use a function to hide them on dom ready: var hide5 = function(){ var div = $('div:visible').filter(function(i){ if (i <5) return this; }).hide(); }; $(document).ready(function(){ hide5(); $(a).click(hide5); }); EDIT 2 - I updated the fiddle http://jsfiddle.net/sbpkR/2/ $('div').hide(); $('div').filter(function(i){ if (i <5) return this; }).show(); $('button').click(function(){ var divS = $('div:visible:last').nextAll().filter(function(i){ if (i <5) return this; }) ; $('div').hide(); divS.show(); }); EDIT 3 - http://jsfiddle.net/sbpkR/3/ $('div').hide(); $('div').filter(function(i){ if (i <5) return this; }).show(); $('button').click(function(){ var divS = $('div:visible:last').nextAll().filter(function(i){ if (i <5) return this; }) ; divS.show(); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7610724", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-4" }
Q: To run cmd as administrator along with command? Here is my code: try { ProcessStartInfo procStartInfo = new ProcessStartInfo( "cmd.exe", "/c " + command); procStartInfo.UseShellExecute = true; procStartInfo.CreateNoWindow = true; procStartInfo.Verb = "runas"; procStartInfo.Arguments = "/env /user:" + "Administrator" + " cmd" + command; ///command contains the command to be executed in cmd System.Diagnostics.Process proc = new System.Diagnostics.Process(); proc.StartInfo = procStartInfo; proc.Start(); } catch (Exception ex) { MessageBox.Show(ex.Message); } I want to keep procStartInfo.UseShellExecute = true procStartInfo.RedirectStandardInput = false; Is it possible to execute the command without using process.standardinput? I try to execute command I've passed in argument but the command does not executes. A: As @mtijn said you've got a lot going on that you're also overriding later. You also need to make sure that you're escaping things correctly. Let's say that you want to run the following command elevated: dir c:\ First, if you just ran this command through Process.Start() a window would pop open and close right away because there's nothing to keep the window open. It processes the command and exits. To keep the window open we can wrap the command in separate command window and use the /K switch to keep it running: cmd /K "dir c:\" To run that command elevated we can use runas.exe just as you were except that we need to escape things a little more. Per the help docs (runas /?) any quotes in the command that we pass to runas need to be escaped with a backslash. Unfortunately doing that with the above command gives us a double backslash that confused the cmd parser so that needs to be escaped, too. So the above command will end up being: cmd /K \"dir c:\\\" Finally, using the syntax that you provided we can wrap everything up into a runas command and enclose our above command in a further set of quotes: runas /env /user:Administrator "cmd /K \"dir c:\\\"" Run the above command from a command prompt to make sure that its working as expected. Given all that the final code becomes easier to assemble: //Assuming that we want to run the following command: //dir c:\ //The command that we want to run string subCommand = @"dir"; //The arguments to the command that we want to run string subCommandArgs = @"c:\"; //I am wrapping everything in a CMD /K command so that I can see the output and so that it stays up after executing //Note: arguments in the sub command need to have their backslashes escaped which is taken care of below string subCommandFinal = @"cmd /K \""" + subCommand.Replace(@"\", @"\\") + " " + subCommandArgs.Replace(@"\", @"\\") + @"\"""; //Run the runas command directly ProcessStartInfo procStartInfo = new ProcessStartInfo("runas.exe"); procStartInfo.UseShellExecute = true; procStartInfo.CreateNoWindow = true; //Create our arguments string finalArgs = @"/env /user:Administrator """ + subCommandFinal + @""""; procStartInfo.Arguments = finalArgs; //command contains the command to be executed in cmd using (System.Diagnostics.Process proc = new System.Diagnostics.Process()) { proc.StartInfo = procStartInfo; proc.Start(); } A: why are you initializing the process object with arguments and then later on override those Arguments? and btw: the last bit where you set Arguments you concatenate 'command' right upto 'cmd', that doesn't make much sense and might be where it fails (looks like you're missing a space). Also, you are currently using the standard command line, you might want to look into using the runas tool instead. you can also call runas from command line. Also, why are you running 'command' from the command line? why not start it directly from Process.Start with admin privileges supplied then and there? here's a bit of pseudocode: Process p = Process.Start(new ProcessStartInfo() { FileName = <your executable>, Arguments = <any arguments>, UserName = "Administrator", Password = <password>, UseShellExecute = false, WorkingDirectory = <directory of your executable> });
{ "language": "en", "url": "https://stackoverflow.com/questions/7610727", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: How to track direction of a motion? How do I track the direction of a motion in Android ? Think WiiMote, it can track what direction you move it (not talking about the IR lamps), is it possible to do similar in android, if so, how? Some basic code in either Java or B4A is appreciated, but it's enough if you tell me the logic and maths on how to calculate the direction of movement. A: You have to use accelerometer for this. I've seen code using accelerometer in here: http://www.hascode.com/2010/04/sensor-fun-using-the-accelerometer-on-android/ Other stuff about sensors: http://developer.android.com/reference/android/hardware/Sensor.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7610728", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Programmatically searching and choosing a network provider I'm currently developping an application that resets your connection when your signal strength is too low. I'm trying to do this by searching and choosing your network operator (settings-> wireless and networks -> Mobile networks -> Network operators). I noticed this way has a few advantages over switching to airplane mode: - Wifi and/or bluetooth doesn't get disabled - You don't 'loose' your reception and this can still make calls (tested this; you will still lose your data/internet connection, however) I'm trying to find some way to automate this when your signal drops too low. Does anyone know how to do this (preferably without root, but if needed, that's fine as well; Busybox shell commands are fine too)? Thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/7610734", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PDF printing error I am using TCPDF to generate custom size PDF files to generate Courier Receipts. To print this receipt I am using Dot matrix printer with continuous stationery. custom Height of page is 4 inches (288.000) as per TCPDF but acrobat reader is showing minimum height is 4.12 inches. therefore at the time of printing every page get ejected for 4mm extra by printer and my data is shifted 4mm down on receipt. $pdf->AddPage('L', 'CUSTOM_PAGE'); $pdf->writeHTMLCell($w=94, $h=34, $x=15, $y=23, $from, $border=0, $ln=0, $fill=0, $reseth=true, $align='', $autopadding=true); $pdf->writeHTMLCell($w=94, $h=34, $x=120, $y=23, $to, $border=0, $ln=0, $fill=0, $reseth=true, $align='', $autopadding=true); $pdf->lastPage(true); $pdf->SetAutoPageBreak(true,0.00); above is my code to generate PDF.
{ "language": "en", "url": "https://stackoverflow.com/questions/7610740", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MVC3 Cookie not included in request until after refresh or visiting a second page BACKGROUND: I'm using two MVC3 websites for mixed mode authentication. I'm authenticating a person using windows authentication in Site1, and then forwarding that person onto Site2 which uses Forms authentication. My solution was to gather user information in site1 once the user is authenticated via windows auth. I would then write this info to a cookie, and then redirect to Site 2. Site 2 would then use the info found in the cookie to automatically log in the user using Forms Auth. Both applications are in the same domain and should be able to share cookies, however the cookie isn't available after the redirect until the page is refreshed or by clicking on a link in the site (visiting a 2nd page). Anyway, here's my problem. I create the cookie and then forward the user to Site2 from Site1. ...{cookie created here and added to response}... HttpContext.Response.Redirect("http://site2.mydomain.com") When I do this, there isn't a cookie in the request. However, once on the home page of Site2, I can hit refresh, and then my cookie is part of the request and my authentication works. I need my Response to write the cookie to the client, then get that cookie added in the request, but it seems to skip that when using Response.Redirect... UPDATE: I've read that the request will only have cookies included when the cookie exists before the request is made. Since I'm writing the cookie into the response for the request, only subsequent requests will contain the cookie. So, what I need is a way to force a second request, once they get my response from the initial request. So... User sends request ---> response returns with cookie ---> force another request (should contain cookie) ---> return requested page. Can I do this using javascript? Can the javascript check the response for a cookie of a certain name, and when found, cause a redirect to the current page? A: If you have to force the refresh to get a second request, you could perhaps append a Query String parameter from Site1's redirect HttpContext.Response.Redirect("http://site2.mydomain.com?refresh=1"), then in Site2, cause a redirect to the same page sans query string parameter. That's not really ideal though. Could you put that cookie information into a query string for a one off authentication URL that then stores a new cookie and redirects to Site2's homepage?
{ "language": "en", "url": "https://stackoverflow.com/questions/7610742", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Constructor not working, compile error I was looking at a game engine code and I tried to reproduce myself but I got a compile error. Main.as package { import flash.display.Sprite; public class Main extends Sprite { public function Main():void { var firstDoes:AB1 = new AB1(); firstDoes.secondDoes._AB2(); } } } AB1.as package { import flash.display.Sprite; public class AB1 extends Sprite { var secondDoes:AB2 = new AB2(); public function _AB1():void { } } } AB2.as package { import flash.display.Sprite; public class AB2 extends Sprite { public function _AB2():void { this.graphics.beginFill(0x33FF22); this.graphics.drawCircle(50, 50, 20); this.graphics.endFill(); this.addChild(this); } } } Why isn't it working ? Thanks in advance. A: Is it intentional that you have an underscore in your AB1 and AB2 constructor? If not, I would suggest renaming "_AB1" to "AB1", and "_AB2" to "AB2". A: I tried running this code. I don't get a compile error, but I DO get a runtime error. You can't add yourself as a child: this.addChild(this); // <-------- BOOM! A: try deleting this.addChild(this); from AB2, changing var secondDoes:AB2 = new AB2(); to public var secondDoes:AB2 = new AB2(); and adding addChild(secondDoes); to AB1 constructor A: Class name and constructor name should be the same. var secondDoes:AB2; Make this as public. graphics is the property of DisplayObject, so you should use MovieClip or Sprite or Shape to create your circle. Main class : package { import flash.display.Sprite; public class Main extends Sprite { public function Main():void { var firstDoes:AB1 = new AB1(); addChild(firstDoes); } } } AB1 class : package { import flash.display.Sprite; public class AB1 extends Sprite { public var secondDoes:AB2; public function AB1():void{ secondDoes = new AB2(); addChild(secondDoes); } } } AB2 class : package { import flash.display.Sprite; public class AB2 extends Sprite { public var my_mc:Sprite = new Sprite(); public function AB2():void { my_mc = new Sprite(); my_mc.graphics.beginFill(0x33FF22); my_mc.graphics.drawCircle(50, 50, 20); my_mc.graphics.endFill(); addChild(my_mc); } } } A: I think that the issue is with public function Main():void A constructor can't have a return type. You should rather use public function Main()
{ "language": "en", "url": "https://stackoverflow.com/questions/7610751", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Retrieve Email Id from FaceBook Login in vb.net application I want to integrate Facebook with my .net application which is in vb. I want to use facebook login as open id login to my application. I reached to login with fb and get all basic information of my facebook profile. But still I do not get facebook login id(means facebook login email id) in my user information detail retrieved from facebook. Please help me out to solve this. I get first name, last name and etc. but I want email id of facebook login or primary email address. A: You'll have to prompt your users to grant the email permission. Then you'll be able to pull the email field in the same API call that you get their name and basic info.
{ "language": "en", "url": "https://stackoverflow.com/questions/7610753", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: JPA createNativeQuery call procedure with non standart name I'm trying to call an Oracle procedure using Persistence API: @TransactionAttribute(TransactionAttributeType.REQUIRED) public void removeProcess(User user, BigDecimal processId) { EntityManager em = emb.createEntityManager(user); em.createNativeQuery("{ call DOF.DF#DEL_PROCESS(?) }") .setParameter(1, processId) .executeUpdate(); em.close(); } And I got the following exception: Caused by: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.3.0.v20110604-r9504): org.eclipse.persistence.exceptions.DatabaseException Internal Exception: java.sql.SQLException: Invalid column index Error Code: 17003 Call: { call DOF."DF?)" } bind => [1 parameter bound] If i copy DF#DEL_PROCESS to DF_DEL_PROCESS all works fine. How can I escape # in the procedure name?? A: '#' is the default parameter marker used internal in EclipseLink. You can change this using the query hint, "eclipselink.jdbc.parameter-delimiter" Also, if you inline the parameter instead of using setParameter() it should also work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7610757", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: prevent mobile default keyboard when focusing an from showing this is how i'm trying <script type="text/javascript"> $(document).ready(function(){ $('#dateIn,#dateOut').click(function(e){ e.preventDefault(); }); }); </script> but the input stills 'launching' iphone's keyboard ps: i want to do this because i'm using datepicker plugin for date A: inputmode attribute <input inputmode='none'> The inputmode global attribute is an enumerated attribute that hints at the type of data that might be entered by the user while editing the element or its contents. It can have the following values: none - No virtual keyboard. For when the page implements its own keyboard input control. I am using this successfully (Tested on Chrome/Android) CSS-Tricks: Everything You Ever Wanted to Know About inputmode A: Below code works for me: <input id="myDatePicker" class="readonlyjm"/> $('#myDatePicker').datepicker({ /* options */ }); $('.readonlyjm').on('focus',function(){ $(this).trigger('blur'); }); A: I asked a similar question here and got a fantastic answer - use the iPhone native datepicker - it's great. How to turn off iPhone keypad for a specified input field on web page Synopsis / pseudo-code: if small screen mobile device set field type to "date" - e.g. document.getElementById('my_field').type = "date"; // input fields of type "date" invoke the iPhone datepicker. else init datepicker - e.g. $("#my_field").datepicker(); The reason for dynamically setting the field type to "date" is that Opera will pop up its own native datepicker otherwise, and I'm assuming you want to show the datepicker consistently on desktop browsers. A: By adding the attribute readonly (or readonly="readonly") to the input field you should prevent anyone typing anything in it, but still be able to launch a click event on it. This is also usefull in non-mobile devices as you use a date/time picker A: Since I can't comment on the top comment, I'm forced to submit an "answer." The problem with the selected answer is that setting the field to readonly takes the field out of the tab order on the iPhone. So if you like entering forms by hitting "next", you'll skip right over the field. A: Best way to solve this as per my opinion is Using "ignoreReadonly". First make the input field readonly then add ignoreReadonly:true. This will make sure that even if the text field is readonly , popup will show. $('#txtStartDate').datetimepicker({ locale: "da", format: "DD/MM/YYYY", ignoreReadonly: true }); $('#txtEndDate').datetimepicker({ locale: "da", useCurrent: false, format: "DD/MM/YYYY", ignoreReadonly: true }); }); A: You can add a callback function to your DatePicker to tell it to blur the input field before showing the DatePicker. $('.selector').datepicker({ beforeShow: function(){$('input').blur();} }); Note: The iOS keyboard will appear for a fraction of a second and then hide. A: So here is my solution (similar to John Vance's answer): First go here and get a function to detect mobile browsers. http://detectmobilebrowsers.com/ They have a lot of different ways to detect if you are on mobile, so find one that works with what you are using. Your HTML page (pseudo code): If Mobile Then <input id="selling-date" type="date" placeholder="YYYY-MM-DD" max="2999-12-31" min="2010-01-01" value="2015-01-01" /> else <input id="selling-date" type="text" class="date-picker" readonly="readonly" placeholder="YYYY-MM-DD" max="2999-12-31" min="2010-01-01" value="2015-01-01" /> JQuery: $( ".date-picker" ).each(function() { var min = $( this ).attr("min"); var max = $( this ).attr("max"); $( this ).datepicker({ dateFormat: "yy-mm-dd", minDate: min, maxDate: max }); }); This way you can still use native date selectors in mobile while still setting the min and max dates either way. The field for non mobile should be read only because if a mobile browser like chrome for ios "requests desktop version" then they can get around the mobile check and you still want to prevent the keyboard from showing up. However if the field is read only it could look to a user like they cant change the field. You could fix this by changing the CSS to make it look like it isn't read only (ie change border-color to black) but unless you are changing the CSS for all input tags you will find it hard to keep the look consistent across browsers. To get arround that I just add a calendar image button to the date picker. Just change your JQuery code a bit: $( ".date-picker" ).each(function() { var min = $( this ).attr("min"); var max = $( this ).attr("max"); $( this ).datepicker({ dateFormat: "yy-mm-dd", minDate: min, maxDate: max, showOn: "both", buttonImage: "images/calendar.gif", buttonImageOnly: true, buttonText: "Select date" }); }); Note: you will have to find a suitable image. A: I have a little generic "no keyboard" script - works for me with Android and iPhone: $('.readonlyJim').on('focus', function () { $(this).trigger('blur') }) Simply attach add class readonlyJim to the input tag and voila. (*Sorry too much StarTrek here)
{ "language": "en", "url": "https://stackoverflow.com/questions/7610758", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "95" }
Q: Launch4j JRE Installation or bundled I'll ship my application as .exe file on a cdrom. When the end user gonna start the program, the following events should occurs (in case he hasn't got any valid JRE installation): * *If the user hasn't got an internet connection, the program (exe file) should use an embedded JRE (shipped with the cdrom) *If the user has got an internet connection, he should be redirected to the JRE download location (java.com). He should then download the JRE and install it. I won't use the bundled JRE for a user with an internet connection. I configured both download path and JRE bundle in Launch4J, but I can't find how i could configure it for my specialities. Anyone got a clue or solution? Thx A: Refer to file:///C:/Program%20Files/Launch4j/web/docs.html#Configuration_file Certain conditions must be met as follows: Using <path> in jre tab: Run if bundled JRE and javaw.exe are present, otherwise stop with error. Using <path> + <minVersion> [+ <maxVersion>] in jre tab: Use bundled JRE first, if it cannot be located search for Java, if that fails display error message and open the Java download page. Using <minVersion> [+ <maxVersion>] in jre tab: Search for Java, if an appropriate version cannot be found display error message and open the Java download page. So, you must meet the second condition...
{ "language": "en", "url": "https://stackoverflow.com/questions/7610765", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jBPM and Object Oriented Programming and Framework I need to ask a very general question. I recently saw some sparks of the jBPM through tutorial, what I didn't understand, is where do we need such a tool ? Is this tool to replace OOP programming ? A developement process ? In the end, is it possible to generate a BPM which depends to some third party libraries and reuse in that components and logic, as usual a programmer/developer/s.w does ? A: You will need a BPM System everywhere where you want to expose to business people how your systems are being designed to guide the business use case. Tools like jBPM5 will help you to discover your business processes, formalize them and then automate them. You need to understand the difference with systems integrations where you are only orchestrating which systems to call in which order. In no way BPM is a replacement for OOP or a development methodology, but it helps a lot describe in a higher level / business level what your applications will do, and how your applications will drive the business using the business processes definitions. Just to answer your last question I can say that obviously that you can integrate applications with a BPMS, that's one of the main ideas. Instead of re writing all the applications logic that you have in different systems, BPMS allows you and promote to reuse what your company have. Hope it helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/7610771", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jQuery Validate - Set all fields as required by default? I am using the jQuery Validate plugin on my form, and was wondering how I would set every field to be required by default? I am using a custom method called 'methodname' and I tried the following code to no avail: $.validator.setDefaults({ methodname : true }); Any ideas? Thanks! A: Quick'n'dirty fix: $(document).ready(function(){ $('#myform input, #myform textarea').not([type="submit"]).addClass('required'); }); A: This should do the trick, and doesn't require any alteration to the markup: $("#myform input, #myform textarea").each(function () { $(this).rules("add", { required: true // Or whatever rule you want }); }); http://docs.jquery.com/Plugins/Validation/rules#rules.28.C2.A0.22add.22.2C.C2.A0rules_.29 A: I know this question has been answered already, and this answer kind of goes along with what @vzwick posted. $('form :input').not(':image, :button, :submit, :reset, :hidden, .notRequired').addClass('required'); Any field that you may still want to not require, like Address Line 2, you can add the class .notRequired. Other than that, this bit of code will exclude any image buttons, buttons, submits, resets, and hidden form fields. A: Add validation js in your page and 1. Get all names of input, textarea and select fields through loop. 2. Create dynamic rules array 3. Pass the rules array in validate(); var rules_set={}; $('#my-form').find('input').each(function(){ var name=$(this).attr('name'); rules_set[name]='required'; }); $("#my-form").validate({ rules: rules_set, submitHandler: function (form) { form.submit(); } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7610773", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Eliminate a single element type from XML using XQUERY Here is my problem... I need to select everything in an entire xml document, but leaving out one tag. Unfortunately, this tag can vary in depth. Using the following code sample, I would like to remove all <crud>, <crud2> and <...> (etc.) elements. <crud> could have more children, but I don't want them anyways. <body> <h2/> <crud> <crud2/> <...> </crud> <div> <p> </p> </div> <div> <p> </p> <crud> <crud2/> <...> </crud> </div> </body> I've tried a few methods. let $body := "the xml sample" return $body/*[fn:not(descendant-or-self::crud)] This method takes to much. It removes the entire <div> block that contains crud, but I need the <div> and the <p> that is included. All other methods seem to only remove the direct <crud> children of <body> or it removes the container as well. So, I essentially need a method that reaches in every element and removes all the <crud> without taking anything else. The final XML should look like this: <body> <h2/> <div> <p> </p> </div> <div> <p> </p> </div> </body> I greatly appreciate any and all help. A: This kind of processing is most easily done with XSLT, which is more expressive than XQuery: <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output omit-xml-declaration="yes"/> <xsl:template match="node()|@*"> <xsl:copy> <xsl:apply-templates select="node()|@*"/> </xsl:copy> </xsl:template> <xsl:template match="crud"/> </xsl:stylesheet> When this transformation is applied on the provided XML document: <body> <h2/> <crud> <crud2/> </crud> <div> <p> </p> </div> <div> <p> </p> <crud> <crud2/> </crud> </div> </body> the wanted, correct result is produced: <body> <h2/> <div> <p> </p> </div> <div> <p> </p> </div> </body> Explanation: * *The identity rule copies every node "as-is'. *A single template overrides the identity rule/template. It matches anu crud element and its empty body results in crud (and any subtree topped by it) to be stripped off the output. A: This is an easy job using XQuery Update and its copy-statement: copy $c := . modify delete node $c//crud return $c If you can change your original file, you could even use the shorter delete node //crud.
{ "language": "en", "url": "https://stackoverflow.com/questions/7610775", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Javascript Object.innerHtml is not substituting the whole string parameter provided newcell.innerHTML='<td id=\"blah1\">'+BLAH+'</td>'; For some strange reason my <td>BLAH</td> is correctly rendered on the page but any attributes that I give inside the td tag just don't display. Any pointers? Sorry if this might sound very silly, I have very less experience in front end. Any 'must look' tutorials would be appreciated. Thanks A: If newCell in this case represents a <td> then you need to either use outerHTML instead of innerHTML, or programmatically set the properties you need. var newCell = document.createElement("td"); newCell.outerHTML = '<td id=\"blah1\">'+BLAH+'</td>'; or var newCell = document.createElement("td"); newCell.id = "blah1"; newCell.innerHTML = BLAH; A: If you're declaring a Javascript string with single quotes, you don't need to escape any double-quotes that you use inside it. Try newcell.innerHTML='<td id="blah1">'+BLAH+'</td>';.
{ "language": "en", "url": "https://stackoverflow.com/questions/7610781", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What are the supported operators and commands in FQL? I'm trying to compile a complete list but the sources don't agree. Here's what I've got so far. Let me know if I'm missing anything, or if I've put anything in incorrectly. Basic format: SELECT [fields] FROM [table] WHERE [conditions] In the docs: now(), strlen(), substr() and strpos(), IN Unsure: * *AND *OR *LIMIT *ORDER_BY *OFFSET *Anything else? Also: Joins are definitely out right? A: functions supported: me() now() rand() strlen(...) concat(...) substr(...) strpos(...) lower(...) upper(...) operators supported: AND, OR, NOT, IN, ><=, +-*/ OFFSET is a part of LIMIT: offset, rowcount, i.e. LIMIT 5, 5 ORDER BY is supported, DESC, ASC is supported also, SELECT * not supported EDIT: joins not supported but you can do subqueries
{ "language": "en", "url": "https://stackoverflow.com/questions/7610785", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: .htaccess Wildcard Redirect Fix I am using the following code to redirect wildcard subdomains (*.domain.com) to their coresponding folder in /users and redirect direct requests to the /users folder to the subdomain version: Protect Direct Access to Wildcard Domain Folders: RewriteCond %{HTTP_HOST} ^www\.domain\.com$ [NC] RewriteRule ^users/([a-z0-9\-_\.]+)/?(.*)$ http://$1.domain.com/$2 [QSA,NC,R,L] Handle Wildcard Subdomain Requests: RewriteCond %{REQUEST_URI} !^/users/ [NC] RewriteCond %{HTTP_HOST} ^(.+)\.domain\.com$ [NC] RewriteCond %1 !=www [NC] RewriteRule ^(.*)$ /users/%1/$1 [L] This code works well enough, however there are two problems that I can't seem to fix. * *The below scenario seems to happen because there isn't a trailing slash on the requesting URI: username.domain.com/sub1 => username.domain.com/users/username/sub1 username.domain.com/sub1/ => username.domain.com/sub1/ *The users directory can still be accessed directly by using a subdomain: username.domain.com/users/username/sub1 => Works and shouldn't I'm at a loss and would really appreciate if anyone has any ideas. Thank you! A: For the problem 2, I think your first protection rule just needs to redirect all subdomains. It's redirecting www, but lets username.domain.com come through as-is. This will redirect any direct access request to the users path. RewriteCond %{HTTP_HOST} ^.+\.domain\.com$ [NC] RewriteRule ^users/([a-z0-9\-_\.]+)/?(.*)$ http://$1.domain.com/$2 [QSA,NC,R,L] I think it can be a little simpler by just looking for any host ending in domain.com (which would even handle no subdomain, just domain.com) (I didn't test this....) RewriteCond %{HTTP_HOST} domain\.com$ [NC] RewriteRule ^users/([a-z0-9\-_\.]+)/?(.*)$ http://$1.domain.com/$2 [QSA,NC,R,L] For problem 1, I'm stumped too, sorry. It's acting like the trailing slash is failing the rules, so it falls through as-is. But I would expect it to do as you want it to: username.domain.com/sub1/ => username.domain.com/users/username/sub1/ Perhaps try the %{REQUEST_URI} tag, instead of trying to capture .*. I don't see the difference, but maybe it'll help. RewriteCond %{REQUEST_URI} !^/users/ [NC] RewriteCond %{HTTP_HOST} ^(.+)\.domain\.com$ [NC] RewriteCond %1 !=www [NC] RewriteRule .* /users/%1%{REQUEST_URI} [L]
{ "language": "en", "url": "https://stackoverflow.com/questions/7610787", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Add custom headers to WebView resource requests - android I need to add custom headers to EVERY request coming from the WebView. I know loadURL has the parameter for extraHeaders, but those are only applied to the initial request. All subsequent requests do not contain the headers. I have looked at all overrides in WebViewClient, but nothing allows for adding headers to resource requests - onLoadResource(WebView view, String url). Any help would be wonderful. Thanks, Ray A: Try loadUrl(String url, Map<String, String> extraHeaders) For adding headers to resources loading requests, make custom WebViewClient and override: API 24+: WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) or WebResourceResponse shouldInterceptRequest(WebView view, String url) A: You will need to intercept each request using WebViewClient.shouldInterceptRequest With each interception, you will need to take the url, make this request yourself, and return the content stream: WebViewClient wvc = new WebViewClient() { @Override public WebResourceResponse shouldInterceptRequest(WebView view, String url) { try { DefaultHttpClient client = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(url); httpGet.setHeader("MY-CUSTOM-HEADER", "header value"); httpGet.setHeader(HttpHeaders.USER_AGENT, "custom user-agent"); HttpResponse httpReponse = client.execute(httpGet); Header contentType = httpReponse.getEntity().getContentType(); Header encoding = httpReponse.getEntity().getContentEncoding(); InputStream responseInputStream = httpReponse.getEntity().getContent(); String contentTypeValue = null; String encodingValue = null; if (contentType != null) { contentTypeValue = contentType.getValue(); } if (encoding != null) { encodingValue = encoding.getValue(); } return new WebResourceResponse(contentTypeValue, encodingValue, responseInputStream); } catch (ClientProtocolException e) { //return null to tell WebView we failed to fetch it WebView should try again. return null; } catch (IOException e) { //return null to tell WebView we failed to fetch it WebView should try again. return null; } } } Webview wv = new WebView(this); wv.setWebViewClient(wvc); If your minimum API target is level 21, you can use the new shouldInterceptRequest which gives you additional request information (such as headers) instead of just the URL. A: You should be able to control all your headers by skipping loadUrl and writing your own loadPage using Java's HttpURLConnection. Then use the webview's loadData to display the response. There is no access to the headers which Google provides. They are in a JNI call, deep in the WebView source. A: Here is an implementation using HttpUrlConnection: class CustomWebviewClient : WebViewClient() { private val charsetPattern = Pattern.compile(".*?charset=(.*?)(;.*)?$") override fun shouldInterceptRequest(view: WebView, request: WebResourceRequest): WebResourceResponse? { try { val connection: HttpURLConnection = URL(request.url.toString()).openConnection() as HttpURLConnection connection.requestMethod = request.method for ((key, value) in request.requestHeaders) { connection.addRequestProperty(key, value) } connection.addRequestProperty("custom header key", "custom header value") var contentType: String? = connection.contentType var charset: String? = null if (contentType != null) { // some content types may include charset => strip; e. g. "application/json; charset=utf-8" val contentTypeTokenizer = StringTokenizer(contentType, ";") val tokenizedContentType = contentTypeTokenizer.nextToken() var capturedCharset: String? = connection.contentEncoding if (capturedCharset == null) { val charsetMatcher = charsetPattern.matcher(contentType) if (charsetMatcher.find() && charsetMatcher.groupCount() > 0) { capturedCharset = charsetMatcher.group(1) } } if (capturedCharset != null && !capturedCharset.isEmpty()) { charset = capturedCharset } contentType = tokenizedContentType } val status = connection.responseCode var inputStream = if (status == HttpURLConnection.HTTP_OK) { connection.inputStream } else { // error stream can sometimes be null even if status is different from HTTP_OK // (e. g. in case of 404) connection.errorStream ?: connection.inputStream } val headers = connection.headerFields val contentEncodings = headers.get("Content-Encoding") if (contentEncodings != null) { for (header in contentEncodings) { if (header.equals("gzip", true)) { inputStream = GZIPInputStream(inputStream) break } } } return WebResourceResponse(contentType, charset, status, connection.responseMessage, convertConnectionResponseToSingleValueMap(connection.headerFields), inputStream) } catch (e: Exception) { e.printStackTrace() } return super.shouldInterceptRequest(view, request) } private fun convertConnectionResponseToSingleValueMap(headerFields: Map<String, List<String>>): Map<String, String> { val headers = HashMap<String, String>() for ((key, value) in headerFields) { when { value.size == 1 -> headers[key] = value[0] value.isEmpty() -> headers[key] = "" else -> { val builder = StringBuilder(value[0]) val separator = "; " for (i in 1 until value.size) { builder.append(separator) builder.append(value[i]) } headers[key] = builder.toString() } } } return headers } } Note that this does not work for POST requests because WebResourceRequest doesn't provide POST data. There is a Request Data - WebViewClient library which uses a JavaScript injection workaround for intercepting POST data. A: Maybe my response quite late, but it covers API below and above 21 level. To add headers we should intercept every request and create new one with required headers. So we need to override shouldInterceptRequest method called in both cases: 1. for API until level 21; 2. for API level 21+ webView.setWebViewClient(new WebViewClient() { // Handle API until level 21 @SuppressWarnings("deprecation") @Override public WebResourceResponse shouldInterceptRequest(WebView view, String url) { return getNewResponse(url); } // Handle API 21+ @TargetApi(Build.VERSION_CODES.LOLLIPOP) @Override public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) { String url = request.getUrl().toString(); return getNewResponse(url); } private WebResourceResponse getNewResponse(String url) { try { OkHttpClient httpClient = new OkHttpClient(); Request request = new Request.Builder() .url(url.trim()) .addHeader("Authorization", "YOU_AUTH_KEY") // Example header .addHeader("api-key", "YOUR_API_KEY") // Example header .build(); Response response = httpClient.newCall(request).execute(); return new WebResourceResponse( null, response.header("content-encoding", "utf-8"), response.body().byteStream() ); } catch (Exception e) { return null; } } }); If response type should be processed you could change return new WebResourceResponse( null, // <- Change here response.header("content-encoding", "utf-8"), response.body().byteStream() ); to return new WebResourceResponse( getMimeType(url), // <- Change here response.header("content-encoding", "utf-8"), response.body().byteStream() ); and add method private String getMimeType(String url) { String type = null; String extension = MimeTypeMap.getFileExtensionFromUrl(url); if (extension != null) { switch (extension) { case "js": return "text/javascript"; case "woff": return "application/font-woff"; case "woff2": return "application/font-woff2"; case "ttf": return "application/x-font-ttf"; case "eot": return "application/vnd.ms-fontobject"; case "svg": return "image/svg+xml"; } type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); } return type; } A: As mentioned before, you can do this: WebView host = (WebView)this.findViewById(R.id.webView); String url = "<yoururladdress>"; Map <String, String> extraHeaders = new HashMap<String, String>(); extraHeaders.put("Authorization","Bearer"); host.loadUrl(url,extraHeaders); I tested this and on with a MVC Controller that I extended the Authorize Attribute to inspect the header and the header is there. A: This worked for me. Create WebViewClient like this below and set the webclient to your webview. I had to use webview.loadDataWithBaseURL as my urls (in my content) did not have the baseurl but only relative urls. You will get the url correctly only when there is a baseurl set using loadDataWithBaseURL. public WebViewClient getWebViewClientWithCustomHeader(){ return new WebViewClient() { @Override public WebResourceResponse shouldInterceptRequest(WebView view, String url) { try { OkHttpClient httpClient = new OkHttpClient(); com.squareup.okhttp.Request request = new com.squareup.okhttp.Request.Builder() .url(url.trim()) .addHeader("<your-custom-header-name>", "<your-custom-header-value>") .build(); com.squareup.okhttp.Response response = httpClient.newCall(request).execute(); return new WebResourceResponse( response.header("content-type", response.body().contentType().type()), // You can set something other as default content-type response.header("content-encoding", "utf-8"), // Again, you can set another encoding as default response.body().byteStream() ); } catch (ClientProtocolException e) { //return null to tell WebView we failed to fetch it WebView should try again. return null; } catch (IOException e) { //return null to tell WebView we failed to fetch it WebView should try again. return null; } } }; } A: This works for me: * *First you need to create method, which will be returns your headers you want to add to request: private Map<String, String> getCustomHeaders() { Map<String, String> headers = new HashMap<>(); headers.put("YOURHEADER", "VALUE"); return headers; } *Second you need to create WebViewClient: private WebViewClient getWebViewClient() { return new WebViewClient() { @Override @TargetApi(Build.VERSION_CODES.LOLLIPOP) public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) { view.loadUrl(request.getUrl().toString(), getCustomHeaders()); return true; } @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url, getCustomHeaders()); return true; } }; } *Add WebViewClient to your WebView: webView.setWebViewClient(getWebViewClient()); Hope this helps. A: I came accross the same problem and solved. As said before you need to create your custom WebViewClient and override the shouldInterceptRequest method. WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) That method should issue a webView.loadUrl while returning an "empty" WebResourceResponse. Something like this: @Override public boolean shouldInterceptRequest(WebView view, WebResourceRequest request) { // Check for "recursive request" (are yor header set?) if (request.getRequestHeaders().containsKey("Your Header")) return null; // Add here your headers (could be good to import original request header here!!!) Map<String, String> customHeaders = new HashMap<String, String>(); customHeaders.put("Your Header","Your Header Value"); view.loadUrl(url, customHeaders); return new WebResourceResponse("", "", null); } A: You can use this: @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { // Here put your code Map<String, String> map = new HashMap<String, String>(); map.put("Content-Type","application/json"); view.loadUrl(url, map); return false; } A: Use this: webView.getSettings().setUserAgentString("User-Agent");
{ "language": "en", "url": "https://stackoverflow.com/questions/7610790", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "124" }
Q: Logging problems when using modules individually I'm making extensive use of the logging module in all my own modules. This works fine when I create a configuration for the logging module in my main routine. But when I want to test one of my modules individually in an interactive shell and logging.getLogger("foo") is executed I get the error: No handlers could be found for logger "foo" This makes sense of course because the logging module hasn't been configured yet. When I just call logging.basicConfig() in all my modules again my logs will be printed more than once (the python doc also says to only call basicConfig() once in the main thread). So, how is this done cleanly? Can I check if the logging module has already been configured? A: It is explained in the Logging module How-To. You could create a helper module to be included wherever you perform any logging: import logging logging.getLogger('your_top_level_package').addHandler(logging.NullHandler())
{ "language": "en", "url": "https://stackoverflow.com/questions/7610792", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: App was not working in some mobile devices I developed an application. My application includes video recording and playing. I have to play video what I have recorded from mobile. This is working in most of devices(Samsung galaxy ace,Motorola Droid x, etc.,) and not working in some of devices(Droid x2,Nexus,etc.,). I used below code for video playing String temp_path=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)+"/MySaveCellData/dbz_115.3gp"; //Toast.makeText(this,getSaveCellPath(),Toast.LENGTH_LONG).show(); if(temp_path!=null) { //int width = myView.getMeasuredWidth(); // int height = myView.getMeasuredHeight(); //we add 10 pixels to the current size of the video view every time you touch //the media controller. Display display = getWindowManager().getDefaultDisplay(); int width = display.getWidth(); int height = display.getHeight(); MediaController mediaController = new MediaController(this); mediaController.setAnchorView(myView); myView.setMediaController(mediaController); myView.setKeepScreenOn(true); //myView.setVideoAspect(width,height); //myView.setVideo myView.setVideoPath(temp_path); myView.start(); myView.requestFocus(); } else Toast.makeText(this,"Video Path Not Found, or is set to null",Toast.LENGTH_LONG).show(); } What is the problem and solution? A: The problem is not in video playing. The problem in video recording. When I record the video the hardware of device is not supporting to my code. So I changed the code of video recorder. It is working well in all devices.
{ "language": "en", "url": "https://stackoverflow.com/questions/7610793", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Plone make login mandatory on every page but main page A customer wants to have its Plone site behave like this: * *the main page can be seen by anonymous users *you have to be registered and authenticated to see any other page *the site is open for registration, so the forms to authenticate and register should also be made visible by anonymous How one can approach this? Is there a way to hook a python script/class/method/function to any request made by the user? Overriding the main_template.pt and adding a TAL call to a method that does these checks would be enough? The tricky part is that even if the anonymous can only visit the main page, the main page in itself is made up of other content types which should be only viewed by authenticated users (by their restrictions, not because of workflow). I ruled out, maybe a mistake?, workflow because then everything should be made private but still the global_nav is made out of folders which, if the workflow approach was taken, should be private/non-viewable by anonymous. Cheers, A: Try this: * *add a state internally published to your workflow *copy permissions configuration from the "public" state into the new state and than remove the "View" permission from the Anonymous User (maintain the 'Access content information', that's the key). Then add all needed transitions. *put your home page in "public" state *put everything else in 'internally published' state This should work because if you link content's information in the homepage, this will work, but if someone try to access a content he will miss the "view" permission and will be redirected to the login.
{ "language": "en", "url": "https://stackoverflow.com/questions/7610799", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Lucene Proximity Search with multiple words I am trying to build a query to search an Lucene index of names with name variants. The index was built with Lucene.NET version 2.9.2 The user enters for example "Margaret White". Without a name variant option, my query becomes "Margaret White"~1 and it works. Now, I can look up name variants against both firstname and surname to produce an extended list. eg. in this case (and I only include some as an example, since the list can be 100 or more sometimes) we can have Margaret / Margrett White / Whyte The query "margrett white"~1 OR "margaret white"~1 OR "margrett whyte"~1 OR "margaret whyte"~1 gives me the correct result but given a possible 100 x 100 variant combinations, the query string woudl be cumbersome to say the least. I have tried various ways to achieve a more compact query but nothing seems to work. Can anyone give me any pointers or alternative approach. I have control over the index creation process and wonder if there is something I can do at that stage? Thanks for looking Roger A: Do the synonym filter in your indexing process instead of at query time. Just map "white", "whyte", ... to some single word; say "white". Same for "Margaret." Then your query will just be "margaret white"~1 A: I faced a similar problem and solved it by writing my own query parser and manually instantiating query primitives. Writing your own query parser is not necessarily easy, but it gives you a lot of flexibility. In my new query language, I use within/N to specify a proximity query. With it, the following complex queries become possible: margaret within/3 white margaret within/3 (white or whyte) Or even more complex queries ("first name" within/3 margaret) within/10 ("last name" within/3 (white or whyte))
{ "language": "en", "url": "https://stackoverflow.com/questions/7610801", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: xsl: Store multiple items in a variable or param for later use I need to transform an xml to some custom xml format. In the new format i would have many sections node and for each node i am creating a unique id using: <xsl:attribute name="identifier"> <xsl:variable name="uid" select="util:randomUUID()"/>A<xsl:value-of select="util:toString($uid)"/> </xsl:attribute> I need a way to store all of these Ids in a list or array so that i can refer it back from some other template and use them in for-each loop. Is there a way to do this with xsl? Thanks for any help A: Have these globally declared: <xsl:variable name="vrtfRandList"> <xsl:for-each select="yourNodeSet"> <rand><xsl:value-of select="util:randomUUID()"/></rand> </xsl:for-each> </xsl:variable> <xsl:variable name="vRandlist" select="ext:node-set($vrtfRandList)/*"/> Then later use: $vRandlist[$k] Using XSLT 2.0: <xsl:variable name="vRandlist" as="xs:integer*" select="for $i in 1 to count(yourNodeSet) return util:randomUUID() "/>
{ "language": "en", "url": "https://stackoverflow.com/questions/7610802", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: create a distribution file for downloading with wget at github - no git needed I'd like users to be able to issue something like: wget https://nodeload.github.com/opensas/play-demo/zipball/master/opensas-play-demo-bb3a405.zip without having to clone the whole repo, nor browsing to github to manually download it apparently, github issues some kind of redirect when accessing: https://nodeload.github.com/opensas/play-demo/zipball/master and it just downloads some binary file instead... is there some easy way to achieve it??? A: I've just found the asnwer I made a distribution zip file Uploaded it with "add new download" option and now I have the following url to get it: https://github.com/downloads/opensas/play-demo/play-demo-at-jugar-2011_09_29.zip
{ "language": "en", "url": "https://stackoverflow.com/questions/7610804", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Difficulty installing and using Mercurial Chart extension Hi I'm having trouble installing and using the Mercurial ChartExtension When I installed it as per instructions First you need to install the extension; type this in your shell: python ./setup.py install Blockquote I then modified my mercurial.ini file as follows [extensions] chart=/path/to/chart.py Blockquote Then tried running Hg Chart command and got the following error Can anyone help me get this extension working. I know there's the Hg ActivityExtension as well, but i have not had much luck with that either Problem installing Mercurial Activity extension A layman's guide to what steps i need to follow would be of immense help A: Based on the changelog, the Chart extension has not been updated since late 2008. It would probably work if you tried using it with a version of Mercurial released around that same time (Mercurial v1.1.2 was released on Dec. 30, 2008). The latest version of Mercurial is now v1.9.2. The API has changed (probably quite a bit) since v1.1.2. If the extension has not been modified to keep up with the changes to the API, then it will fail in ways similar to the error you found. In this case, the number of arguments for the walkchangerevs method has changed. Updating the extension could be a large task...there is no way to know without inspecting the code. You could try to contact the author (@Ry4an) and ask for help. You could also try to modify the extension yourself.
{ "language": "en", "url": "https://stackoverflow.com/questions/7610805", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Xpath - Group matches as combined results I'm having the following problem, I want to create a Xpath expression that results into 3 matches, where match1=text1text1text, match2=text2text2text2 etc. I'm able to find each p seperate, but i just can't 'group' them. What the expression should say is: "after a[@class="random-a-tag"] give me all the text of all the p-tags that exist before each element where div[@id]" <a class="random-a-tag"></a> <p>text1</p> <p>text1</p> <p>text1</p> <div id="1"></div> <p>text2</p> <p>text2</p> <p>text2</p> <div id="2"></div> <p>text3</p> <p>text3</p> <p>text3</p> <div id="3"></div> A: You can do this in two steps. find all divs //a[@class="random-a-tag"]/following-sibling::div[@id] and for each div @id do: //a[@class="random-a-tag"]/following-sibling::p[following-sibling::div[1][@id="3"]]/text() A: This cannot be done with a single XPath 1.0 expression. The most you can select is the set of p for a given value of @id: /*/a/following-sibling::div [@id=$pId] /preceding-sibling::p [count(. | /*/a/following-sibling::div [@id=$pId] /preceding-sibling::div[1] /preceding-sibling::p ) = count(/*/a/following-sibling::div [@id=$pId] /preceding-sibling::div[1] /preceding-sibling::p ) +1 ] If $pId is (substituted by) 2, and the above XPath expression is applied on this XML document (your XML fragment, wrapped in a top element to make it well-formed XML document): <t> <a class="random-a-tag"></a> <p>text1</p> <p>text1</p> <p>text1</p> <div id="1"></div> <p>text2</p> <p>text2</p> <p>text2</p> <div id="2"></div> <p>text3</p> <p>text3</p> <p>text3</p> <div id="3"></div> </t> then this selects the following nodes: <p>text2</p> <p>text2</p> <p>text2</p> In the above XPath expression we use the wellknown Kayessian (created by @Michael Kay) formula for node-set intersection: $ns1[count(.|$ns2) = count($ns2)] is the intersection of the nodesets $ns1 and $ns2. II. XPath 2.0 solution: (a/following-sibling::div [@id=$pId] /preceding-sibling::p except a/following-sibling::div [@id=$pId] /preceding-sibling::div[1] /preceding-sibling::p )/string() When this XPath 2.0 expression is evaluated against the same XML document (above) and $pId is 2, the result is exactly the wanted text: text2 text2 text2
{ "language": "en", "url": "https://stackoverflow.com/questions/7610810", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }