text stringlengths 8 267k | meta dict |
|---|---|
Q: c# TempData equivalent in php I know I can explicitly set and unset a Session manually but I believe this is worth to ask. In c#, there is a dictionary called TempData which stores data until the first request. In other words, when TempData is called, it is automatically unset. For a better understanding here is an example:
Controller1.cs:
TempData["data"] = "This is a stored data";
Model1.cs:
string dst1 = TempData["data"]; // This is a stored data
string dst2 = TempData["data"]; // This string will be empty, if an exception is not raised (I can't remember well if an exception is raised)
So basically, this is just something like a session for 1 use only. Again, I know that I can set and unset explicitly in php, but still, does php has a function like this one?
A: As the others have pointed out, uses sessions to enable TempData. Here is a simple PHP implementation:
class TempData {
public static function get($offset) {
$value = $_SESSION[$offset];
unset($_SESSION[$offset]);
return $value;
}
public static function set($offset, $value) {
$_SESSION[$offset] = $value;
}
}
Test:
TempData::set("hello", "world");
var_dump($_SESSION); // array(1) { ["hello"]=> string(5) "world" }
TempData::get("hello"); // => world
var_dump($_SESSION); // array(0) { }
Unfortunately, we can not implement ArrayAccess with a static class.
A: You don't have that in PHP, but it shouldn't be too hard to implement it yourself. The actual implementation depends on your exact needs.
*
*Do you need that data across users or separated for each user?
*Do you want it to have a default expiration time?
*Do you want it just in the active request or should it persist until someone retrieves it?
*Are "misses" acceptable (see memcached) or do you want to be sure you find the data when you request it?
A: As @AVD tells, there is no such command. And I can't really see why. The thing with TempData is that it allows you to save some values / objects for a roundtrip to the server.
If you do use Sessions in your website there is no issue to not use Session to store these values. Session storage is placed on the server and the users is identified by a sessionid which is sent to the server each time.
The only performance penalty I can see is if you were to run your session storage outside your process running the http handler. Otherwise they are both in memory and should be pretty fast.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514172",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: uninitialized constant Spec::Rails (NameError) when running spec command I get the following error when trying to run a spec command on a model test.
The command is:
C:\Rspec Test\spec\models>spec bank_account_spec.rb
The error is :
c:/jruby-1.5.0/lib/ruby/gems/1.8/gems/rspec-rails-1.3.0/lib/spec/rails/matchers/
ar_be_valid.rb:2: uninitialized constant Spec::Rails (NameError)
from c:/jruby-1.5.0/lib/ruby/gems/1.8/gems/rspec-rails-1.3.0/lib/spec/ra
ils/matchers/ar_be_valid.rb:31:in require'
from c:/jruby-1.5.0/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31
:inrequire'
from C:/Rspec Test/vendor/rails/activesupport/lib/active_support/depende
ncies.rb:158:in require'
from c:/jruby-1.5.0/lib/ruby/gems/1.8/gems/rspec-rails-1.3.0/lib/spec/ra
ils/matchers.rb:2
from c:/jruby-1.5.0/lib/ruby/gems/1.8/gems/rspec-rails-1.3.0/lib/spec/ra
ils/matchers.rb:31:inrequire'
from c:/jruby-1.5.0/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31
:in require'
from C:/Rspec Test/vendor/rails/activesupport/lib/active_support/depende
ncies.rb:158:inrequire'
from c:/jruby-1.5.0/lib/ruby/gems/1.8/gems/rspec-rails-1.3.0/lib/spec/ra
ils.rb:15
... 13 levels...
from C:/jruby-1.5.0/lib/ruby/gems/1.8/gems/rspec-1.3.0/bin/spec:5
from C:/jruby-1.5.0/lib/ruby/gems/1.8/gems/rspec-1.3.0/bin/spec:22:in `l
oad'
from c:/jruby-1.5.0/bin/spec:22
I actually tried changing version to 1.3.0 in the C:\jruby-1.5.0\bin\spec file but it results in the same error.
A: This error suggests that the rspec framework is not getting loaded in the environment where this code is executing.
uninitialized constant Spec::Rails (NameError)
*
*For rspec with rails 2.x, then follow install steps https://github.com/dchelimsky/rspec/wiki/rails
*For rspec with rails 3.x, follow install steps https://github.com/rspec/rspec-rails
Rails 3 requires rspec 2 . Development of rspec-rails-2 has moved to github.com/rspec/rspec-rails.
A: Not sure if this helps any more, since the question is quite old, but I just found it through google, so this might help someone.
I too had declared my matcher using Spec::Matchers.define, out of some example found online. Apparently, this is outdated, once I changed the definition to RSpec::Matchers.define (mind the 'R' in 'RSpec'), things worked fine again.
I only got the error in debug mode and I am not using JRuby, but this might still be worth a try, and it's more correct anyway.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514176",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Zooming problem in UIScrollView I am using UIScrollView.In that scrollview I placing UIImageViews in serial order.Zooming is not working .This is my code
- (void)viewDidLoad
{
self.view.backgroundColor=[UIColor blackColor];
NSArray *imageArray=[[NSArray alloc]initWithObjects:[UIImage imageNamed:@"test1.png"],[UIImage imageNamed:@"test2.png"],[UIImage imageNamed:@"test3.png"], nil];
scrollView_=[[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width+20, self.view.frame.size.height)];
[scrollView_ setCanCancelContentTouches:NO];
scrollView_.indicatorStyle = UIScrollViewIndicatorStyleWhite;
scrollView_.clipsToBounds = NO;
scrollView_.scrollEnabled = YES;
scrollView_.pagingEnabled = YES;
scrollView_.delegate=self;
scrollView_.showsHorizontalScrollIndicator=NO;
scrollView_.showsVerticalScrollIndicator=NO;
scrollView_.contentSize = CGSizeMake([imageArray count]*self.scrollView_.frame.size.width, self.scrollView_.frame.size.height);
[scrollView_ setMaximumZoomScale:3.0];
[scrollView_ setMinimumZoomScale:1];
[scrollView_ setZoomScale:1];
[scrollView_ setBouncesZoom:YES];
[scrollView_ setBounces:YES];
for(int i=0;i<[imageArray count];i++)
{
UIImageView *imageView=[[UIImageView alloc]initWithImage:[imageArray objectAtIndex:i]];
imageView.frame=CGRectMake((i*320)+(i*20), 0, 320, 480);
[imageView_ setTag:i];
[scrollView_ addSubview:imageView];
[imageView release];
}
[self.view addSubview:scrollView_];
}
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
return [scrollView_ viewWithTag:page_];
}
- (void)scrollViewDidScroll:(UIScrollView *)_scrollView
{
CGFloat pageWidth = _scrollView.frame.size.width;
int page = floor((_scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
self.page_=page;
}
Thanks in advance..
A: Where have you set -
[self.mainScroll setZoomScale:(float)];
I guess by default this is 1. So no zoom happens...
A: Create a container view, and add imageViews into the container view,
then use the container view as zoomview.
- viewDidLoad {
// ---
self.containerView =[[[UIView alloc] init] autorelease];
self.containerView.frame = CGRectMake(0, 0, [imageArray count]*self.scrollView_.frame.size.width, self.scrollView_.frame.size.height);
[scrollView_ addSubView:self.containerView];
for(int i=0;i<[imageArray count];i++)
{
UIImageView *imageView=[[UIImageView alloc]initWithImage:[imageArray objectAtIndex:i]];
imageView.frame=CGRectMake((i*320)+(i*20), 0, 320, 480);
[imageView_ setTag:i];
[self.containerView addSubview:imageView];
[imageView release];
}
// --
}
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
return self.containerView;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514181",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Property on static resource converter not bound I have a value converter with a property I would like to bind to, but the binding never happens, i.e. the dependency property in my value converter always is null.
Background: I want to bind an enum to a combo box but have control over the text that is being displayed.
I implemented the value converter like this:
public class EnumDisplayer : DependencyObject, IValueConverter
{
public static readonly DependencyProperty LocalizerProperty =
DependencyProperty.Register(
"Localizer", typeof(ILocalizer), typeof(EnumDisplayer),
new PropertyMetadata(default(ILocalizer), OnLocalizerChanged));
public ILocalizer Localizer
{
get { return (ILocalizer) GetValue(LocalizerProperty); }
set { SetValue(LocalizerProperty, value); }
}
private static void OnLocalizerChanged(DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
// ...
}
//...
}
And I bind it like this:
<UserControl.Resources>
<Common:EnumDisplayer x:Key="companyTypes"
Localizer="{Binding CompanyTypeEnumLocalizer}" />
<!-- ... -->
</UserControl.Resources>
My class is an adapted version of the EnumDisplayer.
I fail to understand, why OnLocalizerChanged is never called. Can anyone provide some insight?
A: (Stack Team correct me if I am wrong)... ValueConverters do not automatically support in binding and there are reasons...
*
*They arent really something that the WPF framework is actively aware of, given that they dont lie on visual or logical tree.
*They are used as part of inner markup extensions. This is a merky area. Unless they implement marrkup extensions on their own, they would be bound to.
Although there are ways..
*
*Straightforward way is to use MultiBinding instead of single binding. The second binding will replace your converter's need to host a dependncy property.
*http://www.codeproject.com/KB/WPF/AttachingVirtualBranches.aspx
I hope this helps.
A: I think this may be because the ResourceDictionary in which you are creating the instance is not part of the visual tree, so it cannot find the DataContext and the Binding therefore always returns null.
You may be able to get around this by giving your UserControl an x:Name attribute and then binding using ElementName and DataContext.PropertyName:
<UserControl x:Name="Root">
<UserControl.Resouces>
<Common:EnumDisplayer x:Key="companyTypes"
Localizer="{Binding DataContext.CompanyTypeEnumLocalizer, ElementName=Root}" />
</UserControl.Resouces>
</UserControl>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514191",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: PHP extending mysqli_result I have a problem with extending the mysqli_result class.
I am trying to extend the mysqli_result class with a custom class.
Here is my code:
class mysqli_result_extended extends mysqli_result {
public function GetJSON() {
blah blah...
return $json;
}
}
$db = new mysqli('localhost','root','*****','somedb');
$sql = 'SELECT * FROM students';
$result = $db->query($sql);
$result->getJSON(); //This is causing the trouble
When I run the above code, it gives an error:
Call to undefined method mysqli_result::getJSON() in ****.php on line **
What's wrong with this code?
A: You're getting the error because the $db->query($sql) returns a variable of type mysqli_result and not mysqli_result_extended. The mysqli_result class doesn't have a method named getJSON.
So when you define a class B that extends class A, it doesn't mean that all instances of the base class A magically become class B.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514192",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to calculate the number of time i select a particular row in a tableview UITableViewDelegate has a method to identify which row i select in the tableView.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
But how can i know which row i have selected how many times?
A: Just create a integer int count in didSelectRowAtIndexPath: and increase the count by one whenever you select the row. Simple logic.
A: In your datamodel you can have a int variable to know how many times the data has been selected. Increment that in the method you have mentioned in your question. I hope you get the idea now. You cannot use the cell to maintain the count as they are reused.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
Get the data and indexpath.row and increment the count.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514194",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Serialize data using jQuery I'm looking to improve my jQuery code.
The piece of code is submitting data to another PHP page for processing.
At the moment I'm taking data submitted from a form, and taking data from a custom data attribute from the page.
Here's the code
// Add new comment to nit on comment.php page
$('#new_comment_form').bind('submit', function(e) {
// Prevent default
e.preventDefault();
var commentNitId = $('#left_content').attr('data-nit-id');
var commentData = 'nit_id=' + commentNitId + '&new_comment_text=' + $('textarea.new_comment').val();
$.ajax({
type: "POST",
url: "ajax/addComment.php",
data: commentData,
dataType: "json",
success: function(comment_response) {
// Code upon success
},
error: function() {
// Error
alert("Error adding comment");
}
});
});
I'm just wondering if there is a better ("neater") way to serialize the data ready to submit to the form?
Kind Regards,
Luke
A: Yes. If you supply an object (a standard Javascript object) to $.ajax as the data option, jQuery will handle the serialization for you.
$.ajax({
type: "POST",
url: "ajax/addComment.php",
data: {
nit_id: commentNitId,
new_comment_text: $('textarea.new_comment').val()
},
dataType: "json",
success: function (comment_response) {
// Code upon success
},
error: function () {
// Error
alert("Error adding comment");
}
});
If you want to what this produces, the function used internally is jQuery.param. So:
jQuery.param({
nit_id: 5,
new_comment_text: 'foobar'
});
// output: "nit_id=5&new_comment_text=foobar"
Note that this has the added bonus of escaping characters where necessary.
A: Please look at jquery serialize() and serializeArray() functions. They provide a neat way to get form data.
A: $.ajax({
dataType: 'json',
type:'post',
url: "ajax/addComment.php",
data:$(this).parents('form:first').serialize(),
success: function (comment_response) {
// Code upon success
},
error: function () {
// Error
alert("Error adding comment");
},
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514196",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: CSS3 transform an element but not its descendants I have an horizontal menu and I want to rotate 90° left or right some of its tabs.
Problem is that the transform property also rotates descendants.
It looks difficult to put them back in place, is there a solution?
P.S. I want to avoid using images or JS, they are ok as fallbacks.
A: You could apply the reverse rotation on the descendants.
For example
div.parent{
-webkit-transform: rotate(-90deg);
-moz-transform: rotate(-90deg);
}
div.parent span{
-webkit-transform: rotate(90deg);
-moz-transform: rotate(90deg);
}
Example: http://jsfiddle.net/RpcfB/1/
Fyi, you will need to play with padding and/or margin to make it all work.
EDIT
I'm afraid it's more complicated than that.
That's the truth!! Although, I as mentioned, you have to play with the css.
For example, to fix the first one, you need to make these adjustments:
*
*add a class to the first li
#nav_main_gts > li.rotate{ //ADD CLASS HERE
-moz-transform: rotate(-90deg);
-webkit-transform: rotate(-90deg);
-o-transform: rotate(-90deg);
-ms-transform: rotate(-90deg);
filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=-1);
transform: rotate(-90deg);
}
*Then change the second rule to target the next ul not li
*Then fiddle with the margin to get it all in place. Remember, because the first li is rotated, down is not left, so a negative margin-left is needed
#nav_main_gts > li.rotate ul{ //CHANGE TO UL HERE
-moz-transform: rotate(90deg);
-webkit-transform: rotate(90deg);
-o-transform: rotate(90deg);
-ms-transform: rotate(90deg);
filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=1);
transform: rotate(90deg);
margin-left:-100px; //ADD A MARGIN HERE
}
*continue with the others.
Updated example: http://jsfiddle.net/FKCTk/1/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514200",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: getting the error while creating the project in blackberry I am using the blackberry application and I am getting the error while creating the project in blackberry
Error:
InvalidRegex: Pattern value
'([a-zA-Z_]{1,63}[\s-a-zA-Z_0-9.]{0,63}[;]?)*' is not a valid regular
expression.
The reported error was:
''-' is an invalid character range. Write '-'.' at column '{2}'.
I am able to run the simulator, but not getting my application in the download folder of it.
A: Uninstall Java 7 and install JDK 1.6, then run Eclipse plugin with it. There is a bug in the latest plugin for Eclipse.
This is, in fact, not a valid regular expression. It should probably be
([a-zA-Z_]{1,63}[\s\-a-zA-Z_0-9.]{0,63}[;]?)*
This is a quote from RIM: "The problem is with Java 1.7, which the plugin doesn't currently support. You will need to use Java 1.6 32bit for development with the Eclipse plugin." (source)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514202",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Validate XML Schema in Android I need to validate some xml files in the resources of an Android application against an XML Schema. Although there is an available API to create instances of SchemaFactory, there seems to be no implementation for XML Schema, as stated by the answers to these questions: 1, 2 and 3.
Are there any good and lightweight libraries to provide that functionality in the Android platform?
A: Try Lycia. Its around 270 kb. Here is nice step by step example for schema validation. It creates a schema, a small XML referring to schema (via schemaLocation) and then an example to parse the xml with schema validation
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514204",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Easy to setup, multi-threaded server for my Django Piston API I am writing an API that reads from MySQL and Solr (which can give latencies of 150ms) to provide formatted output. I will be hosting this on a VPS, and I need to choose a web server for this application. It will be used only within localhost (and local LAN in future).
I have these concerns:
*
*Launches multiple worker threads to minimize bottlenecks with consurrent requests (Solr can take 150ms to return a request)
*Can easily respawn when a component crashes and restarting is just a matter of servd -restart
*deploying a new application is as simple as copying a folder to the www directory (or equivalent) so that new requests to this app will be served from then on.
I am not optimizing for performance for now, so I need something easy to setup. And is #3 not possible for a non-load balanced Django app?
A: Gunicorn is very simple to deploy and manage. It has no built-in reloading capability but you could easily use an external utility such as watchdog to monitor a directory and reload gunicorn using kill -HUP <pid>.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514212",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: PHP Language Converter I have a script I'm using to convert English text to other spoken languages, and I have a php code handling it like so.
ini_set("max_execution_time", "300");
header('Content-Type: text/html; charset=utf-8');
require_once('googleTranslate.class.php');
$gt = new Google_Translate_API();
$title = $gt->translate($title, "en", $lang);
$keywords = $gt->translate($keywords, "en", $lang);
$body = $gt->translate($body, "en", $lang);
Anyways, when I run this script, it times out before it can translate much text at all, so I was wondering if we could run one piece at a time somehow?
Also, note that the googleTranslate.class.php can be freely downloaded from Google Code.
Cheers
A: Hm, well I think you shoulde cache results at first. Make some script witch caches translated content for needed languages. Else you fast will reach querys limit.
A: Got it. Turns out Google Translate API wasn't the way to go. Instead, I'm using the Bing Translate service. It also doesn't restrict me to certain lengths of text. Thanks for the help. (:
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514213",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Very Basic question on Unit Testing I have a class like this -
public class MyClass : ISomeInterface
{
public MyClass(string connString)
{
// set conn string on a private member
}
// interface methods
public CreateDb(string dbName) {...}
public DropDb(string dbName) {...}
public string GetLastError() {...}
}
It is part of a legacy code and I have to write UnitTests. Now, if I want to write tests just for this class, how do I proceed such that I cover all public methods with 100% test coverage ?
Can anyone provide a small sample w.r.t the class ?
EDIT - The CreateDb and DropDb catch SqlException and sets error message. Error Message is exposed via a public interface method GetlastError()
NOTE: I am using RhinoMocks & MSTest
A: There are three methods in the class.
You have to write unit test for three methods.
For
public <Returntype> MyClass(string ConString)
{
}
There should atleast two unit test.
1) What your code does when ConString is Null or Empty. If it is null or empty then you have to catch the Exception
2) When Connection string is correct, What is last statement or confirmation you will be displaying.
More info on RhinoMocks Link
A: Assuming your class creates some real DB, you'd have two options testing this class:
*
*Let the class create and release the real DB, and have the tests assert that the DB is created as expected.
*Use a DB Mock, and have the tests assert that the calls to the mock were correct. If you want to use this option, you'd have, again, to choose:
a. Don't change your code and use Mocking Framework which supports method call interecption such as TypeMock.
b. Change your code to have a c'tor or property which takes interface of the DB (AkA Dependancy Injection), and use RhinoMocks to mock the DB interface.
Hope it helps, and maybe you could provide more details to the question, so the answer could be more detailed :-)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514215",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: error: unknown type name while compiling dbus i have a c-file containing some dbus stuff and implementing the dbus.h. this is working fine so far. now i intent to split my c-file in a c-file and a header-file. but now - the compile process failes with:
gcc -o dbus `pkg-config --cflags --libs dbus-1` dbus.c
In file included from dbus.c:1:0:
dbus.h:12:27: error: unknown type name ‘DBusMessage’
dbus.h:12:45: error: unknown type name ‘DBusConnection’
dbus.c: In function ‘dbus_send_signal’:
dbus.c:8:4: error: unknown type name ‘DBusMessage’
dbus.c:9:4: error: unknown type name ‘DBusMessageIter’
...
i just split the former c-file like this:
#include "dbus.h" // include local dbus.h
/**
* Connect to the DBUS bus and send a broadcast signal
*/
void dbus_send_signal(char* sigvalue)
{
DBusMessage* msg;
DBusMessageIter args;
DBusConnection* conn;
...
and the local-header dbus.h file:
#ifndef DBUS_H
#define DBUS_H
#include <dbus/dbus.h> // include the global dbus.h
#include <stdbool.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
void dbus_listen();
void dbus_send_signal(char *sigvalue);
...
i didn't change the code itself so i am a little bit confused. just splitting the content in a c- and h-file.
have u an idea? are the gcc parameters wrong?
A: It's just a guess, but perhaps <dbus/dbus.h> also contains
#ifndef DBUS_H
#define DBUS_H
You need to make them not the same, e.g. change your local one to
#ifndef LOCAL_DBUS_H
#define LOCAL_DBUS_H
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514217",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Problem when default page is MainPage.aspx not Default.aspx I have very strange problem. I'm using IIS 7.0 Integrated mode for my application. (pool is ASP 2.0 integrated)
It's working fine when i type www.xyz.com/MainPage.aspx. But when i used simple www.xyz.com then its not working.
I always get this error
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /intranet/default.aspx
I have mapped default document to MainPage.aspx still its not working... I don't have default.aspx page in root. only Mainpage.aspx and I can't change it...
my web.config looks like this (only part of it :):
<configuration>
<system.webServer>
<defaultDocument>
<files>
<clear />
<add value="MainPage.aspx" />
</files>
</defaultDocument>
</system.webServer>
</configuration>
A: Check you web.config and make sure the default.aspx is not listed as one the default pages. Recycle the app pool and restart IIS.
<system.webServer>
<defaultDocument>
<files>
<remove value="Default.htm"/>
<remove value="Default.asp"/>
<remove value="index.htm"/>
<remove value="index.html"/>
<remove value="default.aspx"/>
<remove value="iisstart.htm"/>
<add value="MainPage.aspx"/>
</files>
</defaultDocument>
A: You need to add MainPage.aspx as default page through IIS's document facility. You may also add a default document with IIS7 web.config.
<configuration>
<system.webServer>
<defaultDocument>
<files>
<add value="MainPage.aspx" />
</files>
</defaultDocument>
</system.webServer>
</configuration>
A: I think this setting is locked in IIS7 on applicationHost.config level. You have to change the root config gile or use IIS Administration API do complete this task.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514221",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: how to log off all users who are logged in to my site-php hi is there a way I can unset the sessions of all the users who are logged in to my site. I need this for my admin panel, wherein we might want to logout all the users loggedin while we put up the site for maintenance.
Edit: The Sessions are stored on the filesystem in the /tmp folder. Yes clearing that directory was an option but do we have any other way .
A: If you use cookie based session delete all session files in the folder where you store them.
If you store user sessions in the database, then just delete all records.
A: If you use session_set_save_handler with database set as a sessions storage, you can delete all rows from sessions table.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514228",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How may I get a DataVisualization.Charting Chart to render only the added points, for fast refresh? How may I get a Line-style DataVisualization.Charting.Chart holding many points to render only the points that have been added since the last render, in order to decrease the refresh time?
I have a real-time line Chart showing a plot of measurement values Yn against time X. On adding the first few points rendering is effectively instant, but on adding the thousandth point it is unacceptably slow (~0.5s on this 3.5GHz P4). I need fast refresh on up to 10,000 points. FastLine style is about 10x faster than Line style, but the charts requirement for markers makes this not an option.
Thanks.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514229",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Problem with reiterating BASE URL I somehow messed up my htaccess file which altered my website base URL. The htaccess file is in my public-html directory. My web site URL is supposed to be: http://voidnow.org
I was trying to redirect traffic from voidnow.org to voidnow.org/community, but, I obviously messed it up, royally.
Attempts to reach that voidnow.org on the web take everyone to the following URL:
/community/http://voidnow.org/community/http:/voidnow.org/community/http:/voidnow.org/community/http:/voidnow.org/...
(that erroneous URL reiterates for hundreds of characters.)
Can someone help me with the correct htaccess command to restore my correct URL direction in my htaccess file. I tried removing the htaccess file, and it has no effect. I tried restoring the original htaccess file, with no positive result.
Thanks in advance.
David
A: If you were using 301 redirects then try clearing browser cache & restart (browser) .. or try another browser -- modern browsers do cache permanent redirects.
Right now your site works fine for me -- no redirect at all.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514230",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Java Array and ArrayList When I try to create an ArrayList myArrayList from an array, using Arrays.asList(myArray), I am not getting the List of elements in myArray. Instead I get list of Array.
The size of myArrayList is 1 . When I try to do myArrayList.toArray(), I am getting a two dimensional array. What to do to get the elements of myArray in a list? Is iterating the only option??
A: Firstly, the asList method is the right method:
Integer[] myArray = new Integer[3];
List<Integer> myArrayList = Arrays.asList(myArray);
System.out.println(myArrayList.size()); // prints 3, as expected
The problem may be that you are calling the varargs asList method in such a way that java is interpreting your parameter as the first varargs value (and not as an array of values).
Object myArray = new Integer[3];
List<Object> myArrayList = Arrays.asList(myArray);
System.out.println(myArrayList.size()); // prints 1 - java invoked it as an array of Integer[]
To fix this problem, try casting your parameter as Object[] to force the varargs invocation, eg:
Object myArray = new Integer[3];
List<Object> myArrayList = Arrays.asList((Object[]) myArray); // Note cast here
System.out.println(myArrayList.size()); // prints 3, as desired
A: There are different ways by which you can achieve it.3 example of converting array to arraylist and arraylist to array in java might help.
A: What is the type of myArray? You cannot use Arrays.asList with an array of primitive type (such as int[]). You need to use loop in that case.
A: Would this work?
Object[] myArray = new Object[4]; //change this to whatever object you have
ArrayList<Object> list = new ArrayList<Object>();
for (Object thing : myArray) list.add(thing);
A: Try providing the generic type in the method call. The following gives me a list of 2 String elements.
String[] strings = new String[]{"1", "2"};
List<String> list = Arrays.<String>asList(strings);
System.out.println(list.size());
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514235",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Trying to setup capifony + amazonec2 I'm following the instructions to setup capifony. Now I'm in the step 4 to setup the production server. This is my configuration file:
# deploy.rb
set :application, "MyFirm"
set :deploy_to, "/var/www/myfirm.com"
set :domain, "dev.myfirm.com"
set :scm, :gitrepoit
set :repository, "ssh://myfirm@94.147.25.115:/home/myfirm/myfirm.git"
set :user, "ec2-user"
set :domain, "ec2-46-137-123-97.eu-west-1.compute.amazonaws.com"
ssh_options[:keys] = [File.join("foo.key")]
role :web, domain
role :app, domain
role :db, domain, :primary => true
set :use_sudo, false
set :keep_releases, 3
But when I execute cap deploy:setup, though I've set the public key in the configuration file, it asks me for a password...
* executing `deploy:setup'
* executing "mkdir -p /var/www/myfirm.com /var/www/myfirm.com/
releases /var/www/myfirm.com/shared /var/www/myfirm.com/shared/app/
logs /var/www/myfirm.com/shared/web/uploads"
servers: ["ec2-46-137-123-97.eu-west-1.compute.amazonaws.com"]
Password:
Any idea?
capifony 2.1.1
A: Well.. I thought the path in ssh_options[:keys] is relative to the configuration file (deploy.rb) but actually is relative to the cap file (/var/lib/gems/1.8/bin/cap).
This is working (atfer copying foo.key in /var/lib/gems/1.8/bin/):
ssh_options[:keys] = ["foo.pem")]
absolute paths work also of course:
ssh_options[:keys] = ["/home/me/foo.pem")]
ssh_options[:keys] = [File.join(ENV["HOME"], "foo.pem")]
My last release:
# deploy.rb
set :application, "MyFirm"
set :deploy_to, "/var/www/myfirm.com"
set :domain, "dev.myfirm.com"
default_run_options[:pty] = true
set :scm, :git
set :repository, "myfirm@94.141.21.125:/home/myfirm/myfirm.git"
set :ssh_options, {:forward_agent => true}
set :user, "ec2-user"
set :domain, "ec2-41-137-132-97.eu-west-1.compute.amazonaws.com"
ssh_options[:keys] = ["foo.pem"]
role :web, domain
role :app, domain
role :db, domain, :primary => true
set :use_sudo, false
set :keep_releases, 3
set :shared_files, ["app/config/parameters.ini"]
set :shared_children, [app_path + "/logs", web_path + "/uploads", "vendor"]
set :update_vendors, true
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514242",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to edit EditText and TextView in UI simultaneously I'm implementing a simple chatting application which has a TextView for text messages and a EditText for input.
I update my TextView by following method:
private void addChatContent(String authorName, String content){
final String newLine = authorName+" : "+content+"\n";
chat_content.append(newLine);
scroll.post(new Runnable(){
@Override
public void run() {
scroll.smoothScrollTo(0, chat_content.getBottom()+5000);
}
});
}
A problem I'm facing is: when there are new incoming messages, UI thread will be busy for refreshing the TextView. It makes my EditText become lag, I can hardly edit my input.
I can not refresh the TextView with another thread, right?
So what should I do to overcome this limitation?
Could somebody give me some light? Thanks in advance.
A: Ultimately, and unfortunately, there is only one thread dedicated to the UI. If you are updating the TextView there is no way you can simultaneously have a lag-free experience with the EditText. You already know this, but I fear some people answering this question may not, so here's a reference:
The system does not create a separate thread for each instance of a
component. All components that run in the same process are
instantiated in the UI thread, and system calls to each component are
dispatched from that thread. Consequently, methods that respond to
system callbacks (such as onKeyDown() to report user actions or a
lifecycle callback method) always run in the UI thread of the process
...
When your app performs intensive work in response to user interaction,
this single thread model can yield poor performance unless you
implement your application properly. Specifically, if everything is
happening in the UI thread, performing long operations such as network
access or database queries will block the whole UI. When the thread is
blocked, no events can be dispatched, including drawing events.
...
Additionally, the Andoid UI toolkit is not thread-safe. So, you must
not manipulate your UI from a worker thread—you must do all
manipulation to your user interface from the UI thread. Thus, there
are simply two rules to Android's single thread model:
Do not block the UI thread
Do not access the Android UI toolkit from outside the UI thread
Hence, the answer is quite clear: don't do this. Why does the Textview have to be absolutely, 100% up to date, as the user is updating the EditText field? Why are you scrolling all the way to the bottom; maybe you can get away with deleting most of the contents of the TextView and, when the user scrolls, dynamically re-adding content to it?
IMO you should focus on reducing the amount of work you need to do on the TextView.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514245",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Difficulty using JAPE Grammar I have a document which contains sections such as Assessments, HPI, ROS, Vitals etc.
I want to extract notes in each section. I am using GATE for this purpose. I have made a JAPE file which will extract notes in the Assessment section. Following is the grammar,
Input: Token
Options: control=appelt debug=true
Rule: Assess
({Token.string =~"(?i)diagnose[d]?"}{Token.string=="with"} | {Token.string=~"(?i)suffering"}{Token.string=~"(?i)from"} | {Token.string=~"(?i)suffering"}{Token.string=~"(?i)with"})
(
({Token})*
):assessments
({Token.string =~"(?i)HPI"} | {Token.string =~"(?i)ROS"} | {Token.string =~"(?i)EXAM"} | {Token.string =~"(?i)VITAL[S]"} | {Token.string =~"(?i)TREATMENT[s]"} |{Token.string=~"(?i)use[d]?"}{Token.string=~"(?i)orderset[s]?"} | {Token.string=~"$"})
-->
:assessments.Assessments = {}
Now, when the assessment section is in the end of the document I can retrieve the notes properly. But if it is somewhere between two sections then this will return entire document from assessment section till the end of file.
I have tried using {Token.string=~"$"} in different ways but could not extract ONLY THE ASSESSMENT SECTION IRRESPECTIVE OF ITS PLACE IN THE DOC.
Please explain how can I achieve this using JAPE grammar.
A: That is correct since Appelt mode always prefers the longest possible overall match. Since any Token can match string =~ "$" the assessments label will grab all but the final token in the document.
I would adopt a two pass approach, using an initial gazetteer or JAPE phase to annotate the "section headings" and then another phase with only these heading annotations in its input line
Imports: { import static gate.Utils.*; }
Phase: AnnotateBetweenHeadings
Input: Heading
Options: control = appelt
Rule: TwoHeadings
({Heading.type ="assessments"}):h1
(({Heading})?):h2
-->
{
Long endOffset = end(doc);
AnnotationSet h2Annots = bindings.get("h2");
if(h2Annots != null && !h2Annots.isEmpty()) {
endOffset = start(h2Annots);
}
outputAS.add(end(bindings.get("h1")), endOffset, "Assessments", featureMap());
}
This will annotate everything between the end of the assessments heading and the start of the following heading, or the end of the document if there is no following heading.
A: Tyson Hamilton provides this alternative to annotating EOD since $ doesn't work in JAPE:
Rule: DOCMARKERS
// we need to match something even though we don't use it directly
(({Token})):doc
-->
:doc{
FeatureMap features = Factory.newFeatureMap();
features.put("rule", ruleName());
try {
outputAS.add(0L, 0L, "SOD", features);
outputAS.add(docAnnots.getDocument().getContent().size(), docAnnots.getDocument().getContent().size(), "EOD", features);
} catch (InvalidOffsetException ioe) {
throw new GateRuntimeException(ioe);
}
}
I found that EOD was only recognized in later rules by giving it some length. So I have this:
Rule: DOCMARKERS
Priority: 2
(
({Sentence}) // we need to matching something even though we don't use it directly
):doc
-->
:doc{
FeatureMap features = Factory.newFeatureMap();
features.put("rule", "DOCMARKERS");
try {
outputAS.add(0L, 0L, "SOD", features);
long docsize = docAnnots.getDocument().getContent().size();
// The only way I could get EOD to be recognized in later rules was to
// give it some length, hence the -2 and -1
outputAS.add(docsize-2, docsize-1, "EOD", features);
System.err.println("Debug: added EOD");
} catch (InvalidOffsetException ioe) {
throw new GateRuntimeException(ioe);
}
}
And then you should be able to change the end of your rule to
...| {Token.string=~"$"})
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514246",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to set the id of h:selectBooleanCheckbox dynamically? I have
<wai:collectionIter value="#{listModel.listRows}" valueVar="listRow" odd="odd" even="even" styleVar="rowStyle">
<tr class="#{rowStyle}">
<td>
<h:selectBooleanCheckbox value="#{listRow.rowSelected}" disabled="#{detailModel.readOnly}">
<c:set target="#{component}" property="id" value="#{listRow.rowData.name}"/>
</h:selectBooleanCheckbox>
</td>
<ui:insert name="columnData"/>
</tr>
</wai:collectionIter>
(where wai:collectionIter is a custom tag)
but the corresponding html code looks like
<td>
<c:set target="javax.faces.component.html.HtmlSelectBooleanCheckbox@10cd160" property="id" value="BusinessUnitNumber"></c:set><input type="checkbox" name="searchForm:j_idt100" /
</td>
I must say that c:set target="#{component}" comes from an example I found elsewhere ...
As I'm not a JSF expert and assuming that it is correct, I expected that the resulting html was something like this:
<td>
<input id="BusinessUnitNumber" type="checkbox" name="BusinessUnitNumber"
</td>
Is it completely wrong or do I miss something else?
Thank you for any help.
Francesco
A: Just use a standard JSF iterating component instead of a vague custom tag. E.g. <ui:repeat>:
<ui:repeat value="#{listModel.listRows}" var="listRow" varStatus="loop">
<tr class="#{loop.even ? 'even' : 'odd'}">
<td>
<h:selectBooleanCheckbox
id="foo"
value="#{listRow.rowSelected}"
disabled="#{detailModel.readOnly}" />
</td>
<ui:insert name="columnData"/>
</tr>
</ui:repeat>
It'll worry about uniqueness of the IDs. It will prepend the row index to the given fixed ID like follows:
<tr class="odd"><td><input type="checkbox" name="formid:repeatid:0:foo" id="formid:repeatid:0:foo" /></td></tr>
<tr class="even"><td><input type="checkbox" name="formid:repeatid:1:foo" id="formid:repeatid:1:foo" /></td></tr>
<tr class="odd"><td><input type="checkbox" name="formid:repeatid:2:foo" id="formid:repeatid:2:foo" /></td></tr>
You can make it dynamic by id="#{listRow.rowData.name}", but that's not necessary.
A: Francesco,
You try this:
<h:selectBooleanCheckbox id="#{listRow.rowData.name}" value="#{listRow.rowSelected}" disabled="#{detailModel.readOnly}" />
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514248",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: ffmpeg - compilation problem with g++ I am trying to run a program which uses ffmpeg libraries to decode a mp3 file. I am using following options for compiling the program:
g++ -c play.cpp -o play.o
g++ -o play play.o -L/usr/local/lib -lavutil -lavcodec -lavformat -lavdevice \
-lavfilter -ldl -lasound -L/usr/lib -lSDL -lpthread -lz -lswscale -lm
But while linking I am gettign following errors:
play.cpp:(.text+0x49): undefined reference to `av_dup_packet(AVPacket*)'
play.cpp:(.text+0x66): undefined reference to `av_malloc(unsigned int)'
play.cpp:(.text+0x324): undefined reference to `avcodec_decode_audio3(AVCodecContext*, short*, int*, AVPacket*)'
play.cpp:(.text+0x387): undefined reference to `av_free_packet(AVPacket*)'
and so on...
These reported functions are available in the libavcodec.a etc. which i have already specified with the link options.
Can anyone please tell me what could be wrong here or suggest how to approach debugging this?
A: Is this your own program, not the libav standard example? I might be wrong, but if so you probably could forget to specify extern "C" while including libav headers:
extern "C"
{
#include <avcodec.h>
#include <avformat.h>
}
This can be the problem 'coz you trying to compile sources with C++ compiler and libav (ffmpeg) is compiled using C compiler, so you must mark include headers for library as compiled by C compiler using extern C.
If you do mark includes as extern C already, please post some code chunk from your program to look at..
A: You should make sure with verbose linkin (-Wl,--verbose) that the right version of -lavcodec is chosen, and check with objdump or ldd if the symbols are truly in the library.
You might try switching the order of -l flags, these are very important; however, since play.cpp contains the references to functions in -lavcodec, the flag order already should be right.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514249",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Is there a maximum for UIScrollView contentSize? I'm developing a small iPad-app with a Ganttchart which will show Events in the last 25 hours. I have 5 zoom levels each for 1 hour, 30 min, 15 min, 5 min and 1 min. My cells are 30 pix in width. Starting with the hourly Zoomlevel i have 25 * 30 pixels = 750 width for the content (no need to scroll yet). When zooming the cell width keeps the same, there will just be more cells and I can scroll horizontally. It works perfect for the 30, 15 and 5 mins. When it comes to the 1 minute level (a width of 45000 pixels (30 * 1500), things start to go wrong. The scrollview freezes (I still can kind of scroll, but the display isn't updated).
The drawRect: has been run through (so it should have been drawn correctly). I can see a small scrollbar at the button (it even reaches the end). So I tried to wary the width and it seems that the problems starting at about 16300 pix width.
Is there a work around for this? Or any kind of solution?
I use a ScrollView with an included uiview (Ganttchartview) which drawRect: I have overloaded.
zoom in where CELL_WIDTH is 30 and the zoomLevels are 25, 50, 75, 300, 1500
-(IBAction) zoomIn:(id)sender {
self.zoomIndex++;
int width = CELL_WIDTH * [[self.zoomLevels objectAtIndex: self.zoomIndex] intValue];
self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, width, self.frame.size.height);
[self.parentView setContentSize: CGSizeMake(self.frame.size.width, self.frame.size.height)];
[self setNeedsDisplay];
}
drawRect where the lines are drawn
- (void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetStrokeColorWithColor(context, [UIColor blackColor].CGColor);
CGContextSetLineWidth(context, 2.0);
int interval = [[self.zoomLevels objectAtIndex: self.zoomIndex] intValue];
int width = CELL_WIDTH;
for (int i = 0; i < interval; i++) {
CGContextMoveToPoint(context, width * (i +1), START_AT);
CGContextAddLineToPoint(context, width * (i +1), rect.size.height);
CGContextStrokePath(context);
}
for (int i = 0; i < NUMBER_OF_ROWS; i++) {
CGContextMoveToPoint(context, 0, START_AT + i * CELL_WIDTH);
CGContextAddLineToPoint(context, rect.size.width, START_AT + i * CELL_WIDTH);
CGContextStrokePath(context);
}
}
A: I would recommend for such kind of apps the usage of an infinite scroll view. This consists in a coding trick that based on a fixed (and limited) contentSize gives the user the experience of an infinite scrolling.
A good example has been demonstrated at WWDC 2011 so if you have a developer account you can download the videos (there was a section specifically dedicated to scroll views).
Or you can refer to some examples in the web.
Of course you will need to refactor your code in such way that only needed content is loaded and not the whole content which could fill the available memory.
A: As far as I know there is no maximum for contentSize it's fill till you run out of memory.
Consider it as a bucket where you can fill water but only till if overflows. So is the case here...
So it's advisable to use UITableView as it has better in-built memory management.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514251",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: How to change image boarder to circle I have to use Image as Notification.For that Image boarder should be in elliptical shape.can any one help me to change my image boarder as a circle.
I have mentioned an sample image 10 should be an image component.how can i get circle shape for it.
Thanks in advance.
Yours Rakesh
A: const
BORDER = 3;
Var
Bmp : TBitmap;
w, h: Integer;
x, y: Integer;
begin
Bmp:=TBitmap.Create;
try
Bmp.PixelFormat:=pf24bit;
Bmp.Canvas.Font.Name :='Arial'; // set the font to use
Bmp.Canvas.Font.Size :=20; //set the size of the font
Bmp.Canvas.Font.Color := clWhite; //set the color of the text
w :=Bmp.Canvas.TextWidth(IntToStr(sped1.Value)); //calculate the width of the image
h :=Bmp.Canvas.TextHeight(IntToStr(sped1.Value)); //calculate the height of the image
Bmp.Width := Max(w, h) + BORDER * 2; // get a square
Bmp.Height := Max(w, h) + BORDER * 2; // get a square
x := (Bmp.Width - w) div 2; // center
y := (Bmp.Height - h) div 2; // center
Bmp.Canvas.Brush.Color := clBlue; //set the background
Bmp.Canvas.FillRect(Rect(0,0, Bmp.Width, Bmp.Height)); //paint the background which is transparent
Bmp.Canvas.Brush.Color := clRed; // circle in red
Bmp.Canvas.Pen.Color := clRed; // circle in red
Bmp.Canvas.Ellipse(0, 0, Bmp.Width, Bmp.Height); // draw the circle
Bmp.Canvas.TextOut(x, y, IntToStr(sped1.Value)); //draw the number
img1.Picture.Assign(bmp); // assign the bmp to the image ; image.transparent = true, .stretch = true;
finally
Bmp.Free;
end;
Adjust the different values to what you need...
Updated source from RRUZ
A: If you are referring to a pop-up window as a Notification, you can use windows regions.
This will allow you to create a shaped window of any shape you desire.
Here is a more generic answer which includes:
procedure TForm1.DrawEllipticRegion(wnd : HWND; rect : TRect);
begin
rgn := CreateEllipticRgn(rect.left, rect.top, rect.right, rect.bottom);
SetWindowRgn(wnd, rgn, TRUE);
end;
Hope this is what you're looking for!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514256",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How do I use Error Handling Application Block for WPF Unhandled Exceptions? After I catch an unhandled exception via Application.DispatcherUnhandledException or AppDomain.CurrentDomain.UnhandledException, how should I use the Enterprise Library Error Handling Application Block to do the handling? Can anyone demonstrate some sample code, etc?
How can the end-user easily send the exception details back to developers?
Basically, I'm looking for some guidance on what best practice is after the unhandled error is caught.
A: "Enterprise Library" allows you to create exception handling policies as per the CLR Type of the error. You can use the DispatcherUnhandledException and UnhandledException types for the same.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514260",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to configure where NuGet.exe Command Tool line looks for packages We have successfully set up a couple of local package repositories using the NuGet.Server package and hosted them on a local IIS webserver. We are able to connect from the Package Manager and install no problem. So these are working fine.
In order for us not to have to check in our packages folder we have included the following command line in each project file that includes NuGet references. This works, if the NuGet.exe is in the path on the CI build agent.
However, I would like to move the source configuration form the command line in every project file and put it in just one place, preferably where other pesky developers can't change it ;)
<Target Name="BeforeBuild">
<Exec Command="nuget install $(ProjectDir)packages.config -s
http://domain:80/DataServices/Packages.svc/;
http://domain:81/DataServices/Packages.svc/
-o $(SolutionDir)packages" />
</Target>
Is there a better way?
A: I finally got NuGetPowerTools to install after the advice from digitaltrust on http://blog.davidebbo.com
Although NuGetPowerTools solved my problem, it was overkill for what I wanted. It requires that you check in to version control a .nuget folder that it creates in your solution root. The folder contains NuGet.exe, and a couple of target files. I don't like this as I think version control is for source code, not tools.
I came up with the following solution.
*
*Save NuGet.exe to a folder on your local drive, both on dev and continuous integration machines. I chose C:\tools\nuget\
*Add that filepath to the Path Environment Variable in all environments
*On continuous integration machines, find %APPDATA%\NuGet\NuGet.Config and enter the following
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageSources>
<add key="LocalRepositoryName" value="http://Domain/DataServices/Packages.svc/" />
</packageSources>
You can add more than one entry to packageSources and NuGet will search them in the order that they appear
*The after build code from my question can now be amended to the following.
<Target Name="BeforeBuild">
<Exec Command="nuget install $(ProjectDir)packages.config
-o $(SolutionDir)packages" />
</Target>
The end result of this is that whenever the approved repository location is changed, the config has to be changed in only one place rather than in every csproj file. Also, it is the continuous integration server administrators who determine that location, not the developers in their command line calls.
A: Yes there is ;-)
Take a look at NuGetPowerTools. After running Install-Package NuGetPowerTools, it adds a .nuget folder to your $(SolutionDir) containing nuget.exe, nuget msbuild targets and settings (which you will need to check in).
After that, you simply run Enable-PackageRestore and it sets up msbuild targets into your visual studio project files which will make sure that packages will be fetched in a prebuild step, even on your build server, without checking in any packages. (don't forget to check in the .nuget folder though!).
This way, you simply manage the nuget package sources in a nuget msbuild settings file (in the .nuget folder) central to your solution, instead of in each project.
Cheers,
Xavier
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514264",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: c++ serialization options I'm working in a project where I'm writing a plugin for a particular package.
This package implements a "new" method in one of its headers, and as such, I am unable to include <strstream> as it also implements "new".
The package sdk also includes a thinned out and very old version of boost, which means that I can't use the boost serialization classes. It is built on Qt for VS2008, and we are (required for this project) to be in VS2005, so I can't include Qt either.
I need to be able to get data from an externally running application, sending the data over TCPIP. What is the best way for me to serialize out the data from the source and read it back in with these limitations?
I'm currently tempted to make a struct which could contain all possible data that might be sent over, and then just copying the memory of that struct into a block of bytes which gets sent over, but this sounds like a bad approach to me.
Thanks,
Liron
A: Google Protobuf
A: boost.serialization is the way to go here. It is the most comprehensible serialization library for C++ that I know of, and it comes with support for standard containers.
A: You can extract the bytes from your data and pass it around, see a basic example.
QByteArray vectorToBin(const QVector<qint32> & vec)
{
size_t size = sizeof(qint16);
QByteArray result;
foreach(qint16 e, vec) {
for(int n = 0; n<=(size-1)*8; n+=8) {
char c = static_cast<char>((e >> n));
result.append(c);
}
}
return result;
}
QVector<qint32> binToVector(const QByteArray & bytes)
{
QVector<qint32> result;
size_t size = sizeof(qint16);
for(int i=0; i<bytes.size(); i+=size) {
qint16 e = ((bytes[i+1] & 0xff)<<8) | (bytes[i] & 0xff);
result << e;
}
return result;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514270",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I configure VIM so that files with extension .less are edited with zen-coding? How can I configure VIM so that files with extension .less are edited with zen-coding?
I can use within the zencoding notepad + + on windows normally. But now I want to use the same way inside vim.
A: ZenCoding is probably activated on a per-filetype basis, if that's the case, just type :set filetype=css.
If you want this setting to stick, add this line to your .vimrc:
autocmd BufRead,BufNewFile *.less set filetype=css
If you want to retain the normal features that go with .less files (if any) you can do :set ft=less.css but some plugins don't like that.
A: I first tried to write a comment, but found then something that could be an answer.
So I think the question is: How can I configure VIM so that files with extension .less are edited with zen-coding?
At the official site for zen-coding, there are lists of editors that support zen-coding:
*
*Official
*third-party
*Unofficial
There for VIM, the following sites are mentioned:
*
*Sparkup
*Zen Coding for VIM
I have read into both, and both seem to expand shortcuts to HTML code, not to less-code. But perhaps I have misunderstood the question.
A: I didn't know you could use Zencoding for css. I use it in Vim for html.It s great!I started using Less and I was wondering an hour ago ,If something like this existed. I guess it's something to work on.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514271",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: how to hide/show fragment defined in xml I have been trying to hide/show fragment and add another fragment.
This is xml
<FrameLayout
android:id="@+id/frag_content"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<fragment
class="com.tugce.MitsActionBar.KartvizitFragment"
android:id="@+id/frag_kartvizit"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</FrameLayout>
After calling something else and calling this fragment again, its mAdded property is false so when i tried to access getView() it is null.
I tried every edit in this post: Android Honeycomb: How to change Fragments in a FrameLayout, without re-creating them?
But still cannot manage to make it work.
A: You can add android:visibility flag to the parent layout (in this case framelayout) of the fragment inside xml and use that in your java code.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514274",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Lua create array by code I've been trying to get me a array like this:
["Some String"] = true,
["Some other string"] = true
etc
by using code.
I havn't got any clue on how to create a array. i've tried:
local tempArray
tempArray = {}
tempArray["Some String"] = true
but this doesn't work, it sais tempArray = nil.
What am I doing wrong?
A: There's nothing wrong at all in the code you've posted.
A: I've always created arrays in Lua like:
local myArray = {
["Hello"] = 'World',
["Testing"] = '123'
}
That should work, if it doesn't make sure your Lua installation is up to date and working correctly.
A: There is, of course nothing wrong in the code you posted. However, it might act oddly in an interactive environment, depending on how chunks are collected and handed to the parser.
As written, you declare a local tempArray and then apparently use it. If those lines are typed into the interactive Lua prompt which takes each line as an individual chunk, then the local created in the first line will be created and discarded. The second line will create a global variable with the same name, and the third line will use the global to set a field. You can demonstrate this like this:
C:\Users\Ross>lua
Lua 5.1.4 Copyright (C) 1994-2008 Lua.org, PUC-Rio
> local tempArray
> tempArray = {}
> tempArray["Some String"] = true
>
> table.foreach(tempArray,print)
Some String true
>
> print(type(_G.tempArray))
table
>
Here, I've demonstrated that the table tempArray exists and has exactly the one key with the value true. By printing the type of _G.tempArray I've demonstrated that a global variable was created.
By using a do ... end pair to force the interactive prompt to treat the whole block as a single chunk, we both create and use the local variable. Unfortunately after the end of the chunk, the local is now out of scope and can't be seen any more.
C:\Users\Ross>lua
Lua 5.1.4 Copyright (C) 1994-2008 Lua.org, PUC-Rio
> do
>> local tempArray
>> tempArray = {}
>> tempArray["Some String"] = true
>> end
> print(type(_G.tempArray))
nil
> table.foreach(tempArray,print)
stdin:1: bad argument #1 to 'foreach' (table expected, got nil)
stack traceback:
[C]: in function 'foreach'
stdin:1: in main chunk
[C]: ?
>
I don't know enough about WoW to speak with authority, but it is likely that locals declared in a script may have interesting issues with visibility and value persistence. If they use a significant amount of sandboxing of scripts, even globals in a script may not be visible to other scripts.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514278",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Get modifier keys, which have been pressed while starting an app / applescript I need to get a list of keys (e.g. the shift key, alt, command ...) which have been pressed when i started an app, especially an ApplesScript on Mac OS X.
A: See post #5 by StefanK at MacScripter / Tiger shiftKey detect error. He wrote a command line tool called checkModifierKeys which may be what you need. The code is posted too so you can adjust it if needed.
A: You can use the following code to detect is modifier keys are being held down using "vanilla" applescript.
on isModifierKeyPressed()
set modiferKeysDOWN to {command_down:false, option_down:false, control_down:false, shift_down:false}
if (do shell script "/usr/bin/python -c 'import Cocoa; print Cocoa.NSEvent.modifierFlags() & Cocoa.NSAlternateKeyMask '") > 1 then
set option_down of modiferKeysDOWN to true
end if
if (do shell script "/usr/bin/python -c 'import Cocoa; print Cocoa.NSEvent.modifierFlags() & Cocoa.NSCommandKeyMask '") > 1 then
set command_down of modiferKeysDOWN to true
end if
if (do shell script "/usr/bin/python -c 'import Cocoa; print Cocoa.NSEvent.modifierFlags() & Cocoa.NSShiftKeyMask '") > 1 then
set shift_down of modiferKeysDOWN to true
end if
if (do shell script "/usr/bin/python -c 'import Cocoa; print Cocoa.NSEvent.modifierFlags() & Cocoa. NSControlKeyMask '") > 1 then
set control_down of modiferKeysDOWN to true
end if
return modiferKeysDOWN
end isModifierKeyPressed
A: A shorter form of Mike Woodfill's answer:
set {shiftDown, ctrlDown, altDown, cmdDown} to words of (do shell script "python -c 'import Cocoa;m=Cocoa.NSEvent.modifierFlags();print m&Cocoa.NSShiftKeyMask>0,m&Cocoa.NSControlKeyMask>0,m&Cocoa.NSAlternateKeyMask>0,m&Cocoa.NSCommandKeyMask>0'")
Note, that you get the modifiers as strings, so you have to compare them like this if (altDown = "True") then ...
If you really want boolean modifiers, look at this code:
set mods to {}
repeat with m in words of (do shell script "python -c 'import Cocoa;m=Cocoa.NSEvent.modifierFlags();print m&Cocoa.NSShiftKeyMask,m&Cocoa.NSControlKeyMask,m&Cocoa.NSAlternateKeyMask,m&Cocoa.NSCommandKeyMask'")
set end of mods to m as number as boolean
end repeat
set {shiftDown, ctrlDown, altDown, cmdDown} to mods
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514280",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Log4j: How to configure multiple appenders: one directed to the console and a file and the other strictly to a file? For my application, I have managed to configure log4j to generate multiple logs.
Both of the appenders output to the console and to a file. But since the first log is my main log, I feel that this log should be the only log outputed to the console.
Would it be possible to disable the second log so that log4j does not use the console but still write to the file?
log4j.rootLogger=DEBUG, stdout
# stdout is set to be ConsoleAppender sending its output to System.out
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{dd MMM yyyy HH:mm:ss SSS}ms %-5p [%t] - %m%n
log4j.appender.X=org.apache.log4j.FileAppender
log4j.appender.X.File=X.log
log4j.appender.X.Append=false
log4j.appender.X.layout=org.apache.log4j.PatternLayout
log4j.appender.X.layout.ConversionPattern=%d{dd MMM yyyy HH:mm:ss SSS}ms %-5p [%t] - %m%n
log4j.logger.X=DEBUG,X
the second appender 'Y' is configured the same way as 'X' .
I was also thinking of disabling altogether the console for both appenders and use: tail -f X.log inside a shell window to view the logs but it is not very practical when working inside Eclipse.
Any tips would be greatly appreciated.
Regards,
A: The only way I know of is disabling additivity for certain loggers (categories), at the point where you direct them into one appender or the other. E.g.
log4j.logger.com.foo.bar=INFO, X
log4j.additivity.com.foo.bar=false
A: What about not outputting the root logger to stdout and instead send your X logger to both X and stdout appenders? This way your Y logger would not output to stdout as well.
log4j.logger.X=DEBUG,X,stdout
A:
Both of the appenders output to the console and to a file.
I think you are confused about the difference between a logger and an appender.
An appender only goes to one place - in your configuration you have declared a ConsoleAppender and a FileAppender. These are two separate entities. Neither of these appenders outputs to more than one location.
Loggers can be configured to send their output to zero to many appenders, and you have configured all of your loggers to send their output to the console by virtue of the rootLogger.
If you would like to have only certain loggers send output to the console, then don't configure the root logger to use the console, but only the specific logger names to do so.
If you would like to have all loggers except X send their output to the console, then you need to disable additivity for X so that it does not inherit from the root logger.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514281",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Strange session behaviour in Google Chrome for Twitter OAuth for some strange reason in Google Chrome one of my scripts is having serious problems. I'm setting up a page that requires twitter/facebook connections. Basically what you are doing is:
*
*visit page (Facebook+Twitter class are started, some session settings are being set etc)
*Click the connect button for one of the networks
*fill in your connection details
*sign up at our website (clicking submit).
Now everything works perfectly in IE/Firefox/Safari, however Chrome is doing some really crazy stuff. I would like to ask you to visit this page:
Not Important Anymore
Most likely in Firefox/IE/Safari it will just display an empty var_dump() of the $_SESSION variable. At first this is what it does in Chrome aswel, BUT! If you refresh the page once in Firefox/IE/Safari the session is still empty, but in Chrome it is showing some keys already.
I have absolutely no clue where these keys come from.. this is the content of viewsessions.php:
session_start();
echo '<pre>';
var_dump($_SESSION);
if(isset($_GET['u'])) {
unset($_SESSION);
}
As far as I know there cannot happen anything else but the above and Firefox/IE/Safari are showing the right behaviour.
It wouldn't be a big problem if everything was working fine, but al the 'requestoken_XXXX' session keys belong to the Twitter OAuth.. and because the requesttoken is refreshed on everypage the Authentication redirect to my website can not find a matching token and thus not validate the authentication.
Can anyone see what is happening? Is some page being called in the back? Is this some Chrome related issue that is known? I really don't have any clues left what this could be..
Thanks in advance.
A: Problem solved..
For some reason this file:
<IfModule mod_rewrite.c>
Options +FollowSymLinks
Options -Indexes
RewriteEngine On
RewriteBase /
# Bestaande bestanden of mappen uitsluiten
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^(.*?)$ $1 [L]
RewriteRule ^start/$ login.php [L,QSA]
RewriteRule ^logout/$ logout.php [L,QSA]
RewriteRule ^timeline/$ timeline.php [L,QSA]
RewriteRule ^(.*)$ index.php [L]
</IfModule>
Did some request to index.php (I guess...), seems a bit odd because I have stated that if it's an existing file or directory it should just open the file: RewriteRule ^(.*?)$ $1 [L] and I also flagged it as the last rule to follow.
Removing this last RewriteRule solved the problem. Still not sure why Chrome overrules the [L] parameter.. if anyone could explain it, that would be awesome.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514289",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why does InetAddress.isSiteLocalAddress() in Java source code always returns false I was checking the source file of java.net.InetAddress Class and found that few methods always return false. For example
/**
* Utility routine to check if the InetAddress is a site local address.
*
* @return a <code>boolean</code> indicating if the InetAddress is
* a site local address; or false if address is not a site local unicast address.
* @since 1.4
*/
public boolean isSiteLocalAddress() {
return false;
}
Am I missing something? Why would we need a method that always returns false? It is same for all the methods starting with 'is' in this Class. See http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/net/InetAddress.java
A: InetAddress has some subclasses that override those methods and return useful results.
Like Inet4Address: It returns true if the address is "local" according to RFC 1918. There's a line comment:
// refer to RFC 1918
// 10/8 prefix
// 172.16/12 prefix
// 192.168/16 prefix
For a context free internet address (= not IPv4 and not IPv6) it makes sense to return false because local site doesn't exist without a context.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514293",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Using QApplication with command line arguments QApplication::QApplication ( int & argc, char ** argv )
Initializes the window system and constructs an application object
with argc command line arguments in argv.
Warning: The data referred to by argc and argv must stay valid for the
entire lifetime of the QApplication object. In addition, argc must be
greater than zero and argv must contain at least one valid character
string.
From this link: http://doc.qt.io/qt-4.8/qapplication.html#QApplication
What can be the arguments to the executable file? Any examples?
I tried specifying something like:
anisha@linux-dopx:~/Desktop/notes/qt> make
g++ -c -m64 -pipe -O2 -Wall -W -D_REENTRANT -DQT_NO_DEBUG -DQT_GUI_LIB -DQT_CORE_LIB -DQT_SHARED -I../../../qtsdk-2010.05/qt/mkspecs/linux-g++-64 -I. -I../../../qtsdk-2010.05/qt/include/QtCore -I../../../qtsdk-2010.05/qt/include/QtGui -I../../../qtsdk-2010.05/qt/include -I. -I. -o widgets.o widgets.cpp
g++ -m64 -Wl,-O1 -Wl,-rpath,/home/anisha/qtsdk-2010.05/qt/lib -o qt widgets.o -L/home/anisha/qtsdk-2010.05/qt/lib -lQtGui -L/home/anisha/qtsdk-2010.05/qt/lib -L/usr/X11R6/lib64 -lQtCore -lpthread
anisha@linux-dopx:~/Desktop/notes/qt> ./qt 2 f g
anisha@linux-dopx:~/Desktop/notes/qt>
Nothing special happened, nor I knew what I was doing or what I was supposed to do.
EDIT 1: The code on which I tried the ./qt -style=windows.
#include <QtGui>
int main (int argc, char *argv[])
{
QApplication app (argc, argv);
QWidget objQWidget;
objQWidget.show ();
objQWidget.resize (320, 240);
objQWidget.setWindowTitle ("Text to be shown on the title bar\n");
// Adding a "child" widget.
QPushButton *objQPushButton = new QPushButton ("Text to be shown on the button", &objQWidget);
objQPushButton->move (100, 100);
objQPushButton->show ();
return app.exec ();
}
A: The arguments passed in the constructor are later accessible through the static method
QStringList QCoreApplication::arguments(). By this, command line arguments can be handled everywhere in your code.
A: Continue reading that documentation. The set of flags QApplication acts on is listed there.
Try for example:
./qt -style=windows
The arguments that QApplication doesn't deal with are simply left alone. The ones it does process are removed (which is why that function takes non-const arguments).
A: The suggestion about using QCoreApplication is only recommended of you have a console application. If you are using a QApplication instead, and want to access command-line arguments from inside a QWidget, you can do it with the global pointer qApp:
Here you can find the documentation from Nokia, or here from qt-project.org . In the documentation browser of Qt Creator I couldn't find it, so it is at best not that easily accessible.
so you can find:
int my_argc = qApp->arguments().count();
QString my_argv_0 = qApp->arguments.at(0);
...
and so on.
I know this question is old, but took me some time to find a way to do it from within my Main Window, so hope this helps someone else.
A: Thanks, Dissident penguin! This helped me a lot!
Just note that:
QString my_argv_0 = qApp->arguments.at(0);
should be replaced with:
QString my_argv_0 = qApp->arguments().at(0);
(note the additional () after 'arguments')
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514299",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to control conversion error with struts2 i've got a form with 3 fields, two String (one select and a text field) and an int. When i put a letter or something else than an int (52.4 or aaa) in the field i got an error that i cannot "catch", my select disapear and on the message box i ve got a message from my validation xml file (in french) and another one in english (i suppose sent by struts).
error in tomcat :
(ognl.OgnlValueStack 60 ) Error setting expression 'userSize' with value '[Ljava.lang.String;@14aa6c3'
error on message box :
Invalid field value for field "userSize".
test size
JSP code :
<s:form action="sendUserCreation" method="POST">
<s:action namespace="/" name="civilityPicklist" executeResult="true"/><br />
<s:textfield name="lastName" /><br />
<s:textfield name="userSize" /><br />
struts.xml code :
<action name="createUser">
<result>/jsp/user/create.jsp</result>
</action>
<action name="sendUserCreation" class="fr.action.UserAction" method="createUser">
<result>/jsp/splash.jsp?messKey=${messKey}</result>
<result name="input">/jsp/user/create.jsp</result>
</action>
<action name="civilityPicklist" class="fr.imaps.oxygene.portal.action.CivilityPicklistAction">
<result>/jsp/user/civilityPicklist.jsp</result>
</action>
UserAction-validation.xml code:
<validators>
<field name="userSize">
<field-validator type="conversion">
<message>test size</message>
</field-validator>
</field>
</validators>
UserAction code :
private int userSize;
public int getUserSize() {
return userSize;
}
public void setUserSize(int userSize) {
this.userSize = userSize;
}
I thought the "conversion" validation type will "catch" this kind of problem but it seems not... what's wrong with my code ?
A: I've been taking a quick look at this and I think that the reason for the double message is that, in my case at least, it looks like conversion errors may be being handled twice, firstly by the StrutsConversionErrorInterceptor and again by the AnnotationValidationInterceptor. Both these interceptors are in the struts-default stack.
Removing the StrutsConversionErrorInterceptor from the stack removes the Struts generated message and leaves the user defined message as the only error message displayed. However, I've not had time yet to investigate any other side consequences of removing this inreceptor.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514301",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How to Store Multiple Options selected by User in a Table So I want my users to be able to restrict who may contact them.
There are several factors they should be able to filter, including Age (e.g. Must be between 18 - 29), income (must earn between $25,000 - $60,000), what they're looking for (e.g. Friendship, Hang out, etc.), what drugs they do (Marijuana, Meth, Cocaine, etc), etc.
The problem is, I want them to be able to select and store multiple choices for some of the criteria (e.g. drugs), but I do not know how I should store that in the DB or how I should structure the table to best accomplish that.
For example, how would I store a user's row that for "drugs" chose "Marijuana", "Cocaine", and "Heroin" within this context? Would I simply store those as comma-separated values in the "Drugs" column? Or should I do it in a completely different way?
What would be the best way to do this (considering I will obviously have to retrieve and check this information every time a user wants to contact another user) and why?
A: No, don't store the values in CSV format in the database. Instead create a join table called user_drug and store one row for each user/drug combination:
user
id name income
1 Foo 10000
2 Bar 20000
3 Baz 30000
drug
id name
1 Marijuana
2 Cocaine
3 Heroin
user_drug
user_id drug_id
1 1
1 2
2 1
2 3
3 3
A: A DB column (at least theorethically) should NOT hold multiple values. Unfortunately, there are some programmers that store multiple values in a single column (values separated by comma for examples) - those programmers (in most cases) destroy the concept of DB and SQL.
I suggest you to read about Database Normalization to get a start in organizing your tables. And, do your best to achieve the Codd's Third Normal Form
A: You can try with this:
criterium
------------
user_id type value
1 AGE_MIN 18
1 AGE_MAX 29
1 INCOME_MIN 25000
1 INCOME_MAX 60000
1 DRUGS Marijuana
1 DRUGS Meth
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514302",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: PHP - converting XML to array in PHP - parsing a soap xml in php and storing it in database I want to convert a soap xml response and store it in a database. Here is the XML that I have.
<ENV:Envelope xmlns:ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://example.com/soap/example">
<ENV:Body>
<ns1:GetCentresResponse>
<ExampleCentre>
<ns1:Cent>
<ID>200</ID>
<Name>example2</Name>
<Code>ex2</Code>
<Email>example2@example2.com</Email>
<Address1>example2, example2 </Address1>
<Address2>example2, example2 </Address2>
<City>example2</City>
<PostCode>111111</PostCode>
<Telephone>1111111111</Telephone>
<Location>11.11,-11.11</Location>
<URL>/example2/exam2/ex2</URL>
</ns1:Cent>
</ExampleCentre>
</ns1:GetCentresResponse>
</ENV:Body>
</ENV:Envelope>
I get this soap response from the server. I want to convert this to a array and store it in database. What should I do? I know the answer might be pretty straight forward, but hey, am a newbie :D
Would really appreciate any help I get.
Thank you in anticipation.
Regards
A: The best solution would be to use PHP's SoapClient class to do the call which will return you an object and then converting this object to an array, like so:
<?php
$client = new SoapClient("http://localhost/code/soap.wsdl");
// Soap call with HelloWorld() method
$something = $client->HelloWorld(array('option1' => 'attribute1'));
// Convert object to array
$array = (array)$something;
?>
Which you can then store in the database.
A: If you can't use SoapClient to retrieve the SOAP response in a PHP object, then use SimpleXML to parse the soap response.
For example (where $xmlstr contains the SOAP response):
$element = new SimpleXMLElement( $xmlstr );
$centerElement = $element->Body->GetCentresResponse->ExampleCentre->Cent;
$center = array(
$centerElement->ID,
$centerElement->Name,
$centerElement->Code,
$centerElement->Email,
$centerElement->Address1,
$centerElement->Address2,
$centerElement->City,
$centerElement->PostCode,
$centerElement->Telephone,
$centerElement->Location,
$centerElement->URL,
);
Now you can store $center in the database.
A: Parse SOAP response to an Array using following code:
You just have to call function with SOAP-XML. After that it will return a Plain XML, then you must convert it to an array using JSON encode-decode.
$plainXML = mungXML($soapXML);
$arrayResult = json_decode(json_encode(SimpleXML_Load_String($plainXML, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
// FUNCTION TO MUNG THE XML SO WE DO NOT HAVE TO DEAL WITH NAMESPACE
function mungXML($xml)
{
$obj = SimpleXML_Load_String($xml);
if ($obj === FALSE) return $xml;
// GET NAMESPACES, IF ANY
$nss = $obj->getNamespaces(TRUE);
if (empty($nss)) return $xml;
// CHANGE ns: INTO ns_
$nsm = array_keys($nss);
foreach ($nsm as $key)
{
// A REGULAR EXPRESSION TO MUNG THE XML
$rgx
= '#' // REGEX DELIMITER
. '(' // GROUP PATTERN 1
. '\<' // LOCATE A LEFT WICKET
. '/?' // MAYBE FOLLOWED BY A SLASH
. preg_quote($key) // THE NAMESPACE
. ')' // END GROUP PATTERN
. '(' // GROUP PATTERN 2
. ':{1}' // A COLON (EXACTLY ONE)
. ')' // END GROUP PATTERN
. '#' // REGEX DELIMITER
;
// INSERT THE UNDERSCORE INTO THE TAG NAME
$rep
= '$1' // BACKREFERENCE TO GROUP 1
. '_' // LITERAL UNDERSCORE IN PLACE OF GROUP 2
;
// PERFORM THE REPLACEMENT
$xml = preg_replace($rgx, $rep, $xml);
}
return $xml;
}
print_r($arrayResult);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514304",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Scroll through tabellayout doesn't work in Android I'm trying to make my tablelayout which is nested in a relativeview scrollable.
Tried a couple of tutorials but nothing worked. Here is the xml and my java code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:background="@color/white" android:padding="10px"
android:layout_width="fill_parent" android:layout_height="fill_parent">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/textView1"
android:paddingBottom="10dp" android:text="Mijn Rooster"
android:textSize="20sp" android:layout_alignParentTop="true"
android:layout_alignLeft="@+id/tablelayout"></TextView>
<ScrollView android:id="@+id/ScrollView01"
android:layout_width="wrap_content" android:layout_height="wrap_content">
<TableLayout android:id="@+id/tablelayout"
android:layout_width=
"fill_parent" android:layout_height="wrap_content"
android:stretchColumns="0" android:layout_below="@+id/textView1"
android:layout_above="@+id/btnsearch">
</TableLayout>
</ScrollView>
<Button android:id="@+id/btnsearch" android:layout_width="wrap_content"
android:text="Zoek op Datum" android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"></Button>
</RelativeLayout>
And here is the JAVA code:
TableLayout tl = (TableLayout) findViewById(R.id.tablelayout);
if (date_selected == null) {
for (int i = 0; i < roostermap.size(); i++) {
TableRow trdaydatetime = new TableRow(this);
TableRow trinfo = new TableRow(this);
trdaydatetime.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
TableRow.LayoutParams rowSpanLayout = new TableRow.LayoutParams(
TableRow.LayoutParams.FILL_PARENT,
TableRow.LayoutParams.WRAP_CONTENT);
rowSpanLayout.span = 3;
TextView txtDay = new TextView(this);
TextView txtTime = new TextView(this);
TextView txtResult = new TextView(this);
// Set Text
txtDay.setText(roostermap.get(i).getDay(
roostermap.get(i).getRoster_date().getDay(),
roostermap.get(i).getRoster_date())
+ " " + df.format(roostermap.get(i).getRoster_date()));
txtTime.setText(dft.format(roostermap.get(i).getRoster_start())
+ " - " + dft.format(roostermap.get(i).getRoster_end()));
txtResult.setText(roostermap.get(i).getWorkplace_name());
// Day&Date Layout
txtDay.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
txtDay.setPadding(5, 5, 0, 0);
txtDay.setTextColor(Color.BLACK);
// Text Time layout
txtTime.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
txtTime.setTextColor(Color.BLACK);
txtTime.setPadding(0, 5, 10, 0);
txtTime.setGravity(Gravity.RIGHT);
// Text Result layout
txtResult.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
txtResult.setPadding(5, 0, 0, 5);
trdaydatetime.addView(txtDay);
trdaydatetime.setBackgroundResource(R.drawable.trup);
trdaydatetime.addView(txtTime);
trinfo.addView(txtResult, rowSpanLayout);
trinfo.setBackgroundResource(R.drawable.trdown);
tl.addView(trdaydatetime, new TableLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
tl.addView(trinfo, new TableLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
}
A: In order for the 'scrolling' to work you need the content of the ScrollView to be larger than the ScrollView itself. Since you have set the android:layout_height value to wrap_content, the height of the ScrollView matches the height of its content - which means no scrolling.
Fix the android:layout_height value of the ScrollView by either setting it to fill_parent (possibly with android:layout_weight) or a pixel value.
A: Eliminate the ScrollView. You cannot combine two Views which are both scrollable, especially if the scroll in the same direction.
A TableView itself handles scrolling if the content is larger then the height of the TableView.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514307",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Passing Model Between Silverlight Views Since the basic navigation mechanism in Silverlight only allows passing arguments in a querystring, when we want to pass complex data (e.g models) between our views, we use the IEventAggregator's pub\sub mechanism.
But the question is - is there a better way to pass complex information between views?
What are the cons of using the IEventAggregator for this?
A: This is why I switched to a ViewModel first approach. Views really aren't configurable nor should they really be passing ViewModels around. It made a lot more sense to me for a ViewModel to load another ViewModel like:
Show.Screen<OrderDetailsViewModel>(vm => vm.OrderId = orderId);
This is from the Build your own mvvm framework talk and is also similar to how Caliburn Micro works.
A: I can't tell you why IEventAggregator is bad, maybe it's not so intuitive? When you look at your app - you want to see what's going on and doing events with some data doesn't seem to be good. Event is event. You can share some data via Region's context in PRISM.
I'm solving same kind of issues using MEF. So, you can define something like
[Export]
public class MyModelService
{
// Code here whatever shared data you want
}
public class MyViewModel
{
// Import this shared ModelService
[Import]
public MyModelService ModelService
}
So, if you had some data in ModelService - by default MEF will compose it just once (effectively making it shared) and every time you import it inside ViewModel this instance will be there. Then you can use Events originated from ModelService to tell components when data updated, etc.
A: I'm currently using a Session idea, like in ASP.NET. I've defined a static object named SilverlightSession and add a Values property of type Dictionary. Then I just add to the values dictionary or update it and cast it
public static class SilverlightSession
{
public static Dictionary<string, object> Values { get; private set; }
}
in the app.xaml.cs startup:
SilverlightSession.Values = new Dictionary<string, object>();
Then you can have your models in "session" until the application closes.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514308",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Upload word file with cfinder integrated into ckeditor Is there a posibility to upload a file with ckfinder when integrated into ckeditor? I'm trying to upload a word document and insert the link into the text that is currently edited in ckeditor, but i can only upload images and flash files. Is there a way to browse the server and upload any files without placing another ckfinder control for the upload of non-embeddable files?
I am using it on a 2.0 asp.net page
A: Use the link dialog, it should have a browse server button if you have integrated CKFinder correctly.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514316",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to attach a submit listener to all forms without jQuery I need to attach a submit listener to every form in an iframe but I can't use jQuery.
What's the best way of doing this? I'd rather not use window.onload because that requires waiting until the images have loaded which may take time. Obviously, $(document).ready() would have been perfect, but as I said, I can't use jQuery for this.
Thanks
A: Onload will do the trick. Martin's jQuery approach will be maybe faster.
for(var i=0; i<document.forms.length; i++){
var form = document.forms[i];
form.addEventListener("submit", myListener,false);
}
A: Just roll your own :) here is the code that jQuery uses to have the ready event, take what you need, it's free (but do mention in your code where it came from ;)
bindReady: function() {
if ( readyList ) {
return;
}
readyList = jQuery._Deferred();
// Catch cases where $(document).ready() is called after the
// browser event has already occurred.
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
return setTimeout( jQuery.ready, 1 );
}
// Mozilla, Opera and webkit nightlies currently support this event
if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", jQuery.ready, false );
// If IE event model is used
} else if ( document.attachEvent ) {
// ensure firing before onload,
// maybe late but safe also for iframes
document.attachEvent( "onreadystatechange", DOMContentLoaded );
// A fallback to window.onload, that will always work
window.attachEvent( "onload", jQuery.ready );
// If IE and not a frame
// continually check to see if the document is ready
var toplevel = false;
try {
toplevel = window.frameElement == null;
} catch(e) {}
if ( document.documentElement.doScroll && toplevel ) {
doScrollCheck();
}
}
},
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514322",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Java : How to draw graphic object? I am developing a small desktop application in Netbeans. The application is complete and working fine. A small description of application is as follow:
The application is basically an object manager, where user add new object, remove old objects and connect object with each other. What i did is that i simply add 3 panel and change its type to titled border. One for Add object one for remove and one for connect.
Status:
Every thing is working fine as expected.
What Left:
In order to make UI more appealing i added a new panel at the end and called it "Object Viewer". I am planing to visualize the steps which user performs e.g
*
*If user add an object then i that pannel i will daraw a little
circle and fill it with green color
*Similarly if user remove some object then again i will draw another
cricle and fill that with red
*And when user connects two object then i will draw two circle and
connect them with a dotted line
This is my first java application, i only want to know how do i acheive this task. Some links or experience are highly appreciated
A: As for custom painting in swing, have a look here: http://download.oracle.com/javase/tutorial/uiswing/painting/
However, I'd suggest using a graph visualization library like JUNG etc. Using this you'd basically only have to define your object graph.
A: You can either do that manually with Java 2D, which I don't recommend, or, since you are using Netbeans (and I assume the Netbeans Platform, but this is not required), I would strongly suggest looking at the Netbeans Visual Library. It can do exactly what you want.
A: As Nico Huysamen said you can do that with Java 2D. But because it's your first Java application I strongly recommend to do it manually with this lybrary in order to understand how higer level lybraries work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514323",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to take screenshot programmatically on Android? I want to take a fullscreen screenshot programmatically ,
for example, one of the android home screen or a menu.
How can I get a view of the home screen in my application?
I want to take it programmatically!!!
It doesn't matter if it requires root mode!
Help me please and sorry for my English!
A: Follow the link
https://code.google.com/p/android-screenshot-library/downloads/list
it allows you entire screenshot of any screen not only your app
adb shell /system/bin/screencap -p /sdcard/img.png
this is a shell command take screenshot simple and fast
Try this
Process sh = Runtime.getRuntime().exec("su", null,null);
OutputStream os = sh.getOutputStream();
os.write(("/system/bin/screencap -p " + "/sdcard/img.png").getBytes("ASCII"));
os.flush();
os.close();
sh.waitFor();
A: Use following code
Bitmap bitmap;
View v1 = MyView.getRootView();
v1.setDrawingCacheEnabled(true);
bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
Here MyView is the View through which we need include in screen.
A: In the adb shell you can use command as
adb shell screencap -p /sdcard/screen.png
adb pull /sdcard/screen.png
adb shell rm /sdcard/screen.png
I found this code on this guide on How to take a screenshot on Android.You can refer it for more details.Hope this helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514325",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: Creating 20 objects in a loop I need some newbie help.
So basically im trying create 20 individual objects (players). Each player has a name , age and height.
Instead of writing 'Person *player = [[Person alloc] init];' Twenty times, I have made a loop.
I think the loop has worked because the [myArray count] has 20 objects.
My questions:
Are the 20 objects unique ( all with same name, age, height) ?
Whats the best way to give each object in each element of MyArray a name,age,height ?
So my end goal is to be able to do something like this:
NSLog(@"%@ is %i high and is %i years old", player1.name, player1.height, player1.age);
NSLog(@"%@ is %i high and is %i years old", player2.name, player2.height, player2.age);
etc...
I hope the above makes sense and I really appreciate your help.
#import <Foundation/Foundation.h>
#import "Person.h"
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSMutableArray *myArray = [[NSMutableArray alloc]initWithCapacity:20];
for (int i = 0; i < 20; i++)
{
Person *player = [[Person alloc] init];
player.age = 10;
player.height = 10;
player.name = @"player";
[myArray addObject:player];
[player release];
}
NSLog(@"The number of players in myArray = %i", [myArray count]); // I now have 20 players (objects) in myArray.
//How can I now give each player object an individual name, age & height ??
[pool drain];
return 0;
}
A: *
*Are the objects unique? YES, they are.
*What the best way to give each object a name,age,height? this question is not clear, so the way you gave an age, height and name to your objects in the loop is correct but of course you're providing the same info to all objects; giving them unique names depends on your application logic, for example you could assign the age randomly in this way:
player.age = arc4random()%90;
You can do the same for the height (eventually with a slightly more complicated formula, e.g. 140+arc4random()%50). Finally for the height you can assign a derived name in this way:
player.name = [NSString stringWithFormat:@"Player-%d",i];
which assigns names Player-0, Player-1, ...
*
*Finally to print-out the data in the NSLog:
NSLog(@"Player %d : name=%@ height=%d age=%d",i,player.name,player.height,player.d)
or in a different loop:
int i = 0;
for(Person *player in myArray) {
NSLog(@"Player %d : name=%@ height=%d age=%d",i,player.name,player.height,player.d);
i++;
}
A: A couple of items.
If I understand your follow up question properly, what you are looking to do is access the objects you have stored in your array so that you can change the values of their properties.
However, the above poster answered the actual question you asked, and you should mark his correct.
If you wanted to go through each item in the array you would do the following:
for (int i=0; i<[players count]; i++) {
Player *aPlayer = [players objectAtIndex:i];
aPlayer.name = @"joe";
}
If you only wanted to access a single player:
Player *aPlayer = [players objectAtIndex:4];
aPlayer.name = @"joe";
Also you may want to customize your Player class and override the description so that you don't have to repeatedly type complex NSLog statements.
-(NSString *)description{
return [NSString stringWithFormat:@"name = %@ age = %d height = %d", self.name, self.age, self.height];
}
By overriding the description method calling NSLog on your object will return the string from this statement.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514326",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to show html formatted content (without image) in a winform? I want to show html formatted string in my winform application. What control should I use?
A: If you just want "simple" HTML formatting (e.g. underline, bold, text color, etc) you could use this custom control from Oscar Londono on code project: http://www.codeproject.com/KB/edit/htmlrichtextbox.aspx
A: Use WebBrowser control to display html content in WinForms applications.
You can specify just html content:
Dim html As string = "<span>my html content</span>"
webBrowser.DocumentText = html
or specify path to the html content:
webBrowserNotes.Url = "my-html-content.html"
A: One option could be to use WebBrowser Control. Have a look at this link.
A: The webbrowser control. You can find it under common controls.
A: Using the WebBrowser Control would be a good option. But if you want to use HTML5 you would be better of looking at .NET web browser libraries such as GeckoFX
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514328",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: WARNING: builder-2.1.2 has an invalid nil value for @cert_chain How do I get rid of this warning or fix it?
gem install rails --version=3.0.10
Fetching: activesupport-3.0.10.gem (100%)
Fetching: builder-2.1.2.gem (100%)
WARNING: builder-2.1.2 has an invalid nil value for @cert_chain
Fetching: i18n-0.5.0.gem (100%)
Fetching: activemodel-3.0.10.gem (100%)
Fetching: rack-1.2.4.gem (100%)
Fetching: rack-test-0.5.7.gem (100%)
Fetching: rack-mount-0.6.14.gem (100%)
Fetching: abstract-1.0.0.gem (100%)
WARNING: abstract-1.0.0 has an invalid nil value for @cert_chain
Fetching: erubis-2.6.6.gem (100%)
Fetching: actionpack-3.0.10.gem (100%)
A: You cannot fix or get rid of this warning without submitting a patch to the gem that would fix it. I do not know what is causing it, so I cannot advise on that part.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514331",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Remove in Jquery divs with draggables and resizables i have a question:
When you make a div as draggable and resizable and later when you want remove, i need destroy draggable and resizables? The same for droppables.
Example:
$("element").draggable("destroy").resizable("destroy").remove();
or only need?:
$("element").remove();
The same for when you want replace html of a div that have elements with draggables:
$(".parent .elements").draggable("destroy").resizable("destroy").parent().html(newHtml).find(".newsElements").draggable().resizable();
or only need?:
$(".parent").html(newHtml).find(".newsElements").draggable().resizable();
Thanks.
A: $('.class')
.html('bla')
.remove();
Thats all.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514337",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Loop a XML in javascript and get values Im trying to print out the content of an xml string but can't get it to work. Anyone that can see my misstake?
XML string:
<row>
<text>Hello</text>
<value>1</value>
</row>
<row>
<text>Hello2</text>
<value>2</value>
</row>
<row>
<text>Hello3</text>
<value>3</value>
</row>
The XML is a string that is sent to showXML function.
Javascript:
function showXML(xmlText) {
var ele = document.getElementById("Content");
ele.style.display = "block";
var doc = StringtoXML(xmlText); //Coverts string to XML
var html = "";
var rows = doc.getElementsByTagName("row");
for (var i = 0; i < rows.length; i++) {
var text = rows[i].getElementsByTagName("text").nodeValue;
var value= rows[i].getElementsByTagName("value").nodeValue;
html = html + " text: " + text + " value: " +value;
}
ele.innerHTML = html;
}
function StringtoXML(text){
if (window.ActiveXObject){
var doc=new ActiveXObject('Microsoft.XMLDOM');
doc.async='false';
doc.loadXML(text);
} else {
var parser=new DOMParser();
var doc=parser.parseFromString(text,'text/xml');
}
return doc;
}
Thx for all the help!
A: Here are the correction required in your for loop
var text = rows[i].getElementsByTagName("text")[0].childNodes[0].nodeValue;
var value= rows[i].getElementsByTagName("value")[0].childNodes[0].nodeValue;
getElementsByTagName returns an array/collection.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514339",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Transaction management for call to two service methods for a single unit of action We are refactoring a legacy application. The old code did something like this in a Controller method:
*
*Call DAO1.update()
*Call DAO2.update()
We’ve placed an in between a service layer, so the above code now looks like:
*
*Call Service1.update() --> Call DAO1.update()
*Call Service2.update() --> Call DAO2.update()
Each of the above two update methods have been marked transactional (using spring transactions). Old code didn’t handle transactions that well – now, we want a user action (controller method) to map only to a single transaction. How can we achieve that using spring transactions itself?
PS:
*
*We did checked Hibernate’s Open Session in View pattern, but we
would like a solution that makes use of Spring transactions – the
above scenarios are not that common and we are worried about
performance decay in OSIV pattern.
*We can combine the two service methods above into a single method but would welcome a bit cleaner situation that won’t hinder reuse.
A:
We can combine the two service methods above into a single method but would welcome a bit cleaner situation that won’t hinder reuse.
IMHO if you are attempting to execute these two service methods as one "unit of work", then the cleanest solution is to have both of them called in a @Transactional method in the service layer.
A: If you want to keep using the @Transactional annotation, then you sure have to wrap your calls in a broader, annotated method. So, either you define business services, which may become quite boilerplate/redundant indeed, or you make your controller's handling method transactional itself (as a @Component it is a Spring-managed bean so you can use @Transactional there too), or you define a flexible, generic, callback-based template:
@Component
public class TxWorker {
@Transactional
public <T> T doInTx(Callable<T> callback) throws Exception {
return callback.call();
}
}
The drawback of the latter is that it may become a bit messy if you overuse it.
Note that you may combine the OpenSessionInView pattern and Spring-managed transactions, since the Hibernate session (or JPA entityManager) may span across many tx (see What is the difference between Transaction-scoped Persistence context and Extended Persistence context?). But its main goal is to provide lazy-loading while rendering views, so it is not exactly what you're looking for.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514349",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: C# Ado.net, Error: "There was an error parsing the query." I am writing a program in C# using Visual Studio 2010 and gets an error when retrieving data from a .sdf-file.
Here follow the code of the class retrieving data from the database:
//DataAccess.cs
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlServerCe;
/// <summary>
/// Demonstrates how to work with SqlConnection objects
/// </summary>
namespace GameDAL
{
/// <summary>
/// Serve as main database layer.
/// </summary>
///
public class DataAccess
{
SqlCeConnection conn = null;
SqlDataReader rdr = null;
// 3. Pass the connection to a command object
SqlCommand cmd = null;
string strConnection =null;
string dbfile =null;
string TABLE_NAME = "Statistics";
string conString;
/// <summary>
/// Initialise connection and connection string
/// </summary>
public DataAccess()
{
InitConnection();
}
public void InitConnection()
{
// Create a connection to the file Statistics.sdf in the program folder
MessageBox.Show("test new reflection");
dbfile = new System.IO.FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location).DirectoryName + "\\Statistics.sdf";
MessageBox.Show("test time new conn");
conn = new SqlCeConnection("datasource=" + dbfile);
MessageBox.Show("test before opening");
conn.Open();
MessageBox.Show("test before new connectionstr");
conString = Properties.Settings.Default.StatisticsConnectionString;
if (conn == null)
MessageBox.Show("warning connis null !!!!!");
}
/// <summary>
/// Returns connection to database.
/// </summary>
/// <returns></returns>
public SqlCeConnection GetConnection()
{
return conn;
}
/// <summary>
/// /// Write one row to database containing winner name ,winner score and, winner nr of cards.
/// </summary>
/// <param name="winnerName">Name of winner</param>
/// <param name="winnerScore">Score of winner</param>
/// <param name="winnerNrOfCards"></param>
public void WriteDataToDatabase(string winnerName, int winnerScore, int winnerNrOfCards )
{
// Retrieve the connection string from the settings file
// Open the connection using the connection string.
using (conn)
{
// Insert into the SqlCe table. ExecuteNonQuery is best for inserts.
using (System.Data.SqlServerCe.SqlCeCommand com = new System.Data.SqlServerCe.SqlCeCommand("INSERT INTO"+TABLE_NAME + "VALUES(@winnerName, @winnerScore, @winnerNrOfCards)", conn))
{
com.Connection = conn;
com.Parameters.AddWithValue("@winnerName", winnerName);
com.Parameters.AddWithValue("@winnerScore", winnerScore);
com.Parameters.AddWithValue("@winnerNumberOfcards", winnerNrOfCards);
com.ExecuteNonQuery();
}
}
}
/// <summary>
/// Read data from database.
/// Put data in array list with DataFromDatabase-instances, containing the stats for each game.
/// <returns>Returns arrayList with all data of database..</returns>
public List<DataFromDatabase> ReadAllDataFromDataBase()
{
string winnerName;
int winnerScore;
int winnerNrOfCards;
if (conn == null)
InitConnection();
//System.Collections.ArrayList arrayListWithStatsFromDatabase= new System.Collections.ArrayList ();
List<DataFromDatabase> dataFromDatabaseList = new List<DataFromDatabase> ();
SqlCeCommand com = new SqlCeCommand("SELECT winnerName, winnerScore, winnerNumberOfCards FROM Statistics");
MessageBox.Show("Now we inside ReadAllData and will be using conn");
if (conn == null)
MessageBox.Show("warning connis null !!!!! before using CONN");
else
MessageBox.Show("conn is " + conn);
using (conn)
{
// Read in all values in the table.
MessageBox.Show("conn OK.. comm is" + com);
//("SELECT * FROM"+ TABLE_NAME, conn);
using (com)
{
com.Connection = conn;
MessageBox.Show("Now we inside ReadAllData and will be using reader..");
SqlCeDataReader reader = com.ExecuteReader();
MessageBox.Show("Now we inside ReadAllData and..after exec reader reader..");
//Add data from each row in table of database.
while (reader.Read())
{
winnerName = reader.GetString(0);
winnerScore = reader.GetInt32(1);
winnerNrOfCards = reader.GetInt32(2);
dataFromDatabaseList.Add(new DataFromDatabase(winnerName, winnerScore, winnerNrOfCards));
}
} //end of using
} //end of using 2
return dataFromDatabaseList;
} //end of methods
} //end of class
} //end of namespace..
//Database table:
Statistics.sdf
Table name: Statistics
Columns: winnerName, winnerScore,winnerNumberOfCards
The bug occurs in this methods:
ReadAllDataFromDatabase() when executing SqlCeDataReader reader = com.ExecuteReader();
Error message: '{"There was an error parsing the query. [ Token line number = 1,Token line offset = 58,Token in error = Statistics ]"}'
Error report:
System.Windows.Markup.XamlParseException was unhandled
Message=Anropet av konstruktorn av typen BlackJack.MainWindow som matchar de angivna bindningsbegränsningarna utlöste ett undantag. radnummer 4 och radposition 76.
Source=PresentationFramework
LineNumber=4
LinePosition=76
StackTrace:
vid System.Windows.Markup.XamlReader.RewrapException(Exception e, IXamlLineInfo lineInfo, Uri baseUri)
vid System.Windows.Markup.WpfXamlLoader.Load(XamlReader xamlReader, IXamlObjectWriterFactory writerFactory, Boolean skipJournaledProperties, Object rootObject, XamlObjectWriterSettings settings, Uri baseUri)
vid System.Windows.Markup.WpfXamlLoader.LoadBaml(XamlReader xamlReader, Boolean skipJournaledProperties, Object rootObject, XamlAccessLevel accessLevel, Uri baseUri)
vid System.Windows.Markup.XamlReader.LoadBaml(Stream stream, ParserContext parserContext, Object parent, Boolean closeStream)
vid System.Windows.Application.LoadBamlStreamWithSyncInfo(Stream stream, ParserContext pc)
vid System.Windows.Application.LoadComponent(Uri resourceLocator, Boolean bSkipJournaledProperties)
vid System.Windows.Application.DoStartup()
vid System.Windows.Application.<.ctor>b__1(Object unused)
vid System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
vid MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
vid System.Windows.Threading.DispatcherOperation.InvokeImpl()
vid System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state)
vid System.Threading.ExecutionContext.runTryCode(Object userData)
vid System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
vid System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
vid System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
vid System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
vid System.Windows.Threading.DispatcherOperation.Invoke()
vid System.Windows.Threading.Dispatcher.ProcessQueue()
vid System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
vid MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
vid MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
vid System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
vid MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
vid System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
vid MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
vid MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
vid System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
vid System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
vid System.Windows.Application.RunDispatcher(Object ignore)
vid System.Windows.Application.RunInternal(Window window)
vid System.Windows.Application.Run(Window window)
vid System.Windows.Application.Run()
vid BlackJack.App.Main() i D:\Programmering\C-sharp Malmö Advancd\BlackJack3\BlackJack\BlackJack\obj\x86\Debug\App.g.cs:rad 0
vid System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
vid System.AppDomain.nExecuteAssembly(RuntimeAssembly assembly, String[] args)
vid System.Runtime.Hosting.ManifestRunner.Run(Boolean checkAptModel)
vid System.Runtime.Hosting.ManifestRunner.ExecuteAsAssembly()
vid System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext, String[] activationCustomData)
vid System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext)
vid System.Activator.CreateInstance(ActivationContext activationContext)
vid Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssemblyDebugInZone()
vid System.Threading.ThreadHelper.ThreadStart_Context(Object state)
vid System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
vid System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
vid System.Threading.ThreadHelper.ThreadStart()
InnerException: System.Data.SqlServerCe.SqlCeException
Message=There was an error parsing the query. [ Token line number = 1,Token line offset = 58,Token in error = Statistics ]
Source=SQL Server Compact ADO.NET Data Provider
HResult=-2147217900
NativeError=25501
StackTrace:
vid System.Data.SqlServerCe.SqlCeCommand.CompileQueryPlan()
vid System.Data.SqlServerCe.SqlCeCommand.ExecuteCommand(CommandBehavior behavior, String method, ResultSetOptions options)
vid System.Data.SqlServerCe.SqlCeCommand.ExecuteReader(CommandBehavior behavior)
vid System.Data.SqlServerCe.SqlCeCommand.ExecuteReader()
vid GameDAL.DataAccess.ReadAllDataFromDataBase() i D:\Programmering\C-sharp Malmö Advancd\BlackJack3\BlackJack\GameDAL\DataAccess.cs:rad 133
vid BlackJack.GameManager.ReadInDataFromDatabase() i D:\Programmering\C-sharp Malmö Advancd\BlackJack3\BlackJack\BlackJack\GameManager.cs:rad 660
vid BlackJack.MainWindow.ResetListANDGUIWithStatisticsAndReadInNewDataFromDatabase() i D:\Programmering\C-sharp Malmö Advancd\BlackJack3\BlackJack\BlackJack\MainWindow.xaml.cs:rad 94
vid BlackJack.MainWindow..ctor() i D:\Programmering\C-sharp Malmö Advancd\BlackJack3\BlackJack\BlackJack\MainWindow.xaml.cs:rad 71
InnerException:
What is the reason for this error?
A: Statistics is a reserved word, escape its name with [] notation as string TABLE_NAME = "[Statistics]".
A: You have:
string TABLE_NAME = "Statistics";
and
"INSERT INTO"+TABLE_NAME + "VAL
combine those and you get
"INSERT INTOStatisticsVAL
What you should have is:
"INSERT INTO "+TABLE_NAME + " VAL
or (better; works for keywords and names with spaces etc):
"INSERT INTO ["+TABLE_NAME + "] VAL
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514350",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: ASP.NET VB Compare 3 Date In my ASP.Net (VB Code) that I had 3 variable to store 3 different date.
how can I compare 3 variable to find the last day between 3 date ?
e.g.
date1 = '21/01/2011'
date2 = '31/12/2011'
date3 = '19/09/2011'
the result should be '31/12/2011' after comparsion
Thanks
Joe
A: You can just compare them:
Dim date1 As DateTime = #01/21/2011#
Dim date2 As DateTime = #12/31/2011#
Dim date3 As DateTime = #09/19/2011#
Dim last as DateTime = date1
If date2 > last Then
last = date2
End If
If date3 > last Then
last = date3
End If
A: This should work, with Linq library
Dim t1 As DateTime = DateTime.Parse("12/4/2011")
Dim t2 As DateTime = DateTime.Parse("12/2/2011")
Dim t3 As DateTime = DateTime.Parse("12/3/2011")
Dim dates As New List(Of DateTime)()
dates.Add(t1)
dates.Add(t2)
dates.Add(t3)
Dim latestdate As DateTime = dates.Max()
When you put it in a list you don't need worry if you have 3 dates or 300. This will always work.
A: Use DateTime.Compare method.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514356",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Why isn't my new payment method showing up on one-page-checkout in Magento? I have followed the tutorial located in the wiki:
http://www.magentocommerce.com/wiki/5_-_modules_and_development/payment/create-payment-method-module
The module is visible in the backend.
This means, the "Config->advanced->advanced", and "config->Payment Methods" tabs of the backend both function properly. After setting the module to active, I go through the checkout process on the frontend and it doesn't show up.
I have tried the module twice. One with the desired company and module names I chose, another with the default names from the wiki. Neither of them work on the frontend.
Did I miss something? Have others followed the wiki and had it work with the onepagecheckout?
I have checked my error logs but saw no error produced.
I have delayed posting my code because they are the exact same as the wiki article linked above. But I will post code if requested.
A: It turns out I needed to define a Block and create the form.phtml file corresponding to my payment module.
An example I used to get mine working is located here:
http://www.magentocommerce.com/boards/viewthread/230559/
It is apparently "known" that the wiki is incomplete, according to the author of the above post on another thread:
http://www.magentocommerce.com/boards/viewthread/230704/#t326542
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514360",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Does the delete[] operator work with dynamically allocated memory returned through a pointer? I'm wondering how the delete[] operators works with pointers returned by a function, rather then having the dynamic allocation in the same scope as the delete statement. Let's say I have a trivial function like this:
int *getArray()
{
int *returnVal = new int[3];
returnVal[0] = returnVal[1] = returnVal[2] = 0;
return returnVal;
}
Now, when I need to use that array in my code, I would do the following:
int *vals = getArray();
// use values...
delete[] vals;
However, I'm wondering, how does the C++ compiler know how big the memory block that was allocated was (and thus how many memory elements to delete from vals)? Is this a valid technique, or would I have to delete each array value individually (like in the code below)?
int *vals = getArray();
// use values...
delete vals + 2;
delete vals + 1;
delete vals;
A: You should only delete[] things obtained via new[]. In your code that's the value returned by getArray(). Deleting anything else is illegal.
However, I'm wondering, how does the C++ compiler know how big the
memory block that was allocated was.
Each implementation stores the allocated size (and the type I think) in some way.
*
*One common idea is to store the bookkeeping information (or an index
of some sort) right before the actual allocated memory.
*Another idea is to use the actual pointer as the key to a data structure that holds the required information
Of course this is overly simply explained (it's more like an explanation for C ). In C++ there is the added detail of destructors and whatnot.
A: It's completely OK to delete memory out of the new[] scope. Read more here and here is the quote in case you are lazy to check the link.
[16.14] After p = new Fred[n], how does the compiler know there are n objects to be destructed during delete[] p?
Short answer: Magic.
Long answer: The run-time system stores the number of objects, n,
somewhere where it can be retrieved if you only know the pointer, p.
There are two popular techniques that do this. Both these techniques
are in use by commercial-grade compilers, both have tradeoffs, and
neither is perfect. These techniques are:
*
*Over-allocate the array and put n just to the left of the first Fred object.
*Use an associative array with p as the key and n as the value.
A: Short answer: It works.
In fact, the only valid thing to do with a pointer obtained from new[] is to delete[] it.
The compiler will insert additional information into the memory that it obtains from the OS to allow it to keep track of how large the allocated blocks are. This information allows data that are only identified by a pointer to be correctly destructed and deallocated.
A: You do not and should not delete each element in turn. You get undefined results. When allocating memory the compiler includes housekeeping data.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514365",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: how animate an UIBarButtonItem I want to animate an UIBarButtonItem like the TheElements example project does.
I'm pretty sure I've to use the customView property but I don't want to use an image to be able to do that because I need to change titles with some Localized strings (multi language).
So is it possible to create a UIButton which looks like a UIBarButtonItem ?
A: Here is the code.
NSArray *images = [NSArray arrayWithObjects:
[UIImage imageNamed:@"image0.png"],
[UIImage imageNamed:@"image1.png"],
nil];
imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"image0.png"]];
imageView.animationImages = images;
UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
button.bounds = self.imageView.bounds;
[button addSubview:self.imageView];
[button addTarget:self action:@selector(buttonTouched:) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem * barButton = [[[UIBarButtonItem alloc] initWithCustomView: button] autorelease];
Some things to notice:
The UIButton is of zero area as it does not have its bounds set upon initialization, thus the bounds are initialized with the bounds of the UIImageView (which has its bounds initialized from the image).
The UIButton handles the action/target for the touch event. The UIBarButtonItem's action/target are not set.
To animate:
[imageView startAnimating];
A: For Swift-3.x
Create IBOutlet of UIBarButtonItem and implement didSet as follows
@IBOutlet weak var leftMenuBtn: UIBarButtonItem! {
didSet {
let icon = UIImage(named: "myCustomIcon")
let iconSize = CGRect(origin: .zero, size: icon!.size)
let iconButton = UIButton(frame: iconSize)
iconButton.setBackgroundImage(icon, for: .normal)
leftMenuBtn.customView = iconButton
iconButton.addTarget(self, action:#selector(leftMenuClicked(_:)), for: .touchUpInside)
}
}
Then Implement selector method for above created left menu button
func leftMenuClicked(_ sender: Any) {
/* Following is the code to animate ButtonView by rotation of 90 degrees,
just replace with your own custom animation. */
var transform = CGAffineTransform(rotationAngle: CGFloat(M_PI_2))
UIView.animate(withDuration: 0.5) {
self.leftMenuBtn.customView!.transform = transform
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514373",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Best practice when validating input in MATLAB When is it better to use an inputParser than assert when validating input in a MATLAB function. Or is there other, even better tools available?
A: I personally found using the inputParser unnecessarily complicated. For Matlab, there are always 3 things to check - Presence, Type and Range/Values. Sometimes you have to assign defaults. Here is some sample code, very typical of my error checking: dayofWeek is the argument, 3rd in the function. (Extra comments added.) Most of this code predates the existence of assert() in Matlab. I use asserts in my later code instead of the if ... error() constructs.
%Presence
if nargin < 3 || isempty(dayOfWeek);
dayOfWeek = '';
end
%Type
if ~ischar(dayOfWeek);
error(MsgId.ARGUMENT_E, 'dayOfWeek must be a char array.');
end
%Range
days = { 'Fri' 'Sat' 'Sun' 'Mon' 'Tue' 'Wed' 'Thu' };
%A utility function I wrote that checks the value against the first arg,
%and in this case, assigns the first element if argument is empty, or bad.
dayOfWeek = StringUtil.checkEnum(days, dayOfWeek, 'assign');
%if I'm this far, I know I have a good, valid value for dayOfWeek
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514374",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Chaining two functions () -> Task and A->Task I don't know if I am thinking in the wrong way about TPL, but I have difficulty understanding how to obtain the following:
I have two functions
Task<A> getA() { ... }
Task<B> getB(A a) { ... }
This seems to occur often: I can asyncronously get an A. And given an A, I can asynchronously get a B.
I can't figure out the correct way to chain these functions together in TPL.
Here is one attempt:
Task<B> Combined()
{
Task<A> ta = getA();
Task<Task<B>> ttb = ta.ContinueWith(a => getB(a.Result));
return ttb.ContinueWith(x => x.Result.Result);
}
The ContinueWith is where I get confused. The returned type is a "double-Task", Task<Task<B>>. This somehow just seems wrong to me.
UPDATE 2011-09-30:
By coincidence I found the extension method TaskExtensions.Unwrap that operates on a Task<Task<T>> to give a Task<T>.
So until we get C# 5.0, I can do ta.ContinueWith(a=>...).UnWrap() in situations like this where the continuation itself returns a task.
A: In case you are familiar with LINQ (and the Monad concept behind it), then below is a simple Task monad which will allow you to compose the Tasks.
Monad implementation:
public static class TaskMonad
{
public static Task<T> ToTask<T>(this T t)
{
return new Task<T>(() => t);
}
public static Task<U> SelectMany<T, U>(this Task<T> task, Func<T, Task<U>> f)
{
return new Task<U>(() =>
{
task.Start();
var t = task.Result;
var ut = f(t);
ut.Start();
return ut.Result;
});
}
public static Task<V> SelectMany<T, U, V>(this Task<T> task, Func<T, Task<U>> f, Func<T, U, V> c)
{
return new Task<V>(() =>
{
task.Start();
var t = task.Result;
var ut = f(t);
ut.Start();
var utr = ut.Result;
return c(t, utr);
});
}
}
Usage example:
public static void Main(string[] arg)
{
var result = from a in getA()
from b in getB(a)
select b;
result.Start();
Console.Write(result.Result);
}
A: While the accepted answer would probably work
Task<B> Combined()
{
Task<A> ta = getA();
Task<B> ttb = ta.ContinueWith(a => getB(a.Result)).Unwrap();
return ttb;
}
Is a much more elegant way to implement this.
A: If you are unable to use await, you can certainly use Unwrap, but it handles exceptions sub-optimally. The method I prefer is Then as described in this article. Composition becomes simple and elegant:
Task<B> Combined()
{
return getA().Then(getB);
}
For those interested in the details, I wrote a blog post a while ago about exactly this problem of composing asynchronous methods, and how monads provide an elegant solution.
A: Does your getB have to be a method which returns Task<B> rather than B?
The problem is that ContinueWith is:
public Task<TNewResult> ContinueWith<TNewResult>(
Func<Task<TResult>, TNewResult> continuationFunction,
CancellationToken cancellationToken
)
So in your case, because getB returns Task<B>, you're passing in a Func<Task<A>, Task<B>>, so TNewResult is Task<B>.
If you can change getB to just return a B given an A, that would work... or you could use:
return ta.ContinueWith(a => getB(a.Result).Result);
Then the lambda expression will be of type, Func<Task<A>, B> so ContinueWith will return a Task<B>.
EDIT: In C# 5 you could easily write:
public async Task<B> CombinedAsync()
{
A a = await getA();
B b = await getB(a);
return b;
}
... so it's "just" a matter of working out what that ends up as. I suspect it's something like this, but with error handling:
public Task<B> CombinedAsync()
{
TaskCompletionSource<B> source = new TaskCompletionSource();
getA().ContinueWith(taskA => {
A a = taskA.Result;
Task<B> taskB = getB(a);
taskB.ContinueWith(t => source.SetResult(t.Result));
});
return source.Task;
}
Does that make sense?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514375",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: C++ Programm crashes only in debugger I've trouble with my application. Every time I launch it in the debugger it crashes when adding an item to a map. When I start it as standalone app it works properly.
The Objekt which has the map is deleted and recreated, and after the recreation the debugger crashes with an error and the whole pc is frozen. The only way is do a hard restart.
Does anyone know what might be the problem?
P.s.: This is the relevant code snippet:
Header:
/**
* List of propertyKey value
*/
typedef std::map<std::string, boost::any> Changes;
/**
* List of id changes
*/
typedef std::map<std::string, Changes> ChangesMap;
ChangesMap m_changeList;
Methodbody:
void PushController::CollectAttributeChanges(
const std::string &id, const std::string &key, const boost::any &value)
{
(m_changeList[id])[key] = value;
}
Best regards,
Gerrit
A: Have you built your app with any flags that can affect the STL binary compatibility in some way (e.g. _SECURE_SCL=0) and is boost built in the same way?
Could another part of the application be corrupting the heap?
You can insert _CrtCheckMemory() calls throughout your code to detect heap corruptions closer to when they occurred.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514381",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to hide the tool tip when mouse is out of the control Hi all i have written a code for Jquery in which both Click & Hover functions will work for the same control which works fine. But when i hover my mouse on a control tool tip showing fine, but if i move my mouse out of the control tool tip remains as it is so can any one tell me where should i change.
This is what i written
<script type="text/javascript">
$(document).ready(function()
{
$('#foobar9').bind('mouseover click',function(e) {
if(e.type == 'click'){
var close = true
}
else
{
var close = false
}
var url = $(this).attr('href');
$(this).formBubble({
url: url,
dataType: 'html',
cache: false,
closeButton: close });
return false; });
});
</script>
The reference site is http://lyconic.com/resources/tools/formbubble
As per the given answer i tried this
<script type="text/javascript">
$(document).ready(function()
{
$('#A1').bind('mouseover mouseout click',function(e) {
if(e.type=='mouseout')
{
$.fn.formBubble.close(thisBubble);
}
if(e.type == 'click'){ // do some click event stuff
var close = true
}
else
{ // do some hover event stuff
var close = false
}
var url = $(this).attr('href');
$(this).formBubble({
url: url,
dataType: 'html',
cache: false,
closeButton: close });
return false; });
});
</script>
<div>
<a href="ajaxtest/index10.html" class="ohhai-world" id="A1">HTML-based AJAX (Click)</a>
</div>
A: try to use delegate() or just do the mouseout() event.
$('#foobar9').delegate('body','mouseover mouseout click',function(e) {
if(e.type === 'click'){
// ...
}else if(e.type === 'mouseover'){
// ...
}else if(e.type === 'mouseout'){
//...
}
});
Edit:
i try something here, and works for me, check this:
html:
<a href="#" id="A1">Static Text (Hover)</a>
js:
$('#A1').bind('mouseover mouseout', function(e) { //hover
if(e.type == "mouseover"){
$(this).formBubble({
closeButton: false
});
$.fn.formBubble.text('hover hover hover hover');
}
if(e.type == "mouseout"){
var thisBubble = $.fn.formBubble.bubbleObject;
$.fn.formBubble.close(thisBubble);
}
});
js click:
$('#A1').bind('click', function(e) { //hover
$(this).formBubble({
alignment: {
bubble: 'left',
pointer: 'top-right'
},
text: 'text'
});
return false;
});
A: This will help you
http://api.jquery.com/mouseout/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514391",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Loading on canvas in facebook doesn't work...? My server gives a pretty bad response time for facebook apps.
I want the show a loading image while it's still a blank page.
I tried via ajax but that didn't work, since I include a file that does the auth part, and redirects to the same page when auth is successful.
Tried some other things to (like jquery) but that didn't work either.
Anyone knows how to do it? I know how to do this on a regular website, but it doesn't work in Facebook... The loading image needs to appear when the page is polling the facebook servers to get user ID, name, about_me, etc.
Thanks a lot!
A: If the page is an iframe canvas page, you could return a basic page with a loading image and then use jquery, XMLHttpRequest, or other ajax techniques to populate the rest of the page. You should also make sure you are caching the user data so that you don't have to wait for Facebook to return it everytime.
It also sounds like you could use a better server.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514393",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: app submission to app store with xcode 4 How is app submission to app store with Xcode 4 different from previous xcode versions? What happens once we click the submit button of Archives-organiser.
A: First we need to click on validation, before that on itunesconnect we have to upload the binary and after that it will validate when we do validation, on Succesfully validation, click submit button and app will be submitted on app store
below is the link it will help you
http://www.weston-fl.com/blog/?p=2442
A: As far as i know there is no difference is the way Apple receives and evaluates your app. XCode 4 provides a different interface to submit apps (when compared to older versions).
See How to submit apps in XCode 4 for more...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514412",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to split big switch statement I'm making an online game and when I receive data from a client, i receive several 'structures' ( say 'my position', 'use potion 23', 'attack player 45', 'talk bla bla', logout, etc.), those structures are read securely and put into structs, pushed on a list and (later on, when the server has time) processed.
The thing is that the processing is a Big switch statement (switch on a sort of enum-"RTTI") and I have over 60 different structs which are all different.
So the .cpp containing the processing code starts to get fairly big and it won't shrink any time as I constantly add functionalities to the game (the c++ is somewhere between 4000-5000 lines).
I can see a simple solution to this, each case calls a function in another file but that will literally (note to harriyott, yes literally as my project and my drive will be flooded with new files) explode the number of files I need to know and keep track of.
I know I can cut it up (the cases) in several fileN.cpp and make '#include "file1.cpp" #include "file2.cpp" etc. in the processing file but that seems horribly wrong.
And any other way that I have 'thought up' to circumvent this problem seems way too 'hacky'.
So the question is, how do you split up a big switch statement nicely?
A: You can
*
*replace the switch with a mapping from the enums to handler functions (the function implementations themselves can be in the same file, or in different files, as you prefer), or
*(the more object oriented solution) make all the structs in question inherit from a common interface declaring a handler method, make each implement the desired functionality in its specific handler method, then call them polymorphically.
A: By using map_list_of. Something like this :
class Base
{
public:
virtual ~Base(){}
virtual void foo()=0;
};
class D1 : public Base
{
virtual void foo() { /*1*/ };
};
class D2 : public Base
{
virtual void foo() { /*2*/ };
};
Base* Lookup( const int v )
{
const static map< int,Base* > next = map_list_of( 1,new D1)(5,new D2);
return next[v];
}
A: It seems to me that boost::variant could make your life easier. You build your main event type as a boost::variant of classes and then use static_visitor classes to do your magic. Essentially a switch, but wrapped nicely and type-safely in logic.
A: Why not go for another approach where you have a map (hashmap) with message id as key mapped to handlers. Each handler handles a single message.
The processing would then just do a lookup based on the incoming message (id) and call the found handler.
A: You could use an class with an abstract function, say process. Instead of structs create the appropriate class. Then instead of the switch all you need to do is call the `process`` function for the element on the list.
A: Use Object Oriented approach, use the select ONLY to select the appropriate class. The design will be more flexible, and it will pay off later when you will add more actions, objects or whatever.
i receive several 'structures' ( say 'my position', 'use potion 23',
'attack player 45', 'talk bla bla', logout, etc.),
You can already spot some exemplary classes: like GameObject for all potions, etc, or GameActor for player and monsters. Later, you can have some GameAction class that can accept "source" and "destination" of the action, like Axe and Ogre. You can have UseAction or AttackAction inheriting from GameAction, with setSourceOfAction(obj), setDestinationOfActon(o) and doAction() methods.
At the end you won't need th bloated switch() at all, or maybe to select through a few of the base classes. I think this is the way.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514418",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Maven: security problems by repository and pluginRepositories defined in pom? Imagine the current situation:
You are an developer and want to participate in a new (open source) project. The project can be build via different ways - one of them is Maven.
If you now download the source code repository and start the build process your system is exposed to multiple security risks from my understanding:
*
*The default Maven [plugin-]repositories are accessed via http - via an Man-in-the-Middle attack someone could could send you manipulated packages. In case of an intercepted plugin-repository this could lead to injected code executed as part of the build process
*In the file pom.xml you can add 3rd party repositories and plugin-repositories. If an attacker manages to add his own plugin-repository to a project pom.xml (e.g. of an open source project) and other can be attacked by those plugins. In case of the 3rd party repositories I am not sure - can a repository defined in a project pom.xml override repositories defined at user or system level?
From my point of view this are severe security problems - or is there a mistake description?
If I have a Maven based project - how can I make sure that it is safe to run Maven? Is there a list of repositories that are trustworthy (contain only code that does not harm the computer it is executed on)?
A: At the first glance your arguments are correct. But there there are some issues to be aware of or which are not the simple to solve for an potential attacker.
The repository which is used in the majority of cases is Maven Central which is under control of Sonatype (as far as i know). This means to have access to those machines and modify the contents of the repository itself or just inject some content which might be not that simple based on the checksums, but of course it does not make it impossible. Furthermore if you are downloading artifacts from the internet you have an up-to-date virus-scanner active which controls everything first before it will be put on your hard-drive. This is of course not 100% safe.
Coming to the second part: If you are using a project which defines repositories inside the pom this not "Best practice"...Ok...let us assume this. So you will use this "infected" project pom. But how has it be put into the project? This means the attacker must have commit access to the project which means in other words he has been shared the project for a long time. Furthermore other people of the project would have reviewed the commit...so this wouldn't be that simple but of course not impossible.
Based on the things i wrote before how could someone give the guaranty that a repository contains only "safe" artifacts? Who should control/check that? And how long would it take to get an artifact into that repository?
So the simple answer is: No it's not 100% safe to use Maven but if we think a little bit about that the internet is not 100% safe as well. In my opinion the risk via the internet is much higher than from a Maven repository, but of course we should ignore this.
The only possible solution for this is to use a Repository Manager which is the only source from where artifacts will be downloaded which means to configure the settings.xml to use only this. And very important that you control every artifact which is put into that repository and do some "security" checks on them. But who will do this and who has the time/money/resources for such things?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514421",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: What wrong with this php user defined function? I cant find that what i have missed in this function so its generating this ERROR some time not always ?
ERROR :-
Notice: Undefined offset: 13 in /home/chandrak/public_html/tmp/c/Crawler.php on line 131
Line number 131 is defined in the below code.
function crawlImage($url)
{
$content=$this->getContent($url);
$domain=$this->getDomain($url);
//echo $domain,'<br>';
$dom = new DOMDocument();
@$dom->loadHTML($content);
$xdoc = new DOMXPath($dom);
//Read the images that is between <a> tag
$atags = $xdoc ->evaluate("//a"); //Read all a tags
$index=0;
for ($i = 0; $i < $atags->length; $i++)
{
$atag = $atags->item($i); //select an a tag
$imagetags=$atag->getElementsByTagName("img");//get img tag
$imagetag=$imagetags->item(0);
if(sizeof($imagetag)>0)//if img tag exists
{
$imagelinked['src'][$index]=$imagetag->getAttribute('src');//save image src
$imagelinked['link'][$index]=$atag->getAttribute('href');//save image link
$index=$index+1;
}
}
//Read all image
//Betweem <img> tag
$imagetags = $xdoc ->evaluate("//img"); //Read all img tags
$index=0;
$indexlinked=0;
for ($i = 0; $i < $imagetags->length; $i++)
{
$imagetag = $imagetags->item($i);
$imagesrc=$imagetag->getAttribute('src');
$image['link'][$index]=null;
/*LINE NO 131 */ if($imagesrc==$imagelinked['src'][$indexlinked]) //THIS IS LINE NUBER 131
{
$image['link'][$index]=$this->convertLink($domain,$url,$imagelinked['link'][$indexlinked]);
$indexlinked=$indexlinked+1;
}
$image['src'][$index]=$this->convertLink($domain,$url,$imagesrc);
$index=$index+1;
}
return $image;
}
A: Change the line to:
if (isset($imagelinked['src'][$indexlinked]) && $imagesrc == $imagelinked['src'][$indexlinked]) {
...and the error should disappear.
EDIT here is an edited version of the function with that error avoided, and a couple of pointless variables removed, and a couple of lines concatenated, and a missing { added.
function crawlImage ($url) {
$domain = $this->getDomain($url);
//echo $domain,'<br>';
$dom = new DOMDocument();
@$dom->loadHTML($this->getContent($url));
$xdoc = new DOMXPath($dom);
// Read the images that is between <a> tag
$atags = $xdoc->evaluate("//a"); // Read all <a> tags
for ($index = 0, $i = 0; $i < $atags->length; $i++) {
$atag = $atags->item($i); // Select an <a> tag
$imagetags = $atag->getElementsByTagName("img");//get img tag
$imagetag = $imagetags->item(0);
if (sizeof($imagetag) > 0) { // If <img> tag exists
$imagelinked['src'][$index] = $imagetag->getAttribute('src'); // Save image src
$imagelinked['link'][$index] = $atag->getAttribute('href'); // Save image link
$index++;
}
}
// Read all images between <img> tag
$imagetags = $xdoc->evaluate("//img"); //Read all img tags
for ($indexlinked = 0, $i = 0; $i < $imagetags->length; $i++) {
$imagetag = $imagetags->item($i);
$imagesrc = $imagetag->getAttribute('src');
$image['link'][$i] = NULL;
if (isset($imagelinked['src'][$indexlinked]) && $imagesrc == $imagelinked['src'][$indexlinked]) {
$image['link'][$i] = $this->convertLink($domain,$url,$imagelinked['link'][$indexlinked]);
$indexlinked++;
}
$image['src'][$i] = $this->convertLink($domain,$url,$imagesrc);
}
return $image;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514422",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Custom Payment Module not appearing in frontend during checkout I'm having some issues with my custom payment module.
The problem is that whatever I try, I can't see the selection for my payment method in the frontend.
This might seem like a duplicate of similar questions, but I've already read them and the solutions didn't work out for me.
The setup
File tree:
/app/code/local/CatalystCode/EwirePayment/
-controllers/
--CallbackController.php
-etc/
--config.xml
-etc/
--system.xml
-Model/
--Payment.php
The content
config.xml:
<?xml version="1.0"?>
<config>
<modules>
<CatalystCode_EwirePayment>
<version>0.1.0</version>
</CatalystCode_EwirePayment>
</modules>
<global>
<resources>
<ewirepayment_setup>
<setup>
<module>CatalystCode_EwirePayment</module>
</setup>
<connection>
<use>core_setup</use>
</connection>
</ewirepayment_setup>
<ewirepayment_write>
<connection>
<use>core_write</use>
</connection>
</ewirepayment_write>
<ewirepayment_read>
<connection>
<use>core_read</use>
</connection>
</ewirepayment_read>
</resources>
<events>
<controller_front_init_routers>
<observers>
<CatalystCode_ewirepayment_model_observer>
<type>singleton</type>
<class>CatalystCode_EwirePayment_Model_Observer</class>
<method>checkForConfigRequest</method>
</CatalystCode_ewirepayment_model_observer>
</observers>
</controller_front_init_routers>
</events>
<frontend>
<routers>
<ewirepayment>
<use>standard</use>
<args>
<module>CatalystCode_EwirePayment</module>
<frontName>ewirepayment</frontName>
</args>
</ewirepayment>
</routers>
</frontend>
</global>
<default>
<payment>
<ewirepayment>
<active>1</active>
<model>ewirepayment/payment</model>
<order_status>pending</order_status>
<title>Pay with Ewire</title>
</ewirepayment>
</payment>
</default>
</config>
system.xml:
<?xml version="1.0"?>
<config>
<sections>
<payment>
<groups>
<CatalystCode_EwirePayment>
<label>Ewire Payment</label>
<sort_order>670</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>0</show_in_store>
<fields>
<active translate="label">
<label>Enabled</label>
<frontend_type>select</frontend_type>
<source_model>adminhtml/system_config_source_yesno</source_model>
<sort_order>1</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>0</show_in_store>
</active>
<company_id translate="label">
<label>CompanyID</label>
<frontend_type>text</frontend_type>
<sort_order>2</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>0</show_in_store>
</company_id>
<encryption_key translate="label">
<label>Encryption key</label>
<frontend_type>text</frontend_type>
<sort_order>3</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>0</show_in_store>
</encryption_key>
<payment_action translate="label">
<label>Payment Action</label>
<frontend_type>select</frontend_type>
<source_model>paygate/authorizenet_source_paymentAction</source_model>
<sort_order>4</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>0</show_in_store>
</payment_action>
<order_status translate="label">
<label>New order status</label>
<frontend_type>select</frontend_type>
<source_model>adminhtml/system_config_source_order_status_processing</source_model>
<sort_order>5</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>0</show_in_store>
</order_status>
<test translate="label">
<label>Test mode</label>
<frontend_type>select</frontend_type>
<source_model>adminhtml/system_config_source_yesno</source_model>
<sort_order>6</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>0</show_in_store>
</test>
<title translate="label">
<label>Title</label>
<frontend_type>text</frontend_type>
<sort_order>7</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
</title>
</fields>
</CatalystCode_EwirePayment>
</groups>
</payment>
</sections>
</config>
Payment.php
<?php
class CatalystCode_EwirePayment_Model_Payment extends Mage_Payment_Model_Method_Abstract
{
protected $_code = 'ewirepayment';
protected $_isInitializeNeeded = true;
protected $_canUseInternal = false;
protected $_canUseForMultishipping = false;
/**
* Return Order place redirect url
*
* @return string
*/
public function getOrderPlaceRedirectUrl()
{
// TODO - fix the url when I'm able to select my payment method...
return Mage::getUrl('customcard/standard/redirect', array('_secure' => true));
}
}
A: Seems like you are missing a models section so it has no idea where to find your classes.
<?xml version="1.0"?>
<config>
<modules>
<CatalystCode_EwirePayment>
<version>0.1.0</version>
</CatalystCode_EwirePayment>
</modules>
<global>
<models>
<ewirepayment>
<class>CatalystCode_EwirePayment_Model</class>
</ewirepayment>
</models>
<resources>
<ewirepayment_setup>
<setup>
<module>CatalystCode_EwirePayment</module>
</setup>
<connection>
<use>core_setup</use>
</connection>
</ewirepayment_setup>
<ewirepayment_write>
<connection>
<use>core_write</use>
</connection>
</ewirepayment_write>
<ewirepayment_read>
<connection>
<use>core_read</use>
</connection>
</ewirepayment_read>
</resources>
<events>
<controller_front_init_routers>
<observers>
<CatalystCode_ewirepayment_model_observer>
<type>singleton</type>
<class>ewirepayment/observer</class>
<method>checkForConfigRequest</method>
</CatalystCode_ewirepayment_model_observer>
</observers>
</controller_front_init_routers>
</events>
<frontend>
<routers>
<ewirepayment>
<use>standard</use>
<args>
<module>CatalystCode_EwirePayment</module>
<frontName>ewirepayment</frontName>
</args>
</ewirepayment>
</routers>
</frontend>
</global>
<default>
<payment>
<ewirepayment>
<active>1</active>
<model>ewirepayment/payment</model>
<order_status>pending</order_status>
<title>Pay with Ewire</title>
</ewirepayment>
</payment>
</default>
</config>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514426",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to compile CoreAudio PlayFile sample code for 64 bit? This is a newbie CoreAudio question. I downloaded Apple's PlayFile sample code. If I use the provided Xcode project, it builds it as 32 bit, passing -arch i386 to the compiler. If I build from the command line and and pass -arch i386 it still all works fine, but if I remove that flag or change it to -arch x86_64, the program dies on AUOpenGraph with an error code of -2005 (badComponentType).
How do I compile it as a 64 bit program? I'd like to know just the flags to pass to clang or gcc.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514427",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Need clarification on timers in JMeter I studied that there are timers available in JMeter. In this constant delay timer, who sets constant time. Whether jmeter puts the delay time between the thread requests or user has to set the time. If the user sets, Where can he set the timer in tool. If anybody knows can you please share your answers.
A:
By default, a JMeter thread sends requests without pausing between each request.
If you add a Timer element, then
The timer will cause JMeter to delay a certain amount of time before each sampler which is in its scope.
Adding a Constant Timer element in a thread group will produce the delay configured in Thread Delay property before each request in the thread group.
A: You set the value on the Timer Module. You can parametrize this to a variable if you'd like.
Check out the user manual - it will answer all your timer questions. If, after reading - you still have questions, feel free to re-ask.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514429",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Send Partial Page as File Attachment via Email Asp.Net Is it possible to send a partial page, say content of an IFrame or Content of a Panel as an attachment in an Email?
I am dynamically creating manufacturing drawing pages with dynamic dimensioning. I'd like the user to be able to click an Email button and send it as attachment to the vendor.
A: You can use Server.Execute to execute a page, capture the output in your TextWriter, and then use that string to build an html attachment for your e-mail. The server.execute is still executed in the current user context, so if you put their selections in the Session or so, it´s easy enough to build the nexessary html. There are some pitfalls though:
*
*If you´re linking to images and using hrefs, either make those absolute links or use a base href tag in your head
*I´d beware of sending html attachments: spam filters and virus scanners could block them.
Good luck!
Menno
A: Winnovative.WnvHtmlConvert.PdfConverter p = new Winnovative.WnvHtmlConvert.PdfConverter();
p.LicenseKey = "NotPostingTHat";
p.PdfDocumentOptions.GenerateSelectablePdf = true;
/*
... Setting a bunch of options ...
*/
p.PdfFooterOptions.DrawFooterLine = false;
System.IO.TextWriter writer = new System.IO.StringWriter();
string html = "";
string pdfType = GetPdfType();
switch (pdfType.ToUpper())
{
case "THEME":
HttpContext.Current.Server.Execute("~/Pdf/Theme.aspx", writer);
break;
/* More cases */
}
html = writer.ToString();
if (html.Length > 0)
{
byte[] bytes = p.GetPdfBytesFromHtmlString(html);
context.Response.ContentType = "application/pdf";
context.Response.OutputStream.Write(bytes, 0, bytes.Length);
}
else
{
context.Response.ContentType = "text/plain";
context.Response.Write("No data found!");
foreach (string item in context.Request.Form.AllKeys)
context.Response.Write(String.Format("{0}: {1}\n", new object[] { item, context.Request.Form[item] }));
}
Nothing to it. This was in an .ashx.
Menno
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514430",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Integer values are being reset to 0 when the sub in which they are assigned values is ended In the following code I have two class scoped variables intCompanyID and intEmployeeID. When I set them to a value in btnFetch_Click then try to read them later in btnSubmit_Click they are set to zero.
Why is this?
Option Explicit On
Imports MySql.Data.MySqlClient
Imports System.Data
Public Class EmployeeQuestionaire
Inherits System.Web.UI.Page
Dim intCompanyID As Integer
Dim intEmployeeID As Integer
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Handles Me.Load
End Sub
Protected Sub btnFetch_Click(ByVal sender As Object, ByVal e As EventArgs)
Handles btnFetch.Click
intEmployeeID = Convert.ToInt32(txtUserID.Text)
intCompanyID = 1
msgbox (intEmpoyeeID & " " & intCompanyID) ' this shows the values
End Sub
Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As EventArgs)
Handles btnSubmit.Click
MsgBox(intCompanyID & " " & intEmployeeID) 'shows O O
End Sub
A: ASP.NET will not store any state in between trips to the web-server. Therefore, you will need to find somewhere to store your values. You can use the Session object:
Protected Sub btnFetch_Click
Session ("MyEmployeeId") = Convert.ToInt32(txtUserID.Text)
End Sub
Protected Sub btnSubmit_Click
intEmployeeID = Session("MyEmployeeId")
End Sub
Alternatively, you can re-read the txtUserId each time:
Protected Sub btnFetch_Click
intEmployeeid = Convert.ToInt32(txtUserID.Text)
End Sub
Protected Sub btnSubmit_Click
intEmployeeID = Convert.ToInt32(txtUserID.Text)
End Sub
There are many other ways, but ultimately I think you need a much better basic understanding of ASP.NET. It's very different to WinForms programming, or whatever you've used. For one, you really shouldn't use MsgBox as your code will generally be running on a web-server with no-one to click "OK"!
A: Every time a page is posted back, the ASP.NET create the page object and generates all the controls and variables you have defined so you need to use ASP.NET state management technique to preserve the state between requests.
For instance,
Protected Sub btnFetch_Click(ByVal sender As Object, ByVal e As EventArgs)
Handles btnFetch.Click
int intEmployeeID;
int.TryParse(txtUserID.Text,out intEmployeeID);
Session("intCompanyID")=1
Session("intEmployeeID")=intEmployeeID;
msgbox (intEmpoyeeID & " " & Session("intCompanyID"))
End Sub
Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As EventArgs)
Handles btnSubmit.Click
If Not IsNothing(Session("intCompanyID")) Then
MsgBox(Session("intCompanyID) & " " & Session("intEmployeeID"))
End If
End Sub
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514431",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
} |
Q: Blackberry connection issue When connecting with a ConnectionFactory works on the simulator and doesn't work on a real device Torch 9800 works on Curve 9300 i ran the Network Diagnosis Tool on both showed an successful test with wifi on the curve but on the torch all tests fail, the strange part is that the browser works but both application and Network Diagnosis Tool fail. Can someone give me a clue ?
Added code :
ConnectionFactory cf = new ConnectionFactory();
cf.setPreferredTransportTypes(new int[]{
TransportInfo.TRANSPORT_TCP_WIFI,
TransportInfo.TRANSPORT_TCP_CELLULAR,
TransportInfo.TRANSPORT_WAP,
TransportInfo.TRANSPORT_WAP2,
TransportInfo.TRANSPORT_MDS,
TransportInfo.TRANSPORT_BIS_B
});
ConnectionDescriptor cd = cf.getConnection(s);
if (cd!=null){
connection = (HttpConnection) cd.getConnection();
}else {
String appendix = getBlackBerryConnectionParams();
System.out.println("Strng: "+appendix);
connection = (HttpConnection) Connector.open(s+appendix);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514436",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Fetch Facebook friends list using java code is it possible to get facebook friends list without having the facebook api key user
can you explain
thank you
A: No. The user needs to approve your application which returns an access token before you can get any information about the user, including their friend list.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514437",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Solr : Getting Collations from a query response Im trying to configure SOLR spell checking. My request and response seem to be working fine. Only problem is how do i get the Collations from the response.
This is the part of my response that has the collations.
What methods in the API do i use to extract the 3 collations.
<str name="collation">ipod tough</str>
<str name="collation">ipad tough</str>
<str name="collation">wood tough</str>
<str name="collation">food tough</str>
This is the method that im using currently:
List<String> suggestedTermsList = new ArrayList<String>();
if(aQueryResponse == null) {
return suggestedTermsList;
}
try {
SpellCheckResponse spellCheckResponse = aQueryResponse.getSpellCheckResponse();
if(spellCheckResponse == null) {
throw new Exception("No SpellCheckResponse in QueryResponse");
}
List<Collation> collationList = spellCheckResponse.getCollatedResults();
for(Collation c : collationList){
suggestedTermsList.add(c.getCollationQueryString());
}
}catch(Exception e) {
Trace.Log("SolrSpellCheck",Trace.HIGH, "Exception: " + e.getMessage());
}
return suggestedTermsList;
My response header is like so:
spellcheck={suggestions={ipood={numFound=5,startOffset=0,endOffset=5,suggestion=[ipod, ipad, wood, food, pod]},collation=ipod tough,collation=ipad tough,collation=wood tough,collation=food tough}}}
I get 4 collations which I want to add to a List suggestedTermsList which I then return to the calling code. Right now my ArrayList has 4 collations but it only has the last collation repeated 4 times. i.e food tough - four times.
A: I think you want to call QueryResponse.getSpellCheckResponse() and go from there. Here are some links to documentation you might find helpful:
http://lucene.apache.org/solr/api/org/apache/solr/client/solrj/response/SpellCheckResponse.Collation.html
http://lucene.apache.org/solr/api/index.html?org/apache/solr/client/solrj/response/SpellCheckResponse.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514443",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to get a specific jQuery item from a list of items? I have this:
<ul>
<li>first</li>
<li>second</li>
<li>third</li>
<li>fourth</li>
</ul>
Then I select it all with jQuery: $('ul').find('li'); or $('ul li');
How can I, from those two jQuery selectors get the, for instance only second li, or third, and to leave first and fourt alone?
I thought it might work with:
$('myselector').get(indexNumber); // however, it won't work.
Any ideas for this issue? Thanks.
A: Use :eq() Selector. For for example, for second element use:
$("ul li:eq(1)");
A: The get method returns the DOM element, so then you would have to wrap it inside a new jQuery object.
You can use the eq method:
var j = $('ul li').eq(1); // gets the second list item
A: I would try:
$("ul li:nth-child(2)")
A: $('li').get(0) will return plain DOM element. you cannot call jQuery methods on same.
A: you can use nth-child
$("ul li:nth-child(2)") //this will select second child because it is 1 based index
here is a fiddle http://jsfiddle.net/xyyWh/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514448",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
} |
Q: exponential growth over time - how do I calculate the increase over a delta-time? This is probably a silly / stupid question, but I'm still gonna ask it :
if I have an initial start value at Time 0 (which is in my case always 1.0) and a rate of growth, how do I figure out the increase between Time1 and Time2 ?
A: Tn = T1 + 0.5 (rate of growth)^2
Dose this make sense? The last term one half of the square of the rate of growth.
Thus the difference between the time periods is
diff(Tn - T1) = 0.5 (rate of growth)^2
A: increase = value at time2 - value at time1. Seems simple, is simple. The value is equal to T0*(rate of growth)^Ti, where Ti is your time.
A: If i understand correctly:
f(t2) - f(t1) where f(t) = initial * growth_factor^t
A: If you assume a relative rate of growth r your value as a function of time is given by
f(t) = exp(r*t)
(already incorporated f(0)=1 and f'(0)=r) and thus the absolute difference is
D = f(t2) - f(t1) = exp(r*t2) - exp(r*t1)
while the relative increase is given by
d = f(t2)/f(t1) - 1 = exp(r*t2)/exp(r*t1) - 1 = exp(r*(t2-t1)) - 1
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514449",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Sorting an arraylist of my own type in Java I have a type in Java called Item which is defined as follows:
private Integer itemNo;
private String itemName;
private String itemDescription;
...
And I would like to be able to sort an arraylist of this type in descending order according to itemName.
From what I read, this can be done via:
Collections.sort(items, Collections.reverseOrder());
Where items is:
ArrayList<Item> items = new ArrayList<Item>();
But I find that the call to Collections.sort gives me a:
Item cannot be cast to java.lang.Comparable
Run time exception.
Can anyone advise on what I need to do?
A: Declare Item to be Comparable, and implement the comapreTo method to compare itemName in reverse order (ie compare "that to this", rather than the normal "this to that").
Like this:
public class Item implements Comparable<Item> {
private Integer itemNo;
private String itemName;
private String itemDescription;
public int compareTo(Item o) {
return o.itemName.compareTo(itemName); // Note reverse of normal order
}
// rest of class
}
A: You need your custom Item to implement Comparable , or otherwise you can do it using Comparator
A: You should probably make Item implement Comparable, or create a Comparator to your Item, and use Collections.sort(List,Comparator)
code snap:
Comparator:
public static class MyComparator implements Comparator<Item> {
@Override
public int compare(Item o1, Item o2) {
//reverse order: o2 is compared to o1, instead of o1 to o2.
return o2.getItemName().compareTo(o1.getItemName());
}
}
usage:
Collections.sort(list,new MyComparator());
(*)note that the static keyword in MyComparator's declaration is because I implemented it as an inner class, if you implement this class as an outer class, you should remove this keyword
A: You need to implement the Comparable interface and define the compareTo(T o) method.
See also:
*
*How to use Comparable Interface
A: You need to make your Item class implement the java.lang.Comparable interface.
public class Item implements Comparable<Item> {
// your code here, including an implementation of the compare method
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514451",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Windows system login credentials i am developing a scheduler in which i want to match the username and password entered by the user with the system's login credentials in c#.Is there any way to do this.
A: Why don't you use the Windows Task Scheduler?
Just look http://www.codeproject.com/KB/cs/tsnewlib.aspx
BTW you can gather the currently logged on user by using System.Environment or from the current Thread.
A: WindowsIdentity.GetCurrent().Name;
A: Getting the default credentials for the current user:
CredentialCache.DefaultCredentials;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514455",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: With Watin, how do I wait until an element gets a certain CSS class? I want to use Watin's WaitUntil method to wait until an element gets a certain CSS class (JavaScript adds the class dynamically). How do I do this?
var element = browser.Div("my-div");
element.WaitUntil(...); // What to do here??
A: Try one of these:
element.WaitUntil(Find.ByClass("your_class_name"));
element.WaitUntil(d => d.ClassName == "your_class_name");
Keep in mind, that element with class="your_class_name other_class_name" will probably (I'm not 100% sure) not be found.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514456",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to open the image in the Android's default gallery
Possible Duplicate:
How to open phones gallery through code
I have outputted a image in my app. Can I call the default Android's gallery to display the image instead of using ImageView to view the image.
Thank you very much!
A: try this for open gallery
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);//
startActivityForResult(Intent.createChooser(intent, "Select Picture"),10);
A: You should be able to display the image in gallery using this code..
Intent intentquick = new Intent(Intent.ACTION_VIEW);
intentquick.setDataAndType(<full path to image to be displayed>,"image/*");
intentquick.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intentquick);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514457",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Joomla: mod_login parameters not showing up in administrator backend I am trying to change the Name/username parameter value to "Name" in the mod_login parameters. But for my Joomla installation (Joomla! 1.5.23), only a few parameters are shown (Caching + Encrypt Login Form).
Is there a way to display more parameters in the backend? If not, where can I edit the parameter? Is there an ini file somewhere?
A: Usually modules parameters are stored in an XML file within the directory with the same name as the module, under the 'modules' folder (if admin modules, those are under 'administrator/').
In that file are stored the parameters used by a module, which are shown in the module configuration in Back-End.
As for mod_login, those params are not editable, but if you open the mod_login.php file (under administrator/modules/mod_login/) you'll find the html relative to that form.
<p id="form-login-username">
<label for="modlgn_username"><?php echo JText::_('Username'); ?></label>
<input name="username" id="modlgn_username" type="text" class="inputbox" size="15" />
</p>
<p id="form-login-password">
<label for="modlgn_passwd"><?php echo JText::_('Password'); ?></label>
<input name="passwd" id="modlgn_passwd" type="password" class="inputbox" size="15" />
</p>
Add a value="(your value here)" and it set.
Alternatively, if you want to do things well done, open the XML file and add
<param name="name_default" type="text" default="Name" label="Default value for username" description="Default value for username" />
And in mod_login.php you call this parameter with
$default_value = $params->get('name_default');
And just put into the form:
<input name="username" id="modlgn_username" type="text" value="<?php echo $default_value;?>" class="inputbox" size="15" />
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514460",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: HttpValueCollection and NameValueCollection What is the difference between HttpValueCollection and NameValueCollection?
If possible please explain with example.
Thanks
A: One point that is not obvious in Darin's answer is that NameValueCollection does not override ToString() method, while HttpValueCollection overrides it. This particular property and implicit URL encoding of values makes the latter one a right choice if you want to convert the collection back to query string.
public class Test
{
public static void Main()
{
var httpValueCollection = HttpUtility.ParseQueryString(string.Empty);
httpValueCollection["param1"] = "value1";
httpValueCollection["param2"] = "value2";
Console.WriteLine(httpValueCollection.ToString());
var nameValueCollection = new NameValueCollection();
nameValueCollection["param1"] = "value1";
nameValueCollection["param2"] = "value2";
Console.WriteLine(nameValueCollection.ToString());
}
}
Outputs:
param1=value1¶m2=value2
System.Collections.Specialized.NameValueCollection
A: NameValueCollection is case sensitive for the keys, HttpValueCollection isn't. Also HttpValueCollection is an internal class that derives from NameValueCollection that you are never supposed to use directly in your code. Another property of HttpValueCollection is that it automatically url encodes values when you add them to this collection.
Here's how to use the HttpValueCollection class:
class Program
{
static void Main()
{
// returns an implementation of NameValueCollection
// which in fact is HttpValueCollection
var values = HttpUtility.ParseQueryString(string.Empty);
values["param1"] = "v&=+alue1";
values["param2"] = "value2";*
// prints "param1=v%26%3d%2balue1¶m2=value2"
Console.WriteLine(values.ToString());
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514461",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "35"
} |
Q: Help with PHP looping system Hey I have a set of results returned from the database, they are numbers which represent 1 - 18 which are the drivers_id, it could return any number of those dependant on how many drivers retired from a race. I am then matching them up to the users drivers and if they match then to -10 points from the users points.
If they do not match then to +5 points. If the query returns no set at all then i know that the users four drivers can be +5 points each, but if it returns 5 rows, then how can I loop through those and match them up? and if there is no match add +5 points to that drivers variable, but it has to be after all the result set has been compared as that driver might be a match to the next row in $row. Thanks a lot for any help provided!.
p.s each driver_id in the result set is unique, so once a comparison
is true then that driver_id will not appear again.
$results = mysql_query("SELECT drivers_id FROM results_retired WHERE drivers_id IN ('$driver1', '$driver2', '$driver3', '$driver4') AND track_id = '$track'") or die ("Failed to update" . mysql_error());
$retireddrivers = mysql_fetch_array($results)
if(in_array($driver1, $retireddrivers)){
$driveronepoints -= $driver_points_system["retired"];
}
else {
$driveronepoints += $driver_points_system["completion"];
}
if(in_array($driver2, $retireddrivers)) {
$drivertwopoints -= $driver_points_system["retired"];
}
else {
$drivertwopoints += $driver_points_system["completion"];
}
if(in_array($driver3, $retireddrivers)) {
$driverthreepoints -= $driver_points_system["retired"];
}
else {
$driverthreepoints += $driver_points_system["completion"];
}
if(in_array($driver4, $retireddrivers)) {
$driverfourpoints -= $driver_points_system["retired"];
}
else {
$driverfourpoints += $driver_points_system["completion"];
}
I have made some changes now to the code, is the in_array function ok to use in this instance??
thanks
A: It looks like you're missing the concept of rows vs columns.
mysql_fetch_* will return you one row -- that is, one of the retired drivers' IDs -- with each call. You'll need to collect them into an array before you can use in_array.
while ($retired_driver = mysql_fetch_array($results))
{
$retireddrivers[] = $retired_driver['driver_id'];
}
Also, if you can manage it, i'd consider putting drivers 1-4 into an array as well. Then you can do like
// Ideally, $driver[1-4]* won't exist at all -- you'd pull the info from the DB,
// or from the form, and stuff it directly into the array.
// This code right here is just to make existing code work
$drivers = array(
array('id' => $driver1, 'points' => &$driver1points),
array('id' => $driver2, 'points' => &$driver2points),
array('id' => $driver3, 'points' => &$driver3points),
array('id' => $driver4, 'points' => &$driver4points),
);
foreach ($drivers as $driver)
{
if (in_array($driver['id'], $retireddrivers))
{
$driver['points'] -= $driver_points_system['retired'];
}
else
{
$driver['points'] += $driver_points_system['completion'];
}
}
considerably reducing duplication of code.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514469",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to create a Restful web service with input parameters? I am creating restful web service and i wanted to know how do we create a service with input parameters and also how to invoke it from a web browser.
For example
@Path("/todo")
public class TodoResource {
// This method is called if XMLis request
@PUT
@Produces( {MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON})
public Todo getXML() {
Todo todo = new Todo();
todo.setSummary("This is my first todo");
todo.setDescription("This is my first todo");
return todo;
}
and i can invoke it using
http://localhost:8088/JerseyJAXB/rest/todo
and I want to create a method like
@Path("/todo")
public class TodoResource {
// This method is called if XMLis request
@PUT
@Produces( {MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON})
public Todo getXML(String x, String y) {
Todo todo = new Todo();
todo.setSummary(x);
todo.setDescription(y);
return todo;
}
In case of soap based web services i would invoke it like this
http://localhost:8088/JerseyJAXB/rest/todo?x=abc&y=pqr
but I want to know how to invoke it using rest and also can I pass the parameters as I am doing in the above example when I use rest and jersey.
A: You can.
Try something like this:
@Path("/todo/{varX}/{varY}")
@Produces({"application/xml", "application/json"})
public Todo whatEverNameYouLike(@PathParam("varX") String varX,
@PathParam("varY") String varY) {
Todo todo = new Todo();
todo.setSummary(varX);
todo.setDescription(varY);
return todo;
}
Then call your service with this URL;
http://localhost:8088/JerseyJAXB/rest/todo/summary/description
A: Be careful. For this you need @GET (not @PUT).
A: another way to do is get the UriInfo instead of all the QueryParam
Then you will be able to get the queryParam as per needed in your code
@GET
@Path("/query")
public Response getUsers(@Context UriInfo info) {
String param_1 = info.getQueryParameters().getFirst("param_1");
String param_2 = info.getQueryParameters().getFirst("param_2");
return Response ;
}
A: If you want query parameters, you use @QueryParam.
public Todo getXML(@QueryParam("summary") String x,
@QueryParam("description") String y)
But you won't be able to send a PUT from a plain web browser (today). If you type in the URL directly, it will be a GET.
Philosophically, this looks like it should be a POST, though. In REST, you typically either POST to a common resource, /todo, where that resource creates and returns a new resource, or you PUT to a specifically-identified resource, like /todo/<id>, for creation and/or update.
A: You can try this... put parameters as :
http://localhost:8080/WebApplication11/webresources/generic/getText?arg1=hello
in your browser...
package newpackage;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.Consumes;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PUT;
import javax.ws.rs.QueryParam;
@Path("generic")
public class GenericResource {
@Context
private UriInfo context;
/**
* Creates a new instance of GenericResource
*/
public GenericResource() {
}
/**
* Retrieves representation of an instance of newpackage.GenericResource
* @return an instance of java.lang.String
*/
@GET
@Produces("text/plain")
@Consumes("text/plain")
@Path("getText/")
public String getText(@QueryParam("arg1")
@DefaultValue("") String arg1) {
return arg1 ; }
@PUT
@Consumes("text/plain")
public void putText(String content) {
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514470",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "20"
} |
Q: IE7 Div width bug I ran into a very strange bug with IE7. Here is my HTML structure
<div id="tt_message_kudos_top">
<div id="tt_kudo_position">
<span> Kudos </span>
</div>
<div id="TT_kudos_reply">
<div class="lia-message-actions lia-component-actions">
<div class="lia-button-group">
<span class="lia-button-wrapper lia-button-wrapper-secondary"><a href="/t5/forums/replypage/board-id/Services/message-id/1" id="link_35" class="lia-button lia-button-secondary reply-action-link lia-action-reply">Reply</a></span>
</div>
</div>
</div>
The main CSS code to control these div are:
#tt_message_kudos_top {
float: right;
}
#tt_kudo_position {
float: left;
}
#TT_kudos_reply {
float: left;
}
The page looks fine in firefox, chrome, IE8,9. However, the TT_kudos_reply div automatically expand width space and float to right edge of this div.
I tried to give a fix width in TT_kudos_reply will solve the problem, However, the content of the TT_kudos_reply is dynamically change. See screenshots.
I also try to apply lia-button-wrapper, display:inline, it won't affect.
Any suggestions? Thanks.
Cheers,
Qing
A: Initial thought - clear the float of reply. This should force it's siblings to the next line:
#TT_kudos_reply {
clear:right; float: left;
}
But without seeing more of your CSS, it's hard to make a solid suggestion.
If you'd be up for an easy refactor, you could do the following (assuming the "Accept as Solution" is intended to fall below "Reply")...
Instead of a div for both, hard code the width of tt_kudo, then use a definition list for the reply and accept button.
<div>Kudo</div>
<dl>
<dt>Reply</dt>
<dd>Accept</dd>
</dl>
Since the default behavior of the DL seems to work with your design, styling it to meet your needs should prove easy to do.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514491",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to get the fields that match the request? I need your help to get more information in my solR query's response.
i've got a simple input text which allows me to query several fields in the same query.
So my query looks like this
"q=email:martyn+OR+name:martynn+OR+commercial:martyn ..."
Is it possible in the response to know the fields where "martynn" has been found?
A: Add this to your query string:
hl=true&hl.fl=*
which tells solr to highlight the fields where the matches were made.
This solr wiki page describes all the highlighting parameters available with solr.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514492",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Error in regex when first character is \ works fine with any other character For a project that I am doing I have to read a String. This String may contain one or more hexadecimal representations of unicode characters (e.g. "\u0161" for "š"). I want to convert these codes to the correct character representation.
To do this, I first need to detect that there is an hexadecimal sequence of the format "\uAAAA" in my String, and therefor I wrote the following regular expression:
Pattern classPattern = Pattern.compile("\\u[0-9a-fA-F]{4}");
Matcher classMatcher = classPattern.matcher("\\u1ECD");
System.out.println(classMatcher.find());
Unfortunately this generates a " java.util.regex.PatternSyntaxException: Illegal Unicode escape sequence near index 2" error.
However, if I replace the "\", just for testing purposes by an "@" the regex works as expected:
Pattern classPattern = Pattern.compile("@u[0-9a-fA-F]{4}");
Matcher classMatcher = classPattern.matcher("@u1ECD");
System.out.println(classMatcher.find());
This leads me to believe that I am doing something wrong with the back slash. I tried also many other sequences, but none of them worked. Please help.
A: The '\u' has a special meaning in the Java regex world, namely around matching actual unicode characters. You have to double escape the \ to get the match you desire.
Pattern classPattern = Pattern.compile("\\\\u[0-9a-fA-F]{4}");
[update] As comments have pointed out, my reasoning for giving the right answer was flawed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514493",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to replace preview of post with full content using jQuery / Javascript? In a php variable $preview I save about 4 lines of a post without any tags. In the $full I save full of the post with tags.
This is what I used to have, an expand/collapse toogle http://fiddle.jshell.net/r4F8Q/22/ when I was saving the entire post. But it doesn't look good without tags so I need to go one step forward.
My question is how to change it, so it shows $preview until the user clicks on expand and show the $full post?
Thank you
A: Put two elements in the output HTML of your PHP script; one containing the preview and one containing the full text. Then just hide the full one (CSS "display: none;") and on a click show the element containing the full text while hiding the element containing just the preview?
A: Here is my version: http://fiddle.jshell.net/r4F8Q/28/
I've used separate blocks for preview and full content and fadeIn\fadeOut for animating it
A: If you modify the html a little you could save the preview in a div and the full message in another and then toggle the dive like this:
<div id="post">
<div id="image">
<img alt="image" border="0" src="here-goes-an-image.png">
</div>
<div id="text expanded">
<a href="#" class="toggle">(expand)</a>
<h2><a href="#" target="_blank">This is the title</a></h2>
<div id="authorANDtime">
<b>from <a href="#">author</a>, 22 mins ago.</b>
</div>
<div id='preview'>Here goes the preview vHere goes the preview Here goes the preview Here goes the preview Here goes the preview Here goes the preview Here goes the preview Here goes the preview Here goes the preview Here goes the preview </div>
<div id="thepost">
Here goes the content of the post. Here goes the content of the post. Here goes the content of the post. Here goes the content of the post. Here goes the content of the post. Here goes the content of the post. Here goes the content of the post. Here goes the content of the post. Here goes the content of the post. Here goes the content of the post.
HERE IS THE HIDDEN CONTENT. HERE IS THE HIDDEN CONTENT. HERE IS THE HIDDEN CONTENT. HERE IS THE HIDDEN CONTENT. HERE IS THE HIDDEN CONTENT. HERE IS THE HIDDEN CONTENT. HERE IS THE HIDDEN CONTENT. HERE IS THE HIDDEN CONTENT. HERE IS THE HIDDEN CONTENT.
</div>
</div>
</div>
$('#thepost').hide();
$('.toggle').click(function(){
$('#preview').toggle();
$('#thepost').toggle();
if($('#preview').is(':visible')){
$(this).text('(expand)');
}else{
$(this).text('(collapse)');
}
});
http://fiddle.jshell.net/r4F8Q/27/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514498",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Styling normal html elements with UiBinder I have the following UiBinder code:
...
<div>
<g:Label>Hello,</g:Label>
<g:Button ui:field="button" />
</div>
...
Now I want to style the div element and lets say give it a red border. The clear way as far as I know is, to define a style attrinute like this:
<ui:style>
.redborder {
border: 1px solid red;
}
...
</ui:style>
so the code all in all would look like this :
...
<div styleName="{style.redborder}">
<g:Label>Hello,</g:Label>
<g:Button ui:field="button" />
</div>
...
but in the HTML page the red border isn't drawn. Now I looked into the page with Firebug (or how you call the thing in Google Chrome) and saw, that the div element has the correct class name, but the borwser can't find the class yet. If on hte other hand I put same style element to the button everything works fine.
Does anybody has an idea what it behaves like this?
Regards,
Stefan
A: On regular DOM elements, your DIV in this case, there is no setStyleName() method, so just use the class attribute:
<div class="{style.redborder}"> ... </div>
styleName="..." works on GWT widgets because it is translated to call the setStyleName() method.
By the way, you might want to consider using addStyleNames="..." on your widgets as this allows you to add (multiple) CSS class names without accidentally dropping already existing class names.
A: To use it like regular HTML, you got to think in regular HTML!
Lets take your case as example :
<ui:style>
.redborder {
border: 1px solid red;
}
...
</ui:style>
...
<div class="{style.redborder}"> <!--Notice I used class instead of styleName-->
<g:Label>Hello,</g:Label>
<g:Button ui:field="button" />
</div>
....
So just use "class" attribute instead of "styleName".
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514510",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: PHP crypt() with sha256 in Zend Server CE 5.5 truncates the supplied salt During an upgrade from Zend Server CE 5.1 to Zend Server CE 5.5, PHP also got an upgrade from 5.3.5 to 5.3.8. After this transition the login function for a zend application I'm working on suddenly broke.
Trying to debug it, it looks likes the implementation of crypt() doesn't reflect the PHP manual, or I've misunderstood it. If I would venture a guess, it's the latter.
I'm using a 16 character long salt as part of a larger salt using SHA256, which is used as the example in the PHP manual.
$password = //string entered at login
$salt = '$5$rounds=250000$1234abcd5678defg$';
After I've hashed the entered password
$hash = crypt($password, $salt);
I get a string like this as the return value:
$5$rounds=250000$1234abcd5678$tI.Oiz.YwWjIwT3K.SLU8SwUZ9J0/odBCkbE6t0igeB
What baffles me is that the 16 character salt, that is part of the larger part (1234abcd5678defg above), now is truncated to 12 characters.
Is this as intended? The crypt() function also seems to return different results now than before - is that usual between versions of PHP? Nothing in the changelog suggest any radical changes to the encryption algorithms.
A: This is the response I received from Zend:
Thank you for the feedback. The issue you reported is considered a bug. The developers will provide a fix, which will be included in one of the upcoming releases of the product.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514512",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: controlling mouse with pyusb I have to make a application, that do the followings:
*
*disable that the given usb mouse move the pointer in the screen (just the given, not all mouses).
*get the coordinates of the mouse pointer
*change the y coordinate of the mouse pointer
I've tried out pyusb, but i've never found any examples for any of the 3 problems.
Any ideas?
A: I don't know enough pyusb but you can deal with the second issue with Tkinter (one of the most used GUI with Python). Here is a sample of code (found here):
# show mouse position as mouse is moved and create a hot spot
import Tkinter as tk
root = tk.Tk()
def showxy(event):
xm = event.x
ym = event.y
str1 = "mouse at x=%d y=%d" % (xm, ym)
root.title(str1)
# switch color to red if mouse enters a set location range
x = 100
y = 100
delta = 10 # range
if abs(xm - x) < delta and abs(ym - y) < delta:
frame.config(bg='red')
else:
frame.config(bg='yellow')
frame = tk.Frame(root, bg= 'yellow', width=300, height=200)
frame.bind("<Motion>", showxy)
frame.pack()
root.mainloop()
Yet, it seems like you cannot change the cursor position with Tkinter only (see this thread for some workarounds). But if you are trying to set position within a text, you can use a widget as described in this SO thread: Set cursor position in a Text widget.
To disable mouse, you could have a look at this post and adapt the code to disable mouse instead of touchpad (but the post gives some interesting keys to begin with).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514515",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to create pdf from ASP.Net web Form I have developed a ASP.Net application and I have developed a web Form with some entries. Now i want to convert this form into PDF file, is it possible ?
Any good and free library for this ?
A: To create pdf file you can use itextsharp or pdf sharp
A: You can use free libraries such as ITextSharp or for more complex scenarios you can use the server version of TxtControl to generate documents from websites.
TxtControl also offers a OnDemand service for creating documents...
A: You may find the Ghostscript library useful http://www.ghostscript.com/
A: Document doc = new Document(PageSize.A4);
// Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 100f, 0f);
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=hello.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
PdfWriter.GetInstance(doc, Response.OutputStream);
string imagepath = Server.MapPath("IMG");
doc.Open();
doc.Add(new Paragraph());
Image gif = Image.GetInstance(imagepath + "/asd.jpg");
doc.Add(gif);
PdfPTable table1 = new PdfPTable(2);
table1.WidthPercentage = 90;
PdfPCell cell11 = new PdfPCell();
cell11.AddElement(new Paragraph("Receipt ID : " + 124325));
cell11.AddElement(new Paragraph("Date : " + "25-Feb-2013"));
cell11.AddElement(new Paragraph("Photo Status : " + "No"));
cell11.VerticalAlignment = Element.ALIGN_LEFT;
PdfPCell cell12 = new PdfPCell();
cell12.AddElement(new Paragraph("Transaction ID : " + 4544));
cell12.AddElement(new Paragraph("Expected Date Of Delivery : " + "25-Feb-2013"));
cell12.VerticalAlignment = Element.ALIGN_RIGHT;
table1.AddCell(cell11);
table1.AddCell(cell12);
PdfPTable table2 = new PdfPTable(3);
//One row added
PdfPCell cell21 = new PdfPCell();
cell21.AddElement(new Paragraph("Photo Type"));
PdfPCell cell22 = new PdfPCell();
cell22.AddElement(new Paragraph("No. of Copies"));
PdfPCell cell23 = new PdfPCell();
cell23.AddElement(new Paragraph("Amount"));
table2.AddCell(cell21);
table2.AddCell(cell22);
table2.AddCell(cell23);
//New Row Added
PdfPCell cell31 = new PdfPCell();
cell31.AddElement(new Paragraph("type"));
cell31.FixedHeight = 300.0f;
PdfPCell cell32 = new PdfPCell();
cell32.AddElement(new Paragraph(5));
cell32.FixedHeight = 300.0f;
PdfPCell cell33 = new PdfPCell();
cell33.AddElement(new Paragraph("20.00 * noOfCopy = " + (20 * Convert.ToInt32(5)) + ".00"));
cell33.FixedHeight = 300.0f;
table2.AddCell(cell31);
table2.AddCell(cell32);
table2.AddCell(cell33);
PdfPCell cell2A = new PdfPCell(table2);
cell2A.Colspan = 2;
table1.AddCell(cell2A);
PdfPCell cell41 = new PdfPCell();
cell41.AddElement(new Paragraph("Name : " + "fdfgdg"));
cell41.AddElement(new Paragraph("Advance : " + "245"));
cell11.VerticalAlignment = Element.ALIGN_LEFT;
PdfPCell cell42 = new PdfPCell();
cell42.AddElement(new Paragraph("Customer ID : " + 34345));
cell42.AddElement(new Paragraph("Balance : " + 20545));
cell42.VerticalAlignment = Element.ALIGN_RIGHT;
table1.AddCell(cell41);
table1.AddCell(cell42);
doc.Add(table1);
doc.Close();
//pdfDoc.Open();
//htmlparser.Parse(sr);
//pdfDoc.Close();
Response.Write(doc);
Response.End();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514516",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: htaccess to redirect index.php without parameter I am looking for the Redirect for .htaccess:
www.mydomain.com/A/ and www.mydomain.com/A/index.php without a parameter must be redirected to "www.mydomain.com/B/".
www.mydomain.com/A/index.php with a parameter like www.mydomain.com/A/index.php?id=123 is OK and must not be redirected.
A: You need to use mod_rewrite. You need to make sure that mod_rewrite is installed and enabled. Here is the rule for your URL:
Options +FollowSymLinks
RewriteEngine On
RewriteCond %{QUERY_STRING} ^$
RewriteRule ^A/(index\.php)?$ http://www.mydomain.com/B/ [NC,R=301,L]
The rule will match both /A/ and /A/index.php and will only redirect if query string is empty.
A: I think you can use a redirect match for that
RedirectMatch "/A/index\.php$" http://www.mydomain.com/B
RedirectMatch "/A/$" http://www.mydomain.com/B
RedirectMatch "/A$" http://www.mydomain.com/B
I hope this will work :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514519",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is there equivalent of onbeforedeactivate event for Firefox etc.? this works in IE
$('#blah').bind('beforedeactivate', fnBlah);
but I can not find equivalent for Firefox and other browsers
A: beforedeactivate is an IE-specific event handler. The closest you can get are the focusout and blur events.
Usage in JQuery:
function eventHandler(){
//...
};
$("element").focusout(eventHandler);
$("element").blur(eventHandler);
Links to JQuery implementations:
*
*Focusout
*Blur
A: You can use
object.addEventListener ("blur", handler, useCapture);
or
object.attachEvent ("onblur", handler);
found here: http://help.dottoro.com/ljjhfrjd.php
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514521",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Exception - instance error When you start catching exception and the exceptions autoloader controller error pops up:
Argument 1 passed to Controller_Exception:: __construct () must be an instance of Autoloader_Exception, string given, Called in 'source'
try {} catch (Autoloader_Exception $ e){ throw new Controller_Exception ('Some Error'); }}
Controller_Exception class { public function __construct ($ Autoloader_Exception e) { } }
Question two, how can I build an exception class? Does anybody know a good example?
A: The first issue is that you are using
new Controller_Exception ('Some Error')
According to the error message 'Some Error' must be an Autoloader_Exception. Depending on what you want to do you could use:
new Controller_Exception ($e)
For the second question you can read about creating your own exceptions here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514533",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Zend Login Problem I am new in Zend Framwork. I write a action for login is given below :
public function authAction()
{
$request = $this->getRequest();
$registry = Zend_Registry::getInstance();
$auth = Zend_Auth::getInstance();
$DB = $registry['rdvs'];
$authAdapter = new Zend_Auth_Adapter_DbTable($DB);
$authAdapter->setTableName('user')
->setIdentityColumn('user_name')
->setCredentialColumn('password');
// Set the input credential values
$uname = $request->getParam('username');
$paswd = $request->getParam('pwd');
$authAdapter->setIdentity($uname);
$authAdapter->setCredential(md5($paswd));
// Perform the authentication query, saving the result
$result = $auth->authenticate($authAdapter);
if($result->isValid()){
//print_r($result);
$data = $authAdapter->getResultRowObject(null,'password');
$auth->getStorage()->write($data);
$this->_redirect('/service/');
}else{
$this->_redirect('/index/');
}
}
When i rum my web app then its given Exception :
Message: No database adapter present
I don't understand where i difine database or phpmyadmin connection.
A: It's likely that something is messed up in the registry object. What you can do, instead, is when you create the database connection call Zend_Db_Table_Abstract::setDefaultAdapter($db) instead of putting it into the registry. Most of the components in ZF will look there if a database adapter isn't explicitly given to them.
A: replace
$DB = $registry['rdvs'];
with
$DB = Zend_Db_Table::getDefaultAdapter();
I hope you have setup your db configuration in your application.ini properly if not then
append the following in [production] section of your application.ini and setup the values accordingly like username , password , dbname
resources.db.adapter = PDO_MYSQL
resources.db.isDefaultAdapter = true
resources.db.params.host = localhost
resources.db.params.username = root
resources.db.params.password =
resources.db.params.dbname = myDbName
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514536",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: MVC Validation input-validation-error CSS not working with the custom validation MVC Validation "input-validation-error" CSS not working with the custom validation, any help please ?
A: I used another methodology to solve this problems
is to create my own attribute that inherits from the .net built-in Attribute
for more details please visit This
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514537",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: encount DOMException when remove node i encount DOMException.HIERARCHY_REQUEST_ERR when navigate the Document object to remove a pecific node, and after google this error code, It says:
"HIERARCHY_REQUEST_ERR: Raised if this node is of a type that does not allow children of the type of the newChild node, or if the node to insert is one of this node's ancestors or this node itself, or if this node is of type Document and the DOM application attempts to insert a second DocumentType or Element node"
I have check the node type which i want to remove, both Element and Text type will cause the exception
here is my code
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document dom = builder.parse(new ByteArrayInputStream(smil.getBytes()));
Element root = dom.getDocumentElement();
Node node = root.getFirstChild();
dom.removeChild(node);
it goes
org.w3c.dom.DOMException
at org.apache.harmony.xml.dom.InnerNodeImpl.removeChild(InnerNodeImpl.java:180)
A: I found one method can solve this situation
change
dom.removeChild(node);
to
node.getParentNode().removeChild(node);
it seems works for me :-)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514544",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to convert an address stored in char array to actual address? I have following char array:
char hex[16] = "0x7fffa410c240"
How can i convert it into numerical address that can be assigned to another variable.
Important is that i have to keep the base of value remaining the same i.e. 16 (hexadecimal).
Thanks in advance.
A: Try the function strtoull which returns unsigned long long.
On Visual Studio strtoull is not available, but _strtoui64 can probably be used.
EDIT
As R.. mentions in the comments you should probably use sscanf(hex, "%p", ..) or strtoumax which has the same prototype as strtoull but returns an uintmax_t.
A: void *ptr;
sscanf(hex, "%p", &ptr);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514546",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to use footer in joomla 1.5 I am new in joomla 1.5 and I think it's not use footer menu but I want write some text on footer.So please tell me how this is possible.
A: its easy to implement .i have already done in my site.i have used this Module for that purpose.
Steps:-
1.Create your Article (write your text)path-->your domin/administrator-->content-->Article Manager -->New Article
2.Install that modules .
3.give your Article id into that module parameter .
4.Set module on the "footer" position.
Now you got result.
All The Best...
With Regards,
R.Ram kumar.
A: The easiest way would be to create a custom HTML module, insert your content in there and then put that module on the "footer" position.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514550",
"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.