text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: Jboss with UTC timezone We have setup our server timezone (Windows) UTC (coordinated universal time) , but when we start the JBoss I could see -5 hours from system time in the console as well as in the jboss log. For e.g., system is 0900 HRS jboss log and console shows as 0400 HRS.
Please throw some idea where we should configure in jboss to pickup UTC time.
Rgds
Balaji
A: You can always enforce a timezone using a Java system property during startup, this does not apply to JBoss only:
java -Duser.timezone=UTC [...]
or programatically:
System.setProperty("user.timezone", "UTC");
I'm not a JBoss expert, but I guess JBoss provides a way to explicitly set the timezone, e.g. using administration console or configuration script.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594849",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Disable input submit button with js in IE & FF doesnt' work I have a problem, with disabling a input button with javascript in a aspx document at ie.
The js look's like
<script language="javascript" type="text/javascript">
function SetButtonStatus(sender, target)
{
if (searchinput.value.length < 4)
{
document.getElementById(target).disabled = true;
}
else
{
document.getElementById(target).disabled = false;
}
}
</script>
I call the input button with
<input name="searchinput" type="text" value="" id="searchinput" onkeyup="SetButtonStatus(this, 'searchsubmit')" />
In Chrome everything works fine. If i type more then 4 characters in the inputfield, the button will be enabled. But in IE & FF nothing happens... Why? How could i fix this?
A: You are depending on the non-standard "Create a global variable for every element that has an id" that is supported by Chrome and IE in some rendering modes.
Replace searchinput with sender (since you have defined sender and passed a reference to the element you are interested in already).
A: <script language="javascript" type="text/javascript">
function SetButtonStatus(sender, target)
{
// use document.getElementById("searchinput") instead of searchinput or in your case can use sender
document.getElementById(target).disabled = document.getElementById("searchinput").value.length < 4;
}
</script>
A: Why don't you just use jquery it handles all browsers internaly and you don't have to worry about them. Make it like this:
<input name="searchinput" type="text" value="" id="searchinput"/>
<input type="button" value="button" disabled="true" id="buttonSearch"/>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(function(){
$('#searchinput').keydown(function(e){
var lenght = 3;
if(e.keyCode ==8)
{
lenght = 5;
}
if (searchinput.value.length < lenght)
{
$('#buttonSearch').attr("disabled", true);
}
else
{
$('#buttonSearch').removeAttr('disabled');
}
});
});
</script>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594851",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: syntax error in mysql during tringger definition I'm trying to use a trigger defined as follows
-- the table
CREATE TABLE codici_ddt(
id_ordine VARCHAR(15) NOT NULL,
id_invoice VARCHAR(15) NOT NULL,
ddt_numero INT(8) NOT NULL,
fatturazione DATE NOT NULL,
ddt VARCHAR(20) NOT NULL,
FOREIGN KEY(id_ordine) REFERENCES ordini_dal_web(id_ordine),
PRIMARY KEY(id_ordine)
);
--the_trigger
DELIMITER $$
CREATE TRIGGER genera_numero_ddt BEFORE INSERT ON codici_ddt FOR EACH ROW
BEGIN
DECLARE ultimo_ddt INT(8);
SELECT COALESCE(max(ddt_numero),1) INTO ultimo_ddt
FROM codici_ddt
WHERE data_fatturazione >= MAKEDATE(YEAR(NEW.data_fatturazione) ,1)
AND data_fatturazione < MAKEDATE(YEAR(NEW.data_fatturazione)+1,1);
SET NEW.ddt_numero = (ultimo_ddt+1)
SET NEW.ddt = CONCAT(NEW.ddt_numero,'/',(SUBSTRING(SUBSTRING_INDEX(NEW.data_fatturazione,'-',1),-2)),'c');
END $$
DELIMITER ;
the message returned from mysql is
1064 - You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'SET NEW.ddt =
CONCAT(NEW.ddt_numero,'/',(SUBSTRING(SUBSTRING_INDEX(NEW.data_fatt' at
line 11
the CONCAT should be right, where is my error?
many thanks!
A: You miss ';' at the end of line.
SET NEW.ddt_numero = (ultimo_ddt+1);
A: Missing semi-colon. Also you are referencing data_fatturazione instead of just fatturazione.
Try this:
DELIMITER $$
CREATE TRIGGER genera_numero_ddt BEFORE INSERT ON codici_ddt FOR EACH ROW
BEGIN
DECLARE ultimo_ddt INT(8);
SELECT COALESCE(max(ddt_numero),1) INTO ultimo_ddt FROM codici_ddt
WHERE fatturazione >= MAKEDATE(YEAR(NEW.fatturazione) ,1)
AND fatturazione < MAKEDATE(YEAR(NEW.fatturazione)+1,1);
SET NEW.ddt_numero = (ultimo_ddt+1);
SET NEW.ddt = CONCAT(NEW.ddt_numero,'/',(SUBSTRING(SUBSTRING_INDEX(NEW.fatturazione,'-',1),-2)),'c');
END $$
DELIMITER ;
|
{
"language": "it",
"url": "https://stackoverflow.com/questions/7594852",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: How to load master-details data(more than 2 hierarchy) using WCF RIA Services I'm trying to get my head around treeviews and am able to do two levels, but I'm stumped with adding the 3rd level. I assume you make a 3rd Hierarchical Template - but I'm not sure how this is loaded. I'm using the AdventureWorks database as sample data.
I'm using the Product, ProductCategory, and ProductSubCategory tables.
My Metadata looks like. (just the interesting bits)
public partial class Product
{
public string Name { get; set; }
public int ProductID { get; set; }
public string ProductNumber { get;set; }
public ProductSubcategory ProductSubcategory { get; set; }
public Nullable<int> ProductSubcategoryID { get; set; }
}
public partial class ProductCategory
{
public string Name { get; set; }
public int ProductCategoryID { get; set; }
[Include]
[Composition]
public EntityCollection<ProductSubcategory> ProductSubcategory { get; set; }
}
public partial class ProductSubcategory
{
public string Name { get; set; }
[Include]
[Composition]
public EntityCollection<Product> Product { get; set; }
public ProductCategory ProductCategory { get; set; }
public int ProductCategoryID { get; set; }
public int ProductSubcategoryID { get; set; }
My Queries look like :
public IQueryable<Product> GetProduct()
{
return this.ObjectContext.Product;
}
public IQueryable<ProductCategory> GetProductCategory()
{
return this.ObjectContext.ProductCategory.Include("ProductSubcategory");
}
public IQueryable<ProductSubcategory> GetProductSubcategory()
{
return this.ObjectContext.ProductSubcategory.Include("Product");
}
My Code behind (which is where I'm having the problem understanding how to load two queries). I want to return Products under ProductSubCategory under ProductCategory.
public partial class Tree : Page
{
public Tree()
{
InitializeComponent();
AdventureWorksContext ads = new AdventureWorksContext();
trvTree.ItemsSource = ads.ProductCategories;
ads.Load(ads.GetProductCategoryQuery());
}
}
A: Try modifying your GetProductCategory query as such:
{
return this.ObjectContext.ProductCategory.Include("ProductSubcategory").Include("ProductSubcategory.Product");
}
I don't know if it'll work in your case, where you want to build a tree, but it should include the data as needed.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594857",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: writing and installing your own leiningen plugin I have been able to run a custom plugin from within my projects project.clj, and even leiningen/plugin.clj (ie just a private plugin) - but when I go to put this plugin in its own project - I am unable to get it to work at all.
Following the advice, I should create a new project, and have a namespace of leiningen.myplugin etc etc... but the jar that I produce doesn't seem to provide the new task in the project (either via jar, or via clojars).
http://nakkaya.com/2010/02/25/writing-leiningen-plugins-101/
https://github.com/technomancy/leiningen/blob/stable/doc/PLUGINS.md
Anyone who has published a plugin care to confirm if the above is correct - or is there some crucial step I am missing? (I assume my task goes in core.clj in the plugin project)
A: Do you have the :eval-in-leiningen option set to true in the project.clj?
In addition if you want to use the task all around with your leiningen without having to add it to the dev dependencies of the project where you need to use it you need to use lein plugin install
Or did i miss something about your problem
A: Note that eval-in-leiningen doesn't need to be used for very simple project-specific plugins or tasks, and it can sometimes wreak build havoc. You can enable a Leiningen task for a given project by just using .lein-classpath for that project. More information here:
Project-level Leiningen Plugin
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594862",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Is MySQL breaking the standard by allowing selecting columns that are not part of the group by clause? I am used to Microsoft technologies including SQL Server. Today I ran across a Q&A where the following passage from the MySQL documentation was quoted:
Standard SQL would reject your query because you can not SELECT
non-aggregate fields that are not part of the GROUP BY clause in an
aggregate query. MySQL extends the use of GROUP BY so that the select
list can refer to nonaggregated columns not named in the GROUP BY
clause. This means that the preceding query is legal in MySQL. You
can use this feature to get better performance by avoiding unnecessary
column sorting and grouping. However, this is useful primarily when
all values in each nonaggregated column not named in the GROUP BY are
the same for each group. The server is free to choose any value from
each group, so unless they are the same, the values chosen are
indeterminate.
Is MySQL breaking the standard by allowing this? How? What is the result of allowing this?
A:
Is MySQL breaking the standard by allowing this? How?
It lets you write a query like that:
SELECT a.*, COUNT(*)
FROM a
JOIN b
ON b.a = a.id
GROUP BY
a.id
Other systems would require you to add all columns from a into the GROUP BY list which makes the query larger, less maintanable and less efficient.
In this form (with grouping by the PK), this does not contradict the standard since every column in a is functionally dependent on its primary key.
However, MySQL does not really check the functional dependency and lets you select columns not functionally dependent on the grouping set. This can yield indeterminate results and should not be relied upon. The only thing guaranteed is that the column values belong to some of the records sharing the grouping expression (not even to one record!).
This behavior can be disabled by setting sql_mode to ONLY_FULL_GROUP_BY.
A: Short answer
It's a speed hack
That is enabled by default, but that can be disabled with this setting: https://dev.mysql.com/doc/refman/8.0/en/group-by-handling.html
Long answer
The reason for the non-standard shorthand group by clause is that it's a speed hack.
MySQL lets the programmer determine whether the selected fields are functionally dependent on the group by clause.
The DB does not do any testing, but just selects the first result that it finds as the value of the field.
This results in considerable speed ups.
Consider this code:
SELECT f1, f2, f3, f4 FROM t1 GROUP BY f2
-- invalid in most SQL flavors, valid in MySQL
MySQL will just select the first value it finds, spending a minimum amount of time.
f1,f3, f4 will be from the same row, but this relation will fall apart if multiple tables with joins are involved.
In order to do the same something simular in SQL-server you'd have to do
SELECT MIN(f1), f2, MIN(f3), MIN(f4) FROM t1 GROUP BY f2
-- valid SQL, but really a hack
The DB will now have to examine all results to find the minimum value, huffing and puffing.
f1, f3, f4 will most likely have no relation to each other and will not be from the same row.
If however you do:
SELECT id as `primary_key`, count(*) as rowcount, count(f2) as f2count, f2, f3, f4
FROM t1
GROUP BY id
All the rest of the fields will be functionally dependent on id.
Rowcount will always be 1, and f2count will be either 0 (if f2 is null) or 1.
On joins, where lots of tables are involved, in a 1-n configuration like so:
Example:
Website 1 -> n Topics 1 -> n Threads 1 -> n Posts 1 -> 1 Person.
And you do a complicated select involving all tables and just do a GROUP BY posts.id
Obviously all other fields are functionally dependent on posts.id (and ONLY on posts.id).
So it makes no sense to list more fields in the group by clause, or to force you to use aggregate functions.
In order to speed things up. MySQL does not force you to do this.
But you do need to understand the concept of functional dependency and the relations in the tables and the join you've written, so it puts a pot of burden on the programmer.
However using:
SELECT
posts.id, MIN(posts.f2)
,MIN(threads.id), min(threads.other)
,MIN(topics.id), ....
,MIN(website.id), .....
,MIN(Person.id), ...
FROM posts p
INNER JOIN threads t on (p.thread_id = t.id)
INNER JOIN topic to on (t.topic_id = to.id)
INNER JOIN website w ON (w.id = to.website_id)
INNER JOIN person pe ON (pe.id = p.person_id)
GROUP BY posts.id //NEVER MIND THE SYNTAX ERROR WITH THE ALIASES
Puts exactly the same mental burden on the programmer.
A:
Standard SQL would reject your query because you can not SELECT non-aggregate fields that are not part of the GROUP BY clause in an aggregate query
This is correct, up to 1992.
But it is plainly wrong, from 2003 and beyond.
From SQL-2003 standard, 6IWD6-02-Foundation-2011-01.pdf, from http://www.wiscorp.com/, paragraph-7.12 (query specification), page 398:
*If T is a grouped table, then let G be the set of grouping columns of T. In each ((value expression)) contained
in ((select list)) , each column reference that references a column of T shall reference some column C that
is functionally dependent on G or shall be contained in an aggregated argument of a ((set function specification))
whose aggregation query is QS
Now MYSQL, has implemented this feature by allowing not only columns that are functionally dependent on the grouping columns but allowing all columns. This is causing some problems with users that do not understand how grouping works and get indeterminate results where they don't expect.
But you are right to say that MySQL has added a feature that conflicts with SQL-standards (although you seem to think that for the wrong reason). It's not entirely accurate as they have added a SQL-standard feature but not in the best way (more like the easy way) but it does conflict with the latest standards.
To answer your question, the reason for this MySQL feature (extension) is I suppose to be accordance with latest SQL-standards (2003+). Why they chose to implement it this way (not fully compliant), we can only speculate.
As @Quassnoi and @Johan answered with examples, it's mainly a performance and maintainability issue. But one can't easily change the RDBMS to be clever enough (Skynet excluded) to recognize functionally dependent columns, so MySQL developers made a choice:
We (MySQL) give you (MySQL users) this feature which is in SQL-2003 standards. It improves speed in certain GROUP BY queries but there's a catch. You have to be careful (and not the SQL engine) so columns in the SELECT and HAVING lists are functionally dependent on the GROUP BY columns. If not, you may get indeterminate results.
If you want to disable it, you can set sql_mode to ONLY_FULL_GROUP_BY.
It's all in the MySQL docs: Extensions to GROUP BY (5.5) - although not in the above wording but as in your quote (they even forgot to mention that it's a deviation from standard SQL-2003 while not standard SQL-92). This kind of choices is common I think in all software, other RDBMS included. They are made for performance, backward compatibility and a lot of other reasons. Oracle has the famous '' is the same as NULL for example and SQL-Server has probably some, too.
There is also this blog post by Peter Bouman, where MySQL developers' choice is defended: Debunking GROUP BY myths.
In 2011, as @Mark Byers informed us in a comment (in a related question at DBA.SE), PostgreSQL 9.1 added a new feature (release date: September 2011) designed for this purpose. It is more restrictive than MySQL's implementation and closer to the standard.
Later, in 2015 MySQL announced that in 5.7 version, the behaviour is improved to conform with the standard and actually recognize functional dependencies, (even better than the Postgres implementation). The documentation: MySQL Handling of GROUP BY (5.7) and another blog post by Peter Bouman: MySQL 5.7.5: GROUP BY respects functional dependencies!
A: All the big DBMSs have their own flavours and extensions; otherwise why would there ever be more than one of them?
Following the SQL Standards stringently is nice and all, but providing extensions with more functionality is even better. The quote from the documentation explains how this functionality is useful.
There isn't much of a conflict in this case, so I don't really see the issue.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594865",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
}
|
Q: Scala version of Wicket I've read that there should be a (pure) Scala version of the Wicket web framework. But I can not find a project website or anything else about it. Where can I find it?
A: From the related discussion on the Forum for Wicket Core developers, it doesn't seem to have been released yet.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594870",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Perl Dancer after hook Is there a way in Dancer to execute a code after every request?
I tried with an after hook but it seems that it doesn't execute after a file request...
There is a hook called 'after_file_render' which is executed a decent number of times after each request but I am not sure what is its purpose. Is it always called after every request?
A: The after_file_render hook is run after each successful request for a static file (e.g., a CSS file or an image), while the after hook runs after an action is performed by a route handler.
If you want to run the same code for both after and after_file_render, you can put it in a subroutine and assign it to the two hooks using a reference, e.g.:
sub foo {
...
}
hook after_file_render => \&foo;
hook after => \&foo;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594876",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: find tag inside text string I have an xml document (from a feed), which I'm extracting values from:
$(feed_data).find("item").each(function() {
if(count < 3) {
//Pull attributes out of the current item. $(this) is the current item.
var title = $(this).find("title").text();
var link = $(this).find("link").text();
var description = $(this).find("description").text();
Now inside "description" i need to get the img element, but this is causing me some problems. "descripttion" is a regular string element and it seems i can't call the ".find()" method on this, so what do i do?
I have tried calling .find():
var img = $(this).find("description").find("img");
But it's a no go. The img is wrapped in a span, but I can't get to this either. Any suggestions? I'd prefer to avoid substrings and regex solutions, but I'm at a loss.
I've also tried turning the "description" string into an xml object like so:
var parser = new DOMParser();
var desc = parser.parseFromString(test,'text/xml');
$(desc).find("img").each(function() {
alert("something here");
});
But that doesn't work either. It seems like it would, but I get a "document not well formed" error.
A: Try enclosing the contents of the description tag in a dummy div, that seemed to work better for me, and allowed jQuery's .find() to work as expected.
e.g.
$(feed_data).find("item").each(function() {
if(count < 3) {
//Pull attributes out of the current item. $(this) is the current item.
var title = $(this).find("title").text();
var link = $(this).find("link").text();
var description = '<div>' + $(this).find("description").text() + '</div>';
var image = $(description).find('img');
A: Hi and thanks for the prompt replies. I gave GregL the tick, as I'm sure his solution would have worked, as the principle is the same as what I ended up with. My solution looks like this:
$(feed_data).find("item").each(function() {
if(count < 3) {
//Pull attributes out of the current item. $(this) is the current item.
var title = $(this).find("title").text();
var link = $(this).find("link").text();
var description = $(this).find("description").text();
var thumbnail = "";
var temp_container = $("<div></div>");
temp_container.html(description);
thumbnail = temp_container.find("img:first").attr("src");
So wrap the string in a div, and then use "find()" to get the first img element. I now have the image source, which can be used as needed.
A: maybe you should try to convert the description text to html tag and then try to traverse it via jquery
$('<div/>').html($(this).find("description").text()).find('img')
note: not tested
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594878",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Dispatcher.Invoke() is not working for the application I am working on a project of my company in which they used Dispatcher.Invoke() in many places.If I am using BeginInvoke instead of Invoke then the Synchronisation between threads working fine but in case of Invoke the application is freezing and even not entering the execution to the delegate method also. Does anybody have any idea why it is happening like this?
Any answer will be appreciated.
Sample Code for Invoke used in the Project:
Dispatcher.Invoke(DispatcherPriority.Send,
new DelegateMethod(MethodtoExecute));
private delegate void DelegateMethod();
void MethodtoExecute()
{
try
{
}
catch (Exception /*ex*/)
{
}
finally
{
}
}
A: Dispatcher.Invoke executes synchronously on the same thread as your application, so whatever you invoke is able to block the main application thread. Dispatcher.BeginInvoke executes asynchronously, so it doesn't tie up the main application thread while executing.
Since you are using DispatcherPriority.Send, which is the highest dispatcher priority level, whatever you are invoking gets run before anything else, including rendering the screen or listening for events. I'd recommend switching that to DispatcherPriority.Background, which runs at a lower priority than Render and Input. See this page for a list of the DispatcherPriority levels and their execution order
I'd highly recommend you look at the answer posted here
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594879",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Is the analyzer really trustworthy concerning the detection of memory leaks? In my app delegate I have the following code snippet:
...
@synthesize model = _model;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
...
// Allocate the model
self.model = [[Model alloc] init];
...
}
- (void)dealloc
{
[_model release];
[super dealloc];
}
...
The XCode Analyzer reports a potential memory leak on the line after the allocation of the model (it did go away when I added an autorelease statement, so I guess it just got mixed up with the line numbers). Is this truly a memory leak or is the analyzer confused? After all a release is done in the dealloc method. So is there a potential of a memory leak here and in which situations?
If that's so I guess the solution would be to add autorelase to the allocation.
A: It's a memory leak if the property is defined as retain because it has a retain count of 2 - once for alloc and once on assignment to the property - but you only release it once. Xcode does get confused about line numbers though.
A: Yes, it is trustworthy!
If you click on the blue arrow icon on the line where the analyzer shows a leak:
it will give you more information about the leak, showing exactly where it originated, and in this case the reason why it appears on the next line:
A: The static analyser is very trust worthy. after all ARC is completely based on it. It has to be good in order for iOS5 programming to work.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594880",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: InstallShield 2011 error 7185 importing Japanese strings in the string table of basic MSI project I am trying to import Japanese strings inside my "Basic MSI" project, it use to work before without any issues but now when I try to import some Japanese strings from a text file then it throws following error (I have changed some of the personal data from the error message.)
ISDEV : error -7185: The Japanese: 日本語 translation for string identifier IDS_XXXX_1111 includes characters that are not available on code page 932.
I think there are some of the characters inside the IDS_XXXX_1111 are not part of code page 932. How to detect those characters using some tool?
Also documentation mentions about changing some encoding settings to UTF-8 in InstallShield 2011, if you are aware then please guide me.
Thanks in advance
Rahul
A: My favorite way to detect such characters is with python. For example, reading a file like the InstallShield string tables in python 2.x:
import codecs
strings = codecs.open("strings.txt", "r", "UTF-16"):
for line in strings.readlines():
line = line.strip()
try:
line.encode("cp932")
except UnicodeError:
print "Can't encode: " + line.encode("cp932", "replace")
Your alternatives are to pinpoint the characters that cannot be represented on the relevant code page and replace them with ones that can, or to go to the Releases view and select yes for the Build UTF-8 Database setting.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594881",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Implementing a CRC check within Android SMS Functionality I am fairly new to android , but I dont see how it is possible to implement a CRC check, or some kind of message integrity check for a SMS sent from one Android device to another. I'm busy looking at XOR Checksum computations , but I am not sure If I am moving in the right direction.
A: Use MD5 or some other built-in hash mechanism.
http://exampledepot.com/egs/java.security/Digest.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594884",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Java: How can I disable clicking on a panel while showing dialog? I want to disable clicking on the background panel or frame while showing a dialogue. And I want the dialogue to appear on top of this panel or frame constantly until it is closed.
How can I do this?
A: Make Dialog/JDialog modal by calling dialog.setModal(true);. This will solve both issues of clicking background panel and remaining on top of panel.
It seems like this method is obsolete so better you should use dialog.setModalityType(Dialog.ModalityType type)
A: You can use JOptionPane for the message dialog.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594888",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: how to check each and every object of array in the userdefaults i am saving selected date from picker in array in userdefaults. So when i select a particular date and click on save that particular date is getting saved in userdefaults.This is done properly.But now i have problem.I need to compare each and every date and time of userdefaults with the current time .If an object gets equivalent to the current date and time then the notification should be shown.How is this possible.Thanks. This is my code
Here i am selecting my date through date picker and saving date in userdefaults.
this is my timepickercontroller.m
- (void)viewDidLoad {
time = [[NSString alloc] init];
CGRect pickerFrame = CGRectMake(0,40,0,0);
datePicker = [[UIDatePicker alloc] initWithFrame:pickerFrame];
datePicker.datePickerMode = UIDatePickerModeTime;
datePicker.date = [NSDate date];
[datePicker addTarget:self action:@selector(convertDueDateFormat) forControlEvents:UIControlEventValueChanged];
[self.view addSubview:datePicker];
[datePicker release];
}
-(void)convertDueDateFormat{
app = (StopSnoozeAppDelegate*)[[UIApplication sharedApplication]delegate];
app.timerdate = [self.datePicker date];
NSLog(@"picker date:%@",selecteddate);
if ([[NSUserDefaults standardUserDefaults] valueForKey:@"time"]==nil)
{
[[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:@"time"];
[[NSUserDefaults standardUserDefaults] synchronize];
NSLog(@"%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"time"]);
}
else
{
NSArray *array = [[NSUserDefaults standardUserDefaults] objectForKey:@"time"];
NSMutableArray *array_dates = [[NSMutableArray alloc] init];
for(int i =0;i<[array count];i++)
{
[array_dates addObject:[array objectAtIndex:i]];
}
[array_dates addObject:app.timerdate];
[[NSUserDefaults standardUserDefaults] setObject:array_dates forKey:@"time"];
[[NSUserDefaults standardUserDefaults] synchronize];
NSLog(@"%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"time"]);
}
}
this is the controller where i am setting notification
-(IBAction)save{
dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"hh:mm a"];
NSDate *currentime = [NSDate date];
currentcheck = [NSString stringWithFormat:@"%@",[dateFormatter stringFromDate:currentime] ];
NSLog(@"currenttime:%@",currentcheck);
timepicker = [[TTimePickerController alloc]init];
if (app.timerdate == NULL && interval == NULL && newsound == NULL)
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"UIAlertView" message:@"Set Date,interval,sound for alarm" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[alert release];
alert = nil;
}
else
{
[self scheduleNotification];
[self saveInDatabase];
}
}
-(void)scheduleNotification
{
[[UIApplication sharedApplication]cancelAllLocalNotifications];
timepicker = [[TTimePickerController alloc]init];
NSDate *newtestdate = [[NSUserDefaults standardUserDefaults]objectForKey:@"time"];
NSLog(@"fireDate=%@", newtestdate);
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
NSDateComponents *dateComponents = [calendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:newtestdate];
NSDateComponents *timeComponents = [calendar components:NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:newtestdate];
NSDateComponents *dateComps = [[NSDateComponents alloc]init];
[dateComps setDay:[dateComponents day]];
[dateComps setMonth:[dateComponents month]];
[dateComps setYear:[dateComponents year]];
[dateComps setHour:[timeComponents hour]];
[dateComps setMinute:[timeComponents minute]];
[dateComps setSecond:[timeComponents second]];
itemDate = [calendar dateFromComponents:dateComps];
[dateComps release];
Class cls = NSClassFromString(@"UILocalNotification");
if (cls!= nil) {
UILocalNotification *notif = [[cls alloc]init];
notif.fireDate = itemDate;
[app.dateFormatter setDateFormat:@"hh:mm a"];
newstring = [app.dateFormatter stringFromDate:notif.fireDate];
NSLog(@"new fire date:%@",newstring);
notif.timeZone = [NSTimeZone defaultTimeZone];
notif.alertBody = @"Alarm";
notif.alertAction = @"View";
notif.soundName = UILocalNotificationDefaultSoundName;
notif.applicationIconBadgeNumber=1;
notif.repeatInterval = 0;
[[UIApplication sharedApplication]scheduleLocalNotification:notif];
[notif release];
}
}
A: Supposing ur time format is like this hh:mm:ss
NSDate *currentTime=[NSDate date];
NSArray *timeArray=[[NSUserDefaults standardUserDefaults]objectForKey:@"time"];
NSDateFormatter* tempFormat = [[[NSDateFormatter alloc]init]autorelease];
[tempFormat setDateFormat:@"h:mm a"];
NSString* tempStr = [NSString stringWithFormat:@"%@",[tempFormat stringFromDate:date]];
if([tempStr isEqualToString:[NSString stringWithFormat:@"%@",[timeArray objectAtIndex:0]]]){
//Make any decision
//Similarly compare all the time in the array by changing the index using for-loop.
}
A: I suspect that what you really want to do is not to compare the dates, but to set the fire date of the notification to the date you got from the array.
To do that, you enumerate the array and launch an NSNotification for each timerDate:
NSArray *timerDates = [NSUser Defaults standardUserDefaults] objectforKey:@"time"];
NSDate *now = [NSDate date];
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
// .... general setup of all notifs here.
for (NSDate * aDate in timerDates) {
localNotif.fireDate = aDate;
//... further setup of each individual notif here....
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
}
[localNotif release];
However, from your code, it looks like you're getting a single date from defaults:
NSDate *newtestdate = [[NSUserDefaults standardUserDefaults]objectForKey:@"time"];
but you save an array there in the method
-(void)convertDueDateFormat{
...
[[NSUserDefaults standardUserDefaults] setObject:array_dates forKey:@"time"];
So which one is it?
If you have an array, you can test its values as dates:
NSArray *timerDates = [NSUser Defaults standardUserDefaults] objectforKey:@"time"];
NSDate *now = [NSDate date];
_block int timerIndex; // can be changed inside the block
// use a block to enumerate the array
[timerDates enumerateObjectsUsingBlock:^(id obj,NSUInteger index, BOOL *stop){
if(fabs([(NSDate *)obj timeIntervalSinceDate:now])< 1.0) {
*stop=YES;
timerIndex = index;
}
} ];
Then use timerIndex to get the right date:
localNotif.firedate = [timerDates objectAtIndex:timerIndex];
Definitely also look at the documentation for comparing dates (Apple class documentation for NSDate is good). This is just one way to do it, and probably not the best.
(sorry about my formatting. I'm kinda new at this)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594892",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Extjs store filtering - include metachars I have a data store having a Note field (a textarea) and want to display all Notes satisfying a user input (even metacharacters).
I've written the following function to handle this:
function notefilter() {
var newfilter = Ext.getCmp('searchnote');
var searchStr = newfilter.getValue();
searchStr = searchStr.replace('?', '\\?').replace('*', '\\*').replace('+', '\\+').replace('{', '\\{').replace('}', '\\}').replace('[', '\\[').replace(']', '\\]').replace('(', '\\(').replace(')', '\\)').replace('|', '\\|').replace('$', '\\$').replace('^', '\\^');
var re = new RegExp(".*" + searchStr + ".*", "ig");
Ext.getCmp('notesgrid').store.filter('Note', re);
}
However the filter fails to search for metacharacters even after escaping them, but it works are all other alphanumeric input.
Am I missing something ?
Thanks in advance !
A: Finally, got the filter working. JavaScript's built in escape() & encodeURIComponent() did the work for me. I do not have to programatically escape the metachars.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594893",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Sandcastle: How to reference own (non-msdn) HTML documentation? We use sandcastle to build our internal help. We have multiple teams working on parts of our solutions independently we need to document those independently. So we have i.e. a team creating component 1 and the help for it, and another team creating component 2 (which depends on component 1) and the help for it.
For easy access to the help is build and updated automatically as HTML help.
So we have the help for component 1 available on: http://internalserver/Components/Component1
Now the html help from Component 2 (will be deployed at: http://internalserver/Components/Component2) should be able to reference the classes in the HTML help for Component1.
How can we configure Sandcastle/Sandcastle help file builder to look in our help for our own components like it does at the MSDN for framework classes?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594898",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: unzip unix command I have a zipped log file. However when I try to
unzip nameofFile.log.zip
I get the following error:
Archive: nameofFile.log.zip
error: cannot create nameofFile.log
what would be stopping it from creating the log?
A: No permission to write in current directory?
Directory of name nameofFile.log already exists?
A: Check file creation permissions for active user. Seems that the current user has no permissions to create a new file.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594908",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Apache Solr - OR in filter query Is it possible to search (with apache Solr) for items which are in one of few categories using filter query, e.g. items in category 'computers' OR 'phones'
When I want to search for items in category computers AND phones I type:
select/?q=...&fq=cat:computers&fq=cat:phones
but it is possible to use OR instead of AND?
A: You can use
fq=cat:(computers OR phones)
A: A filter query is just a query -- as complex as you'd like. So, you can certainly build up a query, e.g.,
fq=(cat1:val1 OR cat2:val2 OR (cat3:(val3 AND val4)))
...or whatever.
The only difference between a filter query and a plain-old query (besides memory and caching issues, which you might want to also think about) is that a filter query doesn't affect the relevancy scores at all. But in terms of complexity, you can do whatever you want.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594915",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "42"
}
|
Q: Automatic ruby folding in vim Is there a way that I can setup vim to automatically fold ruby source files, but only fold at the method level regardless of the level that they are defined?
So it will fold when I have:
class MyClass
def method
...
end
end
but also when I have:
module FirstModule
module SecondModule
class MyClass
def method
...
end
end
end
end
I've experimented with foldmethod=syntax and various fold levels but it doesn't take into account the depth where the method is defined.
Also I don't want nothing inside the method to get folded (if blocks, each blocks, etc).
I think foldmethod=expr would be my best bet, but I haven't manage to figure out how fold expressions work, and the help in vim hasn't been very enlightening.
A: You may have better luck with this, especially if you already have syntax highlighting:
This would go into your ~/.vimrc
"" Enable folding based on syntax rules
set foldmethod=syntax
"" Adjust the highlighting
highlight Folded guibg=grey guifg=blue
"" Map folding to Spacebar
nnoremap za
This is also a great VIMcast on folding: http://vimcasts.org/episodes/how-to-fold/
A: Made a change to Max Cantor's solution, mine works perfectly, it will fold def methods (including the end keyword) and documentations (=begin =end) blocks regardless of where it is (in a class, or indented)
function! RubyMethodFold(line)
let stack = synstack(a:line, (match(getline(a:line), '^\s*\zs'))+1)
for synid in stack
if GetSynString(GetSynDict(synid)) ==? "rubyMethodBlock" || GetSynString(GetSynDict(synid)) ==? "rubyDefine" || GetSynString(GetSynDict(synid)) ==? "rubyDocumentation"
return 1
endif
endfor
return 0
endfunction
set foldexpr=RubyMethodFold(v:lnum)
set foldmethod=expr
Thanks to Max Cantor for his helper methods to print out syntax info.
Let me explain this line by line:
The most important line would be the second line where it gets the stacks of verious level of syntax element in a line.
So if you have a line like def methodname with whitespace or tabs before it, it will always get the stack at the first non blank character. The problem with Max Cantor's solution is that his code will only print out the lowest syntax element found at the first column of the line, so it will always return something random, elements like "rubyContant" which we don't care about.
So by using match(getline(a:line), '^\s*\zs') we can move our cursor to the column of the first non blank character so we can get a more accurate picture of the stacks. +1 because match is zero-indexed.
And then the rest is similar to the GetSynInfo method where we loop through the stack and match the elements we want, and return 1 so they are all on the same fold level and 0 for the rest.
And that's it, a working folding expr function that will only fold ruby define methods :)
Enjoy and have a nice day!
A: I made vim-ruby-fold plugin for simple method folding in ruby. I hope it helps people.
A: Your hunch about using the expr method, I believe, was correct!
You can use the syntax structure of the file to jury-rig your own syntax-style folding. The following in my .vimrc produced expected behavior:
function! RubyMethodFold(line)
let line_is_method_or_end = synIDattr(synID(a:line,1,0), 'name') == 'rubyMethodBlock'
let line_is_def = getline(a:line) =~ '\s*def '
return line_is_method_or_end || line_is_def
endfunction
set foldexpr=RubyMethodFold(v:lnum)
Some caveats:
I'm not sure if the final argument to synID should be 0 or 1. It's the argument that determines whether you get the syntax information for the topmost transparent or non-transparent element at the provided location. When there's no transparent element, the argument has no effect. In the trivial example I tried, it didn't cause any issues, but it might.
It's also worth noting that the line_is_def regex is probably too lenient. It might be better to return -1 in this situation, so a line matching the regex is only folded when it's right next to the folded method block. A more restrictive regex could also work.
If you're feeling squirrely, you could expand on this and return separate foldlevels for rubyClass and rubyModule elements as well.
If you decide to go down that route, there are some useful custom functions in my .vimrc for introspecting into syntax elements and hilighting. They're handiest when mapped to a keybinding for quick use like so:
nnoremap g<C-h> :echo GetSynInfo()<CR>
Please do let me know if this works out for you! It was fun to figure out. Also, for what it's worth, while :help 'foldexpr' is light on details, :help 'fold-expr' is much more helpful, and even has some examples at the top.
A: You might be able to get away with a solution which folds inside a method as well, by using the zO command. zO will recursively open a fold, so if you use it instead of zo, it will be as if nothing inside the method was folded. You could also remap zo to zO if you are feeling squirrely.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594918",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: Pisa pdf converter is very slow with large tables I'm using Pisa to convert HTML to PDF (in a Django project).
It is very slow when handling tables that span over multiple pages:
a 200-rows table takes up to 150 seconds to be converted, while it takes 15 seconds if I split it into smaller tables.
Are there tips or best practices for building HTML tables to be handled by Pisa?
A: I had the same problem. The document was just a front page and a huge table. PDF rendering time was increasing exponentially with the size of my content table.
I made a checklist of things to check out which might be the problem
I did simple timing on my PDF rendering function (since it could be the HTML rendering, passing it to StringIO, or creating the HTTP response), and noticed that the pisa.pisaDocument call did take 60 seconds to return. I did a checklist of things that might be the problem, and worked on them each. The checklist included Images, CSS, Markup complexity, and Frames.
Images barely affected the rendering time (I only had one per page, so YMMV). Neither did Frames.
Markup complexity was the main problem of my template. Apparently pisa will render several columns in a table very, very slowly
The table was taking too much time to render, but I noticed that if I split the table into smaller tables, the rendering time didn't increase exponentially anymore, and the time it took to render everything was cut in half. I used the below code in my Django template:
{% if forloop.counter|divisibleby:20 %}</table><table>{% endif %}
edit: This fix does not work well with repeating table headers so if you're doing repeat="1" you have to know exactly how many rows to fit in each page.
Also, I had this monster of a selector in my CSS:
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video{
...
}
By changing it to * {...} the rendering sped up a bit. This was counter-intuitive since browsers will not render your page as fast when you use the * selector than when you are using the above monster.
Also, for some reason, merging two in-page <style> tags into one tag decreased rendering time, too.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594922",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: When converting to HTTPS canvas page is blank I have gone through the apparently needed process of purchasing SSL certs etc, and have now changed my URLs for the tabs to https.. however when accessing these there is nothing shown.. blank. Works fine with http.
Can anyone help me out please? Can't find any decent documentation on this.
Thanks
A: Did you change the "Canvas URL" to https? "Canvas URL" should be the http url and "Secure Canvas URL" should be https. If you simply change "Canvas URL" to https then it would show a blank page.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594923",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Entity Framework - Crash on Detaching list of objects I am working on a winform application with EF 4.0.
Below code, crashes with issue 'The object cannot be detached because it is not attached to the ObjectStateManager.' when it tries to detach the list from context.
public List<Users> FindUserList()
{
List<Users> lstUsers = null;
var q = from c in context.Users
select c;
lstUsers = q.ToList();
//context.Detach(lstUsers.First());
context.Detach(lstUsers);
return lstUsers;
}
Surprisingly, it works fine if I detach only one object from the list as I have done in the commented code.
Can someone tell, why it crashes when it tries to detach a list? Also, How can we detach all objects of the list?
A: That is because lstUsers is not an entity. But the entity returned by lstUsers.First() is tracked by EF.
A: Try adding .AsNoTracking() to the Users DbSet to detach it from the context. See below.
List<Users> lstUsers = null;
var q = from c in context.Users.AsNoTracking()
select c;
lstUsers = q.ToList();
return lstUsers;
MSDN Reference
https://msdn.microsoft.com/en-us/library/gg679352(v=vs.103).aspx
StackOverflow question regarding AsNoTracking
What difference does .AsNoTracking() make?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594924",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What is the best sorting algorithm to sort an array of small integers? As per question title, if the array is of an odd length and the array elements are numbered 1 - 10.
Example,
3 6 8 1 3 7 7 9 4 1
I was thinking of using heapsort? Since it is an array, merge sort and insertion sort requires shifting, and would not be so efficient.
A: This is my counting sort example
static int[] countingSort(int[] numbers) {
int max = numbers[0];
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] > max)
max = numbers[i];
}
int[] sortedNumbers = new int[max+1];
for (int i = 0; i < numbers.length; i++) {
sortedNumbers[numbers[i]]++;
}
int insertPosition = 0;
for (int i = 0; i <= max; i++) {
for (int j = 0; j < sortedNumbers[i]; j++) {
numbers[insertPosition] = i;
insertPosition++;
}
}
return numbers;
}
A:
the array elements are number from 1 - 10.
With this restriction, counting sort will be far more efficient than any general purpose sorting algorithm - it's O(n)
A: If there are only 10 elements it isn't worth your while to even worry about it. If there are a million it might start to become significant.
A: Edit: A counting sort is probably optimal given the constraint that the elements only range from 1-10. A counting sort applied to this problem will run in O(n) time. A merge sort (as I recommended below) will run in no better than O(nlogn) time. Parallelizing a counting sort could be interesting. Simply assign a subarray with n/p elements to each processor. Each processor would have its own count array of size 9. This step should take O(n/p) time. Then consolidate all the count arrays into a single array, which should take O(p) time. I haven't fully thought through the last step in the counting sort where the elements are placed in order, but it seems as long as the elements of the count array are atomic, you could assign n/p sections of the original array to individual processors and achieve some parallelization. There would be contention at individual elements of the count array, however, potentially substantially reducing concurrency. You might be able to assign subsections of the count array to p processors and you are back to O(n/p) runtime, if the elements are distributed fairly evenly, but you would be limited to 10 processors. If the elements are not distributed evenly, one or more processors could be doing a larger proportion of the work. This is great question; can you do a counting sort in O(n/p) time?
Quicksort is a great in-place sort algorithm that runs fast and conserves memory. However, given the elements only range from 1-10, if you are sorting large numbers of elements, you will end up with large runs of the same number, either initially, or at interim times during the sort. In-order arrays or sub-arrays can really bog down a Quicksort's performance.
If you don't care about memory, a simple Mergesort would suffice. Mergesort is up there with the fastest standard sort algorithms.
The default Collections.sort() implementation in Java 7 is a Mergesort algorithm adapted from 'TimSort.' The default Arrays.sort() implementation in Java 7 is a dual pivot Quicksort.
If you would like to go parallel, a Parallel Quicksort can achieve good results on large arrays with small numbers of processors, but with the same limitations as the sequential Quicksort. PSRS can help scale to larger numbers of processors.
A: You should consider looking at this for complexity chart Complexity Comparison Chart.
The comparison of sorting algorithm is based on their Best, Average, Worst case scenario for time and space complexity.Based on this chart you can see Counting Sort approach is best on both space and time complexity. Other comparable method is Radix Sort.
Worst [Time,Space] complexity of "Counting Sort" :- [O(n+k),O(k)].
Worst [Time,Space] complexity of "Radix Sort" :- [O(nk),O(n+k)].
A: this is an example of simple sort (Insertion sort)
private static void insertionSort(int[] a) {
// [230, 23, 45, 34, 98]
for (int j = 2; j < a.length; j++) {
int key = a[j];
int i = j - 1;
while (i > 0 && a[i] > key) {
a[i + 1] = a[i];
i--;
}
a[i + 1] = key;
}
System.out.println("sorted array: " + Arrays.toString(a));
}
A: Counting sort will be best in this scenario.
Assuming the data are integers, in a range of 0-k. Create an array of size K to keep track of how many items appear (3 items with value 0, 4 items with value 1, etc). Given this count, you can tell the position of an item — all the 1’s must come after the 0’s, of which there are 3. Therefore, the 1’s start at item #4. Thus, we can scan the items and insert them into their proper position.
Creating the count array is O(N)
Inserting items into their proper position is O(N)
I oversimplified here — there is a summation of the counts, and a greatest-to-least ordering which keeps the sort stable.
A: QuickSort is a Divide and Conquer algorithm. It picks an element as pivot and partitions the given array around the picked pivot and then repeats the process. There are many different versions of quickSort that pick pivot in different ways
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594929",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "21"
}
|
Q: Iphone - Multiple Apps, Different App ID, Same Token From what I understand, if there are multiple apps with different App ID installed on a device, the tokens for push notification generated for each apps should be unique one to another.
In my case, I have several apps compiled with different provisioning profiles and each of them is based on different App IDs (though some of them has same Bundle Seed ID, some don't).
For each app I generated development push notification SSL and export the SSL to generate PEM. Next I download the provisioning profile and applied it to XCode.
When I tried to run it on my device, what I get from :
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
on ALL apps are a single same device Token. I wonder why is that?
And when I tried to push a notification via my server, there was no error message received. But the notification never delivered to installed devices.
Please give me suggestions on the problem. Thanks in advance.
A: For development provisioning profiles, the device token will be the same for all other apps on that device using a development provisioning profile.
In production (the App Store), the device token will be unique for each application as far as I know. But I'm not 100% certain.
As for why the push notification wasn't delivered to your devices, that's hard to answer without more detail.
A: The device token is not unique for each application, no matter if it is the production or development environment. You might be wondering, if the device token is the same for all apps then how is it possible that push notifications are routed to the right devices and the right applications? The answer is the app's unique bundle id. Each and every application on the App Store has a unique identifier, e.g.: com.mycompanyname.dummyapp. When an application registers itself for push notifications both the app bundle id and the device token are registered on Apple's servers.
Willy, one last thing that you might want to check, the very first step when configuring Push notifications is the creation of a CertificateSigningRequest.certSigningRequest file from the Keychain manager. If you have 2 apps you have to do this step twice so you end up with 2 different files that will be used in Apple's portal to create the SSL.cer file. Your problem might be that you used the same .certSigningRequest to create the different SSL.cer files instead of using a different one.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594931",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Prevent window from redrawing is it possible to prevent automatic redrawing of window? I want it to redraw only when I issue queue_draw().
Explanation:
I need this because I'm using a 3rd party commercial library for industrial graphics which I can tell when to redraw, but also it redraws when X tells it to and it is not possible to prevent that. Therefore, I need to prevent that because of an app-specific requirements and make it redraw only when I tell it to.
A: Well, what's the point? If you don't make it redraw automatically, you'll be unable to minimize/maximize the window, move it from the background to the foreground... And if these are actions that never happen, then your windows is already redrawn only when you call queue_draw. Just add some trace code in the expose-event handler, and you'll see it.
So I think your're looking to at the wrong solution for the wrong problem.
Edit:
so what you need may be the GTK_APP_PAINTABLE flag.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594938",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Technical term for bit packing By bit packing I mean since int is of 4 bytes, and if we store 1 inside the int, remaining bits will be wasted.
So I'll be packing the next type e.g short's value 2, in the int variable (by right left shifts).
What is this technique called?
A: You said it yourself; Bit Packing.
If you are packing individual bits, the result would be a Bitfield. But in this case of two shorts in the space of an integer, it could also be just byte packing.
But all-in all it is Packing.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594939",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: When does a Category come into effect I'm a little confused by something regarding Categories. If I have written a Category for ClassA called ClassA+Something, at what point does that category come into effect? I'm assuming a single import somewhere will cause the category to be applied to ClassA throughout the project, but where should this import be placed?
A: If the category's source file is part of the build, it'll come into effect before main() runs, regardless of whether the category's header is imported into other files or not. The only difference made by importing the header is that you'll be able to call the category's methods (in any files that import it) without generating compiler warnings.
A: I find it easiest to import categories in the precompiled header file (.pch) for my projects.
That way it's available to all my classes with creating compiler warnings.
A: actually the linker is responsible for adding categories.. if you add -all_load to your linker flags you assure that all categories (+ categories in all sub-libraries) along with all classes are loaded. if you include a header somewhere, the linker will add the category. if you have a complex library tree hierarchy (i had that once with facebook + some other lib depending on SBJson's categories) -all_load is your way to fix crazy runtime errors
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594942",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Control event firing frequency though attaching/detaching to the event. Bad practice? Yesterday I provided an answer to the question How do you control event firing in C#? which, in short, asks the following:
"There is an event that fires whenever a new frame is received from the camera. However, this happens more frequently than I'd like ... How can I control when the event fires?"
In my answer I provided the code below, and this morning I found that I had 2 downvotes without any comments. My concern is not mainly the loss of rep, but rather that this is logic that I am using myself in various applications, and that the downvotes could indicate that my implementations are bad practice or bad for performance. Thus, I am asking this question to clarify if there is anything wrong with attaching/detaching event controllers in this manner?
public MyObject()
{
MyTimer = new System.Timers.Timer(100); // 10 Hz
MyTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
MyTimer.Enabled = true;
}
private void ImageDataUpdated(object sender, EventArgs e)
{
// detach from the event to keep it from firing until the timer event has fired.
MyImageObject.Update -= new UpdateEventHandler(ImageDataUpdated);
// do stuff
}
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
// (re-)attach to the event handler.
MyImageObject.Update += new UpdateEventHandler(ImageDataUpdated);
}
In addition I wrote the following, referring to that it is possible to check if you have any subscribers before actually preparing the data to send to the subscriber. And in some cases this can lead to reduced CPU usage. To me it seems right (again I do this myself), but is there anything wrong with this statement?
Using this strategy there is a good chance that you are preventing the underlying image object from doing additional work while the event handler is detached (of course this depends on the implementation of the image object). Chances are that you are saving CPU-cycles for your own image processing.
A: I imagine they felt that dynamically adding and removing events, based on an unrelated timer, was a bad thing. While that is a neat trick that might be useful somewhere, someday, I tend to agree with them. External control over other object's event handlers does not indicate good encapsulation.
The alternative is to simply check that sufficient time has elapsed in the receiving event handler between calls and decide whether to process or not. This is more consistent with how logic works in real-time games or similar apps and means you are not constantly connecting and disconnecting event handlers from the outside.
The overhead of an actual event call itself is quite small, so do not worry about a few calls per frame, so long as the "slow part" (i.e. the bit doing the actual work) is not executing every time.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594948",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Microsoft JScript runtime error: Object required -Javascript There are the javascript codes inside a web application which was developed with through Microsoft Visual Basic.When to run javascript code on my local machine,it doesn't working on Windows Server 2003.I'm getting the Microsoft JScript runtime error: Object required error with below code.Also,I check out the IDs, no problem.
Code:
function AlertHata(oObject)
{
var iID='';
var dKDVOran=0.0;
var dKDVTutar=0.0;
var dToplamTutar=0.0;
var x=document.getElementById(oObject)
var index=oObject.indexOf('_',14);
iID= oObject.substring(14,index);
dToplamTutar= parseFloat(document.getElementById('Repeater1__ctl' + iID + '_TB_MFistutar').value);
dKDVOran= parseFloat(document.getElementById('Repeater1__ctl' + iID + '_TB_MFkdvO').value);
dKDVTutar=dToplamTutar-( (dToplamTutar) / ((dKDVOran + 100)/100));
dKDVTutar = dKDVTutar.toFixed(2);
dKDVTutar +="";
document.getElementById('Repeater1__ctl' + iID + '_TB_MFisKdv').value=dKDVTutar.replace(".",",");
}
A: "Object required" error typically indicates that you are trying to use (e.g. access property of) uninitialized java-script variable. It would be very difficult to tell problematic code from your question because the context (html document, other scripts etc) are missing.
However, you can use any script debugger to trouble-shoot the issue. IE8/9, Firefox with FireBug and Chrome has script debugger included and you can set break-points if needed. You can also use Visual Studio for script debugging. You can also include debugger; statement in your java-script to force script debugging (make sure to nable script debugging in the IE) - it will typically gives you prompt to select available debuggers (if many).
Once you get set break-point at start of function, just run line by line to see problematic code. Inspect variable values to see which one is uninitialized.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594950",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Find a value from Datatable compare with its max() value - LINQ Query thanks for helps.
Actually I have a datatable Invoice, having fields like invoice_no, Invoice_dt, material_name, unit_price, etc..
But I need to find the unit_price of the item which is the last date entry for that material {max(invoice_dt)} is it possible?
var query = from t1 in invoice
where t1.material_name == MyMaterial && t1.invoice_dt == (invoice.max(invoice_dt))
select t1.unit_price;
From the above my intention is to get the latest date entry of unit_price, that will be the current market price...
A: var maxDate = invoice.Max(t1 => t1.invoice_dt);
var query = from t1 in invoice
where t1.material_name == MyMaterial && t1.invoice_dt == maxDate)
select t1.unit_price;
If you want to retrieve the price for the max date item with the invoices grouped by material name:
var groupedInvoices = invoice.GroupBy(t1 => t1.material_name);
foreach (var group in groupedInvoices)
{
var maxDate = group.Max(t1 => t1.invoice_dt);
var maxDateItem = group.Single(item => item.invoice_dt == maxDate);
Console.WriteLine(maxDateItem.unit_price);
}
A: The easiest way to accomplish this I could come up with was using extensions methods:
var query = invoice.SingleOrDefault(item => item.invoice_dt ==
invoice.Where(inv => inv.material_name == MyMaterial).
Max(inv => inv.invoice_dt)).Select(i => i.unit_price);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594953",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Bloom Filter: How to find k hash functions? A Bloom Filter needs k hash functions, which return a value between 0 and m (m is the length of the bit array).
I have to implement such a bloom filter and I already read some theoretical papers about those filter (how they work, how many hash functions you need, how the error behaves etc.)
Now I have two questions about hash functions:
*
*How do I find k hash functions - which hash functions should I use?
*How do I find hashs functions which return a value between 0 and m? Alternatively, how can I map the output of a hash function to the range 0-m?
A: You can use this - http://en.wikipedia.org/wiki/Universal_hashing
A: You can use the Kirsch-Mitzenmacher optimization:
hash_i = hash1 + i * hash2
Where hash1 is 32 bit, hash2 is 32 bit. In a look you could use:
hash1 = upper 32 bit of a 64 bit hash
hash2 = lower 32 bit of a 64 bit hash
hash = hash1
for(int i=0; i<k; i++) {
hash += hash2
}
A: You can get a bunch of hash values at one time with a cryptographic hash function like MD5 or SHA. Divide the cryptographic hash value into N m-bit pieces, and treat them just like you would the output of N normal hash functions.
A: *
*The characteristics of the k hash functions that should be used are
given on the wikipedia page: Bloom Filter and go in the
algorithm description where it says - The requirement of designing k different independent hash functions...
*For good tutorials on universal hashing : Nice MIT lecture
A: U could use any hash functions....there are many hash simple hash functions available in the net.
Refer http://en.wikipedia.org/wiki/List_of_hash_functions
Use any hash function to get a hash value and in order to get it in the range of 0-m , use the modulus(%) operator.
i.e bitlocation = hash % m;
it might not be efficient ,but it works...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594958",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How do you debug properly in visual studio while using WatiN framework? I have being trying to debug my program which is around couple of hundreds lines of code, I have been trying hard to debug the program properly,
each and every control of the program leaves blocks, starts from different point whenever I press f11 to see each and every step of my code,
Is there is any better approach to do debugging properly by using some other tools.
A: You can get VS to stop when exceptions are thrown - Debug -> Exceptions. Then tick 'Thrown' for CLR Exceptions. http://msdn.microsoft.com/en-us/library/d14azbfh.aspx
You can also put Breakpoints against lines in code. Just click in the left margin or go to Debug -> Windows -> Breakpoints.
A: I personally like this series of articles about debugging:
http://blogs.msdn.com/b/brunoterkaly/archive/2009/02/08/the-art-of-debugging-a-developer-s-best-friend-intro-lesson-1.aspx
But there is a lot more turorials on the net. It is worth researching. When I started programming, I learned that knowing your debugger well can save a lot of time :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594959",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Better page load performance when loading multiple embedded Youtube videos? I have a page which displays multiple (usually 10) embedded videos. The videos use the new IFRAME embed code of youtube and apparently for every IFRAME there is a separate request when loading the page. Is there a way to defer loading the videos after the rest of the page is loaded, so they don't slow down page loading that much?
A: Check out this solution: Load the YouTube Video Player On-Demand
Basically, it's like replacing your YouTube video iframe player codes with jQuery when clicking some thumbnails.
A: This is a jsfiddle demo.
HTML
<div class="youtube-container">
<div class="youtube-player" data-id="1y6smkh6c-0"></div>
</div>
Javascript
(function() {
var v = document.getElementsByClassName("youtube-player");
for (var n = 0; n < v.length; n++) {
var p = document.createElement("div");
p.innerHTML = labnolThumb(v[n].dataset.id);
p.onclick = labnolIframe;
v[n].appendChild(p);
}
})();
function labnolThumb(id) {
return '<img class="youtube-thumb" src="//i.ytimg.com/vi/' + id + '/hqdefault.jpg"><div class="play-button"></div>';
}
function labnolIframe() {
var iframe = document.createElement("iframe");
iframe.setAttribute("src", "//www.youtube.com/embed/" + this.parentNode.dataset.id + "?autoplay=1&autohide=2&border=0&wmode=opaque&enablejsapi=1&controls=0&showinfo=0");
iframe.setAttribute("frameborder", "0");
iframe.setAttribute("id", "youtube-iframe");
this.parentNode.replaceChild(iframe, this);
}
CSS
<style>
.youtube-container { display: block; margin: 20px auto; width: 100%; max-width: 600px; }
.youtube-player { display: block; width: 100%; /* assuming that the video has a 16:9 ratio */ padding-bottom: 56.25%; overflow: hidden; position: relative; width: 100%; height: 100%; cursor: hand; cursor: pointer; display: block; }
img.youtube-thumb { bottom: 0; display: block; left: 0; margin: auto; max-width: 100%; width: 100%; position: absolute; right: 0; top: 0; height: auto }
div.play-button { height: 72px; width: 72px; left: 50%; top: 50%; margin-left: -36px; margin-top: -36px; position: absolute; background: url("http://i.imgur.com/TxzC70f.png") no-repeat; }
#youtube-iframe { width: 100%; height: 100%; position: absolute; top: 0; left: 0; }
</style>
A: Well, I wrote a javascript thingy (called "LYTE") that will create a "dummy player" (which looks & feels like a normal YouTube embed) for every div with a specific class ("lyte") and id with the YouTube-id. Only when clicking the "dummy" player, the actual YouTube iframe is loaded and it indeed has an important impact of the performance of pages that embed YouTube videos. You can see it in action on my blog.
LYTE is currently not really available standalone, only as part of WP-YouTube-Lyte, the WordPress plugin I wrote, but with minimal changes you should be able to extract all relevant code from the plugin.
You basically have to create something like this in your HTML;
<div class="lyte" id="7nuiOe8M6bw" style="width:640px;height:385px;">
<script type="text/javascript"><!--
var nT='newtube-';var bU='http://static.blog.futtta.be/wp-content/plugins/wp-youtube-lyte/lyte/';
var d=document;if(d.addEventListener){d.addEventListener('DOMContentLoaded', insert, false)}else{window.onload=insert}
function insert(){if(!d.getElementById('lytescr')){lytescr=d.createElement('script');lytescr.async=true;lytescr.id='lytescr';lytescr.src='http://static.blog.futtta.be/wp-content/plugins/wp-youtube-lyte/lyte/lyte-min.js';h=d.getElementsByTagName('script')[0];h.parentNode.insertBefore(lytescr, h)}};
--></script></div>
This block will load lyte-min.js, which will fill the div with all graphical elements of the dummy player (image, play button, control bar, title) and will add an eventlistener to the div that will trigger the replacement of the div with the real embedded player when clicked.
You can find the plugin here and look at the code here (wp-youtube-lyte.php creates the div, lyte/lyte.js is the actual javascript ... thingy).
A: Automatic, request reducing, solution
In WordPress plugin form
Here is a WordPress plugin you can download and manually install via the WordPress plugin repository. I created this today just to handle this situation. No changes to content are needed, this works automatically once activated on any and all iframes.
https://wordpress.org/plugins/lowermedia-iframes-on-demand/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594960",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
}
|
Q: Routing in Zend Framework of two modules I have created controller : module/default/index/login
I have added routing in main bootstrap
$router = Zend_Controller_Front::getInstance()->getRouter();
$route = new Zend_Controller_Router_Route(':action', array(
'module' => 'default',
'controller' => 'index',
));
$router->addRoute('defaulth', $route);
When i accessing url/login it work fine
After that I have created another controller : module/user/index/register
When i access url/user/register it return error invalid action
When i access url/user/index/register it works fine.
I have to access with url/user/register
Please suggest any one.
A: I don't know if the name of the route was voluntary (defaulth), but with default you'll overwrite ZF's default main routing, which is :module\:controller\:action\*.
Try :controller\:action\* as the route.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594963",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: WMI call to a different domain Is it possible to read registry key of a remote machine which belongs to a different domain using WMI calls?
A: Yes it's possible, only you must ensure to set the credentials of the connection according to the remote machine to access, and then use the StdRegProv wmi class which allow you to access the registry in local and remote machines. A key point is the namespace where the class is located, that depends of the version of windows installed in the remote machine. so for Windows Server 2003, Windows XP, Windows 2000, Windows NT 4.0, and Windows Me/98/95 the StdRegProv class is available in the root\default namespace and for others versions like windows Vista/7 the namespace is root\CIMV2. check the accepted answer in this question to see a sample.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594965",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Documentation for implementing a Java based Red5 RTMPClient? I'm investigating implementing an RTMP client in Java to do audio conferencing with Red5. There's an RTMPClient and related classes that look like they can be used. However, the implementation seems to be based on a delegate pattern with multiple other classes involved, which is difficult to decipher without docs.
Anyone have any pointers for documentation in this area?
A: The Red5 Reference Manual
Helpfiles and Tutorials
Project and Developer information
Users mailinglist
Developers mailinglist
Google Code project page
javadocs
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594971",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Language Oriented Programming Articles/Papers/Tutorials There is number of tools on the market like MPS, that promote Language Oriented Programming, which supposedly gives ability to programmer to design a (ideal?)language for task. This sounds interesting and boring at same time for some reason, so I was wondering if anyone know and can recommend articles regarding subject.
Thanks
A: Besides Language Oriented Programming, you can also search for Language Workbenches and Domain Specific Languages (DSLs).
For DSL's, Martin Fowler's latest book ("Domain Specific Languages") is the one to read.
On Language Oriented Programming, check Philipp W. Kutter's dissertation, "Montages - Engineering of Computer Languages" (ftp). Check the Cedallion project too.
JetBrains' (creators of MPS) have a good article on the subject: http://www.onboard.jetbrains.com/articles/04/10/lop/
A: "Language oriented programming" is just a new term for quite an old and well-known concept. It is covered in detail in many Lisp textbooks. I'd recommend reading "Practical Common Lisp", it is full of examples of using this approach. There is a huge volume of relevant papers produced by the Haskell community as well, like in this example.
A: The term "domain specific language" (and its precursor, "domain analysis") goes back to the work by James Neighbors on the Draco system.
For a commercial version of this idea, see the discussion at Domain Specific Languages on how the Draco ideas have been built into our DMS Software Reengineering Toolkit.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594973",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: GDB with pthreads I have a C program where the main function creates threads and I have to debug one thread. I am using gdb for he same. However I cannot "break" or "watch" variables on specific C files of this program. For eg. my thread 6 is programmed and uses certain C files and I have to break at line 601 on say call_connect.c. Is this not possible? If I try to, this is what happens:
(gdb) info threads
6 Thread 0xb5c96b70 (LWP 3608) 0xb7fe1424 in __kernel_vsyscall ()
5 Thread 0xb6497b70 (LWP 3607) 0xb7fe1424 in __kernel_vsyscall ()
4 Thread 0xb6c98b70 (LWP 3606) 0xb7fe1424 in __kernel_vsyscall ()
3 Thread 0xb7499b70 (LWP 3605) 0xb7fe1424 in __kernel_vsyscall ()
2 Thread 0xb7c9ab70 (LWP 3604) 0xb7fe1424 in __kernel_vsyscall ()
* 1 Thread 0xb7c9b6c0 (LWP 3603) 0x0804a178 in main ()
(gdb) break 601 thread 6
No line 601 in file "events.c".
(gdb) break call_connect.c:601 thread 6
No source file named call_connect.c.
Also I debugged my C code with -O0 -ggdb and still I can't watch variables.
This is what I get when I try to read a char *ptext variable.
(gdb) print ptext
No symbol "ptext" in current context.
(gdb) watch ptext
No symbol "ptext" in current context.
Can somebody please help?
A: Although I have not extensively used gdb with pthreads but I have a few pointers which you might try out.
*
*You can switch to the thread you want to debug using thread threadnum where threadnum is the id (first column) displayed through info threads.
*Check the source directories being looked up for the file usinf show directories command. If the directory where your source resides is not in the list add it through directory <path_to_source> command
*While setting the breakpoints or watch use auto completion (generally <Tab>) to look for breakpoints and watches you can set.
Please check links under Thread Debugging section in YoLinux pthreads Tutorials for more details.
Hope this helps!
A: Your problem is that your program is compiled without debug info.
The most likely causes: either call_connect.c was compiled without -ggdb flag despite what you have claimed (examine your build log to verify that), or you have a "stray" -s on your link line (which would strip the executable).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594974",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Why is Eclipse and ADB not recognizing my Android Device? My device is Alcatel OneTouch 890 with Android 2.1. I configured in 51-android.rules in rules.d of /etc/udev folder.
My operation system is Ubuntu.
I enabled the usb debugging mode in my device.
HTC and Samsung devices are detecting, but not my Alcatel,
Here is my 51-android.rules file.
#HTC
SUBSYSTEM=="usb", SYSFS{idVendor}=="0bb4", MODE="0666"
SUBSYSTEM=="usb_device", SYSFS{idVendor}=="0bb4", MODE="0666"
#samsung
SUBSYSTEM=="usb", SYSFS{idVendor}=="04e8", MODE="0666"
SUBSYSTEM=="usb_device", SYSFS{idVendor}==”04e8”,ATTRS{idProduct}=="689e", MODE="0666",OWNER="abcd"
#alcatel
SUBSYSTEM=="usb", SYSFS{idVendor}=="1bbb", MODE="0666"
SUBSYSTEM=="usb_device", SYSFS{idVendor}=="1bbb", MODE="0666"
root@abcd:/home/abcd# lsusb
Bus 005 Device 002: ID 0461:4d15 Primax Electronics, Ltd Dell Optical Mouse
Bus 005 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 004 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 003 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 002 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 001 Device 006: ID 1bbb:00f2 T & A Mobile Phones // what is T & A in this line....?
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
root@abcd:/home/abcd# Android/android-sdk-linux_86/platform-tools/adb devices
List of devices attached
A: Alcatel OneTouch 891 - Android 2.1
Reading these helpful tips and some other posts about setting the Android device I wrote down a step by step tutorial how to get the device ready.
Edit the ~/.android/adb_usb.ini and append 0x1bbb line
at the bottom.
This will list:
$ adb devices
List of devices attached
???????????? no permissions
Steps to make it working:
Add your self to the group
Install a 51-android.rules package for your distro, then open the file:
/etc/udev/rules.d/51-android.rules
** if it's not there, list the package files and locate this file.
Append the following section under a comment section called OneTouch or whatever you want to name it:
SUBSYSTEM==”usb_device”, SYSFS{idVendor}==”1bbb”, MODE="0666"
So, the result would be:
# Alcatel OneTouch 891
SUBSYSTEM==”usb_device”, SYSFS{idVendor}==”1bbb”, MODE="0666"
Save the file!
Replug USB of the device several times, then restart the adb daemon:
Distro specific:
*
*Archlinux
$ rc.d restart adb
*ubuntu, redhat, fedora, centos
$ service adb restart
Or manually:
$ adb kill-server
$ adb start-server
$ adb devices
will list your device.
Finally:
My results showing in bash:
$ adb devices
List of devices attached
0123456789ABCDEF device
*
*If still no results:
run this command:
$ udevadm trigger
then replug your device again.
or simply reboot.
Proof:
Dalvik:
http://wstaw.org/m/2011/11/13/plasma-desktopos8794.jpg
File Manager:
http://wstaw.org/m/2011/11/13/plasma-desktopgt8794.jpg
A: Try to kill and start the adb server after closing eclipse.
So try :
*
*close eclipse
*go to platform-tools directory
*do : sudo ./adb kill-server
*disable the development debugging on your phone
*enable it again
*do : sudo ./adb start-server
*do : ./adb devices
It should work. I had this problem several times and by doing this it was working after doing instructions I give you.
Hope it is helping!
EDIT: That might be not working as most of the android developers moved to Android studio and other emulators.
A: check this out
http://developer.android.com/guide/developing/device.html#setting-up
it is weird that alcatel isn't included
A: First, check the kind of quotes you are using in your udev rules. It looks like you might be using non-ASCII double quotes. See the difference between the quotes around usb and usb_device, etc.
SUBSYSTEM=="usb", SYSFS{idVendor}=="1bbb", MODE="0666"
SUBSYSTEM==”usb_device”, SYSFS{idVendor}==”1bbb”, MODE="0666"
You can also just use sudo with ADB, as suggested by @JeremyD. Doing that makes this file essentially irrelevant.
Second,
*
*Edit ~/.android/adb_usb.ini (or if you are running as root, check /root/.android)
*If the file already exists, add 0x1bbb to the end; otherwise do: echo 0x1bbb >> adb_usb.ini
*adb kill-server
*adb start-server
*Check output of adb devices for your device
Hope this helps.
A: For those who would be interested to find out a perrenial solution for adb recognizing devices on CentOS, I found a solution.
First, running adb as root is NOT a good solution, because adb may be restarted by any user at any moment ; even IDE auto-restarts adb, and then adb is blind again.
My solution was to create a group "adb", and add my user to this group.
Then in 51-android-rules, add the GROUP like this :
SUBSYSTEM=="usb", SYSFS{idVendor}=="0bb4", MODE="0666", GROUP="adb"
Reload udev rules.
If you are using a gnome session, restart your session because gnome holds a cache upon your groups...
Open a new xterm, verify that you belong to the adb group : $ groups
Then $ adb devices should start adb server then identify your devices.
A: I also have an Alcatel Phone and I solve this issue by following:
1.#lsusb
Bus 002 Device 021: ID 18d1:0002 Google Inc. //This is my alcatel phone
2.Add following to /etc/udev/rules.d/51-android.rules:
SUBSYSTEM=="usb", ATTRS{idVendor}=="18d1", ATTRS{idProduct}=="0002", MODE="0666"
Note:I noticed that expected "idVendor", you also need to add "idProduct".
3.#sudo service udev restart
4.Unplug the phone and plug again.
5.#adb devices
List of devices attached
TCL-Martini device
A: I know the accepted answer worked for the OP, but for people having this issue in the future where the above answers do not work, the following worked for me.
This universal udev rule -
ACTION=="add", SUBSYSTEM=="usb", ENV{DEVTYPE}=="usb_device", ENV{ID_USB_INTERFACES}=="*:ff420?:*", MODE="0666"
from this question - ADB not detecting device samsung i777 in ubuntu 12.04
Helped me solve this problem on a "BLU Dash Jr" phone (vendor = Spreadtrum) as mentioned in my related question here:
Spreadtrum (Vendor ID 1782) Issues Connecting to adb
A: I use ArchLinux I Installed this package:
https://aur.archlinux.org/packages.php?ID=51476
it installed all rules I need
more details on arch and android:
https://wiki.archlinux.org/index.php/Android
A: In your device make sure you are using your usb interface as MTP or PTP. Some times it starts with mass storage interface by default an seems that adb is not granted permission to access the device.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594975",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
}
|
Q: Using SignalR with ASP.NET MVC3 I'm attempting to use SignalR hubs in an application, but am having no luck currently. I've read through Scott Hanselman's article, and also looked at this blog post which shows how to implement it in MVC, basically doing the same thing. Unfortunately, I'm having no luck. On the client side, the javascript seems to work fine [apart from nothing happening] but when I place breakpoints in the code it shows that the controller is being called, not the hub code. The code I'm using is this:
// Client side javascript:
var hooking;
$(function() {
// Setup SignalR
hooking = $.connection.hooking;
hooking.removeLead = function(ref) {
$("lead" + ref).remove();
};
$.connection.hub.start();
}
});
// Hooking.cs (placed in application root)
public class Hooking : Hub
{
public void Submit(string jsonString)
{
var serializer = new JavaScriptSerializer();
var json = serializer.Deserialize<HookingLeadResult>(jsonString);
Clients.removeLead(json.Ref); // Remove lead from client hooking windows
// update lead gen
}
}
When I call hooking.submit(resultJson); later in my code for some reason it calls the Index action of my HookingController (which is the current page). Anyone know how to correctly call the Submit function from Hooking.cs?
A: Did you look at the network traffic in firebug or some other tool that sniffs http traffic to make sure you have no errors? It might be something to do with routing.
Also a side note, you don't need to serialize anything we do that for you. Just send objects back and forth.
When you're in an mvc app you need to include the hub script like any other static script:
<script src="@Url.Content("~/signalr/hubs")" type="text/javascript"></script>
A: There were two issues with this - 1. For some reason an old version of jquery.validate was causing errors, but updating it sorted this. 2. I attempted to cast to a nullable int, which I guess isn't supported. I'm sure there are more elegant ways to solve this, but I simply cast my nullable data inputs to strings and parsed them if not null
A: jquery.validate.js was the culprit. For some reason it was triggering GET request, and after excluding the js file, SignalR requests started triggering POST request. Perhaps I should update it as Jordan Wallwork mentioned.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594978",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Avoid separate function for commandLink action I would like to use a property of a form element instead of using an additional function to just return a certain value.
Current situation
XHTML file:
<h:commandLink action="#{menuBean.navigationAction(menuItem)}" ... >
Managed Bean behind it:
public function navigationAction(MenuItem entry) {
return entry.getForward();
}
Desired situation
I would like to skip the method call and directly use the property of menuItem to set the destination. Like this:
<h:commandLink action="#{menuItem.forward}" />
This does unfortunately not work, as the method cannot be found. Is it even possible to do so?
A: You could try this:
<h:link outcome="#{menuItem.forward}" .../>
The outcome parameter takes a value expression that must resolve to a string. The action attribute of h:commandLink needs a method expression.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594979",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: how to use TFHpple in iphone i use this code for html file but it not working how to solve it some one help
it show this message /Users/pradeepyadav/Desktop/htmldemo/TestHtml.m:45:0 /Users/pradeepyadav/Desktop/htmldemo/TestHtml.m:45: warning: 'TFHpple' may not respond to '-search:'
- (void)viewDidLoad {
[super viewDidLoad];
NSData *data = [[NSData alloc] initWithContentsOfFile:@"example.html"];
// Create parser
xpathParser = [[TFHpple alloc] initWithHTMLData:data];
//Get all the cells of the 2nd row of the 3rd table
NSArray *elements = [xpathParser search:@"//table[3]/tr[2]/td”];//here i get message search is not use in TFHpple.h
// Access the first cell
TFHppleElement *element = [elements objectAtIndex:0];
// Get the text within the cell tag
NSString *content = [element content];
[xpathParser release];
[data release];
}
This Is my html file
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><META http-equiv="Content-Type" content="text/html; charset=utf-8"><title>Ryanair.com</title><link rel="stylesheet" type="text/css" href="css/Ryanair/Standard.css" xmlns:ms="urn:schemas-microsoft-com:xslt" xmlns:usr="urn:the-xml-files:xslt"><link rel="stylesheet" type="text/css" href="css/Ryanair/datePicker.css" xmlns:ms="urn:schemas-microsoft-com:xslt" xmlns:usr="urn:the-xml-files:xslt"><script type="text/javascript" src="/data/js/skysales_3F5DBD0632207A3932CD626AEDC1A849.js"></script><script type="text/javascript" src="/data/js/skysales_B5A6631CD62DEC33073F138AE4A7C8D2.js"></script><script src="http://www.google.com/jsapi"></script><script type="text/javascript" charset="utf-8">
google.load('ads.search', '2');
</script><script type="text/javascript" language="javascript" xmlns:ms="urn:schemas-microsoft-com:xslt" xmlns:usr="urn:the-xml-files:xslt">
Date.dayNames=['Sunday','Monday','Tuesday','Wednesday','Thusday','Friday','Saturday'];
Date.monthNames=['January','February','March','April','May','June','July','August','September','October','November','December'];
if (typeof jQuery != 'undefined') {
$.dpText={
TEXT_PREV_YEAR:'Previous year',
TEXT_PREV_MONTH:'Previous month',
TEXT_NEXT_YEAR:'Next year',
TEXT_NEXT_MONTH:'Next month',
TEXT_CLOSE:'Close',
TEXT_CHOOSE_DATE:' '
};
}
var datePickerFormat='yyyy-mm-dd';
var datePickerDelimiter='-';
Date.format=datePickerFormat;
var pln="en";
var pcu="IE";
</script></head><body><noscript xmlns:ms="urn:schemas-microsoft-com:xslt" xmlns:usr="urn:the-xml-files:xslt"><p class="error noprint">
ERROR:
This service makes use of Javascript, which appears to be turned off.
Click <a href="activateJavascript.htm">here</a> to learn how to activate it.
</p></noscript><form novalidate="true"method="post" action="FRSelect.aspx" id="SkySales" ><div><input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value=""><input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value=""><input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUBMGRkg4UKvNNb1NbM14/2n9zUxhNQ++A="></div><div id="header" style="width: 100%;"><div id="blu"><a href="http://www.ryanair.com"><img src="Images/Ryanair/logoyelbg.gif" width="228" height="42" alt="Ryanair.com Homepage" title="Ryanair.com Homepage"></a></div><div id="yel" onclick="this.firstChild.innerHTML='WWW156 2011-09-29 06:31:09 reglixj3c555jw1v|413894465 ';"><span title="DNS: www156 62.73.129.156 10.37.2.156 "> </span>Search » <b>Select</b> » Services » Payment » Itinerary</div><input type="hidden" id="sysdate" value="2011-09-29"><input type="hidden" id="systime" value="06:31:09"></div><div><div id="body"><div id="wrapper"><div id="error"><input type="hidden" name="errorlist" value=""><script language="Javascript" type="text/javascript">
$(document).ready(function(){
var msg = "";
if (msg.length > 0) {
msg = msg.replace(/([\.|:])\s*([^\.]+)/g,"$1``$2")
var msg_array = msg.split("``");
var newMsg = "";
for (var idx = 1; idx < msg_array.length + 1; idx++){
if (newMsg.indexOf(msg_array[msg_array.length - idx]) == -1) {
newMsg = msg_array[msg_array.length - idx] + "\n" + newMsg ;
}
}
alert(newMsg);
}
});
</script></div><div id="main"><p><b>Here are the flights and fares available on the requested date(s).</b></p><ol><li>Select the flight of your choice.</li><li>Click on the fare name to see the fare rules.</li></ol><script language="javascript" type="text/javascript">
$(document).ready(function() {
var minDepArr = ('2011 09 29 12 31').split(' ');
var minDep = new Date(minDepArr[0],minDepArr[1]-1,minDepArr[2],minDepArr[3],minDepArr[4]);
$(".avlLst").each(function(){
if($(this).find("input[type='radio']").size() == 0){
$("input[id$='_ButtonSubmit']").attr('disabled', 'disabled').css('background-color','#C0C0C0');
}
});
$("input[type=radio]").each(function() {
var re = new RegExp("[0-9]{2}\/[0-9]{2}\/[0-9]{4}\\s[0-9]{2}\:[0-9]{2}");
var m = re.exec($(this).val());
if(m != null){
var regexp = /([0-9]{2})(\/)([0-9]{2})(\/)([0-9]{4})(\s)([0-9]{2}):([0-9]{2})/gi;
var depArr = m[0].replace(regexp,'$5 $1 $3 $7 $8').split(' ');
var dep = new Date(depArr[0],depArr[1]-1,depArr[2],depArr[3],depArr[4]);
if(dep <= minDep){
$(this).attr('disabled', 'disabled').attr('checked','');
}
}
});
});
function setTabIndex(marketIndex, index){
var fld=['',
''];
var i=marketIndex==1?0:1;
document.getElementById(fld[i]).value = index;
postBack();
}
function postBack(){
;
}
var pleaseWaitMessage = 'Please Wait...';
var marketHeaders = ['','Going Out','Coming Back'];
function feesTaxes(fltKeys,names){
var mkts=[];
for(var k in names){
var market=names[k].charAt(names[k].length-1);
mkts.push(market);
$("div#taxAndFeeInclusiveDivBody"+market).css('background-color','#A3AECC').find(".hdr").html('<span>'+pleaseWaitMessage+'</span>').css('background-color','#FFFF99')
.ajaxError(function(evt,req,sett){
$(this).html('<span>Unavailable... try again!</span>').css('background-color','#FFBBBB');
});
}
$.get("FRTaxAndFeeInclusiveDisplay-resource.aspx",
{'flightKeys':fltKeys.join('+++'), 'numberOfMarkets':fltKeys.length, 'keyDelimeter':'+++'},
function(data,stat){
$htm=$(data);
for(var i=0,ml=mkts.length;i<ml;i++){
if($($htm[i]).html().match(/RefreshWindow/) ) {
window.location.reload(true);
}
$("div#taxAndFeeInclusiveDivBody"+mkts[i]).css('background-color','white').html('<p class="hdr">'+marketHeaders[mkts[i]]+'</p>'+$($htm[i]).html());
}
$('big#totalPrice').text($($htm[$htm.size()-1]).text());
}
);
}
function selFlight(o){
if(!o) return false;
$(o).parents('table:first').find("div[class^='planeImg']").css('background-position','top left');
$(o).parents('table:first').find("tr").removeAttr('class');
var tro=$(o).parents('tr:first').attr('class','on');
var pval=[],pname=[],doJson=true;
var A=parseIDDate(tro.attr("id"));
var outDTarr=new Date(A[1],A[2],A[3],A[4]+1,A[5],A[6]);
$(".avlLst table").each(function(){
var $chkbs=$(this).find("input[type='radio'][name*='market']");
if(A[0]==1 && $chkbs.is("input[name*='market2']"))
{
$chkbs.each(function(){
var troB=$(this).parents('tr:first');
var B=parseIDDate(troB.attr("id"));
var inDTdep=new Date(B[1],B[2],B[3],B[4],B[5],B[6]);
if(outDTarr>=inDTdep)
{
$(this).attr('disabled', 'disabled').attr('checked','');
$("div[class^='planeImg']", troB).css('background-position','top left').attr('disabled', 'disabled');
}else
{
$(this).attr('disabled', '');
$("div[class^='planeImg']", troB).attr('disabled', '');
}
});
}
var $chkb=$chkbs.filter(':checked');
if($chkb.size()!=0)
{
pval.push($chkb.val());pname.push($chkb.attr('name'));
$chkb.parent().prev().children('div').css('background-position','top right');
}
else if($chkbs.is(':enabled'))
{
doJson=false;
if(A[0]==1)
{
$chkbs.filter(':enabled:first').attr('checked','true').trigger('click');
}
}
else $("div[id*='taxAndFeeInclusiveDivBody']", this.parent).find("*:not(.hdr)").remove();
});
if(doJson)
{
feesTaxes(pval,pname);
}
}
function parseIDDate(s){
var a=s.split('_');
for(var k in a) a[k]=parseInt(a[k].replace(/^0([0-9]+)/,'$1'));
return a;
}
var nbrMarkets=2;
var dateRanges=[[],[new Date(2011,9,2), new Date(2011,9,2)],[new Date(2011,9,5), new Date(2011,9,5)]];
var localization={
inPast:'You cannot search earlier than the current date.',
datesOverlap:'Your outbound date range cannot overlap your return date range',
timesOverlap:'Please recheck the flights you selected\nYour second flight(s) must DEPART at least 1 hour(s) after your first flight(s) ARRIVES!',
bookToday:'Unfortunatley due to security restrictions, If you wish to book a flight departing today.\nYou must either make the booking through your local RYANAIR CALL CENTER or at the AIRPORT.'
};
function checkDate(market,days){
var flexi=Math.abs(days)==7?true:false;
var idx=days>0?1:0;
var today=new Date(), tomorrow=new Date(); tomorrow.addDays(1);
if(idx==0 && dateRanges[market][idx] <= today){
alert(localization['inPast']);
return false;
}
if(nbrMarkets > 1){
var overlap=false;
if(market==2 && idx==0 && dateRanges[market][idx] <= dateRanges[market-1][idx]) overlap=true;
else if(market==1 && idx==1 && dateRanges[market][idx] >= dateRanges[market+1][idx]) overlap=true;
if(overlap){
alert(localization['datesOverlap']);
return false;
}
}
return true;
}
function checkTimes(){
if(nbrMarkets < 2) return true;
var DA=[0,0];
$(".avlLst table input[type='radio']:checked").each(function(){
var A=parseIDDate($(this).parents("tr:first").attr("id"));
DA[A[0]-1]=new Date(A[1],A[2],A[3],A[4],A[5],A[6]);
});
$("input[id*='oTime']").each(function(){
var A=parseIDDate($(this).val());
DA[A[0]-1]=new Date(A[1],A[2],A[3],A[4],A[5],A[6]);
});
if((DA[1]-DA[0]) <= (60*60*1000)){
alert(localization['timesOverlap']);
return false;
}
return true;
}
$(document).ready(function(){
// This could probably be cleaned up
$("a[id*='LinkButtonNextDay1']").click(function(){return checkDate(1,1);});
$("a[id*='LinkButtonNextWeek1']").click(function(){return checkDate(1,7);});
$("a[id*='LinkButtonPreviousDay1']").click(function(){return checkDate(1,-1);});
$("a[id*='LinkButtonPreviousWeek1']").click(function(){return checkDate(1,-7);});
$("a[id*='LinkButtonNextDay2']").click(function(){return checkDate(2,1);});
$("a[id*='LinkButtonNextWeek2']").click(function(){return checkDate(2,7);});
$("a[id*='LinkButtonPreviousDay2']").click(function(){return checkDate(2,-1);});
$("a[id*='LinkButtonPreviousWeek2']").click(function(){return checkDate(2,-7);});
$("a[id*='tab_']").click(function(){
var A=this.id.split("_");
var tabDate=new Date(A[2],A[3]-1,A[4]);
var dtime=new Date(), today=new Date(dtime.getFullYear(),dtime.getMonth(),dtime.getDate());
return true;
});
$("table[id*=ttable] th").click(function(){
eval($(this).find("a").attr("href"));
}).hover(function(){
$(this).find("a").css("text-decoration", "underline");
},function(){ $(this).find("a").css("text-decoration", "none");
});
$(".avlLst table").find("div[class^='planeImg'],input[type='radio']").click(function(){selFlight(this);});
var firstRadio=null;
$(".avlLst table").each(function(){
var $chkbs= $("input[type='radio'][name*='market'][lwst='true']:enabled:first", this);
if($chkbs.size() == 0){
$chkbs = $("input[type='radio'][name*='market']:enabled:first", this);
}
$chkbs.each(function(){
$(this).attr('checked','checked').parents('tr:first').attr('class','on');
if(firstRadio==null) firstRadio=this;
});
var filter=function(){
var flnum=this.value.replace(/.*FR~\s*(\d+)~.*/, 'FR$1');
var a=preselectflights.split(',');
for(var i=0;i<a.length;i++) if(a[i].replace(/\s/g, '')==flnum) return true;
return false;
};
if(preselectflights!=''){
$("input[type='radio'][name*='market']:enabled", this).filter(filter).eq(0).each(function(){
$(this).attr('checked','checked');
firstRadio=this;
});
}
});
$(firstRadio).trigger('click');
displayPopUpFareRule = getFareRule;
displayPopUpFareRule('K','K2LOW|K|FR|BND2||en-IE','ADT');
});
var preselectflights='';
function getFareRule(classOfService, fareRuleKeys, paxTypes){
var url='FareRules.aspx?fareRuleKeys=' + fareRuleKeys +'&class=' + classOfService + '&paxTypes=' + paxTypes;
$('div#fareRules').load(url + ' #main h2,#main div', function() {
$('#main div.avlLst > table td:nth-child(3)').each(function(index, cell) { $(cell).wrapInner('<a href="#" onclick="return false;"></a>'); });
$('#fareRules').jqm({overlay: 30, modal: false, onShow: showFareRules}).jqmAddTrigger('#main div.avlLst > table td:nth-child(3) *').jqmAddClose('#fareRules h2 span');
});
}
function showFareRules(hs)
{
var pos = $(hs.t).offset();
var width = $(hs.t).width();
$('#fareRules').css( { 'left': (pos.left + width) + 'px', 'top': pos.top + 'px' });
hs.w.show();
}
</script><div class="avlBlk"><h2>Going Out <span>From Aarhus - Malaga</span></h2><table><tr><td align="left" class="chgOff"><a id="AvailabilityInputFRSelectView_LinkButtonPreviousDay1" href="javascript:__doPostBack('AvailabilityInputFRSelectView$LinkButtonPreviousDay1','')">« Previous Day</a></td><td align="right" class="chgOn"><a id="AvailabilityInputFRSelectView_LinkButtonNextDay1" href="javascript:__doPostBack('AvailabilityInputFRSelectView$LinkButtonNextDay1','')">Next Day »</a></td></tr></table><div class="avlLst avlLst1"><p id="taxAndFeeInclusiveDivHeader1"><b>Select A Flight</b></p><div id="taxAndFeeInclusiveDivBody1" class="drilldown"><p class="hdr">Select a Flight</p></div><table><tr id="1_2011_9_2_23_05_00"><td><div class="planeImg1" title="Click to select this fare on this flight"></div></td><td><input id="AvailabilityInputFRSelectView_RadioButtonMkt1Fare1" type="radio" name="AvailabilityInputFRSelectView$market1" value="K~K2LOW~BND2~~RoundFrom|FR~2523~ ~~AAR~10/02/2011 19:30~AGP~10/02/2011 23:05" onclick="return raise('SelectFare', new SelectFareEventArgs(1, 1, 'K'))" required="true" requiredError="Please select a flight and fare in every market." checked lwst="true"></td><td>Regular Fare</td><td>Adult<br></td><td align="right" style="font-size:110%;">449.00 DKK<br></td><td></td><td><b>Sun</b>2 Oct 11<br><b>Flight</b>FR 2523</td><td>19:30 Depart<br>23:05 Arrive</td></tr></table><div style="clear:both; width: 100%; text-align: center;"><a href="javascript:infoWin('trvfee',0,0,'EN')">Fares do not include optional fees/charges. For a full list of Ryanair fees, please click here</a></div><div class="clr"></div></div></div><div class="avlBlk"><h2>Coming Back <span>From Malaga - Aarhus</span></h2><table><tr><td align="left" class="chgOff"><a id="AvailabilityInputFRSelectView_LinkButtonPreviousDay2" href="javascript:__doPostBack('AvailabilityInputFRSelectView$LinkButtonPreviousDay2','')">« Previous Day</a></td><td align="right" class="chgOn"><a id="AvailabilityInputFRSelectView_LinkButtonNextDay2" href="javascript:__doPostBack('AvailabilityInputFRSelectView$LinkButtonNextDay2','')">Next Day »</a></td></tr></table><div class="avlLst avlLst1"><p id="taxAndFeeInclusiveDivHeader2"><b>Select A Flight</b></p><div id="taxAndFeeInclusiveDivBody2" class="drilldown"><p class="hdr">Select a Flight</p></div><table><tr id="2_2011_9_5_15_50_00"><td><div class="planeImg2" title="Click to select this fare on this flight"></div></td><td><input id="AvailabilityInputFRSelectView_RadioButtonMkt2Fare1" type="radio" name="AvailabilityInputFRSelectView$market2" value="C~C2LOW~BND2~~RoundFrom|FR~2522~ ~~AGP~10/05/2011 15:50~AAR~10/05/2011 19:30" onclick="return raise('SelectFare', new SelectFareEventArgs(2, 1, 'C'))" required="true" requiredError="Please select a flight and fare in every market." checked lwst="true"></td><td>No Taxes</td><td>Adult<br></td><td align="right" style="font-size:110%;">379.00 DKK<br></td><td></td><td><b>Wed</b>5 Oct 11<br><b>Flight</b>FR 2522</td><td>15:50 Depart<br>19:30 Arrive</td></tr></table><div style="clear:both; width: 100%; text-align: center;"><a href="javascript:infoWin('trvfee',0,0,'EN')">Fares do not include optional fees/charges. For a full list of Ryanair fees, please click here</a></div><div class="clr"></div></div></div><div class="section right" style="width:38%;padding:4px;"><div class="bld" style="font-size:16px;margin-bottom: 4px;"><p style="float:left;"><big>Total</big></p><p class="rght"><big id="totalPrice">Please Wait...</big></p></div><p><small>Optional charges such as administration and checked baggage fees are not included.<br><a href="javascript:infoWin('trvfee',0,0,'EN');">Click here for details</a></small></p></div><div style="display: none; border: 1px solid black; position: absolute; background-color: white; width: 33%; padding: 0 5px 5px 5px;" id="fareRules"></div><div class="btnRight"><input class="buttonRight" onClick="return validate(this) && checkTimes() && preventDoubleClick();" type="submit" name="AvailabilityInputFRSelectView$ButtonSubmit" value="Select and Continue" id="AvailabilityInputFRSelectView_ButtonSubmit"><button id="NewSrch" class="button" onclick="
 window.location='FRSearch.aspx';
 
 return false;
 ">New Search</button><style type="text/css">
.ad_header {color:#191970;font-weight:bold;font-size:11px}
.ad_line1 {color:#0000FF;font-size:13px; text-decoration:underline}
.ad_url {color:#008000;margin-bottom:12px; text-decoration:none}
.ad_text {color:#191970;text-decoration:none}
.wide_ads {padding:5px;}
div.ads ul {margin: 0px; list-style: none;}
.narrow_ads {padding:2px;position: absolute; top: 100px; left: 780px; width:200px;}
</style><div id="wide_ad_unit" class="ads wide_ads"></div><div id="narrow_ad_unit" class="ads narrow_ads"></div><script type="text/javascript" charset="utf-8">
var channels = {'DE':'1901616133','ES':'1730142402','FR':'4307283847','GB':'3975277388','IE':'0091594208','IT':'9330300293','NL':'6066899700','PL':'0911139945','SE':'1735271438','Other':'1974134150'};
var channelid= channels['IE'];
if (channelid == null) channelid='1974134150';
var pageOptions = {
'pubId' : 'pub-3031568651010206',
'query' : 'Malaga Flight',
'channel' : channelid,
'linkTarget' : '_blank',
'siteLinks' : true,
'sellerRatings' : true
};
var adblock = {
'container' : 'narrow_ad_unit',
'number' : 8,
'width' : '250px',
'lines' : 3,
'fontFamily' : 'verdana',
'colorText' : '#191970',
'fontSizeTitle' : '13px',
'fontSizeDescription' : '11px',
'fontSizeDomainLink' : '11px',
'colorBackground' : '#BFD6F7',
'colorDomainLink' : 'blue',
'colorBorder' : '#BFD6F7'
};
var adblock2 = {
'container' : 'wide_ad_unit',
'number' : 5,
'width' : '400px',
'lines' : 3,
'fontFamily' : 'verdana',
'colorText' : '#191970',
'fontSizeTitle' : '13px',
'fontSizeDescription' : '11px',
'fontSizeDomainLink' : '11px',
'colorDomainLink' : 'blue',
'colorBackground' : 'white',
'colorBorder' : 'white'
};
new google.ads.search.Ads(pageOptions, adblock);
</script><div id="YahooBottomSelectAds"></div><script type="text/javascript">
$(document).ready(function(){
keywordsToUse = "Malaga Flight";
resultsHeader = "Sponsored Listings";
currentLanguage = "en";
currentCulture = "IE";
destination = "Malaga";
YahooAds_SetFrame();
});
</script></div></div></div><div class="clr"></div><div id="footer"><div id="fLinks"><a href="http://www.ryanair.com" title="Home">Home</a> | <a href="http://www.ryanair.com/site/EN/faqs.php" title="F.A.Q." target="_blank">F.A.Q.</a> | <a href="http://www.ryanair.com/site/EN/conditions.php?view=privacy" title="Privacy Policy" target="_blank">Privacy Policy</a> | <a href="http://www.ryanair.com/site/EN/conditions.php" title="General Terms & Conditions of Carriage" target="_blank">General Terms & Conditions of Carriage</a> | <a href="http://www.ryanair.com/en/terms-and-conditions/copywrite" title="Terms of Use" target="_blank">Terms of Use</a> | <a href="http://www.ryanair.com/site/EN/faqs.php?sect=CONTACT&div=int_sup" title="Contact Us" target="_blank">Contact Us</a> | <a href="javascript:infoWin('trvfee',0,0,'EN');" title="Fees">Fees</a></div><div id="copyr">Copyright 2009 Ryanair Ltd.</div><input type="hidden" id="language" value=""><input type="hidden" id="culture" value=""><script type="text/javascript"> xtnv=document; xtsd=(window.location.protocol.indexOf('https:')==0?'https://logs152':'http://logc158'); xtsite=(window.location.hostname.indexOf('www.bookryanair.com')!=-1)?'384235':'385193'; xtn2="3"; xtpage="BookingProcess_IE::Select"; xtdi="1"; xt_multc="&x1=2&x2=20111002&x3=20111005&x4=AAR&x5=AGP&x6=1&x7=3"; if(window.xtparam!=null) window.xtparam+=xt_multc; else window.xtparam=xt_multc; </script><script type="text/javascript" src="js/Ryanair/xtcore.js"></script><noscript><img width="1" height="1" alt="" src="http://logc158.xiti.com/hit.xiti?s=384235&s2=3&p=BookingProcess_IE::Select&di=1"></noscript></div></div></div><div class="clr"></div><script type="text/javascript">
//
var theForm = document.forms['SkySales'];
if (!theForm) {
theForm = document.SkySales;
}
function _doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm._EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
//
function register(eventName, functionName)
{
if (eval(events[eventName]) == null)
{
events[eventName] = new Array();
}
events[eventName][events[eventName].length] = functionName;
}
function raise(eventName, eventArgs)
{
var undefined;
if (events[eventName] != undefined)
{
for (var ix=0; ix<events[eventName].length; ix++)
{
if ( eval(events[eventName][ix] + "(eventArgs)") == false)
{
return false;
}
}
}
return true;
}
// --></script><script language="javascript" type="text/javascript"><!--
function SelectFareEventArgs(marketIndex, fltIndex, classOfService)
{
this.paxFares = marketPaxFares['mkt'+marketIndex+'|flt'+fltIndex+'|'+classOfService];
this.marketIndex = marketIndex;
}
// --></script><script language="javascript" type="text/javascript"><!--
function AvailabilityInputFRSelectView_Validate(eventArgs)
{
var dots;
var sel;
var numOfMkts = 2;
var msg = new Array (
"", "",
0 );
for (var i = 1; i <= numOfMkts; i++)
{
sel = '';
dots = document['SkySales']["AvailabilityInputFRSelectView$market" + i];
if (dots == null)
{
alert("");
return false;
}
else if (dots[0]) // array
{
for (var j = 0; j < dots.length; j++)
{
if (dots[j].checked)
{
sel = dots[j].value;
break;
}
}
}
else // single
{
if (dots.checked)
{
sel = dots.value;
}
}
if (sel == '')
{
alert(msg[i-1]);
return false;
}
}
return true;
}
function displayPopUpFareRule(classOfService, fareRuleKeys, paxTypes)
{
var url = '/skysales/FareRules.aspx?fareRuleKeys=' + fareRuleKeys +'&class=' + classOfService + '&paxTypes=' + paxTypes;
if (!window.fareRuleWindow || fareRuleWindow.closed) // has not yet been defined
{
fareRuleWindow = window.open(url,'fareRule','width=250,height=251,toolbar=0,status=0,location=0,menubar=0,scrollbars=1,resizable=0');
}
else
{
fareRuleWindow.open(url,'fareRule','width=250,height=251,toolbar=0,status=0,location=0,menubar=0,scrollbars=1,resizable=0');
fareRuleWindow.focus();
}
}
// --></script><script language="javascript" type="text/javascript"><!--
function paxFare(paxTypeDesc,classDesc,fareRuleKey)
{
this.paxTypeDesc = paxTypeDesc;
this.classDesc = classDesc;
this.fareRuleKey = fareRuleKey;
}
var marketPaxFares = new Array();
marketPaxFares['mkt1|flt1|K'] = new Array();
marketPaxFares['mkt1|flt1|K'][0] = new paxFare('Adult','Regular Fare','K2LOW|K|FR|BND2||en-IE');
marketPaxFares['mkt2|flt1|C'] = new Array();
marketPaxFares['mkt2|flt1|C'][0] = new paxFare('Adult','No Taxes','C2LOW|C|FR|BND2||en-IE');
// --></script><script language="javascript" type="text/javascript"><!--
function AvailabilityInputFRSelectView_initialize()
{
} // end of Availability_initialize
// --></script><script type="text/javascript">
//
var RegisterFunctionsWithEvents = new Array(register('Validate', 'AvailabilityInputFRSelectView_Validate'), register('WindowLoad', 'AvailabilityInputFRSelectView_initialize'));
//
//defined in common.js
$(document).ready(function(){
WindowInitialize();
});
A: The TFHpple class doesn't have a search: method. The method you're looking for is searchWithXPathQuery:.
A: @Rocky this is not an html .this is JavaScript ,and when you trying to execute an xpath search you not get a nil .that's because the table you want is not in the downloaded data ,you can see this table in firefox browser's Developer Tools ,this table is created at runtime with the script above .you can use UIWebView and execute JavaScript from the method stringByEvaluatingJavaScriptFromString to get the innerHTML loaded by webview then use HPPLE .
sorry of my bad english.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594980",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Can I var scope a function? Prevent it from appearing in the global variables scope I'm cleaning up a large website's huge variables scope, normally when cleaning up these things I find the variables and var scope them.
Problem is; say I have a function declaration in a view(cfscript):
function myFunction(){
//doStuff
}
myFunction is now available in the variables scope, it is however only used on this page so i want it in the local scope.
I've tried:
function local.myFunction(){
//doStuff
}
//error!
var myFunction = "";
function myFunction(){
//doStuff
}
//just creates a local string and a global function...
var function myFunction(){
//doStuff
}
//no error but function is still not local...
the following however does work, it does feel kinda nasty though...
function myTMPFunction(){
//doStuff
}
var myFunction = myTMPFunction;
structDelete(VARIABLES, "myTMPFunction");
is there no better, clean way?
A:
is there no better, clean way?
Yes, there is. It is called ColdFusion components aka CFC.
I suspect that you mis-use local scope concept a bit, but you did not say whether your code is inside a CFC or not, so I can only guess: if you are refactoring CFC, what you want is incapsulation, otherwise you just want to start using components and then local scope inside the methods.
A: Based on your comment to Sergii's post,
its used recursive to generate HTML
I would say maybe you should refactor the function into a custom tag.
I generally avoid directly outputting anything from functions and use Custom Tags instead. When I use functions I return some value (or void).
Without more specific information on what the function does, though, it will be hard to give a more concrete answer than that.
However, while not the prettiest, I think your work-around solution would also work, if you'd rather not go through the effort to use a Custom Tag.
function myTMPFunction(){
//doStuff
}
var myFunction = myTMPFunction;
structDelete(VARIABLES, "myTMPFunction");
A: The local scope is only really important within the context of a function. The reason that you var scope variables in a cfc is so that variables that should be local to a function don't leak out of the scope of the function into the component. This becomes especially important if you have components in a persistent scope like session or application.
component{
public void function leakyVariable(){
//this is in variables scope so a) it will exist longer
//than this function call and other functions can access it
foo = "Foo";
//do stuff
}
public void function grabLeakyVariable(){
//look i have a foo
var foobar = foo & "bar";
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594990",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to delete a child node using OmniXML? I'd like to delete the line with pathid="2" in the rowpath section...
<?xml version="1.0" encoding="utf-8"?>
<LostPath Condition="Active" Selected="train.exe" FullPathOfSelected="D:\mygames\arcade\train\" Selected="0">
<rowdir Name="train.exe" GamePath="D:\mygames\arcade\train\" Selected="0" />
<rowdir Name="othelo.exe" GamePath="D:\mygames\arcade\othello\" Selected="3"/>
<rowpath Name="train.exe" PathId="1" LevelPath="D:\mygames\arcade\train\levelpack1" levelsFound="27" />
<rowpath Name="train.exe" PathId="2" LevelPath="D:\mygames\arcade\train\levelpack21" levelsFound="19" />
<rowpath Name="othelo.exe" PathId="0" LevelPath="D:\mygames\arcade\othelo\levelpack1" levelsFound="11" />
</LostPath>
How can I do that ?
A: Try to use this.
uses
OmniXML, OmniXMLUtils;
procedure TForm1.Button1Click(Sender: TObject);
var
XMLNode: IXMLNode;
XMLDocument: IXMLDocument;
begin
XMLDocument := CreateXMLDoc;
if XMLLoadFromFile(XMLDocument, 'XMLFile.xml') then
begin
XMLNode := XMLDocument.SelectSingleNode('/LostPath');
DeleteNode(XMLNode, 'rowpath[@PathId="2"]');
XMLDocument.Save('XMLFile.xml');
end;
end;
A: There are few ways how to delete all nodes with the same attribute value. Here's one of them. But please note, this post doesn't answer this question. It should be asked as another question.
uses
OmniXML, OmniXMLUtils;
procedure TForm1.Button1Click(Sender: TObject);
var
XMLNode: IXMLNode;
XMLDocument: IXMLDocument;
begin
XMLDocument := CreateXMLDoc;
if XMLLoadFromFile(XMLDocument, 'XMLFile.xml') then
begin
XMLNode := XMLDocument.SelectSingleNode('/LostPath');
DeleteAllChildren(XMLNode, 'rowpath[@Name="train.exe"]');
XMLDocument.Save('XMLFile.xml');
end;
end;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594992",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Load Facebook friends information using Android In my application I am integrating with Facebook and I do:
Log in Facebook and get all information of friends and display it in a List View. It will take a time to do this if the user have a number of friends.
So, is there any way to get information of friend in fixed number sequentially. Suppose I want to get the information for the first 10 friends and display it in a list view and further the next 10.
My list view should be updated in a background task and should working smoothly.
A: I think you need to use some already made API or JAR file for Facebook integration.
I just have found one FBRocket and the documentation file for it. You can see that it has two functions. One is List getFriendUIDs() and the second is List getFriends(String[] uids).
And you can get a list of friends for as many UIDs you wish at a time. And from that the Friend object can get information about a friend and use it in your application.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594996",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Does foreach use IEnumerator/IEnumerable for built-in types? Does the foreach loop use interfaces IEnumerator and IEnumerable only for iterating the objects of custom types (classes) or also for iterating the built-in types (behind the scenes)?
A: Foreach doesn't depend on IEnumerable as such. However, if a type implements it then a foreach loop will be able to enumerate it (pattern-based matching).
Behind the scenes it only needs a GetEnumerator() method and the enumerator must contain Current and MoveNext().
From MSDN:
*
*The collection type:
*
*Must be one of the types: interface, class, or struct.
*Must include an instance method named GetEnumerator that returns a type, for example, Enumerator (explained below).
*The type Enumerator (a class or struct) must contain:
*
*A property named Current that returns ItemType or a type that can be converted to it. The property accessor returns the current element of the collection.
*A bool method, named MoveNext, that increments the item counter and returns true if there are more items in the collection.
From MSDN - Using foreach with Collections
UPDATED: See updated MSDN page for this - How to: Access a Collection Class with foreach (C# Programming Guide) .
A: Define enumerator, no IEnumerable declaration.!
public class WorkInfoEnumerator
{
List<WorkItem > wilist= null;
int currentIndex = -1;
public MyClassEnumerator(List<WorkItem > list)
{
wilist= list;
}
public WorkItem Current
{
get
{
return wilist[currentIndex];
}
}
public bool MoveNext()
{
++currentIndex;
if (currentIndex < wilist.Count)
return true;
return false;
}
}
public class WorkInfo
{
List<WorkItem > mydata = new List<WorkItem >();
public WorkInfoEnumerator GetEnumerator()
{
return new WorkInfoEnumerator(mydata);
}
}
Somewhere in code can use :
WorkInfo wi = new WorkInfo();
foreach(WorkItem witem in wi)
{
}
A: foreach uses IEnumerable for both native and custom types. If you look at System.Array for example, which is the base for all array types, it implements IEnumerable.
A: for-each is language construct and does not really differentiate between custom/built-in types.
for each is not dependent on IEnumerable, it uses pattern based matching. See http://blogs.msdn.com/b/ericlippert/archive/2011/06/30/following-the-pattern.aspx
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594998",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: don't run PropertyChangedCallback in DependencyProperty I created a UserControl with a DependencyProperty. I set a value for this UserControl on FormLoad. But when I run the application no value is shown.
My code:
public static readonly DependencyProperty ValueProperty =
DependencyProperty.Register("Value", typeof(PersianDateTime), typeof(UCDatePicker),
new PropertyMetadata(PersianDateTime.Now, new PropertyChangedCallback((onchangedcallback))));
public PersianDateTime Value
{
get { return (PersianDateTime)GetValue(ValueProperty); }
set { SetValue(ValueProperty, value); }
}
private static void onchangedcallback(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
UCDatePicker control = obj as UCDatePicker;
PersianDateTime newdate = (PersianDateTime)e.NewValue;
control.Years = ((PersianDateTime)e.NewValue).Year;
control.Months = ((PersianDateTime)e.NewValue).Month;
control.Days = ((PersianDateTime)e.NewValue).Day;
control.Hours = ((PersianDateTime)e.NewValue).Hour;
control.Minutes = ((PersianDateTime)e.NewValue).Minute;
}
In my FormLoad:
uCDatePicker1.Value = PersianDateTime.Now;
when i use breakpoint ,onchangedcallback doesn't execute.
A: Because you don't change value,
Value is equal to PersianDateTime.Now before and after your assignment
onchangedcallback will be called only if you will assign different value to dependency property, you can change default value of dependency property to some default value if you want property changed event to be called at first assignment
If PersianDateTime is reference type(class for example) change your dependency property like this
...new PropertyMetadata(null,...
But looking on PersianDateTime type, seems it is struct so you can use
...new PropertyMetadata(DateTime.MinValue.ToPersianDateTime(),...
and it will work
Hope this helps
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594999",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: get session variable Array list into Display Tag Hi I have ArrayList get from session in jsp.
<%java.util.ArrayList<Organisation> OrganisationList1 =
(java.util.ArrayList<DAOrganisation>)
request.getSession().getAttribute("organisationArray");%>
Then I try to get this array list and display by using Display Tag.
<display:table class="displayTable" id="orgList"
name="OrganisationList" requestURI="" pagesize="13"
defaultsort="1" sort="list">
<display:column property="organisationName"
title="Organisation Name" sortable="true" headerClass="sortable" paramId="organisationId" paramProperty="organisationId" />
<display:column property="description" title="Description">
</display:column>
</display:table>
But it doesn't show anything in Display Table. I am add pagination to the old coding of other. So, I need follow the structure and can't change it. As far as I know , I can use ArrayList directly with Display Tag. So, I just want to Display the Array List from Session using Display Tag. Thanks.
Edited: In the old code, he tried to convert into Organisation Java Bean by looping and use to display one by one.
Stack Trace:
org.apache.jasper.JasperException: An exception occurred processing
JSP page /organisationlist.jsp at line 81
78: 79: 80: 81: 82: 83:
Stacktrace:
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:519)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:422)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
org.apache.struts2.dispatcher.ServletDispatcherResult.doExecute(ServletDispatcherResult.java:154)
org.apache.struts2.dispatcher.StrutsResultSupport.execute(StrutsResultSupport.java:186)
com.opensymphony.xwork2.DefaultActionInvocation.executeResult(DefaultActionInvocation.java:361)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:265)
com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:163)
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:249)
org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68)
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:122)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195)
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195)
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:148)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:93)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:235)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:89)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:128)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
org.apache.struts2.interceptor.ProfilingActivationInterceptor.intercept(ProfilingActivationInterceptor.java:104)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:267)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:126)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:138)
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:148)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:128)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:176)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:52)
org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:468)
org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:395)
root cause
java.lang.IllegalStateException: Cannot access session scope in page
that does not participate in any session
org.apache.jasper.runtime.PageContextImpl.doGetAttribute(PageContextImpl.java:264)
org.apache.jasper.runtime.PageContextImpl.getAttribute(PageContextImpl.java:249)
org.displaytag.util.LookupUtil.getBeanValue(LookupUtil.java:100)
org.displaytag.tags.TemplateTag.evaluateExpression(TemplateTag.java:84)
org.displaytag.tags.TableTag.initParameters(TableTag.java:932)
org.displaytag.tags.TableTag.doStartTag(TableTag.java:767)
org.apache.jsp.organisationlist_jsp._jspService(organisationlist_jsp.java:223)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:386)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
org.apache.struts2.dispatcher.ServletDispatcherResult.doExecute(ServletDispatcherResult.java:154)
org.apache.struts2.dispatcher.StrutsResultSupport.execute(StrutsResultSupport.java:186)
com.opensymphony.xwork2.DefaultActionInvocation.executeResult(DefaultActionInvocation.java:361)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:265)
com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:163)
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:249)
org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68)
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:122)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195)
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195)
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:148)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:93)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:235)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:89)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:128)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
org.apache.struts2.interceptor.ProfilingActivationInterceptor.intercept(ProfilingActivationInterceptor.java:104)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:267)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:126)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:138)
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:148)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:128)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:176)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:52)
org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:468)
org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:395)
A: JSP tags don't use scriptlet variables. They use JSP EL expressions. scriptlets are something from the past and should not be used anymore in JSPs.
Just use
<display:table name="${organisationArray}" ...>
Or, if you want to be more explicit:
<display:table name="${sessionScope.organisationArray}" ...>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595000",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: C programming while #include "stdafx.h"
int _tmain(int argc, _TCHAR* argv[])
{
int x=0;
int y=0;
while (x<15)y++,x+=++y;
printf ("%i %i",x, y);
getchar ();
getchar ();
return 0;
}
I don't know why x is 20 and y is 8 at the end.
Please explain it step by step.
A: while (x<15)y++,x+=++y;
=>
while (x<15) {
y++;
x += ++y;
}
=>
while (x < 15) {
y += 2;
x += y;
}
So:
Before 1st iteration: x = 0, y = 0;
After 1st iteration: x = 2, y = 2;
After 2nd iteration: x = 6, y = 4;
After 3rd iteration: x = 12, y = 6;
After 4th iteration: x = 20, y = 8;
Note that there is a simple closed formula for these values as well: x = n*n - n and y = 2*n.
A: Remember that :
*
*y++ increments y
*x+=++y first increments y and then adds it to x
Which gives the following values for x and y :
iterations x y
0 0 0
1 2 2
2 6 4
3 12 6
4 20 8
A: If you follow what is going to happen to your variables :
First Loop:
x=0, y=0
y++ => y=1
x+=++y => x=2, y=2
Second Loop:
x=1, y=2
y++ => y=3
x+=++y => x=6, y=4
Third Loop:
y++ => y=5
x+=++y => x=12, y=6
Fourth Loop:
y++ => y=7
x+=++y => x=20, y=8
And while loop will exit.
A: x<15 -> y=1, x=0+(y=2)=2
2<15 -> y=3, x=2+(y=4)=6
6<15 -> y=5, x=6+(y=6)=12
12<15 -> y=7, x=12+(y=8)=20
Done
x=20, y=8
The comma operator enforces the order of execution. x,y means that x is executed first, and then y.
A: I changed it to
#include <stdio.h>
int main()
{
int x=0;
int y=0;
while (x<15) {
y++,x+=++y;
printf ("%i %i\n",x, y);
}
return 0;
}
and it yields
H:\Temp>a.exe
2 2
6 4
12 6
20 8
now.
Why? Because y gets incremented twice in each step, and x gets added the new value. So you essentially get 2+4+6+8 = 20.
But I'm not sure it is defined behaviour. It is if the , operator defines a sequence point.
A: Let's go through the loops (conditions after the loop):
*
*x=2, y=2
*x=6, y=4
*x=12, y=6
*x=20, y=8
In each loop, what effectively is done is:
y+=2
x+=y
which results in the states written above.
A: Alright, this is what is happening every loop in your while clause:
*
*Increment y by one
*Increment y by one additionally
*add y to x
*if x >= 15 stop the loop
Now in numbers, right before the end of the loop:
*
*x = 0, y = 0
*x = 2, y = 2
*x = 6, y = 4
*x = 12, y = 6
*x = 20, y = 8 --> x > 15 --> finish the loop.
A: in every iteration
y increased by 2 ( y +=2 ) ,
after that x increased by x + y ( x= x+y)
it skips when x = 20 ( as x is now > 15 )
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595001",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Error : "Cannot set commandtext while a datareader is active" with ExecuteNonQuery() I listen a data stream and store data as insert statements in a ConcurrentQueue and insert the data with bulk insertion using a System.Threading.Timer with an interval of 1000 . The whole scenario runs on a static class.
Here is the code:
static void timer_Elapsed(object sender, ElapsedEventArgs e)
{
if (queryQueue.IsEmpty)
return;
string text = "";
//bulkBuilder is StringBuilder.
//queryQueue is ConcurrentQueue
bulkBuilder.AppendLine("PRAGMA synchronous = 0;PRAGMA count_changes = FALSE;PRAGMA journal_mode=OFF;Begin;");
while (queryQueue.TryDequeue(out text))
{
bulkBuilder.Append(text);
bulkBuilder.AppendLine(";");
}
bulkBuilder.AppendLine("Commit;");
try
{
sqlCommand.CommandText = bulkBuilder.ToString();
sqlCommand.ExecuteNonQuery();
}
catch (System.Exception ex)
{
Console.WriteLine("Error while inserting Data : " + ex.Message);
}
finally
{
bulkBuilder.Clear();
}
}
Funny thing is, sqlCommand is used just for insertion, just to ExecuteNonQuery() in this timer. And time to time a get an error saying "Cannot set commandtext while a datareader is active." This is nonsense since this code has nothing to do with the inner SQLiteDataReader in the sqlCommand.
How can I get rid of this error?
A: I would create a new SqlCommand (or whatever the type of sqlCommand is) for each SQL statement. Let the connection pool handle making it all efficient - each time you need to do something with the database:
*
*Create and open the connection
*Create the command
*Execute the command
*Dispose of the command and connection (with a using statement)
That way you can't end up with the local state of one command affecting another command, other than due to running out of connection pool space etc.
Developers often try to optimize by using one connection (and potentially command) over and over, but this is a false economy and leads to problems like the one you've shown.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595004",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: what does a c compiler do when doesn't find the matching function Consider the following code:
#include<stdio.h>
int f()
{
printf(" hey ");
return 5;
}
int main()
{
printf("hello there %d",f(4,5));
f(4,5);
return 0;
}
I expected something like too many arguments to function ‘int f()’ but it gives an output even in strict C99 compilation. why is this behavior?
But it seems like a C++ compiler gives an error.
A: C is much less strict than C++ in some regards.
A function signature f() in C++ means a function without arguments, and a conforming compiler must enforce this. In C, by contrast, the behaviour is unspecified and compilers are not required to diagnose if a function is called with arguments even though it was defined without parameters. In practice, modern compilers should at least warn about the invalid usage.
Furthermore, in function prototype declarations (without definition) in C, empty parentheses mean that the parameters are unspecified. It can subsequently be defined with any number of arguments.
To prevent this, use the following prototypeISO/IEC 9899 6.7.6.3/10:
int f(void)
A: In addition to what Konrad wrote, C will also implicitly declare functions for you. For example:
int main(int argc, char** argv)
{
int* p = malloc(sizeof(int));
return 0;
}
will compile (maybe with a warning) without a #include <stdlib.h> that contains the declaration.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595006",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: GlassFish, Java, Grizzly, WebSockets - how to get started? I am faced with the necessity to push some messages to the clients of my web-application in Java. After some reading up on the subject, i decided to use websockets as an emerging and a promicing technology, and to use GlassFish as the server. However, all the examples i find are either quite complicated or outdated and do not compile with Grizzly 2.
Is there a really simple example with just a few lines of code that would push something like "hello, world" to the client?
Thanks in advance,
Timofey.
A: I know what you mean. I've been working on a response to this. You might also be interesting in beginning with websockets comment here. Please read those responses. They might help get you started. The current downloadable javascript code from the suggested demo is intended to provide some flexibility and nice features for testing - although if you download it and look into WSTest.htm, it's really not so complicated. Might be just what you're looking for. Then maybe we can all get together and work things out with grizzly.
UPDATE: As I work through grizzly myself, I found on the Quick Start in the glassfish admin console, there's a hello sample that's pretty easy to set up and run. You'll find instructions there. The sample directory also contains a war file named: websocket-mozilla; so I guess its supposed to use websockets. Someone who's familiar with jsp should review the source code. All I can see is that it's using an http session. No mention of a websocket at all. It's a lot like the hello sample.
A: I use CometD implementation on GlassFish. It has different transport protocols including Websockets (although they don't recommend it yet).
See my answer to another related question.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595007",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Explanation of syntax in for loop? I was trying to do some of the problems on projecteuler, and I got to the one with the sum of squares and squares of sums. I didn't want to brute force it, so I looked up the solution, which was:
sum1 = 0
sum2 = 0
for i in ((x,x ** 2) for x in range(1,100+1)):
sum1 += i[0]
sum2 += i[-1]
print(sum1 ** 2 - sum2)
I do not get:
(x,x ** 2) for x in range(1,100+1)
I've seen this in another code golf solution in javascript too. Is this a specific syntax, or an unfamiliar way of something regular? Can someone please explain?
A: When confronted with complex syntax, add print statements.
for i in ((x,x ** 2) for x in range(1,100+1)):
print i
Not too helpful.
Try this.
a = ((x,x ** 2) for x in range(1,100+1))
print a
for i in a:
print i
Helpful? Maybe.
Try this:
a = ((x,x ** 2) for x in range(1,100+1))
b = list(a)
print b
Hmmm. The for i in a loop stops working, also. This generator object seems to do it's thing once only. Either in a for loop or in the list() (or tuple()) function but not both.
Try this.
for x in range(1,100+1):
print x, x**2
Okay. So, what have we learned?
((x,x ** 2) for x in range(1,100+1)) is a generator expression. http://www.python.org/dev/peps/pep-0289/
It's "iterable" and can be used in a for statement or the list() function.
Also, we've learned to add print statements to explore confusing syntax.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595009",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: The type 'NavigationWindow' does not support direct content I am trying to use NavigationWindow class instead of Window to allow navigation between windows in WPF application. But when adding content to the NavigationWindow in XAML, I am getting an error:
"The type 'NavigationWindow' does not support direct content". How can I overcome this problem?
A: You can't add any content to a NavigationWindow.
It is just a "Window" where the Page is going to run, so you have to tell the NavigationWindow wich Page it is going to initial run, you do that by using "Source"
Like this:
<NavigationWindow x:Class="Tes.TesWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Test" Height="300" Width="300" Source="Window1.xaml">
</NavigationWindow>
See a tutorial here:
http://windowsclient.net/learn/video.aspx?v=4190
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595010",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: codeigniter model vs library which one to use there is a function get_user_group_ids($user_id), it returns all groups the user belongs.
this pings the batch table and gets all the batch_ids. ANd then pings group table and get group_ids corresponding to batch_ids
This is used in event, job and other libraries like eg , get all the job which belongs to my batch. here i need to call this function to get my group ids.
because this is a common function, i have doubt whether to create common library or model
A: If this function is fetching the ID's from a database or other external datasource then a model is the way to go :)
A: I've been in a similar situation where I needed to share a model (an abstract collection of methods) between a framework (CakePHP in my case) and shell scripts for batch jobs. To do so I found that the simplest method was to create a CakePHP model like any other model EXCEPT it didn't extend the base (parent) framework model class (CI_Model in your case). The advantage with this was that I was still able to "load" (initiate) the class from CakePHP using the same conventions as any other framework model but was able to use the same model (the actuall file) in batched shell scripts without needing to load anything extra.
I'm pretty certain the same is possible in CI (although I'm not a heavy CI user):
# the model definition /application/models/CustomModel.php
class CustomModel {
public function __construct() {} # ...
public function get_user_group_ids( $id ) {} # ...
}
# from inside the a controller method:
$this->load->model( 'CustomModel' );
$this->CustomModel->get_user_group_ids( $id ); # ...
# from inside the shell scripts:
require_once( YOUR_CI_PATH . '/application/models/CustomModel.php' );
$obj = new CustomModel();
$obj->get_user_group_ids( $id ); # ...
Hope this helps,
Cheers
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595011",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: SQL SERVER 2008 , Nested procedures issue Considering the following example
Procedure1
..........
IF(@errorcode<>0) ROLLBACK TRANSACTION
ELSE COMMIT TRANSACTION
SELECT @errorcode
Procedure2
..........
WHILE [condition] BEGIN
EXEC @proc1result = Procedure1 [parameters]
IF(@proc1result=0) SET @totalresult=@totalresult+1
END
SELECT @totalresult
The problem is that @totalresult is incremented correctly but the value returned by Procedure2 is 0.
How to get it right?
I am using sql server 2008 and Entity Framework 4.
Procedure1 works well.
A: "but the value returned by Procedure2 is 0"
You do a SELECT @totalresult. Should it be return @totalresult?
Answer to Upendra...
CREATE PROC dbo.TestReturn (@InValue int)
AS
Return @Invalue+1
GO
declare @value int
exec @value = TestReturn 100
select @value
A: (1) For the first stored procedure, you should use RETURN @errorcode and not SELECT @errorcode. This is also my recommendation.
OR (NOT AND)
(2) For the second stored procedure, you should use INSERT ... EXEC Procedure1 like this:
WHILE [condition]
BEGIN
DECLARE @Results TABLE (RetValue INT PRIMARY KEY);
INSERT @Results
EXEC Procedure1 [parameters];
--IF 0=ALL(SELECT a.RetValue FROM @Results a)
IF NOT EXISTS(SELECT * FROM @Results a WHERE a.RetValue <> 0)
SET @totalresult=@totalresult+1;
END
SELECT @totalresult
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595015",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to find the dispatch id of an event generated by an ActiveX control I am writing a wrapper class for an activeX control using FireBreath.
The ActiveX container class has an event sink which listens to the events fired by ActiveX control.
In the code creating the event sink, in the SINK_ENTRY_INFO method one of the parameter is dispatch id of the event.
Where will i find the dispatch id of the event generated by the activeX control?
A: Get the DISPID the same as you would for any other member on the object. You can probably use the IDispatchAPI object from firebreath:
https://github.com/firebreath/FireBreath/blob/master/src/ActiveXCore/IDispatchAPI.cpp#L444
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595016",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: 401 Unauthorized returned on EndGetResponse. Apache Error log: cannot generate context I got a server with Apache running. Now I want to be able to read the contents of a folder there and for that this folder is configured in the Apache httpd.conf something like this:
Alias /folder "E:/Folder"
<Directory "E:/Folder">
AuthName "Public Folder"
AuthType SSPI
SSPIAuth On
SSPIAuthoritative On
SSPIDomain DOMAIN
SSPIOfferBasic On
SSPIOfferSSPI On
SSPIBasicPreferred Off
SSPIOmitDomain On
SSPIUsernameCase lower
require group "DOMAIN\Domain Users"
</Directory>
Now when I use a Browser I can already access this Information with the URL http://ServerName/Folder/
So this workes just fine already. But now I am trying to receive this Folder-Data for my C# application. I am using DefaultNetworkCredentials and my Code looks something like this:
public void CheckFolder()
{
WebRequest request = HttpWebRequest.Create(_uri);
request.Credentials = CredentialCache.DefaultNetworkCredentials;
request.BeginGetResponse(new AsyncCallback(HandleGetAvailableUpdates), request);
}
void HandleGetAvailableUpdates(IAsyncResult state)
{
try
{
if (state.IsCompleted)
{
WebRequest req = state.AsyncState as WebRequest;
WebResponse response = req.EndGetResponse(state);
Stream wStream = null;
wStream = response.GetResponseStream();
byte[] data = new byte[response.ContentLength];
etc.
.
.
.
}
catch (WebException ex)
{
Console.WriteLine(ex.ToString());
}
}
}
req.EndGetResponse(state) now throws the WebException:
The remote server returned an error: (401) Unauthorized.
Going back on Server-Side I have a look at the Apache error.log and there I find:
(OS 87)The parameter is incorrect. : authentication failure for "/folder": user unknown, reason: cannot generate context
This feature of the Program already worked well about two month ago. The C#-Code did not change at all but I dont know if something had been done with the server or the Apache configuration. I also tried to give my Credentials (username and pw, the same I use when accessing via Web-Browser) manually in the C#-Code rather than using the DefaultNetworkCredentials but with no avail. So finally my question would be: Is there something I forgot? Are there any other settings on the server to be made to make it work?
A: Easiest way to find out:
User Fiddler, or Live Http Headers, or any other HTTP packet sniffer to see which headers/post parameters are sent by the browser, and then duplicate all of them programatically.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595018",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Why is this declaration not allowed in Haskell? I know that Functor and Applicative should be superclasses of Monad, but aren't for historical reasons. However, why isn't is possible to declare Monad an instance of Functor? This would have roughly the same effect, but without having to modify existing code. If you're trying to do this, GHC complains:
instance Functor Monad where
fmap = liftM
Class `Monad' used as a type
In the instance declaration for `Functor Monad'
Why is that? There's probably a good reason for it.
A: The reason is that Monad is a type class while an instance declaration requires a type or type constructor. The error message clearly states that. Type classes and type are two distinct kinds of things. They are never interchangable in Haskell.
A: Your syntax is wrong. Monad is a typeclass, not a data type. What you could write is
instance Monad a => Functor a where fmap = liftM
However, this will only work with the extensions FlexibleInstances (permits instances that are not of the form T a1 a2 ... an where a1, a2, ... an are type variables and there is no context) and UndecidableInstances (which permits this specific instance [I don't know why this is needed]).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595023",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: How to use custom file instead of log4j.properties I'm using log4j in my java project. Instead of log4j.properties, i want to configure another file... Can anyone help me... Thanks in advance..
A: This is a FAQ.
Just use java -Dlog4j.configuration=your/file/path.properties. See http://logging.apache.org/log4j/1.2/manual.html#defaultInit for details about this system property.
A: org.apache.log4j.LogManager.resetConfiguration( );
if ( System.getProperty( "log4j.config" ) != null ) {
DOMConfigurator.configureAndWatch( System.getProperty( "log4j.config" ) );
}
else {
DOMConfigurator.configure( Loader.getResource( "log4j.properties" ) );
}
Use this one time; you only have to specify the path to your log4j file via system paramaters:
-Dlog4j.config=/path/to/your/log4j.properties
A: try
PropertyConfigurator.configure("configFilename")
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595025",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Set Timeline Cover in Facebook? Suppose that I am able to upload a photo to user's album, how can it be set to as Timeline Cover. There are some apps who already doing that like myfbcovers.com and firstcovers.com.
A: Just like with the profile picture, apps are NOT allowed to set the cover picture (yet?). The websites you linked to just upload the selected image to your wall (inside the application album NOT the cover album) and ask you to set it manually!
A: I actually just finished up on the same app your working on.
You can not set the cover photo with an application at the moment. Facebook used to allow it but quickly removed this option. Now, only the user can set his/her cover from Profile View. I have no idea why, probably security precautions.
Source: FB app developer of http://fbcoverlover.com/
A: You can set a cover photo for a Page by issuing an HTTP POST to '/PAGE_ID/' with a Page Access Token and the following parameters:
*
*cover - The ID of the photo. Integer. Mandatory.
*offset_y - The percentage offset from top (0-100). The default value is 50. Integer. Optional.
*no_feed_story - The flag indicating whether or not to create a story. The default value is false. Boolean. Optional
A: after you uploaded the photo to the users album you get the photo id as response. you can then redirect the user to the following link to set that pictures as his cover photo:
https://www.facebook.com/[USER_ID]?preview_cover=[PICTURE_ID]
he will see his profile with the picture as his cover and two buttons "save cover" or "cancel".
A: Yes, previously there was a way that our facebook covers application used to do this but they removed it for some reason.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595026",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: regex tweaking advice needed I have this regex which some kind folks on SO helped me with yesterday. Anyway I have been editing it to do another match now and have almost got it. Basically in the following text I need it to match the space before the year and to append a pipe | to that match. I can get it to match but it includes the first digit of the year, what should I do to only match the space. By the way the year may not just be a four digit sequence it may also be 2206 & 2007 or 2004-2008 and so on.
105| Ryan, T.N. 2005. |
$(?:[^|]+\|){1}(.*?)\.\s\d
A: If I understand your question correct, you want to add a | between Ryan, T.N.and 2005..
try this regex
^((?:[^|]+\|){1}.*?\.\s)(?=\d)
and replace with $1 and |
See it here on Regexr
The (?=\d) is positive lookahead, it ensures, that there is a digit ahead without matching it.
A: This should work if I understand you correctly.
$string = preg_replace("#(.*) ([0-9]+.)#", "$1 | $2", "105| Ryan, T.N. 2005. |");
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595041",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Exception starting filter struts2 java.lang.NullPointerException? The error "Exception starting filter struts2 java.lang.NullPointerException" is shown when i Try to run my application. I am programming in Eclipse 3.6 on Struts 2. part of my My Struts.xml looks like below:
<struts>
<!-- remove these constant elements in production -->
<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<constant name="struts.devMode" value="true" />
<package name="app02a" extends="struts-default">
<action name="Product_input">
<result>/jsp/Product.jsp</result>
</action>
<action name="Product_save" class="app02a.Product" method="execute">
<result>/jsp/Details.jsp</result>
</action>
</package>
</struts>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595043",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Mysql char search vs integer I have this query:
SELECT * FROM table WHERE field = 'abcd';
Table has lots of rows (1'000'000'000 or more)
If instead of field = 'abcd' i use something like
SELECT * FROM table WHERE field = 'abcd' AND other_field = 300;
, Where 300 is a number that depends on 'abcd' (f(abcd) => 300), will the query run faster?
A: Search time when using unique indexes
MySQL uses BTree indexes.
This means that a unique row is found in log(n) time.
If you search in 65536 rows, it will take max 16 comparisons to find the row, assuming a fully balanced tree.
If you search in 1,000,000,000 it will take 30 comparisons to find the row, assuming a fully balanced tree and unique values.
If you search on a unique key, it makes very little sense to add extra tests.
Search time using non-unique indexes
If you search on a non-unique tree, the search time will be fast, but of course the resultset will include more than 1 row, and the query time goes up as the number of rows grows.
Provided that MySQL deems it useful to use an index, the initial key will be found in very few tests.
However the real time is spend going though the rows that match.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595046",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Delegates in Haxe Is there something like a delegate in Haxe?
This would come in handy when I use a anonymous function but still want to maintain the current class'es variable scope.
myObject.callback = function(param) { this.variable = param; };
As you can see this is not accessible from within the function body. :-(
A: As far as I know you can do it in latest Haxe version. In earlier versions you should be able to do:
var t=this;
myObject.callback = function(param) { t.variable = param; };
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595047",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Why can't I upload files asynchronously? After a whole-day's study && trying, i finally give up upload files by pure AJAX (ps: this post How can I upload files asynchronously with JQuery? buried my last hope)
My question may be a little meaningless, but i still wanna know why ajax(or XMLHttpRequest) can't handle this? why can't the files transfered like the real httprequest?
A: Javascript cannot read local files for security reasons, so we can't send the data using AJAX.
However you can POST a standard HTML form, and set the form target to be an invisible iframe on the page. This iframe can then use server side code to handle the upload.
If your reason to use AJAX is because you'd like a progress bar as the file is uploading, using this method you can use a server-side static variable to store the progress of the file upload, then use AJAX to make a simple, timed request to another HTTP page which just returns the upload progress.
A: Just as an updated answer in case someone Googles this, XMLHttpRequest level 2 does support AJAX submittal of file inputs.
Browser support:
http://caniuse.com/xhr2
It uses the FormData Javascript object.
How to send FormData objects with Ajax-requests in jQuery?
Don't forget to turn off processData and contentType if you're doing this.
var fd = new FormData();
fd.append( 'file', input.files[0] );
$.ajax({
url: 'http://example.com/script.php',
data: fd,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
alert(data);
}
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595049",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Python - SqlAlchemy: Filter query by great circle distance? I am using Python and Sqlalchemy to store latitude and longitude values in a Sqlite database. I have created a hybrid method for my Location object,
@hybrid_method
def great_circle_distance(self, other):
"""
Tries to calculate the great circle distance between the two locations
If it succeeds, it will return the great-circle distance
multiplied by 3959, which calculates the distance in miles.
If it cannot, it will return None.
"""
return math.acos( self.cos_rad_lat
* other.cos_rad_lat
* math.cos(self.rad_lng - other.rad_lng)
+ self.sin_rad_lat
* other.sin_rad_lat
) * 3959
All the values like cos_rad_lat and sin_rad_lat are values I pre-calculated to optimize the calculation. Anyhow, when I run the following query,
pq = Session.query(model.Location).filter(model.Location.great_circle_distance(loc) < 10)
I get the following error,
line 809, in great_circle_distance
* math.cos(self.rad_lng - other.rad_lng)
TypeError: a float is required
When I print the values for self.rad_lng and other.rad_lng I get, for example,
self.rad_lng: Location.rad_lng
other.rad_lng: -1.29154947064
What am I doing wrong?
A: You can't really use the math module that way:
>>> c = toyschema.Contact()
>>> c.lat = 10
>>> c.lat
10
>>> import math
>>> math.cos(c.lat)
-0.83907152907645244
>>> math.cos(toyschema.Contact.lat)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: a float is required
You'll have combine sqalchemy.func.* in place of math.* in a @great_circle_distance.expression method for all of that kind of cleverness. Unfortunately, you can't do that with sqlite, either; it doesn't provide trig functions
You could use PostgreSQL, which does, or you can try to add these functions to sqlite yourself:
EDIT It's actually not to hard to add functions to sqlite: This is NOT tested.
Have to add the math functions to sqlite:
engine = sqlalchemy.create_engine("sqlite:///:memory:/")
raw_con = engine.raw_connection()
raw_con.create_function("cos", 1, math.cos)
raw_con.create_function("acos", 1, math.acos)
class Location(...):
...
@hybrid_method
def great_circle_distance(self, other):
"""
Tries to calculate the great circle distance between
the two locations by using the Haversine formula.
If it succeeds, it will return the Haversine formula
multiplied by 3959, which calculates the distance in miles.
If it cannot, it will return None.
"""
return math.acos( self.cos_rad_lat
* other.cos_rad_lat
* math.cos(self.rad_lng - other.rad_lng)
+ self.sin_rad_lat
* other.sin_rad_lat
) * 3959
@great_circle_distance.expression
def great_circle_distance(cls, other):
return sqlalchemy.func.acos( cls.cos_rad_lat
* other.cos_rad_lat
* sqlalchemy.func.cos(cls.rad_lng - other.rad_lng)
+ cls.sin_rad_lat
* other.sin_rad_lat
) * 3959
A: Obviously, you cannot get a float from that string.
It is because you are using "self", which, as first parameter of the call, indicates that the method is a part of the object, and not some var you may pass on.
You should try this :
def great_circle_distance(self, first, other):
"""
Tries to calculate the great circle distance between
the two locations by using the Haversine formula.
If it succeeds, it will return the Haversine formula
multiplied by 3959, which calculates the distance in miles.
If it cannot, it will return None.
"""
return math.acos( self.cos_rad_lat
* other.cos_rad_lat
* math.cos(first.rad_lng - other.rad_lng)
+ self.sin_rad_lat
* other.sin_rad_lat
) * 3959
I suppose here above that the global variables "self.cos_rad_lat" and "self.sin_rad_lat"
are initiated with correct values somewhere else in your program, probably in the "init" section of the same object.
A: It does look like you've done everything correctly, but somehow the method is not actually getting 'hybridized'. Could you have done something stupid, like not actually put the decorator on in your source code?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595050",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Merge of two select queries I want to merge these two Select queries into single query. How can i do this?
SELECT link_id, COUNT(*) FROM Loc GROUP BY link_id
SELECT Slink.[xlink:Show],Loc.[xlink:show],
Slink.[xlink:actuate],Loc.[xlink:actuate] ,
href, Sem.SemRoleDescrip
FROM Sem JOIN Loc ON
Sem.SemRoleId = Loc.SemRoleId
JOIN Slink ON Slink.link_id = Loc.link_id
A: One solution would be to
*
*add the COUNT statement as a subquery
*(LEFT) JOIN this subselect with the SLink table
*Add the LinkCount to the list of selected values.
SQL Statement
SELECT Slink.[xlink:Show]
, Loc.[xlink:show]
, Slink.[xlink:actuate]
, Loc.[xlink:actuate]
, href
, Sem.SemRoleDescrip
, SLinkCount.LinkCount
FROM Sem
JOIN Loc ON Sem.SemRoleId = Loc.SemRoleId
JOIN Slink ON Slink.link_id = Loc.link_id
LEFT JOIN (
SELECT link_id, COUNT(*) AS LinkCount
FROM Loc
GROUP BY
link_id
) SLinkCount ON SLinkCount.link_id = Slink.link_id
You might want to read up on Subqueries in the reference manual
12.2.9.8. Subqueries in the FROM Clause
Subqueries are legal in a SELECT statement's FROM clause. The actual
syntax is:
SELECT ... FROM (subquery) [AS] name ...
The [AS] name clause is mandatory, because every table in a FROM
clause must have a name. Any columns in the subquery select list must
have unique names.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595052",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How identity constraint works? Could any one suggest me how can i make 10 as increment in the below statement.
create table Student1(SID int primary key identity(0,10),SName varchar(10))
A: the syntax is IDENTITY [ (seed , increment ) ]. You need to specify both or none. The default is (1, 1)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595054",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: cursor does not change to I-bar on mouseover JTextField Initially the cursor changes to i-bar on mouseover, but after clicking a button (which basically calls setEnabled(false) and then setEnabled(true) on the JTextField) , the cursor doe not change to i-bar on mouseover JTextField.
What could be the reason? Any help or hint in right direction is most welcome.
The focus is also present in both cases.
A: Try using setEditable(true) / setEditable(false) instead of setEnabled.
Thus, the JTextField will still be focusable and its content can be copied into the clipboard, which is not possible when it is disabled. That's the reason why the I cursor is not displayed (because you cannot select the field content).
Edit (after OP comments):
I tried to reproduce what you described but it worked perfectly: I have a JTextField and 2 buttons (one enabler and one disabler); whatever the manipulations, the cursor always has the correct shape when the field is enabled.
I have tested this behavior on Windows, Java6 64 bits, with default LAF.
You should definitely post a snippet that can demonstrate the problem and also tell more about your environment.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595055",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What is the best captcha service available for JSP forms apart from ReCaptcha? I want to secure my form from spambots by using a captcha service. I have tried ReCaptcha but it generates really hard words. Is there any other captcha service available which I can use. I have tried JCaptcha but it is also not very good.
Any help?
A: I personally haven't used this service, but you can try OpenCaptcha
There is also SimpleCaptcha
Hope it helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595059",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Filtering elements from a ListBox via TextBox Hi have created a listbox which is bound to list of machines. As the number of machines may increase dramatically I need to somehow filter by name. For that reason I have provided a TextBox where users can introduce a string to filter out.
I have thought to create another list which it will bind to the view, i.e, a second list just for visualization. However, I think there must be a cleaner way to do it.
<ListBox IsSynchronizedWithCurrentItem="True" Visibility="{Binding MachinesPanelVisibility}"
ItemsSource="{Binding MachineRulesList}" SelectedIndex="{Binding ItemSelectionIndex}" />
<TextBox HorizontalAlignment="Right" Width="162" Text="Filter..." TextWrapping="Wrap" Margin="0,44,18,13" />
On the viewModel:
public class BusinessRulesWizardViewModel : INotifyPropertyChanged
{
public ObservableCollection<string> MachineRulesList
{
get { return _machineRulesList; }
set
{
_machineRulesList = value;
OnPropertyChanged("MachineRulesList");
}
}
public BusinessRulesWizardViewModel(ISystemView systemViewManager,
IEventAggregator eventAggregator)
{
_machineRulesList = new ObservableCollection<string>();
_systemViewManager.GetMachines(page, pageSize).ToList().ForEach(
item => _machineRulesList.Add(item)
);
}
A: Use can use ICollectionView interface to wrap your collection with Filter property set to a predicate that uses the text entered in the TextBox. Here is an example:
<ListBox IsSynchronizedWithCurrentItem="True" Visibility="{Binding MachinesPanelVisibility}"
ItemsSource="{Binding MachineRulesListView}"
SelectedIndex="{Binding ItemSelectionIndex}" />
<TextBox HorizontalAlignment="Right" Width="162"
Text="{Binding FilterText}"
TextWrapping="Wrap" Margin="0,44,18,13" />
-
public class BusinessRulesWizardViewModel : INotifyPropertyChanged
{
public ObservableCollection<string> MachineRulesList
{
get { return _machineRulesList; }
set
{
_machineRulesList = value;
OnPropertyChanged("MachineRulesList");
}
}
public string FilterText
{
get { return _filterText; }
set
{
_filterText= value;
OnPropertyChanged("FilterText");
MachineRulesListView.Refresh();
}
}
public ICollectionView MachineRulesListView { get; private set; }
public BusinessRulesWizardViewModel(ISystemView systemViewManager, IEventAggregator eventAggregator)
{
_machineRulesList = new ObservableCollection<string>();
MachineRulesListView = CollectionViewSource.GetDefaultView(_machineRulesList);
MachineRulesListView.Filter = new Predicate<object>(r => ((string)r).Contains(FilterText));
_systemViewManager.GetMachines(page, pageSize).ToList().ForEach(
item => _machineRulesList.Add(item)
);
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595060",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Android : Downloading files from FTP Server using SimpleFtp? I've upload some files to my ftp server using simpleftp method. Now, i'm in need to download these files from my server using Simpleftp. Is this possible to download it using simpleftp. anyone knows the answer?
A: No, simpleftp is only made for uploading
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595061",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: php stop shell exec on cancel When I cancel a PHP Script by pressing the browser's "Stop"-Button, it seems that an external binary run by exec(..) is not stopped. If the server is configured to not handle more then one script per user, that disables any user activity until the runned command is finished. How cann I tell PHP to kill the executed process when canceled?
A: In short, with an element of difficulty.
Your browser says to the server "Do this page", server then replies with what it got back when it ran the script. If the client goes away, the server usually still completes the script, irrelvant of wether the browser listens or not.
Only way I can think of is, if the server is UNIX, you can possibly do something to try and work out the PID of your running command, and if you read http://php.net/manual/en/features.connection-handling.php you can set things to happen on disconnects. Following on from that you could then having a PID run another command to kill off the command.
However, I wouldnt like to guarentee results.
A: in webpage use exec to lunch process and hold on to the returned pid.
$pid = exec($command);
later in your UI check if process ended and if needed allow user to kill process with something like:
exec("kill -9 $pid");
Since it's started by Apache, Apache should be able to kill it.
I see ajax calls to some sort of REST API, and you should take care not to allow users to kill more then the process they started.
A: $command = 'your command' . ' > /dev/null 2>&1 & echo $!';
exec($command, $output);
echo $pid = (int)$output[0];
Then when you want to kill it:
exec("kill -9 $pid");
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595074",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: what is the use of ClientId in the activemq connectionfactory class Scenario :
private readonly IConnection connection;
this.connection = connectionFactory.CreateConnection();
this.connection.ClientId = clientId;
A: The client id is used to logically identify a connection for the purposes of durable subscriptions, and can generally be ignored otherwise. Durable subscriptions allow a client to disconnect/fall over while consuming a topic, and retrieve any messages that it missed when it reconnects. To achieve this, the broker needs this client id to identify which messages are pending consumption. See http://activemq.apache.org/how-do-durable-queues-and-topics-work.html
Although if you want this sort of functionality, a better alternative exists in ActiveMQ in the form of virtual destinations.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595081",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Is there any way to detect if there's a hardware keyboard on the phone? I've seen other questions like Hardware Keyboard Event
But not seen this for Mango... is there any way to find out if the phone has a hardware keyboard?
A: Use the DeviceStatus.IsKeyboardPresent Property
DeviceStatus.IsKeyboardPresent
Indicates whether the device contains a physical hardware keyboard.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595090",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to Block outgoing calls and Text SMS I am developing an App in which I need to block the teenager from
using mobile while driving, I need to block the call and
sms. please help . any small hints and clues will do. please help me!
A: This code will block your all call (INCOMING AND OUTGOING)
import java.lang.reflect.Method;
import android.content.Context;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import com.CallLogApp.helper.BlockNumberHelper;
import com.CallLogApp.util.UDF;
import com.android.internal.telephony.ITelephony;
public class CustomPhoneStateListener extends PhoneStateListener {
//private static final String TAG = "PhoneStateChanged";
Context context;
public CustomPhoneStateListener(Context context) {
super();
this.context = context;
}
@Override
public void onCallStateChanged(int state, String outGoingNumber) {
super.onCallStateChanged(state, outGoingNumber);
switch (state) {
case TelephonyManager.CALL_STATE_IDLE:
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
endCallIfBlocked(outGoingNumber);
break;
case TelephonyManager.CALL_STATE_RINGING:
break;
default:
break;
}
}
private void endCallIfBlocked(String outGoingNumber) {
try {
// Java reflection to gain access to TelephonyManager's
// ITelephony getter
TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
Class<?> c = Class.forName(tm.getClass().getName());
Method m = c.getDeclaredMethod("getITelephony");
m.setAccessible(true);
com.android.internal.telephony.ITelephony telephonyService = (ITelephony) m.invoke(tm);
if (new BlockNumberHelper(context).isBlocked(outGoingNumber))
{
telephonyService = (ITelephony) m.invoke(tm);
telephonyService.silenceRinger();
telephonyService.endCall();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Here CALL_STATE_OFFHOOK state will call each time when your call going to connect and when you received incoming call
There is no any method that you can know weather it is incoming call or outgoing call
But you can end call which is going to connect in both scenario
A: http://code.google.com/p/krvarma-android-samples/source/browse/trunk/DetectCalls/src/com/varma/samples/detectcalls/receivers/OutgoingCallReceiver.java
A: To block outgoing calls, you need to register a PhoneStateListener like:
telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
telephonyManager.listen(new MyListener(), PhoneStateListener.LISTEN_CALL_STATE);
Then define your MyListener class like:
private class Test extends PhoneStateListener {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
super.onCallStateChanged(state, incomingNumber);
switch(state)
{
case TelephonyManager.CALL_STATE_IDLE:
break;
case TelephonyManager.CALL_STATE_OFFHOOK://this case is for outgoing call
break;
case TelephonyManager.CALL_STATE_RINGING://this case is for incoming call
break;
default:
break;
}
}
}
A: To add the answer by Dharmendra saying that:
There is no any method that you can know whether it is incoming call
or outgoing call
In fact, there is.
To distinguish incoming calls from outgoing calls, you have to listen to Intent.ACTION_NEW_OUTGOING_CALL as well.
Now:
when you see first Intent.ACTION_NEW_OUTGOING_CALL and then CALL_STATE_OFFHOOK, it's an outgoing call;
when you first see CALL_STATE_RINGING and then CALL_STATE_OFFHOOK, it's an incoming call.
At second, you could either use a PhoneStateListener or listen to TelephonyManager.ACTION_PHONE_STATE_CHANGED. From what I could see, first the intent gets received by the BroadcastReceiver, then the PhoneStateListener gets notified.
final IntentFilter theFilter = new IntentFilter();
theFilter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
theFilter.addAction(Intent.ACTION_NEW_OUTGOING_CALL);
mBroadcastReceiver = new MyBroadcastReceiver();
mService.registerReceiver(mBroadcastReceiver, theFilter);
class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
...
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595092",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: GearmanManager Installation I am new to ubuntu and am trying to install gearmanmanager for gearman.
I have downloaded gearmanmanager tar.gz from this location: https://github.com/brianlmoon/Gearma...tarball/master
While trying to install it through install.sh, I got the following error.
Error: Detecting linux distro as redhat- or debian-compatible Which
PHP library to use, pecl/gearman or PEAR::Net_Gearman? install.sh: 55:
select: not found install.sh: 57: Syntax error: "done" unexpected
Please someone guide me in right path to get rid of this error.
A: The install.sh is only for redhat and debian builds. I don't think it will work on Ubuntu. That was a contribution and I did not make it. It's not that hard to get it going yourself. You just need to put either pecl-manager.php or pear-manager.php in your path and create a config.ini file to pass to the one you are going to use.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595095",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: jqgrid post request data json My grid data read is configured for use json format.
This is the configuration
url:"devitem.json",
mtype: "POST",
datatype: "json",
ajaxGridOptions: {
type : 'post',
async : false,
error : function() { alert('Something bad happened. Stopping');},
},
jsonReader : {
root : "rows",
page : "page",
total : "total",
records : "records",
repeatitems : true,
cell : "cell",
id : "0",
userdata : "userdata",
},
The read request from client send always parameters in this format:
_search=false&nd=1317286048991&rows=25&page=1&sidx=device_id&sord=asc&totalrows=100
How I can convert it to json format ?
I have also set the postData option
postData : JSON.stringify({"dev_post_reqtype":"read","dev_post_devndx":"1","dev_post_reccount":"55"}),
It work but obiuovsly cannot be changed
I have this problem with pager. For testing after change the page number I call this function
function DEVpager_event(pgevent) {
var page = jQuery("#DEVtbl").getGridParam('page');
alert (pgevent+page) ;
// changed devndx for test only
var jdata = JSON.stringify({"dev_post_reqtype":"read","dev_post_devndx":"25","dev_post_reccount":"55"}) ;
jQuery("#DEVtbl").jqGrid('setGridParam', 'postData', jdata);
} ;
page is changed with my selection but postData don't change
thanks for help
A: If I understand correct your problem you should use serializeGridData in about the following form:
serializeGridData: function(postData) {
return JSON.stringify(postData);
}
If you need send some additional data to the server you can use additionally
postData: {
dev_post_reqtype: "read",
dev_post_devndx: "1",
dev_post_reccount: "55"
}
or
postData: {
dev_post_reqtype: "read",
dev_post_devndx: 1,
dev_post_reccount: 55
}
depend on the type of dev_post_devndx and dev_post_reccount properties which you need (string or integer).
A: The documentations of jqGrid... probably the worst I have ever seen
Try with this example:
$("#wlistt").jqGrid('navGrid','#pagerwlist',
{ add: true, edit: true, del: true },
{// settings for edit
afterShowForm:afterShowEdit,
afterSubmit:processAddEdit,
beforeSubmit:validateData,
closeAfterAdd: true,
closeAfterEdit: true
}
,{// settings for add
afterShowForm:afterShowAdd,
afterSubmit:processAddEdit,
beforeSubmit:validateData,
closeAfterAdd: true,
closeAfterEdit: true
}
,{} // settings for delete
);
}
}
function afterShowEdit(formId) {
alert('show_edit');
}
function afterShowAdd(formId) {
alert('show_add');
}
function processAddEdit(formId) {
alert('proc_add');
}
function validateData(formId) {
alert('val_dat');
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595098",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: if else nesting in stored procedures I have a stored procedure with if-else statements. i have a scenario where i need a need if else statement inside else statement. i have done this in c# but i need it in sql server since i'm pretty much new to stored procedures.
lemme provide a sample snippet for u ppl.
create procedure [dbo].[usp_getstore_details](@input varchar(100))
as
begin
declare @out varchar(100)
declare @result int
if(LEN(@input)=2)
begin
--select statement here.
end
else if (@input like '%[0-9]%')
begin
--select statement here
end
else
begin
set @result=(len(@input) - len(replace(@input, ',', '') )
if(@result>1)
begin
--select statement here
end
else
begin
--select statement here
end
end
end
Thanks in advance for ur help
A: CREATE PROCEDURE [dbo].[usp_getstore_details]
@input VARCHAR(100)
AS
BEGIN
DECLARE @out VARCHAR(100)
DECLARE @result INT
IF LEN(@input) = 2
BEGIN
--select statement here.
END
ELSE IF @input LIKE '%[0-9]%'
BEGIN
--select statement here
END
ELSE
BEGIN
SET @result = LEN(@input) - LEN(REPLACE(@input, ',', ''))
IF @result > 1
BEGIN
--select statement here
END
ELSE
BEGIN
--select statement here
END
END
END
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595100",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Applying multiple jQuery plugins I have made two jquery plugins which both work in their own right.
If I call them using:
$('input').inputShrink();
$('input').fillForm();
then the two effects work. However, if I do:
$('input').inputShrink().fillForm();
then only the first one is applied. It was my understanding you could do this, is there something in my plugins I need to set up?
A: Quote from the jQuery docs : LINK
Maintain chainability in a plugin, you must make sure your plugin returns the thiskeyword.
In short - remember to return the jQuery object in your plugin.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595102",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Transfer cookie from one domain to another on different servers
Possible Duplicate:
How do I use cookies across two different domains?
Can you please tell me what is the easiest way to transfer cookies from one domain to another on different servers?
I have a website and a forum on different servers and different domains. I've already created the bridge between them regarding users.
Thanks.
A: You could do a an Ajax call from one server to the other, and rebuilding the session on the other server.
To use cross domain you need to use JsonP. Take a look here: http://api.jquery.com/jQuery.ajax/
This way, the site does do a request as the user, so the cookie/session does exists on the other server, and therefore you can set a new one.
A: Basicly: You can't.
Actually, this constitutes two problems:
*
*The split domain issue. If you have different subdomains (i.e. blog.example.net and www.example.net) you can set the domain to example.net for the cookie. If it is entirely different domains, please refer to the solution found on How do I use cookies across two different domains?
*The split server issue. For this, you need to write your own session management which can be distributed over several servers, i.e. via a separate database server. Please refer to the php docs on this matter.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595103",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Python: Inserting characters between other characters at random points For example:
str = 'Hello world. Hello world.'
Turns into:
list = ['!','-','=','~','|']
str = 'He!l-lo wor~ld|.- H~el=lo -w!or~ld.'
A: import random
lst = ['!','-','=','~','|']
string = 'Hello world. Hello world.'
print ''.join('%s%s' % (x, random.choice(lst) if random.random() > 0.5 else '') for x in string)
A: Here's an approach that leans towards clarity, but performance-wise may not be optimal.
from random import randint
string = 'Hello world. Hello world.'
for char in ['!','-','=','~','|']:
pos = randint(0, len(string) - 1) # pick random position to insert char
string = "".join((string[:pos], char, string[pos:])) # insert char at pos
print string
Update
Taken from my answer to a related question which is essentially derived from DrTysra's answer:
from random import choice
S = 'Hello world. Hello world.'
L = ['!','-','=','~','|']
print ''.join('%s%s' % (x, choice((choice(L), ""))) for x in S)
A: Python 3 Solutions
Inspired by DrTyrsa
import random
lst = ['!','-','=','~','|']
string = 'Hello world. Hello world.'
Using f-strings:
print(''.join(f"{x}{random.choice(lst) if random.randint(0,1) else ''}" for x in string))
Using str.format()
print(''.join("{}{}".format(x, random.choice(lst) if random.randint(0,1) else '') for x in string))
I replace random() > 0.5 with randint(0,1) because I find it a bit more verbose while being shorter at the same time.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595106",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Javascript nested switch statement inside if else statement Need some help with the following javascript problem that won't resolve. I'm a novice and doing my best to find a good solution so I can complete my thesis research. The code is designed to run inside an online survey program called Qualtrics. Each var represents pipped data from question responses. I have tested these and they work fine.
One of the switch works fine outside the if-else statement. However, when combined, things don't work.
Any help much appreciated.
var storeLow = ${q://QID83/ChoiceGroup/SelectedChoices};
var storeHigh = ${q://QID82/ChoiceGroup/SelectedChoices};
var cash = 0;
if(storeLow >= 1)
{
switch(storeLow) {
case 5:
cash = 200;
break;
case 3:
case 6:
case 11:
case 12:
cash = 150;
break;
case 1:
case 2:
case 4:
case 7:
case 8:
case 9:
case 10:
case 13:
case 14:
case 15:
case 16:
cash = 100;
break;
default:
cash = 50;
break;
}
} else {
switch(storeHigh) {
case 3:
cash = 200;
break;
case 6:
case 10:
case 11:
case 15:
cash = 150;
break;
case 1:
case 2:
case 4:
case 5:
case 7:
case 8:
case 9:
case 12:
case 13:
case 14:
case 16:
cash = 100;
break;
default:
cash = 50;
break;
}
}
A: A better approach will be using a javascript object to assign Cash ranges,
instead of using ugly code with so many switch cases:
eg.
var myCashCriteria = { '15': 100 , '16' : 100, '17' : 100,'5' : 200 }
var myCash = getCash(16);
function getCash(num)
{
var numKey = num + ''; // convert num to string
if(myCashCriteria[numKey])
return myCashCriteria[numKey];
else
return 0 ; // default value
}
A: I'm going to take a wild guess here and believe that maybe one of your variables is actually carrying string values instead of integers. Try substituting:
switch(storeLow) {
...
switch(storeHigh) {
with
switch( parseInt(storeLow, 10) ) {
...
switch( parseInt(storeHigh, 10) ) {
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595107",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
}
|
Q: Generation of employee id I have form empdetails like this
EmpId:textbox Name:textbox
username:textbox Password:textbox
I need to generate empid and it start with 0001 and display it in the empid field and all other information will be entered employee and i have provided save button when the user clicks on it it should be saved in the db and next time when the user clicks on this form it should display empid as 0002 and the process continues.When the user clicks on the save button it should be saved in the db and it should display in the gridview with id and name field made it as hyperlink.
Can any1 help me on this
With Regards,
Sweety
A: If this is a single user application, you just have to make a max(id) sql to get the largest id and increase the number by one. Use a numberformatting class for the leading 0s.
If this is a multi user application (more than one user could open at the same time) you should create a new table which is made to automatically reserve the number for the time you are in this form. If you cancel the form, the number will be freed again and usable for the next opening. If you create a user, the state moves from open over reserved to used. This will prevent any doubleid errors.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595118",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to add json callback to php file? Created a javascript widget. Had problems with same origin policy. I added the callback to the php file like this:
var jsonp_url = "http://www.example.com/widget/data.php?json_callback=?";
$.getJSON(jsonp_url, function(data) {
for (var i=0;i<data.length-1; i++) {
var li = document.createElement("li");
li.setAttribute("class", "top-coupon");
var coupon_details = document.createElement("div");
coupon_details.setAttribute("class", "coupon-details");
coupon_details.innerHTML=data[i].coupon_name;
li.appendChild(coupon_details);
var image = document.createElement("img");
image.setAttribute("src", "http://static.example.com/images/logos/" + data[i].logo_image);
image.setAttribute("class","logo-image");
image.setAttribute("width","40px");
image.setAttribute("height","40px");
li.appendChild(image);
ul.appendChild(li);
}
});
widget.appendChild(ul);
Now I don't know how to add the callback to the data.php file. This is what I've tried:
while($info = mysql_fetch_array($result)){
$json = array();
$json['coupon_name'] = $info['label'] ;
$json['retailer_name'] = $info['name'] ;
$json['logo_image'] = $info['logo_image'];
$json['permalink'] = $info['permalink'];
$data[] = $json;
}
$data2 = json_encode($data);
echo $data2;
echo $_GET['json_callback'] . '(' . $data2 . ');';
A: Remove echo $data2; - currently your page generates invalid javascript
A: Javascript:
$.getJSON("http://www.example.com/widget/data.php",function(data){
// data is your JSON Object
});
PHP:
$data = array();
while($info = mysql_fetch_array($result)) $data[]=$info;
echo json_encode($data);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595120",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What back end tech to use for a 2-player, turn based, ajax web game?: Python or Java, FastCGI or app server? I'm building a web based 2 player game, client side interface will all be done in an ajax manor with html/css/javascript. I want clients to be able to initiate games and join others, chat etc, but I'm stuck on what the best way to code and communicate with the server is, I would like to use either Java or Python.
Python via FastCGI seems to be more widely accommodated for on hosting providers?
What are the advantages in this case for using a java/python web app like tomcat or django as apposed to taking the fastgci route and what combination would you recommend?
Thanks!
Chris
A: Some direct benefits of using Django instead of rolling your own
*
*Database ORM
*Templating
*User authentication
*Pluggable applications (use other people's stuff, yay!)
Also, Django can be deployed as a FCGI application.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595124",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to optimize the receive loop for thousands of messages in Erlang? In the chapter "Programming Multicore CPUs" of the Programming Erlang book, Joe Armstrong gives a nice example of parallelization of a map function:
pmap(F, L) ->
S = self(),
%% make_ref() returns a unique reference
%% we'll match on this later
Ref = erlang:make_ref(),
Pids = map(fun(I) ->
spawn(fun() -> do_f(S, Ref, F, I) end)
end, L),
%% gather the results
gather(Pids, Ref).
do_f(Parent, Ref, F, I) ->
Parent ! {self(), Ref, (catch F(I))}.
gather([Pid|T], Ref) ->
receive
{Pid, Ref, Ret} -> [Ret|gather(T, Ref)]
end;
gather([], _) ->
[].
It works nicely, but I believe there is a bottleneck in it causing it to work really slow on lists with 100,000+ elements.
When the gather() function is executed, it starts to match a first Pid from a Pids list with a message in the main process mailbox. But what if the oldest message in the mailbox is not from this very Pid? Then it tries all other messages until it finds a match. That being said, there is a certain probability, that while executing the gather() function we would have to loop through all mailbox messages to find a match with a Pid that we have taken from the Pids list. That is N * N worst case scenario for a list of size N.
I have even managed to prove the existence of this bottleneck:
gather([Pid|T], Ref) ->
receive
{Pid, Ref, Ret} -> [Ret|gather(T, Ref)];
%% Here it is:
Other -> io:format("The oldest message in the mailbox (~w) did not match with Pid ~w~n", [Other,Pid])
end;
How can I avoid this bottleneck?
A: The problem is that if you want to have a correct solution you still have to:
*
*check if a given reply comes from one of the processes you have
spawned
*ensure proper result order
Here's a solution which makes use of counters instead of lists - this eliminates necessity to traverse inbox multiple times. Matching of Ref ensures that messages we are receiving are from our children. Proper order is ensured by sorting the result with lists:keysort/2 at the very end of the pmap, which adds some overhead, but it's likely to be less than O(n^2).
-module(test).
-compile(export_all).
pmap(F, L) ->
S = self(),
% make_ref() returns a unique reference
% we'll match on this later
Ref = erlang:make_ref(),
Count = lists:foldl(fun(I, C) ->
spawn(fun() ->
do_f(C, S, Ref, F, I)
end),
C+1
end, 0, L),
% gather the results
Res = gather(0, Count, Ref),
% reorder the results
element(2, lists:unzip(lists:keysort(1, Res))).
do_f(C, Parent, Ref, F, I) ->
Parent ! {C, Ref, (catch F(I))}.
gather(C, C, _) ->
[];
gather(C, Count, Ref) ->
receive
{C, Ref, Ret} -> [{C, Ret}|gather(C+1, Count, Ref)]
end.
A: Joe's example is neat, but in practice you want a more heavyweight solution to your problem. Take a look at http://code.google.com/p/plists/source/browse/trunk/src/plists.erl for instance.
In general, there are three things you want to do:
*
*Pick a work unit which is "big enough". If the work unit is too small, you die by processing overhead. If it is too big, you die by workers being idle, especially if your work is not evenly divided by element count in the list.
*Upper bound the number of simultaneous workers. Psyeugenic proposes splitting it by schedulers, I propose splitting it by a job count limit, 100 jobs say. That is, you want to start off 100 jobs and then wait till some of those completes before you start more jobs.
*Consider screwing the order of elements if possible. It is much faster if you don't need to take the order into account. For many problems this is possible. If the order does matter, then use a dict to store the stuff in as proposed. It is faster for large-element lists.
The basic rule is that as soon as you want parallel, you rarely want a list-based representation of your data. The list has an inherent linearity to it, which you don't want. There is a talk by Guy Steele on the very subject: http://vimeo.com/6624203
A: In this case you can use dict (from pid of spawned process to index in original list) as Pids instead.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595128",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Eclipse key binding for non-commands There are many useful menu items of third-party plugins that are not Eclipse commands. I.e. Team->Update to Head from Subversion plugin, Rerun the last test from TesNG plugin and many others.
Is there a way to add key bindings for them and/or add them on the tool bar without modifying plugin.xml and source code of third-party plugins?
A: Most keys can be configured in Preferences -> General -> Keys.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595132",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: issue about Admob,Android Is there any chance to try Admob without paying a fee,all I want to display some ads in my app on Android.
Admob did ask me about my payment and local tax id and other info...
Please help and any comments are welcomed here
A: It didn't ask my payment. The local tax id field is optional but it's useful when you get payment from Admob. You don't have to pay for it if you want to be only a publisher.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595134",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: With JQuery is $(this).find(e.target) the same as $(e.target, this)
I've always thought it was until I got the above. Am I missing something?
The "input#header-login-email-input.initial-value" is not within "this".
Thanks
A: I assume e.target is the target property of an Event object, so it's a DOM element. When you call $() on a DOM element, it just wraps the element in a jQuery object and returns that, so the context parameter (this) doesn't really do anything.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595135",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Chartbeat and Google Analytics We have Chartbeat installed in our app which gives us live coverage of users coming in. However, one thing that Chartbeat lacks is the ability to display the total number of views a page has had...
So I was thinking of integrating Google Analytics. Is it fine to have both tools installed on our web app? Will this cause any significant performance impact? Any other disadvantages I should know about before proceeding?
A: There may be a slight performance impact, though its likely to be minimal.
Google Analytics, in the default configuration, only executes once per page load; Chartbeat, however, will ping the servers every so often to give a heart-beat to the user.
It's not a bad idea to include both; they're really complementary tools, and there is no conflict between them.
So, besides the widely cached ga.js, which gzipped clocks in at about 12kb, there's not much more overhead, since the 'ping' sent to Google (via __utm.gif) is so lightweight and quick.
Google Analytics is designed to minimize its performance impact, so you really lose very little by adding it.
You can minimize its performance impact by:
*
*Using the asynchronous syntax.
*Placing it at the bottom of your pages, just before </body> (though even this will provide minimal benefit, since the asynchronous syntax loads Google Analytics in a non-blocking way.)
EDIT: Also, depending on your needs, you may be able to replace ChartBeat with the new Google Analytics Real Time that was just announced.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595137",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to Play Multiple Audio Files? Though the question sounds basic and really simple to answer - but I have not found a complete answer either in any book/Forum/website.
Quick Background of My App:
I have a Dependent/Multiple UI Picker (2 UI Pickers - Lets call them P1 and P2), UITEXTVIEW and bar at bottom of the screen. in the bar I have buttons like "Play" ""Pause", "Rewind" and "Forward", every time I scroll the UIpicker P1 the value of the Picker p2 changes and accordingly the text in UITextView.
I have to embed 700 mp3 files in my application (dont be surprised about the idea of putting so many files in an app - total size of all mp3's is 49 mp, these are each 20 second file and at very low bitrate). I want to play each mp3 file with respect to the value in the Pickers.
here is the flow - > I scroll P1 -> Value in P1 Changes -> value of P2 changes -> text in TextView changes.
Its like "Chapters" in P1 and Paragraph number in P2, and actual text of paragraph in TextView.
after this I want to embed mp3 files so that so that with the respective canges in the pickers (P1 and P2) the mp3 in the "play" "pause" "Rewind" and "Forward" should also change.
My Requirement is as follows:
on changing the picker value the the mp3 file refered in the "play" button should change accordingly.
My Idea towards my requirement:
*
*For playing the mp3 files I have to put them in resources folder and refer them using NSBundle
*I might have to make NSDictionary Array for referring the names of the mp3 files
*I might have to create a method (checking the mp3 files based upon the values of pickers) that would be placed in rowdidselect section of UIPicker.
Guys - Please help me on this. your ideas, comments, Answers and suggestions all would be helpful.
Please contribute :-)
Thanks in advance :-)
A: I'd say you have a reasonable approach pretty much figured out. There's more than one way to accomplish this goal but yours is reasonable. Why not try it?
I'd just suggest one AVPlayer and load one clip at a time. Don't keep any loaded clips around after a new clip is loaded. Since you appear only to need to play one file at a time, one player will do and will release the memory as you give it a new clip to play. Since you referenced iOS and your files are small, loading them should be plenty efficient.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595138",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: pkg-config glib-2.0 error on Mac OS X I've got some C code which won't compile.
The error message when I run "make" is:
gcc -Wall -Wno-pointer-sign -g `pkg-config --cflags glib-2.0 gconf-2.0`
\ -c main.c Package glib-2.0 was not found in the pkg-config search
path. Perhaps you should add the directory containing `glib-2.0.pc' to
the PKG_CONFIG_PATH environment variable No package 'glib-2.0' found
Doing a quick search on the Mac using locate I can't see any glib-2.0 files so I'm wondering if I have to install it. And, if so, what's the best way of doing so?
A: Using the --with-internal-glib flag on the ./configure command worked for me.
A: I'll use a system like Fink. The packages are patched as necessary and dependencies are tracked automatically. It is a lot easier than the DIY way.
A: To strictly answer the '2011 question:
Installation is unlikely to proceed without package dependencies, and the easiest way to install a package is to use a package manager like Homebrew, MacPorts or Fink for Mac OS or ZYpp, Pacman or YUM for Linux. Conda is also worth a look as it is python-based and can manage projects containing code written in other languages such as R.
As your primary goal is to install gcc, brew install gcc could do the trick and will fetch dependencies such as glib and put them where it can find it later.
Assuming recent readers (novice and advanced) are trying to adapt the OP problem and answers to their own needs, here is more, along with personal contextual information:
However, as you may have experimented with different installation methods already, different installation paths may exist and available packages may not be where your current manager is normally looking for.
In my case, glib-2.0 could not be found either when installing gtk as a dependency for meson _build. However actually, I had successfully installed a more recent version of glib the usual way, but that pkg-config was unable to find.
As I was novice at the time (and still am, like with stackoverflow), and as a .pc.in Autoconf template file was giving me a hard time, I also chose to bypass the issue by entering brew install gtk in the hope that Homebrew would fetch the exact version needed of glib and install it where most convenient for the package of interest.
An alternative that was not mentioned yet was to locate any file starting with glib without any version number, install a current version of glib the usual way if needed, and add the requested file to the directory, as suggested by the error message. (I wish I had understood and tried Eric and Nathan's solution at the time).
You can add a directory by typing export PKG_CONFIG_PATH=/full/directory/path/to/yourfile, but it would be safe to consult dedicated help pages on the topic.
Comments on how to further improve my answer (form or content) are much welcome.
A: Easiest solution: install Homebrew, type brew install glib, and you should be good to go.
A: Answer for internet searching this,
In linux
sudo apt-get install libgtk2.0-dev
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595140",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: Transaction demarcation/transaction borders in Spring JMS I have a chain of 3 Spring JMS listeners A, B and C implemented on DefaultMessageListenerContainer (DMLC). All DMLCs are deployed in one Java EE application.
A and C:
*
*have a transaction manager injected (the same one),
*they both receive and send messages in transacted sessions,
*the same ConnectionFactory is injected in their DMLC (for receiving) and used for sending.
B:
*
*has no transaction manager,
*sends transactionless messages (Connection.createSession(false, AUTO_ACKNOWLEDGE)),
*has a different, non-XA ConnectionFactory
Question: are transaction borders as illustrated below, and transactions 1 and 2 are separate (ML = message listener)?
| transaction 1 | ? | no transaction | ? | transaction 2 |
(broker) --> [ML A] --> (broker) --> [ML B] --> (broker) --> [ML C] |
Or maybe transaction 1 and 2 are one, and the fact that the "ML B" is non-transactional has no effect on continuity?
Additional question: what happens to the active transaction in the places marked "?", when the message is in the broker?
I don't know how to access transaction manager logs, so I cannot really verify that.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595141",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: JBoss Seam - Dealing with large data returned from SQL I'm looking for techniques/best-practices to do deal with the way our web-based application works.
Currently when a user searches a field it can returns more than 10000 records at once which to me is a waste of bandwidth and memory.
Is there a way to limit the number of returned rows based on the numbers of rows selected to display. i.e. if on the web page user selects 100 rows per page then only return the 100 rows instead of loading all 10000 at once , then when next-page is clicked the next 100 number of rows will be loaded and so on.
UPDATE : The current implementation fetches all the data, binds it to the t:datatable and t:dataScroller for navigation between the pages.
From my reading in JFS 1.1 there is no server-side pagination provided (Correct me if i'm wrong) and to provide such mechanism i need to write custom code such as http://wiki.apache.org/myfaces/WorkingWithLargeTables
Can someone confirm is this is a good solution? Using RichFaces is not an option.
thanks
A: You should do server-side pagination using a jsf component, as an example in richfaces:
http://katzmaier.blogspot.com/2010/03/richfaces-server-side-pagination.html
A: Could you use a Paginator component to control the display of the relevant number of records?
If you need to restrict the number of rows returned this can be specified as part of your query syntax.
A: Take a look at the entityquery class. This one supports already server-side pagination and sorting. It works well with simple or richfaces datatables. Even jquery datatables on top of the plain jsf one is possible if you need some lightweight stuff.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595145",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Python - Converting Hex to INT/CHAR I am having some difficulty changing a hex to an int/char (char preferably). Via the website;
http://home2.paulschou.net/tools/xlate/ I enter the hex of C0A80026 into the hex box, in the DEC / CHAR box it correctly outputs the IP I expected it to contain.
This data is being pulled from an external database and I am not aware how it is being saved so all I have to work with is the hex string itself.
I have tried using the binascii.unhexlify function to see if I could decode it but I fear that I may not have a great enough understanding of hex to appreciate what I am doing.
Attemping to print just using an int() cast also has not produced the required results. I need some way to convert from that hex string (or one similar) to the original IP.
UPDATE: For anyone who comes across this in the future I modified the below answer slightly to provide an exact printout as an IP by using;
dec_output = str(int(hex_input[0:2], 16)) + "." + str(int(hex_input[2:4], 16)) + "." + str(int(hex_input[4:6], 16)) + "." + str(int(hex_input[6:8], 16))
A: A simple way
>>> s = 'C0A80026'
>>> map(ord, s.decode('hex'))
[192, 168, 0, 38]
>>>
if you prefer list comprehensions
>>> [ord(c) for c in s.decode('hex')]
[192, 168, 0, 38]
>>>
A: You might also need the chr function:
chr(65) => 'A'
A: >>> htext='C0A80026'
>>> [int(htext[i:i+2],16) for i in range(0,len(htext),2)]
# [192, 168, 0, 38]
A: For converting hex-string to human readable string you can escape every HEX character like this:
>>> '\x68\x65\x6c\x6c\x6f'
'hello'
from string you can easily loop to INT list:
>>> hextoint = [ord(c) for c in '\x68\x65\x6c\x6c\x6f']
>>> _
[104, 101, 108, 108, 111]
Your example:
>>> [ord(c) for c in '\xC0\xA8\x00\x26']
[192, 168, 0, 38]
A: If you want to get 4 separate numbers from this, then treat it as 4 separate numbers. You don't need binascii.
hex_input = 'C0A80026'
dec_output = [
int(hex_input[0:2], 16), int(hex_input[2:4], 16),
int(hex_input[4:6], 16), int(hex_input[6:8], 16),
]
print dec_output # [192, 168, 0, 38]
This can be generalised, but I'll leave it as an exercise for you.
A: I hope it's what you expect:
hex_val = 0x42424242 # hexadecimal value
int_val = int(hex_val) # integer value
str_val = str(int_val) # string representation of integer value
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595148",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
}
|
Q: PostgreSQL Query precedence Here in the query when i am trying to execute the OR condition before AND conditions it gives wrong result..as web_filename_username_4hr_ts_201109 also gets included..
Wrong Result Query:
SELECT tablename FROM pg_tables
WHERE schemaname = 'public'
and (tablename like 'web%_4hr_ts_%'
and tablename not like 'webs%_4hr_ts_%'
and tablename not like 'webr%_4hr_ts_%'
or tablename like '%web%summary%_4hr_ts_%'
and tablename not like 'web_filename_username%_4hr_ts_%'
)
;
But when i executed all AND before ORing it gives Correct result...
Correct Result Query:
SELECT tablename
FROM pg_tables
WHERE schemaname = 'public'
and (tablename like 'web%_4hr_ts_%'
and tablename not like 'webs%_12hr_ts_%'
and tablename not like 'webr%_4hr_ts_%'
and tablename not like 'web_filename_username%_4hr_ts_%'
or tablename like '%web%summary%_4hr_ts_%'
)
I dont know why....?????????
A: Because the way you have written it it checks in to blocks.
tablename like 'web%_4hr_ts_%'
and tablename not like 'webs%_4hr_ts_%'
and tablename not like 'webr%_4hr_ts_%'
or
tablename like '%web%summary%_4hr_ts_%'
and tablename not like 'web_filename_username%_4hr_ts_%'
now obviously tablename can not match both '%web%summary%_4hr_ts_%' and 'web_filename_username%_4hr_ts_%' so thats always going to be false.
Here is what explain says about it
Nested Loop (cost=0.00..28.55 rows=1 width=64)
Join Filter: (c.relnamespace = n.oid)
-> Seq Scan on pg_class c (cost=0.00..27.45 rows=1 width=72)
Filter: ((relkind = 'r'::"char") AND (((relname ~~ 'web%_4hr_ts_%'::text) AND (relname !~~ 'webs%_4hr_ts_%'::text) AND (relname !~~ 'webr%_4hr_ts_%'::text)) OR ((relname ~~ '%web%summary%_4hr_ts_%'::text) AND (relname !~~ 'web_filename_username%_4hr_ts_%'::text))))
-> Seq Scan on pg_namespace n (cost=0.00..1.09 rows=1 width=4)
Filter: (n.nspname = 'public'::name)
As you can see its added brackets showing that the OR is at the top level. This is why when Im using any OR with AND I always use brackets to ensure the correct evaluation order.
If your ever wondering why a statement doesn't give you what you expect just stick explain in front of it and see what its going to do.
A: Its' dependent on its order of execution, which is normally left to right.
You can over come this using brackets.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595149",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Reading text file line by line in SQL*Plus How to read a text file from Oracle SQL*plus?
If there is a way to read from a bat file and pass the variable as a single line of text file, and simultaneously called from SQL*plus sql file, this option is ok.
A: You can try to use Oracle External Tables.
For example, you have next file:
$ cat employee.dat
smith clerk 800
scott analyst 3000
adams clerk 1100
miller clerk 1300
Create external table:
create table employees (
ename varchar2(10),
title varchar2(10),
salary number(8))
organization external(
type oracle_loader default directory work_dir
access parameters (record delimited by new line fields(
ename char(10), title char(10), salary char(8)))
location ('employee.dat'))
parallel
Now you can use this file as SQL-table:
select * from employees;
A: If the list is already comma separated in the test file, then you can
probably do something as simple as this in SQL*Plus ...
get id.txt
append )
0 select * from my_table where id in (
/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595150",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.