text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: PHP MySQL Dropdown box I have a dropdown box which is populated through MySQL:
echo "<form>";<br>
echo "Please Select Your Event<br />";
echo "<select>";
$results = mysql_query($query)
or die(mysql_error());
while ($row = mysql_fetch_array($results)) {
echo "<option>";
echo $row['eventname'];
echo "</option>";
}
echo "</select>";
echo "<input type='submit' value='Go'>";
echo "</form>";
How do i make it that if one clicks submit it will display a value from a MySQL db
Thanks for the help
A: Just change your query like SELECT result FROM somedb WHERE eventname = '".$eventname."'
Then you just do: (remember to check before while has user already requested info)
The value was: <?php print $row["result"]; ?>
Remember to check $_POST["eventname"] with htmlspecialchars before inserting it to query.
A: 1) Give a name to your <select>, i.e. <select name='event'>.
2) Redirect your form to the display page (and set method POST): <form method='POST' action='display.php'>
3) just display the selected value: <?php echo $_POST['event']; ?>
If you want to use the same page, give a name to your submit button and then do this:
<?php
if (isset($_POST['submit']))
echo $_POST['event'];
?>
Hope it helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554947",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Trouble with while loop and storing data I need to get a while loop to read 6 int values at each repetition and store it in an int local variable. I attempted something like the code below which throws an error. I also tried to change the array size however it still doesnt seem to work.
String fileName = "Data.txt";
int [] fill = new int [6];
try{
Scanner fileScan = new Scanner(new File(fileName));
int i = 0;
while (fileScan.hasNextInt()){
Scanner line = new Scanner(fileScan.nextLine());
i++;
line.next();
fill[i] = line.nextInt();
System.out.println(fileScan.nextInt());
}
}catch (FileNotFoundException e){
System.out.println("File not found. Check file name and location.");
System.exit(1);
}
}
The Error
> run FileApp
0
0
1
java.lang.ArrayIndexOutOfBoundsException: 4
at FilePanel.<init>(FilePanel.java:35)
at FileApp.main(FileApp.java:14)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:271)
>
Can someone help me fix this and explain to me why?
Also the Data.txt contains
1 1 20 30 40 40
0 2 80 80 50 50
0 3 150 200 10 80
1 1 100 100 10 10
A: You're creating an array of size 4, and you're storing values in there for as many values as there are input lines. Except you're actually starting with array index 1, because you're incrementing i before the array store. So when you come to the fourth line, you're trying to use fill[4] which throws the exception you've seen.
Given that your code doesn't know how many lines there will be, I'd suggest using a List<Integer> instead of an array.
You're also not reading 6 int values from each line - you're reading each line, and then parsing the first int from each of those lines.
A: I analyzed your problem.
What you are trying to inside while loop,fileScan.next() you save in line(Scanner reference).There are 4 lines in your Data.txt. Therefore fileScan.next is possible only 4 times. At the end of each loop you print filescan.nextInt(),but at the end of 4th loop it doesn't have next line to print nextInt so it gives error.
And also you have to increment i at the end of while loop otherwise it saves start from fill[1].
A: You can use the following code. May be it may be useful for you.
String fileName = "Data.txt";
int[] fill = new int[12];
try
{
Scanner fileScan = new Scanner(new File(fileName));
int i = 0;
while(fileScan.hasNextInt())
{
Scanner line = new Scanner(fileScan.nextLine());
// System.out.println(fileScan);
// System.out.println(line);
line.next();
fill[i] = line.nextInt();
System.out.println("fill" + fill[i]);
// System.out.println(fileScan.nextInt());
i++;
}
}
catch (FileNotFoundException e)
{
System.out.println("File not found. Check file name and location.");
System.exit(1);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554951",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Mysql data warehouse SQL Query Help please I have the following database
db: exam_2011
tables: score_01, score_02, score_03.....score_12
db: exam_2012
tables: score_01, score_02, score_03.....score_12
the database is the year and the tables are the month;
How can I get the data between 1 July 2011 to 2 February 2012?
Please help to construct the query. The database server is mysql. Thanks. This is not homework or school stuff.
A: I assume that you have a column named day in these tables:
select * from exam_2011.score_07
union all
select * from exam_2011.score_08
union all
select * from exam_2011.score_09
union all
select * from exam_2011.score_10
union all
select * from exam_2011.score_11
union all
select * from exam_2011.score_12
union all
select * from exam_2012.score_01
union all
select * from exam_2012.score_02 where day <= 2
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554954",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Daily Automatic post in facebook users wall I'm trying to do a Script to post a message to all application users wall every day. It works for more or less 10 users but then it suddenly stops. I ask only for the publish_to_stream permission but it seems to work properly. I have read some post saying to add a sleep between facebook api calls but it doesn't seem to work. Have anyone tested this ? I have read also somthing about facebook limits ? Have anyone read something about this limits ?
My code is very simple :
$facebook = new Facebook(array(
'appId' => 'xxxxxxxx',
'secret' => 'xxxxxxxxxxxxxx',
));
$post = array(
'message' => 'Message to user',
);
//for every user
while($row = mysql_fetch_array($res)){
$USER_ID = $row["uid"];
$post_id = $facebook->api("/$USER_ID/feed", "post", $post);
sleep(10);
}
Can anybody put some light on this ?
Thanks in advance!
A: Finally I solved it using a try catch block :
try {
$post_id = $facebook->api("/$USER_ID/feed", "post", $currentPost);
} catch(FacebookApiException $e) {
//error sending the post
}
That was the reason why the script stops.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554956",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: SelectedValue property for a Autocomplete User Control in GridView First off, forgive my English. I created one user control with Textbox and AutoCompleteExtender controls, and it's working fine. Now, I wanted to reflect my textbox similar to a dropdownlist. When i kept the user control in a GridView and accessed the value through a hidden field, i'm getting "0" value. How can i read hidden field value in my page?
UserControl.ascx
<%@ Control Language="C#" AutoEventWireup="true" Code File="UserControl.ascx.cs"
Inherits="UserControl" %> <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<script type="text/java script">
function DispValue(sender, e) {
alert(e.get_value() + " : user control");
document.getElementById(hiddenFieldName.Client ID).value = e.get_value();
}
</script>
<asp:Hidden Field ID="hdnValue" runat="server" Value="0" />
<asp:Text Box ID="txtName" runat="server" Text=""> </asp:Text Box>
<cc1:AutoCompleteExtender ID="ACEName" TargetControlID="txtName" runat="server"
CompletionInterval="10" MinimumPrefixLength="1" Service Method="Get Name"
Service Path="UserControlWebServices.asmx" OnClientItemSelected="DispValue">
</cc1:AutoCompleteExtender>
UserControl.ascx.cs
public partial class UserControl : System.Web.UI.UserControl
{
protected void page_load(object sender, EventArgs e)
{
ACEName.ContextKey = "1";
}
public String SelectedValue
{
get { return this.hdnValue.Value; }
}
public String SelectedText
{
get { return this.Name.Text; }
}
}
MyAspxPage.aspx
<%@ Register Src="~/UserControl.ascx" TagPrefix="puc" TagName="UserControl" %> <head runat="server">
<title></title> </head> <body>
<form id="form1" runat="server">
<asp:Script Manager ID="ScriptManager1" runat="server" EnablePageMethods="true">
</asp:Script Manager>
<asp:Grid View ID="gvPatient" runat="server" AutoGenerateColumns="false" OnDataBound="GridPatient_DataBound">
<Columns>
<asp:Template Field>
<Header Template>
Patient Name
</Header Template>
<Item Template>
<puc:UserControl ID="pucPatient1" runat="server" />
</Item Template>
</asp:Template Field> </Columns>
</asp:Grid View>
<asp:Button ID="btnSave" runat="server" OnClick="Save" Text="Save" OnClientClick="return StartUpload();" />
</form>
</body>
</HTML>
MyAspxPage.cs
DataTable dt;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
dt = new DataTable();
dt.Columns.Add("col1");
dt.Columns.Add("col2");
dt.Columns.Add("col3");
dt.Columns.Add("col4");
dt.Columns.Add("col5");
dt.Columns.Add("col6");
if (Session["dt"] == null)
{
dt = AddRow(dt);
gvPatient.DataSource = dt;
gvPatient.DataBind();
Session["dt"] = dt;
//ViewState["dt"] = dt;
}
else
dt = (DataTable)Session["dt"];//ViewState["dt"];
}
}
private DataTable AddRow(DataTable dt)
{
for (int i = 0; i < 5; i++)
{
DataRow dr = dt.NewRow();
dr[0] = "";
dr[1] = "";
dr[2] = "";
dr[3] = "";
dr[4] = "";
dr[5] = "";
dt.Rows.Add(dr);
}
return dt;
}
protected void GridPatient_DataBound(object sender, EventArgs e)
{
foreach (GridViewRow item in gvPatient.Rows)
{
UserControl ptuc = (UserControl)item.FindControl("pucPatient1");
string id = ptuc.SelectedValue;
}
}
public void Save(object sender, EventArgs e)
{
foreach (GridViewRow item in gvPatient.Rows)
{
if (item.RowType == DataControlRowType.DataRow)
{
UserControl ptuc = (UserControl)item.FindControl("pucPatient1");
string id = ptuc.SelectedValue;//getting null value.
string patientName = ptuc.SelectedText;
}
} }
this is all what i did.
i'm stuck with this please help me.
Sharanamma
A:
Hi friends
Thanks for your valuable reply,
actually its working fine, but small change in UserControl
clientselected event side,i,e
UserControl.ascx function DispValue(sender, e) {
var source = sender.get_id();
var lastIndex = source.lastIndexOf("_");
var replaced = source.substring(0, lastIndex + 1);
var hdnId = replaced + "hdnPatientNumber";
document.getElementById(hdnId).value = e.get_value();
}
UserControl.ascx.cs public String SelectedValue
{
get { return Request.Form[this.hdnPatientNumber.UniqueID];
}
}
Thanking you all, regards, Sharanamma.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554957",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How can I make my ScrollViewer pass Click events through to the control behind it? I have two grids overlaying one another, and the top layer is in a ScrollViewer. The problem is the bottom layer has click events, and they don't get triggered with the ScrollViewer there.
Is there a way to have the ScrollViewer pass click events to the control behind it?
<Grid>
<local:MyBackgroundControlWithClickEvents />
<ScrollViewer>
<local:MyForegroundControlWithClickEvents />
</ScrollViewer>
</Grid>
A: Click events bubble up the visual tree to the root, because your control is not a parent of the ScrollViewer, it will not receive these events. I know they might overlap on screen, but as far as the visual tree is concerned they are siblings, not parent / child.
To make this work, you could change MyBackgroundControlWithClickEvents into a ContentControl and host the ScrollViewer within it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554967",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Move left and right in UIScrollView I have a UIScrollView which scrolls only horizontally. I have a situation where I have views filled by array in UIScrollView. There are three views which altogether make one single component in UIScrollView (there are many such components). Component contains :
*
*UILabel
*UIButton
*UIView (for underlying text)
I have placed two arrow keys(left and right) at the ends of UIScrollView. On touching left arrow I am shifting one position left (with complete string to display) in UIScrollView and one position right (with complete string to display) in case of right arrow button.
Till now I am able to perform left arrow action. But I have no idea how to perform right arrow touch and how to display complete string to touching arrow keys if only part of that string is being displayed.
I know it is weird that I have a UIScrollView and still want to add arrow keys to move it. But can't help it. This is client's requirement. The following is how I implemented left arrow action:
-(IBAction) onClickLeftArrow
{
NSLog(@"BUTTON VALUE : %i",iButtonValue);
if(iButtonValue <= [m_BCListArray count]) {
NSArray *arr = [scrollDemo subviews];
for(int j = 0; j < [arr count]; j++) {
UIView *view1 = [arr objectAtIndex:j];
[view1 removeFromSuperview];
}
XX = 5.0;
int tagcount = [m_BCListArray count]-iButtonValue;
NSLog(@"%@",m_BCListArray);
for(int i = iButtonValue; i >= 1; i--)
{
UILabel *blabel = [[UILabel alloc] initWithFrame:CGRectMake(XX, 6, 120, 26)];
blabel.text = [m_BCListArray objectAtIndex:[m_BCListArray count]-i];
blabel.backgroundColor = [UIColor clearColor];
blabel.textColor = [UIColor whiteColor];
blabel.font = [UIFont systemFontOfSize:14];
[scrollDemo addSubview:blabel];
//underline code
CGSize expectedLabelSize = [[m_BCListArray objectAtIndex:[m_BCListArray count]-1] sizeWithFont:blabel.font constrainedToSize:blabel.frame.size lineBreakMode:UILineBreakModeWordWrap];
CGRect newFrame = blabel.frame;
newFrame.size.height = expectedLabelSize.height;
blabel.frame = CGRectMake(blabel.frame.origin.x, blabel.frame.origin.y, expectedLabelSize.width+10, expectedLabelSize.height);
blabel.numberOfLines = 1;
[blabel sizeToFit];
int width=blabel.bounds.size.width;
int height=blabel.bounds.size.height;
UIButton *btnContent = [UIButton buttonWithType:UIButtonTypeCustom];
[btnContent addTarget:self action:@selector(SelectButton:)forControlEvents:UIControlEventTouchDown];
btnContent.tag = tagcount+1;
btnContent.frame=CGRectMake(XX, 2.0, width+10, height);
[scrollDemo addSubview:btnContent];
scrollDemo.contentSize = CGSizeMake(XX+50, 32);
//scrollDemo.contentSize = CGSizeMake(expectedLabelSize.width,expectedLabelSize.height);
UIView *viewUnderline=[[UIView alloc] init];
viewUnderline.frame=CGRectMake(XX, 26, width, 1);
viewUnderline.backgroundColor=[UIColor whiteColor];
[scrollDemo addSubview:viewUnderline];
[viewUnderline release];
scrollDemo.contentSize = CGSizeMake(XX+width+10, 32);
XX = XX + width+10;
iRight = iRight + 1;
tagcount ++;
// iRight --;
}
}
iButtonValue = iButtonValue+1;
}
A: Set the contentOffset of UIScrollView on the Button click action and u'll get your desired effect.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554968",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: update foreignkey items from django shell Following is the models.py:
class UserProfile(models.Model):
user = models.OneToOneField(User)
belongs_to_user_category = models.ForeignKey(UserCustomCategory, null=True, blank=True)
class UserHistory(models.Model):
date_time = models.DateTimeField()
user = models.ForeignKey(UserProfile, null=True, blank=True)
points_earned = models.DecimalField(max_digits=5, decimal_places=3)
as is clear, userhistory is a foreign key to UserProfile. For the test purpose i wanted to update the points of the user whose name starts with a
I wrote the following code in the python shell:
from myapp.models import *
uobj = UserProfile.objects.all()
for i in uobj:
if i.user.username[0] == 'a':
b = UserHistory.objects.create(user=i)
b.points_earned = random.random(10, 100)
b.date_time = datetime.datetime.now()
b.save()
i have also tried b = UserHistory.objects.get_or_create(user=i) with same error
and i get the following error:
ERROR: An unexpected error occurred while tokenizing input
The following traceback may be corrupted or invalid
The error message is: ('EOF in multi-line statement', (160, 0))
ERROR: An unexpected error occurred while tokenizing input
The following traceback may be corrupted or invalid
The error message is: ('EOF in multi-line statement', (13, 0))
ERROR: An unexpected error occurred while tokenizing input
The following traceback may be corrupted or invalid
The error message is: ('EOF in multi-line statement', (63, 0))
ERROR: Internal Python error in the inspect module.
Below is the traceback from this internal error.
Traceback (most recent call last):
File "/usr/local/lib/python2.6/dist-packages/IPython/ultraTB.py", line 667, in text
locals,formatvalue=var_repr))
File "/usr/lib/python2.6/inspect.py", line 875, in formatargvalues
specs.append(strseq(args[i], convert, join))
File "/usr/lib/python2.6/inspect.py", line 830, in strseq
return convert(object)
File "/usr/lib/python2.6/inspect.py", line 872, in convert
return formatarg(name) + formatvalue(locals[name])
KeyError: 'connection'
IPython's exception reporting continues...
---------------------------------------------------------------------------
IntegrityError Traceback (most recent call last)
IntegrityError: (1048, "Column 'date_time' cannot be null")
A: When you use the create method of the default model manager in Django, it will also attempt to create that instance into the database and save it. You can do this in two ways, but I'll show you what you can do with your approach, which may help in some understanding.
First, you will want to create a UserHistory object, but don't actually save it. This is done by simply instantiating that model class with any default values you'd like:
b = UserHistory(user=i)
After that, you can set the other attributes.
b.points_earned = random.randint(10, 100)
b.date_time = datetime.datetime.now()
b.save()
And this will work. Because you're now saving b after you've set the date_time.
There are ways to improve this of course, you can simply create everything in one call since you're doing it in one logical step, like so:
b = UserHistory.objects.create(
user=i,
points_earned=random.randint(10, 100),
date_time=datetime.datetime.now(),
)
You can further improve this by reading the DateField docs for Django, which will give you some tips on how to set the default date to the current time.
Hope this helps!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554969",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to find and execute a method on another java application currently running on computer using java? For example, lets say I have hello.java (arbitrarily), if it was running and user changed some accessible (not private) variable in that application by providing input while running, this application would have the variable different compared to one not executed yet. And another program (preferably java) can get or show the updated information on that variable from that application.
A: A variable holds a piece of information in memory. If you want to make it accessible from another program, you have two choices :
*
*make it available using some communication protocol (plain socket, RMI, etc.)
*store it in a persistent store (the file system, a database), and have the second program read the persistent value from this persistent store.
A: Yours is the problem of accessing an object in a JVM remotely. RMI seems good choice for this.
Here there will be two parts to your application
*
*RMI server which will be the your application where the variable chance is supposed to happen.
*RMI client which will access the server for latest update information.
There are many good tutorial including the Wiki link above. Check this out.
A: *
*propriatary protocol (via socket)
*embed HTTP server into your application and implement web service based communication.
*use JMX
*Use JDI (Java Debugger Interface).
$1 and $2 require some modification of controlled application. $3 and $4 do not require any modification of your applcation.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554971",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Associating high res images with Open Graph objects I'm building a testing app for the new FB Timeline and I've noticed that when an application posts activity to a user's timeline, and that user then 'features' the activity, the activity is displayed nice and widescreen but the image used is a scaled up version of the image defined in the og:image meta tag.
My question then: Does anyone know a way to associate a high res image with an open graph object so that it can be displayed nicely as a featured event on a user's timeline?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554977",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Post To Facebook message about my app i am already got the fbconnect well and can show the dialog to post on my wall.
but now i want a post to be shown when the user logs in.
post a message that will be ready in NSString Format before.
how can i do it without the dialog box?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554981",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How do I create and use a .NET metadata-only 'Reference Assembly'? Since version 3.0, .NET installs a bunch of different 'reference assemblies' under C:\Program Files\Reference Assemblies\Microsoft...., to support different profiles (say .NET 3.5 client profile, Silverlight profile). Each of these is a proper .NET assembly that contains only metadata - no IL code - and each assembly is marked with the ReferenceAssemblyAttribute. The metadata is restricted to those types and member available under the applicable profile - that's how intellisense shows a restricted set of types and members. The reference assemblies are not used at runtime.
I learnt a bit about it from this blog post.
I'd like to create and use such a reference assembly for my library.
*
*How do I create a metadata-only assembly - is there some compiler flag or ildasm post-processor?
*Are there attributes that control which types are exported to different 'profiles'?
*How does the reference assembly resolution at runtime - if I had the reference assembly present in my application directory instead of the 'real' assembly, and not in the GAC at all, would probing continue and my AssemblyResolve event fire so that I can supply the actual assembly at runtime?
Any ideas or pointers to where I could learn more about this would be greatly appreciated.
Update: Looking around a bit, I see the .NET 3.0 'reference assemblies' do seem to have some code, and the Reference Assembly attribute was only added in .NET 4.0. So the behaviour might have changed a bit with the new runtime.
Why? For my Excel-DNA ( http://exceldna.codeplex.com ) add-in library, I create single-file .xll add-in by packing the referenced assemblies into the .xll file as resources. The packed assemblies include the user's add-in code, as well as the Excel-DNA managed library (which might be referenced by the user's assembly).
It sounds rather complicated, but works wonderfully well most of the time - the add-in is a single small file, so no installation of distribution issues. I run into (not unexpected) problems because of different versions - if there is an old version of the Excel-DNA managed library as a file, the runtime will load that instead of the packed one (I never get a chance to interfere with the loading).
I hope to make a reference assembly for my Excel-DNA managed part that users can point to when compiling their add-ins. But if they mistakenly have a version of this assembly at runtime, the runtime should fail to load it, and give me a chance to load the real assembly from resources.
A: If you are still interested in this possibility, I've made a fork of the il-repack project based on Mono.Cecil which accepts a "/meta" command line argument to generate a metadata only assembly for the public and protected types.
https://github.com/KarimLUCCIN/il-repack/tree/xna
(I tried it on the full XNA Framework and its working afaik ...)
A: Yes, this is new for .NET 4.0. I'm fairly sure this was done to avoid the nasty versioning problems in the .NET 2.0 service packs. Best example is the WaitHandle.WaitOne(int) overload, added and documented in SP2. A popular overload because it avoids having to guess at the proper value for *exitContext" in the WaitOne(int, bool) overload. Problem is, the program bombs when it is run on a version of 2.0 that's older than SP2. Not a happy diagnostic either. Isolating the reference assemblies ensures that this can't happen again.
I think those reference assemblies were created by starting from a copy of the compiled assemblies (like it was done in previous versions) and running them through a tool that strips the IL from the assembly. That tool is however not available to us, nothing in the bin/netfx 4.0 tools Windows 7.1 SDK subdirectory that could do this. Not exactly a tool that gets used often so it is probably not production quality :)
A: To create a reference assembly, you would add this line to your AssemblyInfo.cs file:
[assembly: ReferenceAssembly]
To load others, you can reference them as usual from your VisualStudio project references, or dynamically at runtime using:
Assembly.ReflectionOnlyLoad()
or
Assembly.ReflectionOnlyLoadFrom()
If you have added a reference to a metadata/reference assembly using VisualStudio, then intellisense and building your project will work just fine, however if you try to execute your application against one, you will get an error:
System.BadImageFormatException: Cannot load a reference assembly for execution.
So the expectation is that at runtime you would substitute in a real assembly that has the same metadata signature.
If you have loaded an assembly dynamically with Assembly.ReflectionOnlyLoad() then you can only do all the reflection operations against it (read the types, methods, properties, attributes, etc, but can not dynamically invoke any of them).
I am curious as to what your use case is for creating a metadata-only assembly. I've never had to do that before, and would love to know if you have found some interesting use for them...
A: You might have luck with the Cecil Library (from Mono); I think the implementation allows ILMerge functionality, it might just as well write metadata only assemblies.
I have scanned the code base (documentation is sparse), but haven't found any obvious clues yet...
YYMV
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554984",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "28"
}
|
Q: How to add subtext in TextView? I want to design a Layout in which I want subtext right below main text in Android.
Pictorially something like below.
____________________________________________
|<EMP NAME > | Location | ImageView |
|<designation> | |
|________________________________|___________|
In Iphone, UITableView there is option for detaulTextLable. How can I achieve this in Android. Any Idea?
My Xml file goes like below:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:orientation="horizontal"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_below="@+id/addEmployee"
android:layout_weight="1" android:layout_height="wrap_content"
android:clickable="true" android:padding="2dip" android:layout_margin="5dip"
android:layout_marginBottom="2dip" android:layout_marginTop="2dip"
android:paddingBottom="2dip" android:background="#F5F5F5" android:fitsSystemWindows="true"
android:focusableInTouchMode="true">
<TextView android:layout_weight="1" android:id="@+id/add_employee_name"
android:clickable="true" android:layout_width="0dp" android:text="Enter Name"
android:layout_gravity="fill" android:layout_marginLeft="2dip"
android:layout_marginRight="2dip" android:layout_height="match_parent"
android:gravity="left|center" android:textStyle="bold"
android:paddingLeft="5dip" android:lineSpacingMultiplier="1.0" android:lines="3">
</TextView>
<!--
<TextView android:layout_weight="1" android:id="@+id/add_emp_designation">
</TextView>
Need to add a new text view for employees designation or textview has options for subtitles.
-->
<TextView android:layout_weight="0.4"
android:id="@+id/add_employee_location" android:clickable="true"
android:layout_width="0dp" android:text="Location" android:layout_gravity="fill"
android:layout_marginLeft="0dip" android:layout_marginRight="2dip"
android:layout_height="match_parent" android:textStyle="normal" android:paddingLeft="5dip" android:textColor="#B03060" android:gravity="bottom|right">
</TextView>
<ImageView android:id="@+id/employee_pic"
android:layout_gravity="right" android:src="@drawable/edit"
android:layout_width="wrap_content" android:layout_height="match_parent">
</ImageView>
</LinearLayout>
I am just confused how to achieve above layout. Adding a new textview adds it horizontally. Any idea?
A: Try using a vertical LinearLayout inside your horizontal linear layout. and in turn fill vertical LinearLayout with your desired multi line text
A: try this one:
<RelativeLayout android:layout_height="50sp"
android:layout_width="fill_parent">
<TextView android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:id="@+id/designation"
android:layout_toLeftOf="@+id/location"
android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Name"/>
<TextView android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:id="@+id/designation"
android:layout_width="wrap_content"
android:layout_toLeftOf="@+id/location" android:text="Designation"/>
<TextView android:layout_height="wrap_content"
android:layout_alignParentBottom="true" android:id="@+id/location"
android:layout_toLeftOf="@+id/image"
android:gravity="center_vertical|center_horizontal" android:layout_alignParentTop="true" android:text="Location" android:layout_width="80sp"/>
<ImageView android:textColor="@color/white"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="@+id/image"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:src="@drawable/nologo"/>
</RelativeLayout>
A: check out Relative Layout it will let you position some components relative to the parent and the rest will be relative to the other components you also have Table Layout with RowLayout in android but it's less flexible in my opinion.
A: Provided that you want the Location and ImageView to take up only just as much space as they need, the following layout will do the trick:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="fill_parent"
android:layout_height="wrap_content">
<LinearLayout android:layout_height="fill_parent"
android:layout_width="wrap_content" android:id="@+id/linearLayout1"
android:orientation="vertical" android:layout_weight="1">
<TextView android:text="TextView" android:id="@+id/EMP_NAME"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_weight="1"></TextView>
<TextView android:text="TextView" android:id="@+id/Description"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_weight="1"></TextView>
</LinearLayout>
<TextView android:id="@+id/location" android:text="TextView"
android:layout_height="fill_parent" android:layout_width="wrap_content"
android:gravity="center"></TextView>
<ImageView android:layout_height="wrap_content"
android:layout_width="wrap_content" android:id="@+id/YourImageView"
android:src="@drawable/icon"></ImageView>
</LinearLayout>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554986",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: php cache xml file for 1 hour I am trying to work out how to download an xml file to my server and keep it for 1 hour and then download it again, to cache it to speed my site up, but not having to much joy.
so far I just download it each time:
$data = file_get_contents('http://www.file.com/file.xml');
$fp = fopen('./file.xml', 'w+');
fwrite($fp, $data);
fclose($fp);
Can anyone help me out with adding in some caching for this please?
Thanks in advance
Richard
A: The best solution is to write a CRONJOB that runs once an hour, and generates the xml.
If you are somehow unable to, you could do the following solution using file modification time.
$sFileName = './file.xml';
$iCurrentTime = time();
$iFiletime = filemtime($sFileName);
if ($iFiletime < $iCurrentTime - 3600) {
$data = file_get_contents('http://www.file.com/file.xml');
$fp = fopen($sFileName, 'w+');
fwrite($fp, $data);
fclose($fp);
}
A: in some cases this is what caching means (what you wrote),
Unless you want to save it in memory (actual cache). in this case you need http://memcached.org
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554995",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Sharepoint 2010 deployment problem I have a VS2010 solution with two projects, MyProject.Silverlight and MyProject.Sharepoint. I want to automatically deploy the .xap silverlight ouput into the VirtualDirectories\80\wpresources folder.
The sharepoint project has a single module which references the silverlight output xap file using "project output references". The sharepoint project is configured with the "WebApplication" assembly deployment target.
If I set the .xap deployment type to anything other than ClassResource, the file ends up where I would expect it to be. However, if I choose ClassResource (which is the correct one, right?), I cannot see it being deployd anywhere.
This seems to only be the case when I use the "project output references" option. If I manually add the xap file as an existing item and choose deployment type ClassResource, it ends up in the correct folder.
Any clues?
A: If you want the XAP to be deployed at VirtualDirectories\80\wpresources, why would you choose ClassResources ?
The resources get embedded within the assembly which probably you are not looking for.
http://msdn.microsoft.com/en-us/library/aa543289.aspx
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554998",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Converting SQL Server database to local C# database I have created program that uses SQL Server database to store data. After a while (and lots of stored data) I have realized I don't need database on the server, local database running without server could do the job.
Now I need some advice how to export, convert or whatever, SQL Server database to local (sdf) database? I'm using VS 2010 and SQL Server 2008, I also have SQL Server Management Studio.
A: Check out the SQL Server to SQL Server Compact Edition Copy Tool available on CodeProject in C# source code:
Should do just what you need: copy data from SQL Server to a SQL Server Compact Edition .sdf file.
A: Use the Export database tool? If you are using MS Windows OS then you can access is through the JET interface.
A: Use my Export2sqlce.exe command line utility: http://erikej.blogspot.com/2010/02/how-to-use-exportsqlce-to-migrate-from.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555006",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Including a js or css file in velocity template I tried to add a js file or css file as i mentioned below in the .vm file
<script src='/templates/jquery-1.6.2.js>
it didn't work.
But when i tried adding as given below it worked
<script type="text/javascript">
#include( "jquery-1.6.2.js" )
</script>
But the issue is in the browser if do view source even the jquery-1.6.2.js code also appears.It doesnot hide the js code. Is there any alternate way to add the js or css file in velocity template ??
A: In case someone comes across this question, there is a straightforward way to include CSS styles in a Velocity template. I had a need to add some overrides to a .vm file, and putting a <style> tag with the appropriate rules inside <body> worked. I initially had the <style> inside the <head> tag but that wasn't being picked up by the parser for some reason. It looked fine in IE 8, FF 3.6, and Chrome.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555007",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Find all ContextMenuStrips defined on a Windows Form (not necessarily attached at runtime) In my winforms project, some of the forms have a set of ContextMenuStrips defined on them (through the visual studio designer).
Some of these contextmenustrips have been attached to controls, but others have not.
Now my problem is this: I need to go through all of the ContextMenuStrips at runtime, whether they are attached or not.
I've got some code that will recursively go through all controls and check the ContextMenuStrip property and this works fine.... However I can not get to the ContextMenuStrips that haven't been assigned to a control yet.
A: ContextMenuStrip components that you drop on a form with the designer are added to the "components" collection. You can find them back by iterating it:
For Each co As System.ComponentModel.Component In Me.components.Components
If TypeOf co Is ContextMenuStrip Then
Dim cms = DirectCast(co, ContextMenuStrip)
'' do something
End If
Next
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555012",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Swipe to delete is not working with custom cell I am using custom cell and adding tableview programmetically. I am trying to implement swipe functinality in my application. The tableview datasource method are not called when I try to swipe.
tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, 460) style:UITableViewStylePlain];
tableview.delegate=self;
tableview.dataSource=self;
tableview.backgroundColor=[UIColor clearColor];
tableview.backgroundColor=selectedBackGroundColor;
tableview.separatorColor = [UIColor clearColor];
tableview.editing=YES;
NSLog(@"%f %f",self.view.frame.size.width,self.view.frame.size.height);
[self.view addSubview:tableview];
and this method is calling
-(UITableViewCellEditingStyle)tableView:(UITableView*)tableView editingStyleForRowAtIndexPath:(NSIndexPath*)indexPath
{
return UITableViewCellEditingStyleDelete;
}
after that even cell is also not selecting...am i missing any thing code please help me out?
A: -(void)layoutSubviews
{
[super layoutSubviews];
}
Then Its Working Fine.....Thanks For answering my Question
A: Did you implement -(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath in the datasource.
A: If you have set the tableview to editing already I doubt that swipe to delete (and selections if allowsSelectionDuringEditing is NO) will work at all. Try removing this line:
tableview.editing=YES;
and see if the swiping is enabled.
A: use this implementation instead:
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete)
{
// Delete an object
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555016",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: PHPUnit best practice for fixation of value returned by protected method? consider the following code as PHP-style pseudo code to get my point across.
class C extends PHPUnit_Framework_TestCase
{
public function m1()
{
$v = $this->m2();
if($v == "x")
{
throw new Exception();
}
}
protected function m2()
{
[...];
return $v;
}
}
now I want to add a test that asserts that an Exception is thrown if m2() returns "x".
How can I simulate that?
I thought about using Reflection to redefine the method during runtime, but it seems that Reflection doesn't offer such a functionality and I would have to resort to experimental extensions like classkit or runkit. Would that be the way to go?
In this case I could extend the class and redefine m2() but where would I put that derived class then? In the same file as the test?
The latter solution wouldn't work anymore if I would choose m2 to be private.
I'm quite sure that there is a best practice to deal with this situation.
A: Ether I'm completely off on what you are trying to do here or you are doing something that confuses me greatly.
To me is seems that you are asking for is that you want to check that your test method throws an exception.
class C extends PHPUnit_Framework_TestCase
Why would you want to test your test method?
I'm going to assume that that is the real class and not your test
In that case I always strongly argue for just testing it as if the protected method would be inline in the public method.
You want to test the external behavior of your class. Not the implementation. The protected method is and implementation detail that your test shouldn't care about. That would mean that you would have to change your test when you change that protected method.
And from there on out:
class CTest extends PHPUnit_Framework_TestCase {
public function testM1NormalBehavior() {
}
/**
* @expectedException YourException
*/
public function testM1ThrowsExceptionWhenM2ConditionsAreMet() {
$c = new C('set_Up_In_A_Way_That_Makes_M2_Return_X');
$c->m1();
}
}
A: You can use a partial mock of C to force m2() to return "x". I'll assume that the extends PHPUnit_Framework_TestCase was accidental and that C is actually the class under test and not the unit test itself.
class CTest extends PHPUnit_Framework_TestCase {
/**
* @expectedException Exception
*/
function testM1ThrowsExceptionWhenM2ReturnsX() {
$c = $this->getMock('C', array('m2'));
$c->expects($this->once())->method('m2')->will($this->returnValue('x'));
$c->m1();
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555018",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Moving cursor with t and f, using word as parameter, vim Is it possible in vim to move forward with t and f (or in the other way with T and F), but using words as a parameter ?
A: What about /word?
It can be combined with operators just like anything else:
the lazy cow jumped over the high moon
cursor at start, d/highEnter:
high moon
Bonus
Also, you might be interested in learning some of the ex mode commands like that:
the lazy cow jumped over the high moon
the hazy cow jumped over the high moon
the noble cow jumped over the high moon
the crazy cow jumped over the high moon
Now enter
:g/azy/ norm! /jumped<CR>d/high/e<CR>
(Note: <CR> denotes C-vC-m for the enter key (^M))
Result:
the lazy cow moon
the hazy cow moon
the noble cow jumped over the high moon
the crazy cow moon
The /e flag achieves inclusive behaviour like with f; To get 'till behaviour instead:
:g/azy/ norm! /jumped<CR>d/high/<CR>
Result:
the lazy cow high moon
the hazy cow high moon
the noble cow jumped over the high moon
the crazy cow high moon
A: Try using * or # to search for instances of the word under the cursor. You’ll notice that it sets the pattern to \<foobar\>, so you can use a pattern like that to find the word you want, surrounded by word boundary characters.
A: You probably want to use /word for that kind of search.
set incsearch might also help.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555019",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: How to determine if a function with a given name exist in Javascript / jQuery? Given a function name as a string, how could I determine if such function exist (globally), and if yes, call to this function ?
I tried to do:
function foo() {
alert("foo called");
}
var func_name = "foo";
if (typeof window[func_name] == 'function') {
foo();
} else {
alert(func_name + " is not defined!");
}
But, it doesn't seem to work.
A: The reason your jsfiddle doesn't work is because the named function has been defined within jsfiddle's default onLoad wrapper.
This means that the function is only defined within the scope of that closure, and isn't added to the global object.
For testing purposes, just add your function explicitly to the global object by declaring it as:
window.foo = function() ...
A: I took a look and it seems to work in my browser console, but not in the fiddle. I was able to get it to work in fiddle by explicitly attaching the function to window:
window.foo = function() {
alert("foo called");
}
A: function foo() {
alert("foo called");
}
var func_name = "foo";
var funcObj = null;
try {
funcObj = eval(func_name);
funcObj();
} catch(e) {
// no function defined
}
A: Try with window[func_name] instanceOf Function or you can use jquery.isFunction method
A: Your code works if you change the way you declare the function (if you can do that)
foo = function() {
alert("foo called");
}
JSFIDDLE
A: I suggest you not to use the typeof variable === 'function', I prefer a function for checking a type, instead of the regular type checking. This approach saved me and my colleagues life many times. For example:
isFunction = function(val) {
return typeof val == 'function' && val.call !== 'undefined';
};
window.foo = function() {
alert("foo called");
};
var func_name = "foo",
/*for testing purpose*/fn = foo; // fn = window[func_name];
if (isFunction(fn)) {
fn();
}
else {
alert(func_name + 'is not defined!');
}
ps: the provided example is not the most perfect version of checking a function type because in IE cross-window calls function appears as object.
A: This should help you
if(typeof myFunctionName == 'function') myFunctionName()
Look at this link to seemore info about typeof operator
UPDATE
if(eval("typeof window."+myFnName) == 'function') eval(myFnName+"()");
But like the others stated, your original code works as expected.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555023",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Fastest way to sort an array by timestamp how can i sort this array by timestamp and what is the fastest way (array has many many entries)?
my array
myList = new Array();
myList[0] = {};
myList[0]['title'] = 'I am really new';
myList[0]['timestamp'] = 1317039046;
myList[0]['date'] = '2011-09-26T12:10:46+00:00';
myList[1] = {};
myList[1]['title'] = 'I am the oldest';
myList[1]['timestamp'] = 1315656646;
myList[1]['date'] = '2011-09-10T12:10:46+00:00';
myList[2] = {};
myList[2]['title'] = 'I am older';
myList[2]['timestamp'] = 1316866246;
myList[2]['date'] = '2011-09-24T12:10:46+00:00';
myList[3] = {};
myList[3]['title'] = 'I am old';
myList[3]['timestamp'] = 1316952646;
myList[3]['date'] = '2011-09-25T12:10:46+00:00';
example
http://jsbin.com/ejagup/2/edit#preview
A: myList.sort(function(x, y){
return x.timestamp - y.timestamp;
})
myList is a JavaScript array, which supports the sort method. This method accepts a function as argument, which sorts the array according to the returned value.
Currently, the sort algorithm will place the element with the lowest timestamp first. Swap x.timestamp and y.timestamp if you want to sort the array in the other direction.
A: The easiest way to sort an array by date in JavaScript,
Here is an example of how this method of sorting an array by date in JavaScript looks
const fetchMessageData = () => {
return (
AllMessagesArr.sort((x, y) => {
return new Date(x.timestamp) < new Date(y.timestamp) ? 1 : -1
})
).reverse()
}
console.log("Display messages in Ascending order" ,fetchMessageData())
Sort the array on basis of timestamp
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555025",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "57"
}
|
Q: TFS 2010 API - Get work items from merge I need to send an email on completion of a build in TFS 2010 which details the work items associated with check-ins that have been compiled as part of this build. This works no problem via use of the associatedChangesets variable available in the build workflow.
However, in a production situation, we will merge changes from our Development branch into a Release branch. At this point, the build considers there to have only been one change - which is the aforementioned merging of Development into Release. Obviously this is fairly useless as we need to find out which changes where made in the branch that was merged in, and the work items associated.
Does anyone know how to accomplish this using the TFS 2010 API? It seems to be fairly poorly documented from an API perspective. I know you can expand the merge history node in VS2010 but obviously this is no good as this data needs to be collected programatically so a report email can be sent.
A: OK... I think I found a solution to this although it's clunky and truth be told I'm not exactly sure how it works. But here goes - maybe it will point someone in the right direction.
var associatedWorkItems = new List<WorkItem>();
//Passed in from the build workflow (this variable is available under the 'Run On Agent' sequence as 'associatedChangesets'
IList<Changeset> associatedChangesets = context.GetValue(BuildAssociatedChangesets);
if (associatedChangesets.Count > 0)
{
var projectCollection =
new TfsTeamProjectCollection(new Uri("http://localhost:8080/tfs/DefaultCollection"));
VersionControlServer versionControlServer = projectCollection.GetService<VersionControlServer>();
foreach (var changeset in associatedChangesets)
{
//In order to view the individual changes, load the changeset directly from the VCS.
Changeset localChangeset = versionControlServer.GetChangeset(changeset.ChangesetId);
foreach (Change change in localChangeset.Changes)
{
//Find out what was merged in.
ChangesetMerge[] mergedChangesets = versionControlServer.QueryMerges(
null,
null,
change.Item.ServerItem,
new ChangesetVersionSpec(localChangeset.ChangesetId),
new ChangesetVersionSpec(localChangeset.ChangesetId),
null,
RecursionType.Full);
//Extract work item information from changesets being identified as merged.
foreach (var changesetMerge in mergedChangesets)
{
Changeset actualChange = versionControlServer.GetChangeset(changesetMerge.SourceVersion);
foreach (WorkItem item in actualChange.WorkItems)
{
if (!associatedWorkItems.Exists(w => w.Id == item.Id))
{
associatedWorkItems.Add(item);
}
}
}
}
}
}
Don't ask me exactly how QueryMerges works but all I'm doing here it saying show me what what merged as a part of a changeset checked in. You'll notice that the parameters ChangesetVersionSpec are the same - this means we're just looking at merges from this one changeset.
You'll get back an array of ChangesetMerge objects from QueryMerges(). In the ChangesetMerge class there is a property called SourceVersion - this is the ChangesetId of the original changeset merged in. Once we've got that we can use the VersionControlServer.GetChangeset() method to load the individual set and extract the WorkItem. This is then added to a list of WorkItems which can be manipulated in any way you want (in my case an email). I also used the .Exists() check to make sure the same WorkItem doesn't get recorded twice.
Note that even though you have the collection associatedChangesets from the build workflow, for some reason (for me at least), the Changes[] property inside associatedChangesets was never populated (hence loading each individual changeset using the VersionControlServer.GetChangeset() method as this seems to actually populate all the fields we need.
Like I say, 1. this is a clunky solution (lots of looping - some of which is probably unecessary), 2. I don't fully understand how this works although it seems to produce the required results - I came to this conclusion by doing a lot testing and debugging) and finally - it's the best I could come up with based on the woeful documentation provided by Microsoft.
Hope it helps someone!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555028",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Mechanize get a file instead of a page object i try to scrap a web page. I use Nokogiri/ Mechanize. so if i make
page = agent.get(url)
page.class
=> Mechanize::File
, sometimes i get a page object sometimes a file object. but what i need is, everytime a page object. i tried to add a pluggable_parser for plain/text but this don't work for me.
have anyone an idea how i can fix it, or how i can find out the content-type from a file object or know, how i can cast a file to an page object?
Thanks Michael
A: Most likely the page you're requesting is unavailable and the server returns a plaintext error page.
See the docs on Mechanize::File.
The content type is in page.response['content-type'].
It's definitely possible to change the content type of the response and then create a Mechanize::Page from the data without having to download it again - but I don't think that would give you anything useful.
Check the response code as well, it's in page.code.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555035",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: jQuery search if found element child Hi my html looks like this:
<ul class="first">
<li>
<div class="tg-hey">hey</div>
<div class="tg-hi">hi</div>
<div class="tg-hoi">hoi</div>
</li>
</ul>
<ul class="second">
<li>
<div class="tg-hey">hey</div>
<div class="tg-hi">hi</div>
<div class="tg-hoi">hoi</div>
</li>
</ul>
<ul class="third">
<li>
<div class="tg-hey">hey</div>
<div class="tg-hi">hi</div>
<div class="tg-hoi">hoi</div>
</li>
</ul>
what i need is to find if (for example in <ul class="second">) the <div class="tg-hey"> exist or not.
how can i check it?
A: if($(".second:has(.tg-hey)").length) {
// do something
}
Demo.
If you need to do something to the matching element(s), you don't really need to test first, since nothing will happen if there are no matches, so:
$(".second:has(.tg-hey)").hide();
is perfectly safe.
Another way is to use .is and :has:
if($(".second").is(":has(.tg-hey)")) {
// do something
}
Demo.
but I wouldn't do that since it just seems like too much jQuery for a fairly simple task.
A: Just create the selector and check the length of the result (if it is 0 it will be false, otherwise it is true):
if ($('ul.second div.tg-hey').length) {
alert("It exists");
}
http://jsfiddle.net/SgnvH/
A: $(".second").has(".tg-hey").length > 0
A: Like this?
if ($('ul.second div.tg-hey').length > 0)
// exists
else
// doesn't
A: $('.className').length
if $('.className').length == 0, then the element does not exist.
Edit:
$('.second').length will tell you how many elements have the class "second".
$('.second .tg-hey').length will tell you how many elements have the class "tg-hey" inside the class "second".
This assumes that you are using jQuery!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555036",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Infobox in WPF Bing Maps I've recently started doing some stuff in WPF and I came up with an idea to integrate maps into my application. I tried some stuff with Google Maps, but the capabilities aren't that great, so after a while I gave up on Google Maps in WPF.
A little while later I bumped into Bing Maps. This looked way more promising than Google Maps to use with WPF. I've started playing around with Bing's Maps and the capabilities are great!
However, when I tried to put a pushpin on the map it wasn't immediately clear to me how to add a infobox to the pushpin, when hovering over it. I have found some examples how to do so, but it required procedural code linked to the xaml. I was actually looking for a method without using procedural code.
Is it possible to add a infobox to a pushpin with just xaml? Or does anyone have a good alternative method on how to do so?
There is a tooltip property available though, but I wasn't actually looking for that. I was actually looking for Google Maps' pushpin kind of style (if it is available).
A: Assuming I understand correctly what you want, I believe the short answer is: Sorry, but it's not possible to add a Google-Maps-style info box to a pushpin with just XAML. However, I'll try to help if I can.
Disclaimer: I've been playing with the Bing Maps control for Silverlight, so hopefully this will be applicable to the WPF version of the control as well.
I imagine that you don't want to use the built-in ToolTip either because you want it to look different (i.e. not just a yellow box with text) or because you want it to not disappear when the user moves the mouse away.
If you just want it to look different, I can offer the following. When I specified a template for my Pushpins, I went ahead and used a re-templated ToolTip and allowed the user to click the pushpin to get more information.
Here's the ToolTip template, defined as a StaticResource, which of course could contain anything you want:
<Style x:Key="MyToolTipStyle" TargetType="ToolTip">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<Border CornerRadius="5" BorderBrush="Black" BorderThickness="2" Background="#5c87b2">
<ContentPresenter Margin="5">
<ContentPresenter.Content>
<StackPanel Margin="5" MaxWidth="400">
<TextBlock Text="{Binding Name}" FontWeight="Bold" FontSize="16" Foreground="White" TextWrapping="Wrap"/>
<TextBlock Text="{Binding Description}" Foreground="White" TextWrapping="Wrap"/>
</StackPanel>
</ContentPresenter.Content>
</ContentPresenter>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
And here's where I used it:
<maps:Map>
<maps:MapItemsControl ItemsSource="{Binding SearchResultsManager.Items}">
<maps:MapItemsControl.ItemTemplate>
<DataTemplate>
<maps:Pushpin Location="{Binding Location}" Cursor="Hand" MouseLeftButtonUp="Pushpin_MouseLeftButtonUp">
<ToolTipService.ToolTip>
<ToolTip Style="{StaticResource MyToolTipStyle}" />
</ToolTipService.ToolTip>
</maps:Pushpin>
</DataTemplate>
</maps:MapItemsControl.ItemTemplate>
</maps:MapItemsControl>
</maps:Map>
Then I'd handle when the user clicked on the pushpin to take them to a details area.
private void Pushpin_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
// Get a reference to the object that was clicked.
var clickedSearchResult = (sender as FrameworkElement).DataContext as SearchResultViewModel;
// Do something with it.
}
However, I imagine you want to keep the ToolTip from disappearing, so that the user can click on controls inside it. Unfortunately, I'm not sure there's a simple way to do that. You might have to define your own custom control, which of course would require some C#/VB code.
Perhaps this new control could derive from Pushpin, and it could show the info box content on mouse-over and/or click. You could use the VisualStateManager to keep most of the code in XAML. The C#/VB would just have to provide a dependency property for the content and some overrides to transition between the visual states at the correct times.
I hope that's at least a little bit helpful!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555037",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Why numberOfSectionsInTableView is called twice in UITableViewController? Is there any other reason (than calling "reloadData") why numberOfSectionsInTableView is called twice? I did debugging and found, that it's get called twice during initial startup when no custom reloadData statements are called.
I have created the table with IB but does that might cause a problem?
A: Have a look at the call stack. you can see that this method is being called from two different scenarios.
A: Probably your tableView object may instantiate twice. Once i have encountered the same problem due to this.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555039",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
}
|
Q: How to convert a string to tuple I like to convert in a Python script the following string:
mystring='(5,650),(235,650),(465,650),(695,650)'
to a list of tuples
mytuple=[(5,650),(235,650),(465,650),(695,650)]
such that
print mytuple[0] yields:
(5,650)
A: I'd use ast.literal_eval:
In [7]: ast.literal_eval('(5,650),(235,650),(465,650),(695,650)')
Out[7]: ((5, 650), (235, 650), (465, 650), (695, 650))
As seen above, this returns a tuple of tuples. If you want a list of tuples, simply apply list() to the result.
A: That's not a tuple, that's a list.
If you can depend on the format being exactly as you've shown, you can probably get away with doing something like this to convert it to a list:
mystring2 = mystring.translate(None, "()")
numbers = mystring2.split(",")
out = []
for i in xrange(len(numbers) / 2)
out.append((int(numbers[2 * i), int(2 * i + 1])))
This can probably be improved using some better list-walking mechanism. This should be pretty clear, though.
If you really really want a tuple of tuples, you can convert the final list:
out2 = tuple(out)
A: Use eval
mytuple = eval(mystring)
If you want a list enclose mystring with brackes
mytuble=eval("[%s]" % mystring)
That's the 'simplest' solution (nothing to import, work with Python 2.5)
However ast.literate_eval seems more appropriate in a defensive context.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555044",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: HttpWebRequest an Unicode characters I am using this code:
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
string result = null;
using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())
{
StreamReader reader = new StreamReader(resp.GetResponseStream());
result = reader.ReadToEnd();
reader.Close();
}
In result I get text like 003cbr /003e003cbr /003e (I think this should be 2 line breaks instead). I tried with the 2, 3 parameter versions of Streamreader but the string was the same. (the request returns a json string)
Why am I getting those characters, and how can I avoid them?
A: It's not really clear what that text is, but you're not specifying an encoding at the moment. What content encoding is the server using? StreamReader will default to UTF-8.
It sounds like actually you're getting some sort of oddly-encoded HTML, as U+003C is < and U+003E is >, giving <br /><br /> as the content. That's not JSON...
Two tests:
*
*Use WebClient.DownloadString, which will detect the right encoding to use
*See what gets shown using the same URL in a browser
EDIT: Okay, now that I've seen the text, it's actually got:
\u003cbr /\u003e
The \u part is important here - that's part of the JSON which states that the next four characters form ar the hex representation of a UTF-16 code unit.
Any JSON API used to parse that text should perform the unescaping for you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555049",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: JSF 2 View Expired Weirdest Bug (Update - Occurs when saving state to server only) The bug is this -
I have several forms in my JSF application.
If I activate AJAX calls outside a specific form for 20 clicks or more, I get a "No Saved View State Could be found for the view identifier" exception.
UPDATE 1 This only occurs when the state is saved on the server. When this option is set, the problem doesn't occur:
<context-param>
<description>State saving method: 'client' or 'server' (=default). See JSF Specification 2.5.2</description>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>client</param-value>
</context-param>
END OF UPDATE 1
For example, suppose I have a form A, form B, form C in my app:
(The actuall app is very complex, I will try to bring all the relevant information)
<h:form>
<h:commandButton value="A">
<f:ajax render="@form"/>
<h:commandButton>
<h:form>
<h:form>
<h:commandButton value="B">
<f:ajax render="@form"/>
<h:commandButton>
<h:form>
<h:form>
<h:commandButton value="C">
<f:ajax render="@form"/>
<h:commandButton>
<h:form>
One more important factor, only one form is visible at each point in time, the other forms have display:none.
Finally, All beans are session scoped.
Now, The following clicks will cause the exception (For each row, the last click causes the exception)
*
*Ax20, B
*Ax19, B, C
*Ax10, Cx10, B
*Bx5, Cx5, Bx5, Cx5, A
This will not cause an exception:
*
*Ax18, B, C, A.
In other words, If a button in a form is not clicked in the last 20 clicks, the next time it is clicked, a No save view state exception is thrown.
All buttons in the same form are equivalent to the form, meaning, if form A had buttons A1 and A2 then the following would not cause an exception:
*
*A1x20, A2
*A1x19, B, A2
*A1, A2x20, B, A1
Any Idea?!? This is driving me nuts.
A: You've exceeded the number of views in session limit from a single page on. The limit is by default 15, but is configureable by a context param in web.xml. Each form is technically a separate view with its own view state. When you continuously ajax-update one form while untouching other forms, then their view state in server side will slowly but surely expire.
Saving the view state in the client side will indeed solve this problem, as nothing in the server side session will be stored. It only makes the response size a bit larger (bandwidth is however cheap nowadays).
If you want to keep the view state in the server side, then you should render the other forms from the single ajax form as well so that their view state will be updated as well:
<h:form id="A">
<h:commandButton value="A">
<f:ajax render="@form :B :C"/>
<h:commandButton>
<h:form>
<h:form id="B">
<h:commandButton value="B">
<f:ajax render="@form :A :C"/>
<h:commandButton>
<h:form>
<h:form id="C">
<h:commandButton value="C">
<f:ajax render="@form :A :B"/>
<h:commandButton>
<h:form>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555051",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Move from a single continuous HTML page to "separate pages" using CSS I have a (somewhat long) single page website that uses some CSS (e.g. each content item is a div) I would like to move this to a "set of separate pages" which are navigable by means of a menu.
so instead of
<head>...</head>
<body>
<div>stuff</div>
<div>more stuff</div>
<div>even more stuff</div>
</body>
I'd like to be able to navigate this so from the user-perspective, it appears to be
<head>...</head>
<body>
<div>stuff</div>
</body>
<head>...</head>
<body>
<div>more stuff</div>
</body>
<head>...</head>
<body>
<div>even more stuff</div>
</body>
Should I just break up the page into separate pages, use jQuery to hide all the other <div>'s or is there another more elegant method of achieving this?
A: A lot will depend on the context and what it is you're actually presenting, but if you're looking to break up the content, sometimes a tabbed interface is an acceptable solution. jQuery UI has some Tab functionality built in, and there are other plug-ins to accomplish similar functionality. If it's an FAQ style interface, then it may make sense to hide all the sections and show the sections when they click on the question/title, which can be accomplished with $("SOMETHING").toggle() in jQuery.
A: This should get you started:
<!doctype html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script>
$(function () {
var menu = $("<ul>").prependTo($("body"))
$("body > div").each(function () {
var div = this
var heading = $(this).find("h2").text()
menu.append($("<li>").text(heading).click(function () {
$("body > div").css({ display: "none" })
$(div).css({ display: "block" })
$("body > ul li").removeClass("current")
$(this).addClass("current")
}))
})
$("body > ul > :first-child").click()
})
</script>
<style>
body > ul li.current
{ font-weight: bold }
</style>
</head>
<body>
<div>
<h2>Heading A</h2>
<p>Content A</p>
</div>
<div>
<h2>Heading B</h2>
<p>Content B</p>
</div>
<div>
<h2>Heading C</h2>
<p>Content C</p>
</div>
</body>
</html>
A: There are several options depending on the result that you want to achieve.
Separating a long page into several pages is your standard method.
Another method is to show/hide the sections with some javascript. This will make the page look nicer (e.g. less long).
Another method would be to load in the content via some AJAX, which is a cross between the two. You would have your separate pages, then load the content in through javascript. This has the benefit of both, in that your AJAX loaded content will be a nice transition between pages, but you can code it in a way that search engines will go to the actual page.
Another option (depending on your content), which is a trend these days, is to have some sort of scrolling Parallax background. this is an example of one http://unfold.no/
These websites require knowledge of CSS3/javascript/design in order to create something nice.
A: Something like this should work in jQuery. I don't know of a way to get the same result with pure CSS.
$(document).ready(function() {
// get the hash (the part after the '#') from the URL
var hstr = window.location.hash.slice(1);
if (hstr && $("#"+hstr).length)
// 'hstr' is exactly the ID of the DIV you want to show
$showme = $("#"+hstr);
else
// show the first DIV by default
$showme = $("body > div").eq(0);
$showme.show().siblings().hide();
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555052",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What are the advantages of FastBitmapDrawable compared to Bitmap? package com.android.launcher;
import android.graphics.drawable.Drawable;
import android.graphics.PixelFormat;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
class FastBitmapDrawable extends Drawable {
private Bitmap mBitmap;
FastBitmapDrawable(Bitmap b) {
mBitmap = b;
}
@Override
public void draw(Canvas canvas) {
canvas.drawBitmap(mBitmap, 0.0f, 0.0f, null);
}
@Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
@Override
public void setAlpha(int alpha) {
}
@Override
public void setColorFilter(ColorFilter cf) {
}
@Override
public int getIntrinsicWidth() {
return mBitmap.getWidth();
}
@Override
public int getIntrinsicHeight() {
return mBitmap.getHeight();
}
@Override
public int getMinimumWidth() {
return mBitmap.getWidth();
}
@Override
public int getMinimumHeight() {
return mBitmap.getHeight();
}
public Bitmap getBitmap() {
return mBitmap;
}
}
A: It's not really fair to compare a FastBitmapDrawable to a Bitmap. Traditional Bitmaps are just a type of Object in Java. FastBitmapDrawables however, are a custom class written to extend the functionality of the Drawable class, not the Bitmap class.
A FastBitmapDrawable contains a traditional Bitmap, and makes a few assumptions that make it convenient to use in certain situations. This is the crucial line:
canvas.drawBitmap(mBitmap, 0.0f, 0.0f, null);
This FastBitmapDrawable assumes that the bitmap will be placed at (0, 0) on the screen, and that no special Paint object will be used to draw it.
Really it's just a convenience. You could get the same performance by manually setting the position to (0, 0) and the Paint to null in a normal Drawable, but this class does that for you automatically.
A: This is a utility class, in case you want to alter how a Bitmap is drawn. As it is, it doesn't add any functionality other than default behavior.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555054",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Locale-specific lookup table I'm using a lookup table for optimizing an algorithm that works on single characters. Currently I'm adding a..z, A..Z, 0..9 to the lookup table. This works fine in european countries, but in asian countries it doesn't make much sense.
My idea was that I could perhaps use the characters in the windows default code page as an alphabet for the lookup table.
Pseudocode:
for Ch in DefaultCodePage.Characters do
LookupTable.Add (Ch, ComputeValue (Ch));
What do you think and how could this be achieved? Any alternative suggestions?
A: As you mentioned, it does not make much sense for different scripts. It may only make some sense for alphabet-based languages.
BTW. A-Z is not enough for most of European languages.
I don't quite know what you are doing and what you need this look-up table for but it seems that what you are looking for are Index Characters. You could find such information in CLDR – look for indexCharacters. The resources for various languages are available here.
The only problem you'll face that in fact for some languages Index Characters tend to be Latin based. That is just because these languages do not actually have them... In that case you might want to use so called Exemplar Characters instead but please be warned that it might be just not enough for some use cases.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555063",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: What's the different between ad-hoc distribute and share from archive I want to send my application to tester, as far as I know, I can use ad-hoc distribute and I can share app from archive.
What's the different between ad-hoc distribute and share from archive???
share app from archive is means that
A: In the archive there is the profile you used to compile your code, but if you just build using ad-hoc the profile is not in the .app and you need to send it separatly.
So the share from archive is easier to use than the ad hoc way.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555073",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: HTML5 Saving Image from a Canvas in Javascript (Android) Im trying to make a HTML5 signature capture in Javascript.
It works already but i got a problem running it on Android.
The function canvas.toDataURL(); does not work on Androids standard browser.
Does someone know an alternative for saving a Canvas to an image(png)? Or making it run on Android?
A: Take a look at Hans Schmucker's workaround/reimplementation:
http://forum.xda-developers.com/showthread.php?t=1251575
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555100",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: What convention should I use for instance variables? Is there any instance variable convention used in Ruby code? Namely, I noticed that, in the examples section, instance variable are initialized using the '@' and then the code uses a variable name without the '@':
class BookInStock
attr_reader: isbn
attr_accessor: price
def initialize (isbn, price)
@isbn = isbn
@price = Float (price)
end
def price_in_cents
Integer (price * 100 + 0.5)
end
end
And there are examples where the code, the instance variable is used all the time with the prefix '@'
class BookStock
def set_price (price)
@price = price
end
def get_price
@price
end
end
What is the difference these records? When should I use '@' only in the initialization of an object and when in all the class methods?
A: You can only use the instance variable name without @ if you have defined an attribute reader for this variable (with attr_reader or attr_accessor). This is a lightweight helper to create a method that returns the instance variable's value.
The difference is a question between using the public interface of your class or accessing private data. It is recommended to use the public interface in subclasses or included modules, for example. This ensures encapsulation. So you should not access instance variables from within subclasses or modules.
In the class itself, ask yourself this question: if the implementation of the attribute changes, should my usage the attribute change as well? If the answer is yes, use the instance variable directly; if it's no, use the public attribute.
An example. Suppose we have a Person class that represents a person and should contain that person's name. First there is this version, with only a simple name attribute:
class Person
attr_reader :name
def initialize(name)
@name = name
end
def blank?
!@name
end
def to_s
name
end
end
Note how we use the instance variable for the blank? method, but the public attribute for the to_s method. This is intentional!
Let's say that in a refactoring step we decide that the Person class should keep track of a first_name and last_name seperately.
class Person
def initialize(first_name, last_name)
@first_name, @last_name = first_name, last_name
end
def name
"#{@first_name} #{@last_name}"
end
def blank?
!@first_name and !@last_name
end
def to_s
name
end
end
We now change the name attribute to a regular method, which composes the name from a person's first and last name. We can now see that it is possible to keep the same implementation for to_s. However, blank? needs to be changed because it was dependent on the underlying data. This is the reason why to_s used the attribute, but blank? used the instance variable.
Of course, the distinction is not always easy to make. When in doubt, choose the public API over accessing private data.
A: In your first example, @price is an instance variable.
In the method definition for price_in_cents, price is actually a method call to price(). Because of Ruby's syntactic sugar, () is omitted.
It looks like there's no explicit definition for price(), but attr_accessor :price defined both price() and price=(value) a.k.a. getter and setter. You can try to comment out the attr_accessor :price line, you will get an "undefined local variable or method" exception when the BookInStock's instance calls price_in_cents.
An instance variable is always have an @ prefix. If no accessor methods defined, you can not use that name without @ prefix.
A: Using name = value is an error, because that creates a local variable named name. You must use self.name = value.
As for convention, you can only get away with using @name if you can guarantee that the accessors will always be lightweight attr_accessors. In all other cases, using @name over self.name will violate encapsulation and give yourself a headache. You gave the exact reason in your question — if there is extra logic in the getter/setter, you must duplicate it if you access the instance variable directly.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555106",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Regrading simulation of bank-teller
we have a system, such as a bank, where customers arrive and wait on a
line until one of k tellers is available.Customer arrival is governed
by a probability distribution function, as is the service time (the
amount of time to be served once a teller is available). We are
interested in statistics such as how long on average a customer has to
wait or how long the line might be.
We can use the probability functions to generate an input stream
consisting of ordered pairs of arrival time and service time for each
customer, sorted by arrival time. We do not need to use the exact time
of day. Rather, we can use a quantum unit, which we will refer to as
a tick.
One way to do this simulation is to start a simulation clock at zero
ticks. We then advance the clock one tick at a time, checking to see
if there is an event. If there is, then we process the event(s) and
compile statistics. When there are no customers left in the input
stream and all the tellers are free, then the simulation is over.
The problem with this simulation strategy is that its running time
does not depend on the number of customers or events (there are two
events per customer), but instead depends on the number of ticks,
which is not really part of the input. To see why this is important,
suppose we changed the clock units to milliticks and multiplied all
the times in the input by 1,000. The result would be that the
simulation would take 1,000 times longer!
My question on above text is how author came in last paragraph what does author mean by " suppose we changed the clock units to milliticks and multiplied all the times in the input by 1,000. The result would be that the simulation would take 1,000 times longer!" ?
Thanks!
A: Because the checking is being carried out on a per tick basis if the number of ticks is multiplied by 1000 then there will be 1000 times more checks.
A: With this algorithm we have to check every tick. More ticks there are the more checks we carry out. For example if first customers arrives at 3rd tick, then we had to do 2 unnecessary checks. But if we would check every millitick then we would have to do 2999 unnecessary checks.
A: Imagine that you set an alarm so that you perform a task, like checking your email, every hour. This means you would check your email 24 times in day, assuming you didn't sleep. If you decide to change this alarm so that it goes off every minute you would now be checking your email 24*60 = 1440 times per day, where 24 is the number of times you were checking it before and 60 is the number of minutes in an hour.
This is exactly what happens in the simulation above, except rather than perform some action every time an alarm goes off, you just do all 1440 email checks as quickly as you can.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555108",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Android application should expire after 1 month of its release My android application should work only for 1 month after its release. What to do for that?
A: Please see this question, it has a good answer.
I will give you my experience with trials. At first I tried just using the date on the phone, but then realized if they uninstall and re-install this can be bypassed. This could be fixed by storing the install date somewhere on the file system (hidden), but what happens if the user wipes data or finds the file?
I also tried to just check the date/time at a server anywhere (maybe your www site?), but this imposes restrictions on your application because they must have internet. Soon I realized the need for better license management, so the last solution was used.
The last solution would be to setup a server. You can use the device's unique ID (whichever you choose - I went with the Bluetooth MAC ID because my application requires bluetooth as well), post to a server to check if the user has a trial, if they don't I issue them one, if they do I check the expiration. Now I have complete control over when trials expire. Since my application is a business app that is used in the field, this is very handy if a potential buyer needs another week.
The only issue with the last solution is that if you plan on publishing to Market, you must use their payment system.
Good luck!
A: Just to add a bit more code-related as well:
*
*Use SharedPreferences to store the date on first-start up
*Get the date at every start up - you can use for exampe Date.currentTimeMillis() - and calculate if 1 month has passed
A: Check current date and calculate expiration date.
A: That should be pretty easy, just read the date on the first start-up and store it, then compare the date for every subsequent start-up with the stored date, if its greater that x days, pop-up a message box saying the app has expired.
Or am I missing something ?
/Tony
A: Use alarm Reciever instead, and broadcast when it gets expired.
http://developer.android.com/reference/android/app/AlarmManager.html,
here is a tutorial TOO.. http://moazzam-khan.com/blog/?p=157
A: if you are worried about the data on the device(and you should! unless you encrypt it) you can save the data on a server and retrieve it on each start up.
On the other hand if application crackers worries you, dalvik byte code today is easily reversed using dedexter or smali and with apktools and jarsigner you can actually find the place where the protection is change some jumps, fill the rest of the code with nops to keep it aligned and resign it uploading it to some crackers market where they share it. So it wont help you too much.
You can make life hard for them if you obfuscate your code with proguard, but it will slow them down,wont stop them.
If your app is web based, meaning the user will need to obtain server data from you, create a key for the registered users that will be received from the server (you can base it on their private details + IMEI) and verify your requests with it, if you get wrong\no key from the client reject the request.
It's not 100% proof either since requests could be faked and someone could grab someone else's IMEI and key and face all the requests.
welcome to broken software copy protection world :-)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555109",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Change TextBlock foreground color based on the background I'm looking for a simple way to change the foreground color of a TextBlock based on the color of what is behind it, so that it is more readable. Since an image is more explicit than words, here's what I want:
I assume it could be done with a custom shader effect, but I have no idea how to create it... Anyway, perhaps there is a simpler solution.
Any idea would be welcome!
A: Assuming the above is a progressbar, here is a great solution:
WPF progress bar with dynamic text & text color update
A: Quick and dirty method:
Add both the white and grey textblocks, ensuring the white textblock is "on top" of the grey textblock. Bind the text of the white textblock to that of the grey textblock, so they stay the same.
Add an opacity mask to the white textblock, of which the position and/or size (or whatever required!) is bound to the position and/or size of the green rectangle (not sure if that's a templated ProgressBar or a custom control, but either way it could be done).
This would then give the effect of the text over the green bar being white.
A: You could write an Valueconverter (implement IValueConverter) and pass the BackgroundColor as the converter Parameter. based on the parameter you convert the forground of the Textblock to the desired Value.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555111",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Accessing Form1 Properties From Thread I have an exceptionhandler function that basically just writes a line to a textbox on Form1. This works fine when being run normally but the second I use a thread to start a process it cannot access the property. No exception is thrown but no text is written to the textbox:
Public Sub ExceptionHandler(ByVal Description As String, Optional ByVal Message As String = Nothing)
' Add Error To Textbox
If Message = Nothing Then
Form1.txtErrLog.Text += Description & vbCrLf
Log_Error(Description)
Else
Form1.txtErrLog.Text += Description & " - " & Message & vbCrLf
Log_Error(Description, Message)
End If
MessageBox.Show("caught")
End Sub
Is it possible to access a form's properties from a thread this way or would it be easier to write to a text file or similar and refresh the textbox properties every 10 seconds or so (Don't see this as a good option but if it's the only way it will have to do!).
Also, still new to VB so if I have done anything that isn't good practice please let me know!
A: No, you shouldn't access any GUI component properties from the "wrong" thread (i.e. any thread other than the one running that component's event pump). You can use Control.Invoke/BeginInvoke to execute a delegate on the right thread though.
There are lots of tutorials around this on the web - many will be written with examples in C#, but the underlying information is language-agnostic. See Joe Albahari's threading tutorial for example.
A: You have to use delegates. Search for delegates in VB.
Here a peace of code that does the job.
Delegate Sub SetTextCallback(ByVal text As String)
Public Sub display_message(ByVal tx As String)
'prüfen ob invoke nötig ist
If Me.RichTextBox1.InvokeRequired Then
Dim d As New SetTextCallback(AddressOf display_message)
Me.Invoke(d, tx)
Else
tx.Trim()
Me.RichTextBox1.Text = tx
End If
End Sub
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555112",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Visual Studio Extensibility Package not looking at correct project I have created a new VS 2010 extensibility package. So far, all I want to do is have the user press a button and fill a listview with the entire contents of the solution. I have the following code:
EnvDTE80.DTE2 dte = (EnvDTE80.DTE2)System.Runtime.InteropServices.Marshal.
GetActiveObject("VisualStudio.DTE.10.0");
foreach (Project project in dte.Solution.Projects)
{
foreach(ProjectItem pi in project.ProjectItems)
{
listView1.Items.Add(pi.Name.ToString());
}
}
This does seem to work, however, it populates the list with the contents of the solution with the package in it and not the experimental instance that is launched when this is run. Am I instantiating the reference wrongly?
A:
GetActiveObject method returns first process instance of DTE, not
caller DTE. (in Visual Studio SDK 2010 project on Visual Studio 2010,
type F5 to execure experimental hive may fail)
Look at here and here for more details...
A: No - you need to use ProjectItem.SubProject to get to what you want... depending on the solution structure some recursion could be needed... for some sample code doing nicely all this see http://www.wwwlicious.com/2011/03/envdte-getting-all-projects.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555124",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Trying to link SDL in MinGW's G++ is failing miserably.. :/ Late last night I got bored.. so I began writing a small 'Noughts and Crosses' type game in C++ and SDL. I wrote a fair majority of the basic part of the game, but when I compiled it to check for errors I got the error message: Undefined reference to WinMain@16; So, "Aah, simply add -lmingw32 should help!", I was thinking.
g++ main.cpp -o nac.exe -lmingw32 -lSDLmain -lSDL -SDL_image
Now it went and gave me this: Undefined reference to SDL_main;
I see no wrong with what I have done, I tried moving -lmingw32 to the right side, middle-left and middle-right just to be sure.. Nada!
I don't think it would be my source code, but just incase: http://pastebin.com/r7fEAkr4
ALso I think I kinda failed with the array definition... but I will fix that shortly.
Any help is greatly appreciated!
Erkling
A: Your main function needs this exact signature: int main(int, char**)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555125",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Create one php variable from several Basic question but I've searched and can't quite get this nailed - how can I create 1 variable from several others? I then want to get that into an array.
Something like this (obviously the syntax is wrong!):
$name;
$address;
$post_code;
$full_address = $name, $address, $post_code;
$address[] = $full_address;
My php is very basic so go easy on the abuse!
A: You can do it several ways:
// using sprintf
$address[] = sprintf('%s, %s, %s', $name, $address, $post_code);
// using "Traditional" concatenation
$address[] = "$name, $address, $post_code";
// other version of concatenation
$address[] = $name . ", " . $address . ", " . $post_code;
Or if you want them as an array:
// regular array
$address[] = array($name, $address, $post_code);
// $address[n][0] = name
// $address[n][1] = address
// $address[n][2] = post_code
// keyed array
$address[] = array(
'name' => $name,
'address' => $address,
'post_code' => $post_code
);
// $address[n]['name'] = name
// $address[n]['address'] = address
// $address[n]['post_code'] = post_code
A: Since noone else mentioned it, compact()
$name = 'Mike';
$address = '123 Main St';
$post_code = '55555';
$full_address = compact('name', 'address', 'post_code');
var_dump($full_address);
/* Output:
array(3) {
["name"]=>
string(4) "Mike"
["address"]=>
string(11) "123 Main St"
["post_code"]=>
string(5) "55555"
}
*/
A: Are you simply wanting to append several strings to each other?
If so the correct syntax is this:
$name = 'Dave Random';
$address = 'Some place, some other place';
$post_code = 'AB123CD';
$merged = $name.$address.$post_code;
...using . (dot) to concatentate them. You will probably want to insert a line break, comma etc between them:
$merged = $name.', '.$address.', '.$post_code;
Alternatively, you can specify them all in one new string like this:
$merged = "$name, $address, $post_code";
...note the use of doubles quotes instead of single. It would probably do you well to read this.
Alternatively, you can store them as separate values in an array like this:
$myArray = array();
$myArray['name'] = 'Dave Random';
$myArray['address'] = 'Some place, some other place';
$myArray['post_code'] = 'AB123CD';
...or this:
$myArray = array(
'name' => 'Dave Random',
'address' => 'Some place, some other place',
'post_code' => 'AB123CD'
);
...and your can convert that array to a string with implode():
$merged = implode(', ',$myArray);
A: For a simple array:
$full_address = array($name, $address, $post_code);
For an associative array:
$full_address = array('name'=>$name, 'address'=>$address, 'zip'=>$post_code);
A: Do you want to concatenate strings? You should use string concatenation operator ".".
For example:
$s1 = "foo";
$s2 = "bar";
$s3 = "blabla";
$final_string = $s1 . " " . $s2 . $s3;
echo $final_string; // output: "foo barblabla"
A: Do you mean this basic or how you want it to be done:
$separator = " ";
$full_address = "{$name}{$separator}{$address}{$separator}{$postcode}";
$address[] = $full_address;
A: What you are trying to do is called string concatenation and this is done in PHP with the .-Operator
$name = "Foo";
$address = "Barstreet 1";
$post_code = "12345 Foobar";
$full_address = $name . ", " . $address . ", " . $post_code
A: You're pretty much almost there.
$name = 'Your name';
$address = 'Your address';
$post_code = 'Your post code';
$full_address = "$name, $address, $post_code";
$address[] = $full_address;
A: if you want to concatenate name adress and postcode you can do:
$address[] = $name.$address.$post_code;
or
$address[] = "$name $address $post_code";
if what you want is to add each of the field to the adress array you can do this as :
$address = array($name,$address,$post_code);
or
$address[] = $name;
$address[] = $address;
$address[] = $post_code;
A: You could take a look at standard object:
$address = new stdClass;
$address->postcode = '02115';
$address->name = "John Connor';
or create an Address class by itself, it will be quite useful in your app.
class Address {
public function __construct ($name, $address) {...}
public function getFullAddress() {...} // or other useful functions
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555126",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: iOs multi page browser (safari) like view I want to open multiple pages in my app just like iPhone( safari browser). Have two questions:
*
*What is the best way to hold the views here, One view controller with an array of views to switch from ?
*how to show safari like selection of views,where we can slide through a row or views and select one.
If you have any links or examples for this functionality pls share.
Thanks in advance.
A: There is a open source library that implement something that look like the mobile safari (iPhone) multiple page selection. It is not using some uiwebview in the sample, but I guess it can be adapted to use uiwebview : https://github.com/100grams/HGPageScrollView
I'm also working on a Mobile safari clone, it's not yet implementing multiple pages selection, but I plan to add this when I'll be able to find some time to work on this. You can check this project here : https://github.com/sylverb/CIALBrowser
A: look for uiscrollview uiwebview
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555128",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Native Android/iOS development vs Marmalade SDK Our company is on the verge of picking between native Android/iPhone development and some cross-platform solution, specifically Marmalade SDK (former Airplay SDK).
We are a computer vision company, meaning we need low level access to the camera devices. Also, our applications are computationally expensive, meaning we tend to squeeze out every little bit of processing power available.
Our team has sufficient experience in both Objective-C and Java (or C) to provide platform specific solutions. However our main focus was always on C++, as such we would like to prevent fragmenting out team and rather work with a cross-platform solution.
Our biggest fear is that choosing Marmalade will either sacrifice processing speed (main concern) or severely increase development time by complicating low level access to camera frame buffer.
So my question is, besides the obvious, what are the advantages, but specifically limitations of Marmalade SDK for processor intensive video processing applications.
A: I have used Marmalade/Airplay for almost two years now in my indie game company. For me it's a win because I'm just one programmer, and I can do virtually all my work in Windows using MS Dev Studio (which is my favorite dev environment by far) and because it shields me from having to deal with a lot of the platform-specific details, especially with the various development tools, that could eat up a lot of the time I'd rather spend on game content.
Speed will not be an issue with Marmalade. Your C++ code runs natively. Also, access to camera and other functionality should not be much of an issue; it's either already provided or can be added using the extensions SDK, which is pretty straightforward to use.
Marmalade is a mature product and the company is pretty helpful in resolving issues quickly, even for indie developers that are using the product for free. In addition to the cross-platform-ness, it has some nice tools built in, such as a memory leak tracker, a logging system, graphics analysis tools, and others.
There are some downsides that I've experienced with Marmalade.
*
*Even though in theory any API or third-party SDK is accessible through the extensions system, in practice the thing you need may not exist yet. As an example, a number of developers are currently struggling to get the analytics package Flurry integrated, and it's been a challenge for some. The situation is similar with lots of other third-party SDKs; they may be just a couple lines to integrate if you are doing Objective-C development, but can be more difficult via Marmalade.
*Some things are less natural because of the cross-platform layer through which you operate. Some examples for me have been:
*
*I've had trouble getting my splash screens (application start-up screens) to display properly in all screen sizes on both iOS and Android. And it's been hard to get them to show without some flickering, short black-out periods, or resizing of images as it transitions between the device load of the Marmalade app itself, and then Marmalade's step of loading your app code.
*Marmalade imposes a very simple memory model, where you get a fixed heap up front, and all memory allocation is done through Marmalade. From the system's point of view the app just has and keeps a big block (or a few big blocks) of memory. This has some advantages, but I've had problems squaring this model with the iOS model of, for instance, receiving memory warnings and being expected to jettison any unnecessary resources. It appears to be a case where "one size fits all" ends up actually losing some key functionality.
*You can use the extension manager and some other methods to show native UI elements, but integrating a significant amount of native-look-and-feel UI can be a challenge. So if your app is game-like and users can deal with non-standard buttons and so on, that's fine, but if you anticipate needing significant native UI, it is harder. [edit: Recent versions of Marmalade have added a native UI framework that lets you specify standard UI elements in a generic way and then implements then using the appropriate widgets for the device. I have not used this, but it looks fairly comprehensive.]
*If you run into problems, it's often not clear whether it's a generic OS problem or a Marmalade problem, and it can be lonely trying to find help. For instance, I recently added in-app purchase to my game, on both iOS and Android. IAP is challenging, and even without an additional SDK layer there are lots of special cases to deal with. In my case, I had a situation where my app had been rejected by Apple for a small issue, and while it was in the rejected state my in-app purchase was also in a "rejected" state (even though there was nothing broken about the IAP itself; this is just a quirk of Apple's process). When I was trying to regression test the in-app purchase functionality (while I was submitting the fix for this non-in-app-purchase-related issue), the game was actually crashing, instead of getting an appropriate error result. I was able to determine that the crash wasn't in my game code, so it was either the OS (unlikely) or the Marmalade middle layer for handling the in-app purchase callbacks (which is what it turned out to be [update 11/28/2012: Marmalade has reportedly fixed this problem in a recent SDK update]).
So in a situation like that you can try going on Stack Overflow to get help, but really nobody is there to help you, so you are dependent on the Marmalade team to get back to you with an answer. As I say, they do a pretty good job of this, but there's no way it can compete with nearly instantaneous responses on Stack Overflow from the world-wide community of regular iOS programmers. So I'd say this last one is my biggest concern with using a system like Marmalade. It saves you time up front not having to come up to speed on the details of the various platform SDKs, but when you run into problems you are "at the mercy" of the Marmalade team (or friendly Marmalade community members) to get back to you with an answer. (Keep in mind here that I'm writing as a freebie indie developer who just gets standard priority for issue resolution. You can pay to get guaranteed quick resolution.) For me personally, it's been hard having to keep coming back to my producer and saying "I'm waiting for an answer from the Marmalade guys on this one."
(Another example of issue 3 is that until recently there was a problem with sound effects being delayed on certain Android devices. It was a Marmalade issue, and they did eventually resolve it, but it took a while, and there's basically nothing you can do in the meantime.)
Keep in mind that (as other responders have pointed out) even without Marmalade you can still have the bulk of your code base in C++ on either iOS or Android.
In spite of the long list of potential issues above, I am a fan of Marmalade, and I appreciate all the company has provided for me for free. The tool really shines when it comes to other platforms that you'd otherwise never bother with, such as (for me) bada or PlayBook. You really can deploy to a wide array of devices from the comfort of your PC and Developer Studio (or from a Mac with xcode, if you want to make your life a little harder ;). The simulator tool they have is great, and there have been only a small number of instances where I've had to debug on the device itself; in general if it works on the simulator it just works. IdeaWorks has taken on a huge challenge and they are doing a great job juggling all these features (i.e., basically every features ever offered on a mobile device) on all these platforms (i.e., all significant devices in existence, with the exception of Windows Phone 7 because it does not currently allow native code). It just comes with some caveats.
A: I am biased, being the CTO at Marmalade... but if your key requirements are (1) camera access and (2) the ability to "squeeze out every little bit of processing power available" then Marmalade is a great choice.
Marmalade compiles your C/C++ to native ARM (or x86) instructions... no transcoding, no virtual machines. It's very easy to bring across existing C/C++ code, nearly all the C/C++ standard libraries are supported, etc. And you can use ASM code within your project. Also, you can do all your development either on Windows or Mac, regardless of what platforms you deploy to (yes, you can even compile/test/deploy to iOS purely on Windws).
A: As far as I can tell you from ANDROID Development:
The Camera API from Android itself seems to be a little buggy (in example: before 2.1 there is no solution to get Camera shown in portrait-mode without scrambling the Images).
Another abstraction layer on top of that might be better (in terms of accessibility, features, whatever), or even more worse. What it does for shure: It steals resources, which may be needed for your own App.
A: Marmalade offers an excellent Native Extension framework
http://www.madewithmarmalade.com/marmalade/features/extensions-development-kit
WHich ultimately means that you can jump directly to a native implementation of any particular feature. You still keep the core benefits of cross platform development for your main app.
Also on android because marmalade makes use of the android NDK your c++ code for processing data will be running faster than the corresponding android Java code.
Im making games with Marmalade and the extensions and native code speed make me extremely confident of being able to deliver at least as well as a 'native' app.
A: I would use MoSync Android/iOS, but I would say that, since I work at MoSync.
But in all fairness I prefer the MoSync Camera API.
If you really want to squeeze out all the processing power out you should use ASM.
/Tony
A: Marmalade's not bad, I used it in 2013. Some bugs, some annoyances (fixed memory pools), but overall not a bad experience.
The only real disappointment is the lack of support for Linux. I cannot see how the Marmalade guys can support obscure platforms like Blackberry, but not Linux; it makes no sense. Maybe this will change as Steam OS (a Linux-based, gaming-centric platform) matures, though admittedly Steam OS doesn't bring a whole lot to the table outside of what other OSs bring, for now.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555134",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "38"
}
|
Q: Handle key using javascript onkeydown I have this code
function verifyKey(e)
{
var keycode;
if (window.event)
keycode = window.event.keyCode;
else if (e)
keycode = e.which;
regex=/[1-9]/;
if(regex.test(keycode))
return true;
else
void(0);
}
in the html I added an input and I add the onkeydown event onkeydown="verifyKey(event);"
I like to verify the key before it display on the text
If the key is a number or coma(,) or full stop(.)
then accept the key
else
refuse it
Thanks
A: Here in your code you are testing the regular expression defined with the keycode, so every chearactes on the keyboard will be allowed since the keycode of every key is numbers, so you will not get the result what you expect. Instead of using the regular expression try the below code
<html>
<head>
<script type="text/javascript">
function verifyKey(e)
{
var keycode;
if (window.event)
keycode = window.event.keyCode;
else if (e)
keycode = e.which;
if((keycode>=48 && keycode<=57))
{alert("if")
return true;
}
else if((keycode == 188)||(keycode == 190))
{alert("elseif");
return true;
}
else
{alert("else")
return false;
}
}
</script>
</head>
<body>
<input type="text" onkeypress="return verifyKey(event)" />
</body>
</html>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555136",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Many-to-many messaging on local machine without broker I'm looking for a mechanism to use to create a simple many-to-many messaging system to allow Windows applications to communicate on a single machine but across sessions and desktops.
I have the following hard requirements:
*
*Must work across all Windows sessions on a single machine.
*Must work on Windows XP and later.
*No global configuration required.
*No central coordinator/broker/server.
*Must not require elevated privileges from the applications.
I do not require guaranteed delivery of messages.
I have looked at many, many options. This is my last-ditch request for ideas.
The following have been rejected for violating one or more of the above requirements:
ZeroMQ: In order to do many-to-many messaging a central broker is required.
Named pipes: Requires a central server to receive messages and forward them on.
Multicast sockets: Requires a properly configured network card with a valid IP address, i.e. a global configuration.
Shared Memory Queue: To create shared memory in the global namespace requires elevated privileges.
Multicast sockets so nearly works. What else can anyone suggest? I'd consider anything from pre-packaged libraries to bare-metal Windows API functionality.
(Edit 27 September) A bit more context:
By 'central coordinator/broker/server', I mean a separate process that must be running at the time that an application tries to send a message. The problem I see with this is that it is impossible to guarantee that this process really will be running when it is needed. Typically a Windows service would be used, but there is no way to guarantee that a particular service will always be started before any user has logged in, or to guarantee that it has not been stopped for some reason. Run on demand introduces a delay when the first message is sent while the service starts, and raises issues with privileges.
Multicast sockets nearly worked because it manages to avoid completely the need for a central coordinator process and does not require elevated privileges from the applications sending or receiving multicast packets. But you have to have a configured IP address - you can't do multicast on the loopback interface (even though multicast with TTL=0 on a configured NIC behaves as one would expect of loopback multicast) - and that is the deal-breaker.
A: Maybe I am completely misunderstanding the problem, especially the "no central broker", but have you considered something based on tuple spaces?
--
After the comments exchange, please consider the following as my "definitive" answer, then:
Use a file-based solution, and host the directory tree on a Ramdisk to insure good performance.
I'd also suggest to have a look at the following StackOverflow discussion (even if it's Java based) for possible pointers to how to manage locking and transactions on the filesystem.
This one (.NET based) may be of help, too.
A: How about UDP broadcasting?
A: Couldn't you use a localhost socket ?
/Tony
A: In the end I decided that one of the hard requirements had to go, as the problem could not be solved in any reasonable way as originally stated.
My final solution is a Windows service running a named pipe server. Any application or service can connect to an instance of the pipe and send messages. Any message received by the server is echoed to all pipe instances.
I really liked p.marino's answer, but in the end it looked like a lot of complexity for what is really a very basic piece of functionality.
The other possibility that appealed to me, though again it fell on the complexity hurdle, was to write a kernel driver to manage the multicasting. There would have been several mechanisms possible in this case, but the overhead of writing a bug-free kernel driver was just too high.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555137",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Operator new with nothrow option still throws exception There is such code:
#include <iostream>
int main(){
for(;;){
int* ptr = new (std::nothrow) int;
if(ptr == 0){
std::cout << 0 << std::endl;
break;
}
}
std::cin.get();
return 0;
}
However, this program still throws std::bac_alloc exception, altough new is called with std::nothrow parameter. This program is compiled in Visual C++ 2010. Why the exception is thrown?
Edit:
Using g++ on Windows from mingw, everything works ok.
A: 0 has to be formatted as "0". That's going to take a few bytes; I'll bet that's the cause. Put a breakpoint on std::bad_alloc::bad_alloc and you will know for sure.
A: I just ran your sample from VC2010. It is not new(nothrow) that throws, but __security_check_cookie.
A: This explains why it is still throwing and how you can make it not throw. It seems nothrow is just ignored.
If you still want the non-throwing version of new for the C Runtime Library, link your program with nothrownew.obj. However, when you link with nothrownew.obj, new in the Standard C++ Library will no longer function.
I found an quite in depth article about this but it's kinda dated (VC 6) but maybe the problem still persists. BTW VC ignores all throw() specifications of functions.
When Operator new(std::nothrow) Throws an Exception Anyway
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555138",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: C# application works on Win 7 But not on XP I have built an application in C# and also built a setup for this application. The application on setup works on all Windows 7 machines but doesnt seem to work on any XP machine.
I shall briefly describe what my application does.
The application plays a swf file on startup. The swf file has 3 buttons with separate functions.
Basically on clicking these buttons it has to show certain images which are loaded from sqlite.
The problem is that the application loads the swf correctly, the swf plays completely till the end, then at the end where i have placed 3 buttons the click event does not respond to any button. i am guessing this is a problem with FSCommand and the dlls not getting registered correctly
The dlls that i have added to my setup are
*
*AxInterop.ShockwaveFlashObjects.dll
*Interop.shockwaveFlashObjects.dll
*System.Data.SQLite.dll
*KP-ImageViewerV2.dll (from codeproject.com)
Also the files present are my manifest file and .config file
I tried registering my Dlls manually using RegSrv32 C:\Interop.ShockwaveFlashObject.dll
and also C:\AxInterop.ShockwaveFlashObject.dll
The error i get is
The (DllPath and Name Here) was loaded but DllRegisterServer entry point was not found.
The code that i am using to display my swf file is as below
private void axShockwaveFlash1_FSCommand(object sender,AxShockwaveFlashObjects._IShockwaveFlashEvents_FSCommandEvent e)
{
string btn = e.command.ToString();
if (btn == "play")
{
try
{
frmMain Main = new frmMain();
Main.Show();
this.Hide();
}
catch (Exception ex)
{ MessageBox.Show(ex.ToString()); }
}
if (btn == "syllabus")
{
SQLiteConnectionStringBuilder strbldr = new SQLiteConnectionStringBuilder();
strbldr.DataSource = @Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\TVC E-Excust Customs\\E-ExcustCustoms.s3db";
SQLiteConnection con = new SQLiteConnection(strbldr.ConnectionString);
con.Open();
Syllabus_usageInformation syl = new Syllabus_usageInformation(this);
SQLiteCommand cmd = new SQLiteCommand("SELECT ImageFiles FROM misc WHERE Name='Syllabus new'", con);
SQLiteDataReader reader = cmd.ExecuteReader();
byte[] imageBytes = null;
while (reader.Read())
{
imageBytes = (System.Byte[])reader["ImageFiles"];
}
MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
con.Close();
syl.kpImageViewer1.OpenButton = false;
syl.kpImageViewer1.Image = (Bitmap)Image.FromStream(ms,true);
syl.kpImageViewer1.Zoom = 85;
syl.Show();
this.Hide();
}
if (btn == "usageInformation")
{
SQLiteConnectionStringBuilder strbldr = new SQLiteConnectionStringBuilder();
strbldr.DataSource = @Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\TVC E-Excust Customs\\E-ExcustCustoms.s3db";
SQLiteConnection con = new SQLiteConnection(strbldr.ConnectionString);
con.Open();
Syllabus_usageInformation syl = new Syllabus_usageInformation(this);
SQLiteCommand cmd = new SQLiteCommand("SELECT ImageFiles FROM misc WHERE Name='UsageInformation'", con);
SQLiteDataReader reader = cmd.ExecuteReader();
byte[] imageBytes = null;
while (reader.Read())
{
imageBytes = (System.Byte[])reader["ImageFiles"];
}
MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
con.Close();
syl.kpImageViewer1.OpenButton = false;
syl.kpImageViewer1.Image = (Bitmap)Image.FromStream(ms, true);
syl.kpImageViewer1.Zoom = 82;
syl.Show();
this.Hide();
}
}
My swf file has three buttons as mentioned above. those buttons are in a movie clip i shall paste the AS code as well
Here is what happens in one of the buttons. The remaining 2 are same as this one with just the values changed.
I am pretty new to flash but could this problem be because of the AS version used / or the minimum version of flash being required to run this swf. Just a mention again the video plays but the buttons are non responsive on XP but works on 7?
on (rollOver)
{
if (_root.link != page)
{
this.gotoAndPlay("s1");
}
}
on (releaseOutside, rollOut)
{
if (_root.link != page)
{
this.gotoAndPlay("s2");
}
}
on (press)
{
fscommand("syllabus","syll");
}
If some one needs more explanation or more code or just the entire project let me know will send the project.
I am out of solutions here so any help would be highly appreciated.
A: Alright PROBLEM SOLVED..there is some problem with .net 4.0. I found this because i searched something on google for my problem, i dont remember the search i did but it returned 2 results!! one of which had a conversation, some VS guy and a user were talking about the problem he faced which was similar to mine. the VS guy agreed that indeed the problem was with 4.0 and that they will rectify the problem. Seems i wasted a lot of time.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555139",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Setting the status code message of a HTTP ResponseCode thrown by an @ResponseCode annotate Exception I am currently trying to set the message of a HTTP Status Code thrown by an @ResponseCode annotated Exception.
I have defined the exception:
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
public final class BadRequestException extends IllegalArgumentException {
/**
* The serial version UID.
*/
private static final long serialVersionUID = -6121234578480284282L;
public BadRequestException() {
super();
}
public BadRequestException(String message, Throwable cause) {
super(message, cause);
}
public BadRequestException(String message) {
super(message);
}
public BadRequestException(Throwable cause) {
super(cause);
}
}
If the exception is thrown I throw it again in my @ExceptionHandler annotate method:
@ExceptionHandler(RuntimeException.class)
public String handleRuntimeException(Exception e, HttpSession session) {
if (e instanceof BadRequestException) {
throw (BadRequestException)e;
}
return FAILURE;
}
I generally throw this exception in this way:
if (result.hasErrors()) {
throw new BadRequestException("Bad Request Message.");
}
The HTTP Status Code always returns only "HTTP Status 400 -" without a message is set.
THX!
A: Annotate your exception handler with the @ResponseStatus. Then created a basic error/exception view and pass the exception stack trace or whatever to that view
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555140",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: NSLog an object's memory address in overridden description method I am overriding an object's description method. I need to know how to print the object's memory address to replace {???} in the code below:
-(NSString *) description {
return [NSString stringWithFormat:@"<SomeClass: %@>\nparmeterOne: %@\nparameterTwo: %@",
{???}, self.parameterOne, self.paramterTwo];
}
I want it to print in the console like this:
<SomeClass: 0x4c05600> parameterOne: 12 parameterTwo: sausages
A: The easiest method is to use the super description
- (NSString *)description
{
return [NSString stringWithFormat:@"%@ Area: %@, %@", [super description], self.identifier, self.name];
}
So in the case of this model object that is a subclass of NSObject, you can dodge extra work and remembering %p.
Manually using NSStringWithClass() and %p
- (NSString *)description
{
return [NSString stringWithFormat:@"<%@: %p> Area: %@, %@", NSStringFromClass([self class]), self, self.identifier, self.name];
}
So in the case of an object model in which you have a concrete implementer that is derived from this class you will show the correct class name.
A: To print address use %p format specifier and self pointer:
-(NSString *) description {
return [NSString stringWithFormat:@"<SomeClass: %p>\nparmeterOne: %@\nparameterTwo: %@",
self, self.parameterOne, self.paramterTwo];
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555143",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "120"
}
|
Q: How to place div1 below div2 and keep div1 transparent background? <div id="header"> Header content </div>
<div id="content"> Content </div>
#header {
background-image: url("/Content/Images/bg.png");
background-repeat: repeat-x;
float: left;
height: 45px;
margin: 0;
width: 960px;
z-index: 10;
}
#content {
background-image: url("/Content/Images/separator_shadow_both.png");
background-repeat: repeat-y;
float: left;
margin: -4px 0 0;
padding: 0 10px;
width: 940px;
z-index: 9;
}
Header div have background that have 45 px height - 41 pixel solid color and bottom 4px is transparent shadow. I want that shadow to show above the content. I put content div margin top -4px to crawls under header div, but he appears above instead below of div1. z-indexes are set different... Is it z-index problem or header background can't be positioned above content?
Thank you
A: The z-index property is only relevant for positioned elements. Solution: Set position: relative on #header. You don’t even need the z-index since positioned elements always render on top on non-positioned ones.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555150",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Can I add space between nodes in Forms.TreeView? I want my System.Windows.Forms.TreeView to have spaces between all root nodes.
For example, if they look like this:
A
B
C
D
E
F
G
H
I want them spaced apart like this:
A
B
C
D
E
F
G
H
Thanks!
A: You can use the ItemHeight property which sets the height, in pixels, of each tree node in the tree view. But it just sets the spaces for every TreeNode, you cannot give different heights for different TreeNode. There is no easy way to give different ItemHeights for TreeNodes.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555151",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: In Emacs how to operate (i.e. search) only in code regions? I'd like to isearch/search-replace/occur only in code (that is not in comments or strings).
This must be a common problem, so what packages do this already?
If no existing packages do this, I'm thinking a minor-mode where strings and comments are hidden based on fontification would do the trick. Is there one?
A: Icicles search gives you several ways to do this. Here are two:
*
*Search "things" (e.g. defuns, sexps, xml elements, etc.), ignoring comments (option icicle-ignore-comments-flag). That is, use selected code segments as search contexts, but ignore any comments within code or code inside comments.
*Search the complement of the comments. E.g., define the search contexts as the complement of the zones of text that are font-locked with either face font-lock-comment-face or face font-lock-comment-delimiter-face (which means search all code outside of comments).
After defining the search contexts, just type text to incrementally filter the contexts. And you can replace any matches on demand.
A: Check out narrowing.
A: Yes, you are right. The HideShow minor mode allows you to hide/show block of text, in particular multiline comments.
The hide/show comments is not part of the standard package but on the wiki page you will find the code which does the trick.
Then isearch command does not take into account the hidden comments.
HOWEVER: replace operates on the whole buffer, including hidden blocks.
A: Isearch+ does what you ask (as does Icicles --- see other answer, above).
You can define the contexts that Isearch searches, using any of the following:
*
*A regexp to be matched.
*A given text or overlay property --- The search contexts are the text zones that have the property (e.g. a particular `face' value or combination of values)
*A given Emacs THING (sexp, defun, list, string, comment, etc.) --- The search contexts are the text zones of the given THING type.
Having defined the search contexts, you can also search the complement: the non-contexts. You can toggle between searching contexts and non-contexts anytime in Isearch, using C-M-~.
When searching, by default the zones not being searched are dimmed slightly, to make the searchable areas stand out.
For context-searching with Isearch you need these two libraries:
*
*isearch+.el
*isearch-prop.el
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555156",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Show pagination links for product list on a Magento CMS page I created a CMS Page via the Magento Admin interface, and i put the following code in there:
{{block type="catalog/product_list" name="home.catalog.product.list" alias="products_homepage" category_id="3" template="catalog/product/list.phtml"}}
This shows me products from the category with the id 3.
My magento is configured to display 9 products per page. In the category in question, there are 30 products.
While on my category pages, I can see a paginator, that does not happen on the CMS page. What am I doing wrong?
A: <block type="catalog/product_list_toolbar" name="product_list_toolbar" template="catalog/product/list/toolbar.phtml">
<block type="page/html_pager" name="product_list_toolbar_pager" />
This needs to be added to the xml block where you are attempting to load product so that it gets the toolbar and the pager.
See this link as reference:
Products with Pagination
A: I had this same problem of no pagination links on the default list of products on my home page.
It turned out that following the advice I had seen on many sites to get products on the home page (why this should be a complex task on an e-commerce app is beyond me ...) was not the best way to go.
To solve this problem I removed the code
{{block type="catalog/product_list" name="home.catalog.product.list" alias="products_homepage" category_id="3" template="catalog/product/list.phtml"}}
from the page content and just put in <div></div> (so it would let me save the page).
Then I replaced the XML under the "Design" tab with the XML from the catalog.xml file that defines the pager block. Like this:
<reference name="content">
<block type="catalog/product_list" name="product_list" template="catalog/product/list.phtml">
<action method="setCategoryId"><category_id>3</category_id></action>
<action method="setColumnCount"><columns>3</columns></action>
<block type="catalog/product_list_toolbar" name="product_list_toolbar" template="catalog/product/list/toolbar.phtml">
<block type="page/html_pager" name="product_list_toolbar_pager"/>
</block>
<action method="addColumnCountLayoutDepend"><layout>empty</layout><count>6</count></action>
<action method="addColumnCountLayoutDepend"><layout>one_column</layout><count>5</count></action>
<action method="addColumnCountLayoutDepend"><layout>two_columns_left</layout><count>4</count></action>
<action method="addColumnCountLayoutDepend"><layout>two_columns_right</layout><count>4</count></action>
<action method="addColumnCountLayoutDepend"><layout>three_columns</layout><count>3</count></action>
<action method="setToolbarBlockName"><name>product_list_toolbar</name></action>
</block>
</reference>
This gave me the pagination links I needed. Hope it helps you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555157",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Do these MySQL SELECT queries represent different inner joins?
Possible Duplicate:
which query is better and efficient - mysql
What's the difference, if any, between these two (MySQL) SELECT queries?
SELECT name, salary
FROM employee, info
WHERE employee.id = info.id;
SELECT e.name AS name, i.salary AS salary
FROM employee AS e
INNER JOIN info AS i
ON e.id = i.id;
Both represent an (the same?) inner join on the tables employee and info.
A: Yes both represents INNER JOIN.
SELECT e.name AS name, i.salary AS salary
FROM employee AS e
INNER JOIN info AS i
ON e.id = i.id;
is "explicit join notation" uses the JOIN keyword to specify the table to join, and the ON keyword to specify the predicates for the join.
SELECT name, salary
FROM employee, info
WHERE employee.id = info.id;
The "implicit join notation" simply lists the tables for joining (in the FROM clause of the SELECT statement), using commas to separate them. Thus, it specifies a cross join, and the WHERE clause may apply additional filter-predicates (which function comparably to the join-predicates in the explicit notation).
Check out this example : http://en.wikipedia.org/wiki/Join_%28SQL%29#Inner_join
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555159",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Migrating from MySQL to MariaDB I am migrating my database to MySQL to MariaDB. I have binary storage engine in MySQL and MariaDB does not support it.
How can I convert this to make sure my tables will works? Thank You
A: If this is a binary engine that works with MySQL and you have the source for it, then you should be able to easily port it to MariaDB:
*
*The storage engine interface is 99 % identical. We have mainly move
some functionality from the storage engine (like statistic counting)
to the handler interface which should be trivial to fix.
*A few server functions may have changed names, but nothing that
should not be almost trivial to figure out.
In practice one should be able to port a storage engine for MySQL to MariaDB within 30 minutes or so.
If you don't have the source code, you need to ask the vendor for the storage engine to support MySQL. They should be able to do that without much trouble (as long it's a true plugg-in storage engine and not something that makes big changes to the MySQL/MariaDB upper level code).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555160",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: HTML TD Clickable I have a menu you can see on the top right hand side - www.balibar.co
HTML:
<div id="joinHeader" class="shadow">
<table id="indexNavigation"><tr>
<td><a id="navSearch">Search</a></td>
<td><a id="navLanguages">Languages</a></td>
<td id="activeNavLink"><a id="navLogin">Login</a></td>
</tr></table>
</div>
CSS:
table#indexNavigation {
width: 100%;
height: 25px;
font-weight: normal;
font-size: 1.1em;
border-collapse: collapse;
}
table#indexNavigation td {
text-align: center;
color: white;
width: 33.33%;
border-right: 1px solid #FFF;
cursor: pointer;
}
table#indexNavigation td#activeNavLink {
border-right: none;
}
I want to make the entire TD Clickable.
I've added cursor: pointer; to the TD but it doesn't light up except when over the words.
I tried putting the <a> outside the <td> but this didn't work.
Is there a trick to make this clickable.
Will then hook this up to jQuery for a click event - e.g.:
$('td#activeNavLink').click(function() {
A: Just make your links inside your td tags have a width of 100%. Then they will take up the full width of the cell.
table#indexNavigation td a {
display: block;
width: 100%;
text-align: center;
}
A: You should use a display:block in your CSS.
Here's an example from an unordered list (ul) with block-links: link
A: you have two options
*
*by css only
here you actually make the anchor tag a block element, give it full width and height to make it as big as the table cell...
table td a {
display: block;
width: 100%;
height: 100%;
}
remark you might need to move some paddings and such from the TD element to the A element
*by javascript
this means, adding a click event to the td element, and then triggering the click from the anchor element that's inside that table cell.
$('#mytable td').each(function(){
$(this).css({'cursor': 'pointer'}).click(function(){
$(this).find('a:first').trigger('click');
});
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555163",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: SQL Server concurrency I asked two questions at once in my last thread, and the first has been answered. I decided to mark the original thread as answered and repost the second question here. Link to original thread if anyone wants it:
Handling SQL Server concurrency issues
Suppose I have a table with a field which holds foreign keys for a second table. Initially records in the first table do not have a corresponding record in the second, so I store NULL in that field. Now at some point a user runs an operation which will generate a record in the second table and have the first table link to it. If two users simultaneously try to generate the record, a single record should be created and linked to, and the other user receives a message saying the record already exists. How do I ensure that duplicates are not created in a concurrent environment?
The steps I need to carry out are:
1) Look up x number of records in table A
2) Perform some business logic that prepares a single row which is inserted into table B
3) Update the records selected in step 1) to point to the newly created record in table B
I can use scope_identity() to retrieve the primary key of the newly created record in table B, so I don't need to worry about the new record being lost due to simultaneous transactions. However I need to eliminate the possibility of concurrently executing processes resulting in a duplicate record in table B being created.
A: In SQL Server 2008, this can be handled with a filtered unique index:
CREATE UNIQUE INDEX ix_MyIndexName ON MyTable (FKField) WHERE FkField IS NOT NULL
This will require all non-null values be unique, and the database will enforce it for you.
A: The 2005 way of simulating a unique filtered index for constraint purposes is
CREATE VIEW dbo.EnforceUnique
WITH SCHEMABINDING
AS
SELECT FkField
FROM dbo.TableB
WHERE FkField IS NOT NULL
GO
CREATE UNIQUE CLUSTERED INDEX ix ON dbo.EnforceUnique(FkField)
Connections that update the base table will need to have the correct SET options but unless you are using non default options this will be the case anyway in SQL Server 2005 (ARITH_ABORT used to be the problem one in 2000)
A: Using a computed column
ALTER TABLE MyTable ADD
OneNonNullOnly AS ISNULL(FkField, -PkField)
CREATE UNIQUE INDEX ix_OneNullOnly ON MyTable (OneNonNullOnly);
Assumes:
*
*FkField is numeric
*no clash of FkField and -PkField values
A: Decided to go with the following:
1) Begin transaction
2) UPDATE tableA SET foreignKey = -1 OUTPUT inserted.id INTO #tempTable
FROM (business logic)
WHERE foreignKey is null
3) If @@rowcount > 0 Then
3a) Create record in table 2.
3b) Capture ID of newly created record using scope_identity()
3c) UPDATE tableA set foreignKey = IdOfNewRecord FROM tableA INNER JOIN @tempTable ON tableA.id = tempTable.id
Since I write junk into the foreign key field in step 2), those rows are locked and no concurrent transactions will touch them. The first transaction is free to create the record. After the transaction is committed, the blocked transaction will execute the update query, but won't capture any of the original rows due to the WHERE clause only considering NULL foreignKey fields. If no rows are returned (@@rowcount = 0), the current transaction exits without creating the record in table B, and returns some sort of error message to the client. (e.g. Error: Record already exists)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555166",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Edge-Side-Includes: How do esi:inline tags work I have been looking at the ESI (Edge-Side-Includes) specs, but I cannot quite figure out how esi:inline elements work. Can anyone explain that?
A: Finally, I figured it out. You send a response with an <esi:include> and in the reply to that one you include <esi:inline>-marked fragments for later re-use.
That is a pretty slick way to allow retrieval of many small pieces in one large request.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555172",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: In flex, how to declare a control to take all available width In Flex 4.0, I have a project with a videodisplay, and below it some controls that I've created (play/pause button, HSlider for showing progress, some volume controls...)
The problem arises when the flash is displayed in a window that is too small to fit all controls at their desired width. What I see is that some controls are pushed to the right, out of sight. (Maybe it's because they are in a custom container that acts as a window, but that's needed functionality).
I want to designate the HSlider as having flexible width, so when the user creates a small window, the items in the control bar are still visible, and the HSlider is compressed enough to make that happen...
Cheers!
Edit: the code for my window (it's the VBox that I would like to have variable-sized):
<ns1:CollapsableTitleWindow x="294" y="36.65" backgroundColor="#000000" width="436" height="373" id="wnd" title="test" allowClose="false">
<mx:VideoDisplay width="100%" height="100%" id="vd" autoPlay="false" volume="1"/>
<mx:ControlBar id="ctrlbarLiveVideo1" width="100%">
<mx:Button width="30" height="22" id="btnPlay" click="{doplay();}" icon="{imgPlayButton}"/>
<mx:VBox verticalGap="1" horizontalAlign="right">
<mx:HSlider id="slider" width="100%" invertThumbDirection="true" maximum="{vd.totalTime}" minimum="0" tickInterval="{vd.totalTime/10}" value="{Number(vd.playheadTime)}" />
<mx:Label text="{sec2hms(Number(vd.playheadTime))} / {sec2hms(Number(slider.maximum))}"/>
</mx:VBox>
<mx:HBox id="box" horizontalGap="1" verticalAlign="middle">
<mx:Label id="lblVolume" text = "{String(Math.round(vd.volume*100))+'%'}"/>
<mx:Button label="-" id="btnless" width="34" height="22" verticalGap="0" labelPlacement="top" labelVerticalOffset="0" click = "{vd.volume -= 0.10}"/>
<mx:Button label="+" id="btnmore" width="34" height="22" verticalGap="0" labelPlacement="top" labelVerticalOffset="0" click = "{vd.volume += 0.10}"/>
</mx:HBox>
</mx:ControlBar>
</ns1:CollapsableTitleWindow>
Produces this screenshot:
A: Apparently the answer was: set the minWidth of the HSlider explicitly to 0:
<mx:HSlider minWidth="0" id="slider" width="100%" ... />
And also make the VBox width="100%": (thanks to code90)
<mx:VBox width="100%" verticalGap="1" horizontalAlign="right">
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555174",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to retrieve all tools used in shell script I've got bunch of shell scripts that used some command and other tools.
So is there a way I can list all programs that the shell scripts are using ?
Kind of way to retrieve dependencies from the source code.
A: One way you can do it is at run time. You can run bash script in debug mode with -x option and then parse it's output. All executed commands plus their arguments will be printed to standard output.
A: Uses sed to translate pipes and $( to newlines, then uses awk to output the first word of a line if it might be a command. The pipes into which to find potiential command words in the PATH:
sed 's/|\|\$(/\n/g' FILENAME |
awk '$1~/^#/ {next} $1~/=/ {next} /^[[:space:]]*$/ {next} {print $1}' |
sort -u |
xargs which 2>/dev/null
A: While I have no general solution, you could try two approaches:
*
*You might use strace to see which programs were executed by your script.
*You might run your program in a pbuilder environment and see which packages are missing.
A: Because of dynamic nature of the shell, you cannot do this without running a script.
For example:
TASK="cc foo.c"
time $TASK
This will be really hard to determine without running that cc was called even in such trivial example as above.
In a runtime, you can inspect debug output sh -x myscript as pointed out by thiton (+1) and ks1322 (+1). You can also you tool like strace to catch all exec() syscalls.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555175",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: How to get a string of union set from a vector string? I have a vector string filled with some file extensions as follows:
vector<string> vExt;
vExt.push_back("*.JPG;*.TGA;*.TIF");
vExt.push_back("*.PNG;*.RAW");
vExt.push_back("*.BMP;*.HDF");
vExt.push_back("*.GIF");
vExt.push_back("*.JPG");
vExt.push_back("*.BMP");
I now want to get a string of union set from the above-mentioned vector string, in which each file extension must be unique in the resulting string. As for my given example, the resulting string should take the form of "*.JPG;*.TGA;*.TIF;*.PNG;*.RAW;*.BMP;*.HDF;*.GIF".
I know that std::unique can remove consecutive duplicates in range. It con't work with my condition. Would you please show me how to do that? Thank you!
A: See it live here: http://ideone.com/0fmy0 (FIXED)
#include <iostream>
#include <sstream>
#include <iterator>
#include <algorithm>
#include <vector>
#include <set>
int main()
{
std::vector<std::string> vExt;
vExt.push_back("*.JPG;*.TGA;*.TIF");
vExt.push_back("*.PNG;*.RAW");
vExt.push_back("*.BMP;*.HDF");
vExt.push_back("*.GIF");
vExt.push_back("*.JPG");
vExt.push_back("*.BMP");
std::stringstream ss;
std::copy(vExt.begin(), vExt.end(),
std::ostream_iterator<std::string>(ss, ";"));
std::string element;
std::set<std::string> unique;
while (std::getline(ss, element, ';'))
unique.insert(unique.end(), element);
std::stringstream oss;
std::copy(unique.begin(), unique.end(),
std::ostream_iterator<std::string>(oss, ";"));
std::cout << oss.str() << std::endl;
return 0;
}
output:
*.BMP;*.GIF;*.HDF;*.JPG;*.PNG;*.RAW;*.TGA;*.TIF;
A: I'd tokenize each string into constituent parts (using semicolon as the separator), and stick the resulting tokens into a set. The resultant contents of that set is what you're looking for.
A: You need to parse the strings that contain multiple file extensions and then push them into the vector. After that std::unique will do what you want. Have a look at the Boost.Tokenizer class, that should make this trivial.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555180",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Indeterminate progress bar in HTML+CSS I would like to create an indeterminate HTML+CSS progress bar so it looks like the one on Vista:
(source: microsoft.com)
I would like to:
*
*horizontally adjust it to progress bar width (minimum and maximum width may be defined)
*don't use Javascript but rather just animated GIF
*having only one moving indicator on the whole width
Any suggestions how to do this?
A: NO, NO, NO! It is possible
Using CSS overflow: hidden and keyframe, it can be possible.
For the keyframe, I used from left:-120px(width of the glowing object) to left:100%
The structure I used:
<div class="loader">
<div class="loader-bg left"></div>
<div class="loader-bg right"></div>
<div class="greenlight"></div>
<div class="gloss"></div>
<div class="glow"></div>
</div>
The updated, compact structure using :before and :after:
<div class="loader7">
<span></span>
<div class="greenlight"></div>
</div>
The gradient, masking, glowing and all the effects cost an expensive structure. If anyone has a better idea, please let me know.
At this date, webkit only solution(the ellipse mask for the glow):
Added SVG mask for Firefox and other browsers that do not support -webkit-mask-image: http://jsfiddle.net/danvim/8M24k/
A: *
*css - width:100%
*no Javascript means you will have to do it with html5 which is a bit trickier. An animated GIF would work only if you decide to make the bar fixed-width (otherwise the gif will be skewed)
*to move it: javascript or html5
The easiest way: javascript (like it or not... ;) )
A: GIF-only solution
Vista's indeterminate progress bar doesn't loop right after it goes off on the right...
So I could create a wide enough GIF image and when progress bar would be narrow it would take longer for it to loop and when it'd be wider it loops again sonner. :)
Time of each repeat is the same in both cases but in narrow bar it takes less to get to the end than on the wider ones.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555181",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How would one approach creating a morphable 3D model? A Morphable Model for the Synthesis of 3D Faces
The above video is over 12 years old. How was the software done?
I need something way simpler but basically the same: a morphable model (thorax) that can be altered after being pre-morphed using a picture.
Any links that might provide useful information are appreciated.
Are there any open source projects that might have helpful code that could be studied?
A: What you need is called Morph target animation. Blender implements this, but the feature is called Shape Keys.
You can see an example of morphing at NeHe Productions.
This process works by creating a base vector of points, such as a face and a set of change vectors that contain the differences to various morph targets. A possible morph target would be smile and it would contain the offset values that added to the original face would result in a smiling face.
You can do linear combinations of morph targets and you can even create caricatures, by exaggerating the factors (original + 2*smile).
A: The details are all in their paper:
www.mpi-inf.mpg.de/~blanz/html/data/morphmod2.pdf
In short, you need:
*
*A collection of complete 3D scans of samples of the object class you want to characterize
*A way of performing 'non-rigid registration' to align a reference template to each sample
*Standard statistical analysis (principal components) of the aligned samples
Note that their choice of the name 'Morphable Model' is misleading. They are referring to something much more specific than a set of difference morphs or morph targets.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555183",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory I am using pdfbox in java to convert pdf to images. But when I compile I got the message
Exception in thread "main" java.lang.NoClassDefFoundError:
org/apache/commons/logging/LogFactory.
Here is the code I am following. Kindly help me to get out of this error.
A: You need the Apache Commons Logging library on your classpath.
Chances are that you're missing all the dependencies of PDFBox:
Minimum Requirement for PDFBox
*
*Java 1.5
*commons-logging
A: Add commons-logging.jar file to your project classpath. that will fix the issue.
A: You need to ensure that the apache library is on your class path at runtime.
A: Is the commons logging jar on the classpath? You can download this from Download Commons Logging
A: I had the same problem and I have tried all of the solutions on the web, I had all of the required JAR files in my CLASSPATH ... but it didn't work. then I decided to move my JAR files from my DROPBOX folder to a normal folder and it worked!
So if your JARs are on dropbox or anything like that, move them to a normal folder and add them to your classpath! it will solve the java.lang.NoClassDefFoundError exception.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555185",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "21"
}
|
Q: String to double I hope you can help me out with this 'small' problem. I want to convert a string to a double/float.
NSString *stringValue = @"1235";
priceLabel.text = [NSString stringWithFormat:@"%d",[stringValue doubleValue]/(double)100.00];
I was hoping this to set the priceLabel to 12,35 but I get some weird long string meaning nothing to me.
I have tried:
priceLabel.text = [NSString stringWithFormat:@"%d",[stringValue intValue]/(double)100.00];
priceLabel.text = [NSString stringWithFormat:@"%d",[stringValue doubleValue]/100];
but all without success.
A: This is how to convert an NSString to a double
double myDouble = [myString doubleValue];
A: You have to use %f to show float/double value.
then %.2f means 2digits after dot
NSString *stringValue = @"1235";
NSString *str = [NSString stringWithFormat:@"%.2f",[stringValue doubleValue]/(double)100.00];
NSLog(@"str : %@ \n\n",s);
priceLabel.text = str;
OUTPUT:
str : 12.35
A: I think you have the wrong format string. Where you have:
[NSString stringWithFormat:@"%d", ...];
You should really have:
[NSString stringWithFormat:@"%f", ...];
%d is used for integer values. But you're trying to display a floating point number (%f).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555187",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to update a field of a table with some percentage of its value in SQL? Let suppose I have a table Employee, which have three field i.e EID , Salary, Dept
What I want to do is to increase the salary of every employee of Department 'Accounts' by 5%.
How this could be achieved in SQL Sever Query?
Kindly help me out!
Cheers
A: you can simply create an update statement with the right math. I would do something like this:
update Employee set salary = (salary * 1.05) where Dept = 'Accounts'
A: update Mytable set Sal=1.05*sal where departmentId=xxx
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555189",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Extending Visual Studio 2010 - Replace text in editor with keyboard shortcut I want to write an extension for the Visual Studio 2010 editor, that replaces/edits the selected text. I've figured out how to do this the "old way" by selecting a "Other Project Types - Extensibility - Add In", but as far as I know, this is pretty much legacy, and includes alot of COM Interop and mess like that.
The samples I can find online for the new type of extensibility-project ("New Project - C# - Extensibility") only manipulates stuff like colors and makes boxes around letters and useless stuff like that.
Can this be done with MEF and VSIX, or do I have to fall back to the legacy-method?
What I want to do:
*
*Create an extension that adds a menu item (and maybe a toolbar button)
*When the user clicks the button/menu item (or a assigned keyboard shortcut), the current selected text is changed according to the add-ins behavior.
I've managed to do this with legacy add-in, but it feels "wrong" working with so much interop, when the new MEF stuff is out there. Any samples, code examples, tutorials etc. is greatly appreciated!
A: Legacy approach is to use Visual Studio Integration Package services, but now you can leverage power of the MEF Framework. Take a look here:
*
*Extending the Editor
*Managed Extensibility Framework in the Editor
*Walkthrough: Highlighting Text
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555190",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: temporary object creation in copy constructor I am reading about copy constructor in C++
It was mentioned that an object is passed usuing call by value and return by values constructs a temporary objects that are never seen by the user. My understanding is that when we call by val for example
myclass b;
void myfunc(myclass c) {} //c(b) copy constructor is called.
Where temporary object is created?
Thanks!
A: The copy is created in the function scope of myfunc(). That is, c is in scope of the entire function, which includes (and is slightly larger than) the function body. The copy is destroyed when the function returns, i.e. at the semicolon of myfunc(b);.
A: In the case of pass-by-value, a copy is made into the argument (rather than the temporary), so in the particular code in your example, there will be two objects:
myclass b;
myfunc( b ); // b is copied to argument "c" by means of the copy constructor
In the case of return by value, things are a bit more complex, in the code:
type f() {
type tmp;
return tmp; // copies into temporary (again, copy constructor)
}
int main() {
type x = f(); // copies from temporary into x (copy constructor)
x = f(); // copies from temporary into x (assignment operator)
}
there are in theory 3 objects of type type. The compiler will create space for a type object before calling f in a location that is defined by the calling convention (this will be where the temporary is created), then the function is called and tmp is created inside f, it gets copied to the temporary in the return statement. Finally the temporary is copied to the x variable in main.
In many cases, though, the compiler can optimize away the temporaries by carefully choosing the locations of the variables. Most compilers will be able to optimize 2 of the 3 objects away in the previous example.
For a longer description you can read these:
*
*http://definedbehavior.blogspot.com/2011/08/value-semantics-nrvo.html
*http://definedbehavior.blogspot.com/2011/08/value-semantics-copy-elision.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555195",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Highcharts.js: how can stacked area graph animations be smooth? I'm trying to make a realtime-updating stacked area graph in Highcharts.js. The problem is that the "area" of the graph disappears during .addPoint() animation.
I'm trying to achieve this effect: http://jsfiddle.net/DgKKX/5/
...But when I try it for area graphs, this happens: http://jsfiddle.net/DgKKX/6/
Anyone got a clue on how to make the "area" animate as well?
A: Try duration and easing options of animation property similar to jsfiddle.net/DgKKX/5
Maybe you could also change area to 'areaspline' so that graph will be smooth
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555196",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: In Spring MVC validation, Is it possible to show only one error message per field at a time? Example,
I have
@NotEmpty //tells you 'may not be empty' if the field is empty
@Length(min = 2, max = 35) //tells you 'length must be between 2 and 35' if the field is less than 2 or greater than 35
private String firstName;
Then I input an empty value.
It says, 'may not be empty
length must be between 2 and 35'
Is it possible to tell spring to validate one at a time per field?
A: Use custom constraints for your field. For example, will use annotate @StringField.
@Target(ElementType.FIELD)
@Constraint(validatedBy = StringFieldValidator.class)
@Retention(RetentionPolicy.RUNTIME)
public @interface StringField {
String message() default "Wrong data of string field";
String messageNotEmpty() default "Field can't be empty";
String messageLength() default "Wrong length of field";
boolean notEmpty() default false;
int min() default 0;
int max() default Integer.MAX_VALUE;
Class<?>[] groups() default {};
Class<?>[] payload() default {};
}
Then make some logic in StringFieldValidator class. This class implemented by an interface ConstraintValidator <A extends Annotation, T>.
public class StringFieldValidator implements ConstraintValidator<StringField, String> {
private Boolean notEmpty;
private Integer min;
private Integer max;
private String messageNotEmpty;
private String messageLength;
@Override
public void initialize(StringField field) {
notEmpty = field.notEmpty();
min = field.min();
max = field.max();
messageNotBlank = field.messageNotEmpty();
messageLength = field.messageLength();
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
context.disableDefaultConstraintViolation();
if (notEmpty && value.isEmpty()) {
context.buildConstraintViolationWithTemplate(messageNotEmpty).addConstraintViolation();
return false;
}
if ((min > 0 || max < Integer.MAX_VALUE) && (value.length() < min || value.length() > max)) {
context.buildConstraintViolationWithTemplate(messageLength).addConstraintViolation();
return false;
}
return true;
}
}
Then you can use annotation like:
@StringField(notEmpty = true, min = 6, max = 64,
messageNotEmpty = "Field can't be empty",
messageLength = "Field should be 6 to 64 characters size")
And after all, you will have only one error message shown in right order.
A: Yes it is possible. Just create your own annotation like this:
@Documented
@Constraint(validatedBy = {})
@Target({ ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE })
@Retention(RetentionPolicy.RUNTIME)
@ReportAsSingleViolation
@NotEmpty
@Length(min = 2, max = 35)
public @interface MyAnnotation {
public abstract String message() default "{mypropertykey}";
public abstract Class<?>[] groups() default {};
public abstract Class<?>[] payload() default {};
}
important part is the @ReportAsSingleViolation annotation
A: A better solution would be to have some markup in your error message so that it formats nicely, such as a <br />, and use a CSS class to format the overall message. As noted in Bozho's comment, a user should be aware of everything that is incorrect.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555201",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: How to correctly return callbacks from C++ engine to obj-c program? First the situation:
There is C++ written engine implemented in Objective C program. iPhone xcode to be precise. It uses OpenGL to draw everything. It has "renderFrame" method that is called every frame (approximately 50 times per second). User has many buttons that navigate to other Objective C views. These buttons are drawn and handled in C++ engine too. When user presses one of them, the C++ engine sends callback to the program that a button is pressed (so program can change views).
My way of making this work:
Since there is a "renderFrame" method, i made it to return integer value each time. Most of the time it is 0. But when it returns something else, it has a meaning. For example if "renderFrame" returns 2, that means second button is pressed. To handle all these returned values i must build quite huge chunk of IFs.
So my question:
Since i am a fresh programmer i want to know whether this is a good approach or is it something only a junior may come up with. This engine will be ported to many other systems including android and even PC, so i do not know whether i can and if i should implement other kind of callback system. I also would like to know if this can get me performance issues and what would be more professional approach.
P.S. At the moment i have implemented more than 20 callbacks like this and everything works just fine. I can react instantly and precisely each frame.
Thank you for your suggestions.
A: It's a bad design for a number of reasons. First, what happens if more than one event took place? Two button clicks at once? Do you send 2 + 3? Do you ignore one and hope it wasn't important?
What happens when what you need to send isn't just a single binary fact? What if you want to send what button was clicked and where that happened? Or you need to transmit a number or character?
You should have a callback class, something like MyGraphicsCallbacks with functions like Button1Clicked(int locationX, int locationY), and then calling these functions when their respective events occur.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555202",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Getting a lits of all child controls of a control, by type im trying to make a method that creates a List with the name of all the child controls of a DetalsView that are of type string.
The closest i got was:
foreach (Control c in dv.Controls)
{
if (c is Label)
{
controlsToCheck.Add(c.ID);
}
}
foreach (string s in controlsToCheck)
{
Label lbl = (Label)dv.FindControl(s);
if (lbl.Text == "")
{
lbl.Text = "None";
lbl.CssClass = "bold";
}
}
However, all this does is iterate once in the first foreach, and then exit (ie. dv.Controls only returns one item). If i use FindControl, i can get to the items, but it means i have to do it for each item.
Any toughts?
Thanks!
Edit: here is my DetailsView (i cut some things out, which where just more controls so it fits on the page):
<asp:DetailsView DefaultMode="ReadOnly" FieldHeaderStyle-CssClass="dwHeader" CssClass="marginLeftRightBottom10px"
AutoGenerateDeleteButton="true" AutoGenerateEditButton="true" GridLines="None"
ID="dvIndividualItem" runat="server" AutoGenerateRows="False" DataSourceID="sqldsSingleItem"
OnDataBound="dvIndividualItem_DataBound">
<Fields>
<asp:TemplateField>
<HeaderTemplate>
<h1>
Item Name:</h1>
<p>
The name of the item.</p>
</HeaderTemplate>
<ItemTemplate>
<asp:Label runat="server" ID="lblItemName" Text='<%# Bind("itemName") %>'></asp:Label>
</ItemTemplate>
<InsertItemTemplate>
<asp:TextBox runat="server" ID="tbItemName"></asp:TextBox>
</InsertItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
<h1>
Item Description:</h1>
<p>
The description of the item.</p>
</HeaderTemplate>
<ItemTemplate>
<asp:Label runat="server" ID="lblItemDescription" Text='<%# Bind("itemDescription") %>'></asp:Label>
</ItemTemplate>
<InsertItemTemplate>
<asp:TextBox runat="server" ID="tbItemDescription"></asp:TextBox>
</InsertItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
<h1>
Item Image:</h1>
<p>
The image of the item.</p>
</HeaderTemplate>
<ItemTemplate>
<asp:Image runat="server" ID="imgItem" Width="40px" Height="40px" />
</ItemTemplate>
<InsertItemTemplate>
<asp:TextBox ReadOnly="true" runat="server" ID="tbItemImage"></asp:TextBox>
</InsertItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
<h1>
Item Type:</h1>
<p>
Specifies the item type.</p>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblItemType" Text='<%# Eval("itemType") %>' runat="server" />
</ItemTemplate>
<%-- <InsertItemTemplate>
<asp:DropDownList AutoPostBack="true" OnSelectedIndexChanged="ddlItemTypes_SelectedIndexChanged"
DataTextField="itemType" DataValueField="typeId" DataSourceID="sqldsTier1Category"
ID="ddlItemTypes" runat="server">
</asp:DropDownList>
<asp:SqlDataSource ConnectionString="<%$ ConnectionStrings:myDbConnection%>" ID="sqldsTier1Category"
runat="server" SelectCommand="dbo.getItemCategories" SelectCommandType="StoredProcedure">
</asp:SqlDataSource>
</InsertItemTemplate>--%>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
<h1>
Item SubType:</h1>
<p>
Specifies the sub-item type.</p>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblSubItemType" Text='<%# Eval("itemSubType") %>' runat="server" />
</ItemTemplate>
<%-- <InsertItemTemplate>
<asp:DropDownList OnDataBound="ddlItemSubTypes_OnDataBound" AutoPostBack="true" DataTextField="itemSubType"
DataValueField="subTypeId" DataSourceID="sqldsTier2Category" ID="ddlItemSubTypes"
runat="server">
</asp:DropDownList>
<asp:SqlDataSource ConnectionString="<%$ ConnectionStrings:myDbConnection%>" ID="sqldsTier2Category"
runat="server" SelectCommand="dbo.getItemSubCategories" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:ControlParameter ControlID="dwNewItem$ddlItemTypes" Name="typeId" PropertyName="SelectedValue"
DbType="Int16" />
</SelectParameters>
</asp:SqlDataSource>
</InsertItemTemplate>--%>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
<h1>
Item SubSubType:</h1>
<p>
Specifies the sub-sub-item type.</p>
<p>
<i>Not always applicable.</i></p>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblSubSubItemType" Text='<%# Eval("itemSubSubType") %>' runat="server" />
</ItemTemplate>
<%-- <InsertItemTemplate>
<asp:DropDownList DataTextField="itemSubSubType" DataValueField="subSubTypeId" DataSourceID="sqldsTier3Category"
ID="ddlItemSubSubTypes" runat="server">
</asp:DropDownList>
<asp:SqlDataSource ConnectionString="<%$ ConnectionStrings:myDbConnection%>" ID="sqldsTier3Category"
runat="server" SelectCommand="dbo.getItemSubSubCategories" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:ControlParameter ControlID="dwNewItem$ddlItemSubTypes" Name="subTypeId" PropertyName="SelectedValue"
DbType="Int16" />
</SelectParameters>
</asp:SqlDataSource>
</InsertItemTemplate>--%>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
<h1>
Requires Sword Swinger Class?</h1>
<p>
Specifies whether the item can only be used by the Sword Swinger.</p>
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="cbReqSwordSwinger" Text='<%# Bind("requiresSwordSwinger") %>' runat="server" />
</ItemTemplate>
<%-- <InsertItemTemplate>
<asp:CheckBox runat="server" ID="cbReqSwordSwinder" />
</InsertItemTemplate>--%>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
<h1>
Requires Rat Catcher Class?</h1>
<p>
Specifies whether the item can only be used by the Rat Catcher.</p>
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="cbReqRatCatcher" Text='<%# Bind("requiresRatCatcher") %>' runat="server" />
</ItemTemplate>
<InsertItemTemplate>
<asp:CheckBox runat="server" ID="cbReqRatCatcher" />
</InsertItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
<h1>
Requires Spell Mumbler Class?</h1>
<p>
Specifies whether the item can only be used by the Spell Mumbler.</p>
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="cbReqSpellMumbler" Text='<%# Bind("requiresSpellMumbler") %>' runat="server" />
</ItemTemplate>
<InsertItemTemplate>
<asp:CheckBox runat="server" ID="cbReqSpellMumbler" />
</InsertItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-CssClass="colorBlue dwHeader">
<HeaderTemplate>
<h1>
Strength permanently added:</h1>
<p>
Specifies the amount of strength the item permanently adds to your character.</p>
<p>
<i>Only available when the item is set to type "Consumable"</i></p>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblPermanentStrength" Text='<%# Bind("permanentStrength") %>' runat="server" />
</ItemTemplate>
<InsertItemTemplate>
<asp:TextBox Enabled="false" runat="server" ID="tbItemPermanentStr"></asp:TextBox>
</InsertItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-CssClass="colorBlue dwHeader">
<HeaderTemplate>
<h1>
Agility permanently added:</h1>
<p>
Specifies the amount of agility the item permanently adds to your character.</p>
<p>
<i>Only available when the item is set to type "Consumable"</i></p>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblPermanentAgility" Text='<%# Bind("permanentAgility") %>' runat="server" />
</ItemTemplate>
<InsertItemTemplate>
<asp:TextBox Enabled="false" runat="server" ID="tbItemPermanentAgl"></asp:TextBox>
</InsertItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-CssClass="colorBlue dwHeader">
<HeaderTemplate>
<h1>
Magical Power permanently added:</h1>
<p>
Specifies the amount of magical power the item permanently adds to your character.</p>
<p>
<i>Only available when the item is set to type "Consumable"</i></p>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblPermanentMagicalPower" Text='<%# Bind("permanentMagicalPower") %>'
runat="server" />
</ItemTemplate>
<InsertItemTemplate>
<asp:TextBox Enabled="false" runat="server" ID="tbItemPermanentMP"></asp:TextBox>
</InsertItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-CssClass="colorBlue dwHeader">
<HeaderTemplate>
<h1>
Health Points restored:</h1>
<p>
Specifies the amount of health points the item restores.</p>
<p>
<i>Only available when the item is set to type "Consumable"</i></p>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblHPRestored" Text='<%# Bind("restoresHealthPoints") %>' runat="server" />
</ItemTemplate>
<InsertItemTemplate>
<asp:TextBox Enabled="false" runat="server" ID="tbItemRestoresHp"></asp:TextBox>
</InsertItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-CssClass="colorBlue dwHeader">
<HeaderTemplate>
<h1>
Mana Points restored:</h1>
<p>
Specifies the amount of mana points the item restores.</p>
<p>
<i>Only available when the item is set to type "Consumable"</i></p>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblManaRestored" Text='<%# Bind("restoresMana") %>' runat="server" />
</ItemTemplate>
<InsertItemTemplate>
<asp:TextBox Enabled="false" runat="server" ID="tbItemRestoresMana"></asp:TextBox>
</InsertItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-CssClass="colorBlue dwHeader">
<HeaderTemplate>
<h1>
Health Points permanently added:</h1>
<p>
Specifies the amount of health points the item permanently adds to your character.</p>
<p>
<i>Only available when the item is set to type "Consumable"</i></p>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblPermanentHP" Text='<%# Bind("permanentHealth") %>' runat="server" />
</ItemTemplate>
<InsertItemTemplate>
<asp:TextBox Enabled="false" runat="server" ID="tbItemPermanentHP"></asp:TextBox>
</InsertItemTemplate>
</asp:TemplateField>
</Fields>
</asp:DetailsView>
A: Try this
public static IEnumerable<Control> GetAllControls(Control parent)
{
foreach (Control control in parent.Controls)
{
yield return control;
foreach (Control descendant in GetAllControls(control))
{
yield return descendant;
}
}
}
and call
List<Control> ControlsToCheck = GetAllControls(dv).OfType<Label>().ToList();
A: I modified Bala R's solution a little. I made it a generic extension method that only yeilds the type of control you are interested in so you don't need to call .OfType<T> as a second step:
public static IEnumerable<T> GetControls<T>(this Control parent) where T : Control
{
foreach (Control control in parent.Controls)
{
if (control is T) yield return control as T;
foreach (Control descendant in GetControls<T>(control))
{
if (control is T)
yield return descendant as T;
}
}
}
Used like this:
List<Label> labels = dv.GetControls<Label>().ToList();
or
foreach(Label label in dv.GetControls<Label>())
{
//do stuff
}
A: When you are iterating through dv.Controls, it's only showing controls at the first level underneath your DetalsView. You need to iterate through all the child controls, and then their children, etc. if you need to find all the Labels.
The answer by @Bala R. is a great example of this. You can also find some examples on this answer.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555209",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Unable to retrieve data from web sql database in phonegap app I am working on a phonegap app on iOS that needs to store some data. I am using the storage API given in phonegap docs and I believe the data is being inserted. But when I am trying to retrieve the data using SELECT statement, I am not getting any output in the alert boxes.
the "loading2" alert is being shown but after that i dont get any output.
My code is as below (picked up from phonegap wiki):
// load the currently selected icons
function loadCelebs(mydb)
{
try
{
alert("loading2");
mydb.transaction(
function(transaction)
{
transaction.executeSql('SELECT * FROM celebs ORDER BY name', [], celebsDataHandler(transaction,results));
});
}
catch(e)
{
alert(e.message);
}
}
// callback function to retrieve the data from the prefs table
function celebsDataHandler(tx, results)
{
// Handle the results
alert(results);
}
A: Try changing it to:
mydb.transaction(
function(transaction)
{
transaction.executeSql('SELECT * FROM celebs ORDER BY name', [], celebsDataHandler);
});
You don't want the (tx, results) part in the transaction() call. You are only passing a reference to the callback handler so that it can run it when it is done. By adding the (tx, results) you are executing and passing in the result.
Also, consider passing in an error handler. It can make debugging easier if you know what the errors are.
function errorCB(err) {
alert("Error processing SQL: "+err.code);
}
mydb.transaction(
function(transaction)
{
transaction.executeSql('SELECT * FROM celebs ORDER BY name', errorCB, celebsDataHandler);
}
);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555220",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: C#, Component class In my current project I have been provided with a solution that contains 3 simple classes and 1 component class. There is some code in component class that i need to access in one of my simple class. I am trying to create an instance of component class but there is error that Component class does not exist. Please guide either i am going in wrong direction? If so then how can i solve my problem. How can i access code given in component class. I am working in Visual Studio 2010 and .NET 4.0 with C#.net
Thanks
Khizar
A: Giving the lack of specifics, I'm gonna make a wild guess:
The signature of Component is:
class Component
{
//Class members
}
by default, the class is internal, which means it's only available in the assembly it resides.
Change it to:
public class Component
{
//Class members
}
And fix the namespaces (CTRL + ";")
A: You can't just access the running instance - you will have to pass pointer to the component class instance to the simple class, common way is passing the pointer when creating the class.
For example, in the component class where you create the simple class:
SimpleClass mySimpleClass = new SimpleClass(this);
Now in the simple class, add class member and change the constructor:
ComponentClass m_ComClass;
public SimpleClass(ComponentClass parent)
{
m_ComClass = parent;
}
And finally in the place where you need to access method of the Component class from within the simple class, have:
void SomeAction()
{
m_ComClass.SomeFunc();
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555224",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: FB logon appearing behind Acitivity screen I am trying to logon to FB from within an activity.
For some reason the FB logon screen appears behind the activity screen.
The activity theme is defined as "android:theme="@android:style/Theme.Dialog" because I want it to look like a dialog.
This is what I am getting:
I tried changing my activity not to be theme dialog but didn't help.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555225",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Java Webapp and KeyStore I'm designing a small tool (web interface and web services), for signing some blob's of data with a private RSA key. The application will have more than one private key (ie. for different types of blob's), and in the future we might deprecate some of the keys (and add new ones).
The question is where should I store the KeyStore file? Adding it to META-INF doesn't seems like a good idea, as it would be overwritten with a software update. Other options, would be to store to something like /etc/myapp/keys.keystore or to a table in a blob column.
So, what is the "canonical" way of storing a keystore?
A: I don't think there's a canonical way. Perhaps the best option would be to have the keystore external to the application, and configure it's location (for example via -Dkeystore.location=/home/.. (something similar to this).
A: In the past, I've stored keystores on the file system, as a file with the .jks extension. The app in question always runs as a particular user, so we put the file in (a subdirectory of) the user's home directory. We then had some code along the lines of
String keystorePath = System.getProperty("ourapp.keystore.path");
File keystoreFile;
if (keystorePath!=null)
keystoreFile = new File(keystorePath);
else
keystoreFile = new File(System.getProperty("user.home"), "ourapp.jks");
if (!f.exists()) {
// Some sort of whining, return
}
// ...load and deal with keystore...
I don't think there's a canonical way to do this (though I might be wrong). This way has worked well for our use case.
A: I've not tried this, but it looks like the recommended way to do this is using environment entries in context.xml.
Tomcat docs here
Related stackoverflow question here
Also, how you are describing how you're going to implement the encryption sounds like there are potentially some problems with it. Read the user erickson's recommendations in various answers to see how to do this right. Here is a question to start with: Java 256-bit AES Password-Based Encryption
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555231",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Migrate SSE2 to Arm NEON intrinsincs I have the following code in SSE2 intrinsincs. It processes input from a Kinect.
__m128i md = _mm_setr_epi16((r0<<3) | (r1>>5), ((r1<<6) | (r2>>2) ), ((r2<<9) | (r3<<1) | (r4>>7) ), ((r4<<4) | (r5>>4) ), ((r5<<7) | (r6>>1) ),((r6<<10) | (r7<<2) | (r8>>6) ), ((r8<<5) | (r9>>3) ), ((r9<<8) | (r10) ));
md = _mm_and_si128(md, mmask);
__m128i mz = _mm_load_si128((__m128i *) &depth_ref_z[i]);
__m128i mZ = _mm_load_si128((__m128i *) &depth_ref_Z[i]);
mz = _mm_cmpgt_epi16(md, mz);
mZ = _mm_cmpgt_epi16(mZ, md);
mz = _mm_and_si128(mz, mZ);
md = _mm_and_si128(mz, md);
_mm_store_si128((__m128i *) frame,md)
if(_mm_movemask_epi8(mz)){ ... }
This basically unpacks 11 uint8_t (r0-r10) to 8 uint16_t in an SSE register(mmask is constant and created previously). It then loads two more registers with the corresponding elements from two arrays that serve as bounds. It checks them and creates a register which has the elements that don't fit in the criteria zeroed out. It then stores them and goes to further process each element. The movemask serves as a nice optimization when none of the elements pass in which case the processing can be skipped.
This works nice and now I want to port it to NEON as well. Most of it is straightforward except two parts. Looking at the assembler output(gcc) from the SSE2 code I see that instead of doing 8 uint16_t moves in _mm_setr_epi16 it shifts and ors them into uint32_t and finally does 4 moves. That seems efficient and since the compiler takes care of it I didn't change the code. Should I apply that manually in the NEON case? Instead of 8 vsetq_lane_u16 do the shifting and perform 4 vsetq_lane_u32? Will I have any issues with endianess and will it be worthwhile?
The final part is the movemask as I haven't been able to find an equivalent. Can anyone suggest something?
A: I'd prefer starting with plain C code instead of SSE2; there might be optimization opportunities not easily seen at this low level
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555235",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Encrypt data between C#, ANDROID and IPHONE I'm developing a application to Windows(C#), Iphone, Android and Iphone which will connect to a SOAP WebService, that store information on a Database.
I'm looking for a way to encrypt/decrypt the information between those platforms. Is there any cross platforms library?
A: As @Sascha says, AES is available on pretty much every platform. What you have to do is to make sure that everything else is the same on both platforms:
*
*The same mode; use either CBC or CTR mode.
*The same IV; set it explicitly, don't use the default because it will often be different on different systems.
*The same key; obvious, but they need to be the same at the byte level because text can be encoded differently on different systems. Explicitly state the encoding you are using.
*The same padding; for AES use PKCS7, again don't rely on the default which may be different on different systems.
Whatever you chose do set things explicitly and don't rely on defaults. Defaults can differ between systems and any difference will cause decryption to fail.
A: Have you looked at MonoTouch and MonoDroid by Xamarin?
Using these libraries you could probably just use native .Net XML Services between all three and share all your backend code.
A: I would like to recommend the Advanced Encryption Standard (AES). It's very secure and i'm sure every platform has a good default implementation of this algorithm.
Have a look at the detailes: AES on wikipedia
A: The last time I develop an iPhone and Android app I, need to get and post data to a .NET Soap WebService. I use AES to encrypt/decrypt the data
You can download the zip file sample project that I've followed to do encryption/decryption in objective-c and .NET from this link.
http://dotmac.rationalmind.net/2009/02/aes-interoperability-between-net-and-iphone/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555241",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: App with WRITE_APN_SETTINGS permission is not available to Galaxy Tab 10.1 GT-P7500 on Android Market I have found that Android application with WRITE_APN_SETTINGS permission is not available to Samsung Galaxy Tab 10.1 GT-P7500 on Android Market. I can see also from developer console that app is not available to this device.
On the other hand, here http://developer.android.com/guide/appendix/market-filters.html is mentioned that "Strictly, Android Market does not filter based on 'uses-permission' elements".
When I removed following line
<uses-permission android:name="android.permission.WRITE_APN_SETTINGS"></uses-permission>
from manifest, app became suddenly available on Market and developer console confirm support of GT-P7500.
Here is a link to device specification http://acellphonereviews.com/samsung-galaxy-tab-10-1-3g-gt-p7500-review-price-specs.html.
Does anybody have explanation for this Market filtering behaviour and can help how to make app with APN permission available for GT-P7500 ?
Thanks for any hint, Gudaps.
A: I solved problem by adding following to manifest:
<uses-feature android:name="android.hardware.telephony" android:required="false"/>
A: Could it be that, implicit, WRITE_APN_SETTINGS adds the android.hardware.telephony feature to your app? Try adding this feature by hand and set it to required=false. (Don't forget to check if the feature is available on the device manually, i.e. avoid the NPE if the feature is not available.)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555243",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Boost named_mutex and remove() command I have a class which can be created by multiple threads. But at one function the code needs to be protected, so I decided to use the boost interprocess mutex. Every class creates or opens the same Mutex in it's constructor:
MyClass::MyClass()
{
boost::interprocess::named_mutex m_Lock(
boost::interprocess::open_or_create, "myLock" );
}
So now there comes the point where the critical code part is called:
int MyClass::MyFunction()
{
boost::interprocess::scoped_lock<boost::interprocess::named_mutex> lock(
m_Lock, boost::interprocess::try_to_lock);
if(!lock)
{
return -1;
}
// else do some stuff here
}
To clean up after the function ( and like its described on the boost page ) I use the remove command in my class destructor:
MyClass::~MyClass()
{
boost::interprocess::named_mutex::remove("myLock");
}
Actually all this code works fine, but there is one concern I have:
As it is said in the description of the remove command :
Erases a named mutex from the system. Returns false on error. Never throws.
So that means the remove command just erases the Mutex out of the system - even if another thread has just locked it ( I tried this case already - it isn't locked then anymore ).
So my problem is the following:
For example I have 3 Threads ( A, B and C ) - now the following happens:
*
*Process A creates an Instance of the class, calls the function and locks it
*Process B creates an Instances of the class, calls the function but can't access code ( then waits e.g. )
*Process A finishes with the protected code and it gets unlocked
*Process B gains access to the protected code and locks it
*Process A deletes the Instance of the class -> the remove command is called
*Process C creates an Instance of the class, calls the function and can access the code since the remove command erased the Mutex --> Error!
So now someone may say " Then don't call remove! " - Well is that possible? I mean since the named_mutex writes to the system I doubt it is erased without an explicit call, even if the program ends.
Anyone has some help?
A: From the boost docs, the remove call, is unnecessary. The destructor of named_mutex will automatically take care indicating to the OS that the process no longer needs the resource. You're probably fine with just relying upon the built-in behavior of the destructor for cleanup.
If you explicitly call remove, you'll likely cause any other processes or threads attempting to use the named mutex to fail on any operations on the mutex. Depending on how your usage is orchestrated, this could either cause data races or crashing/exceptions being thrown in other processes.
~named_mutex();
Destroys *this and indicates that the calling process is finished
using the resource. The destructor function will deallocate any system
resources allocated by the system for use by this process for this
resource. The resource can still be opened again calling the open
constructor overload. To erase the resource from the system use
remove().
A: You probably need a shared usage counter for the mutex. Lock the mutex in the destructor, decrement it, and if it's zero after the decrement, deallocate the still locked mutex. You will prevent your current race condition by that.
A: According to the boost manual:
*
*This is a mutex with a global name, so it can be found from different processes. However, this mutex can't be placed in shared memory. @Toby
*The destructor function will deallocate any system resources allocated by the system for use by this process for this resource. The resource can still be opened again calling the open constructor overload. To erase the resource from the system use remove().
I think the above should have addressed your questions.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555253",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: Asp.net http tunelling Application Is there any open source http tunneling software written in asp.net ? I know i can simply get http response and display it in an iframe, but this is not the result want. The links should be replaced, the styles of the page content should be set respectively. This needs lots of parsing and editing stuff. It would be great if there is an open source control or project that can do it for me. Unfortunately i couldn't find any on the web.
A: If I understand correctly, you want to be able to display content from a different domain in an asp.net page without using IFRAMES? If that's so, I don't think that is possible today.
There is; however, a jQuery plugin that allows you load content from other websites using JSONP+YQL. Se here and here.
A: From your page's code behind, use the System.Net.WebClient to make a webrequest to the other site and then take the returned HTML and display it on your page.
Edit:
If you don't want to manually fix all of the HTML yourself, take a look at the Application Request Routing module in IIS7. It can act like a proxy and pull in content from other domains.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555254",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: c++ even more generalized operator templating So I just learned (thanks guys) about decltype. I now can write really nice vector templates that actually outperform valarrays(!):
template <typename T, typename U>
vector<decltype(T()*U())> operator*(const vector<T>& A, const vector<U>& B){
vector<decltype(T()*U())> C = vector<decltype(T()*U())>(A.size());
typename vector<T>::const_iterator a = A.begin();
typename vector<U>::const_iterator b = B.begin();
typename vector<decltype(T()*U())>::iterator c = C.begin();
while (a!=A.end()){
*c = (*a) + (*b);
a++; b++; c++;
}
return C;
}
Is it possible to make this kind of templating even more "meta", in the sense that we allow the operator ("*") itself to be a template parameter? I.e. have one single template definition that works for *, +, %, etc, where the appropriate operator op is used in *c = (*a) op (*b)?
I'm betting it is not, but it would be nice!
A: As you expected, this answer is "no." :)
However, you can use the preprocessor to generate such functions:
#define OPERATOR_BLOB(optype) \
vector<…> operator optype (…) { … }
OPERATOR_BLOB(*)
OPERATOR_BLOB(+)
…
A: Use std::declval<T&&>() instead of just T(), it might not have a default constructor (since std::vector does not require a default constructor, only a copy constructor). Also, be very sure about type & reference & rvalue reference correctness and forwarding, classes may implement things differently for values, references, const references, rvalue references. Test it with several classes.
Also, mind you that the return type extraction might not work for compound assignment operators in GCC due to an unimplemented feature.
And yes, I solved it with parameterized macros in my pointer wrapper class: http://frigocoder.dyndns.org/code/Frigo/Lang/ref
For example
#define PROXY_BINARY_OPERATOR(_) \
template <class Arg> \
decltype(std::declval<T&&>() _ std::declval<Arg&&>()) operator _ (Arg&& arg) \
{ \
return std::forward<T>(get()) _ std::forward<Arg>(arg); \
} \
template <class Arg> \
decltype(std::declval<const T&&>() _ std::declval<Arg&&>()) operator _ (Arg&& arg) const \
{ \
return std::forward<T>(get()) _ std::forward<Arg>(arg); \
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555255",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Ways to model child view model interaction with the parent view model? Consider some sort of Personal Information Management presentation with a PimDetailVm that takes a Person object as it's Model. The presentation will manage various aspects about a person (name, contact points, addresses, etc), which together would bloat the original view model.
So I want to split off satellite view models for each. The original view model still has responsibility for permitting and committing updates though, so at a minimum its needs to know whether IsDirty and IsValid are true, and the current state of the Model.
Cheers,
Berryl
UPDATE
There is (was) too much text in my original post; maybe organizing this better will get more responses and leave a trail of something useful, so
Parent / Child synchronization options
*
*INPC
*
*Pros - already implemented by VM
*Cons - fires multiple times, arguably should be restricted for DataBinding only
*Mediator
*
*Pros - clean separation of intention
*Cons - not sure how to implement and use in a generic fashion
*Event Aggregator
*
*Pros - common abstraction
*Cons - not sure how to implement and use in a generic fashion
*Domain event (ie, PersonUpdated) and let the model be the synch source
*
*Pros - arguably the event belongs here, simplifies VM infrastructure
*Cons - not sure
*Intra View Model Event (ie, ViewModelUpdated)
*
*Pros - cleaner than INPC since it fires only one and its intention is clear
*Cons - not sure
*Hard link (ie, Parent.Update())
*
*Pros - intention is clear, easier to debug
*Cons - tight coupling
*inherit from Dependency Object
*
*Pros - Will likes it
*Cons - not reusable, tight coupling to WPF dispatcher
*inherit VM from DynamicObject
*
*Pros - you can do what you want
*Cons - changes ViewModel structure, complex to inexperienced programmers
*incorporate AOP with an interceptor
*
*Pros - do what you want
*Cons - learning curve, not obvious
A: Just to close this out really, Pete Brown addresses some aspects of this here.
Josh Smith also has two very useful classes in hi MVVM Foundation library that address this problem: Messenger and PropertyObserver.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555267",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Integrating google+ api in iphone project I am developing an application in which I have to give support for google + login also.i follow this link to download the latest version of google +(gdata)api and I integrated it in my project.When I run it it was showing 16 errors.I added json files.Now it is showing 2 errors of some redundant files.
Please suggest me how to solve this or any other way to integrate google + api.
Any help would be highly appreciated.
A: The library for using the Google Plus API from iOS and Mac is google-api-objectivec-client.
It includes a sample Cocoa app using the Plus API, as well as the gtm-oauth2 library for signing in from iOS apps.
A: Looks like you forgot to include some frameworks! Or maybe you haven't set some paths the right way for the json files
A: A complete guide and step by step objective c API integration can be seen here
A: Had the same issue of integration of Google Api Client for Objective C.
I am not an expert but wrote a tutorial how I integrated it so someone may save time. It can be found here
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555268",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Are you allowed to retrieve sequence inside a trigger I want to be able to get teh sequence value and use the same value on several operations in a trigger to do an audit operation for a table. So when a table is updated, I want to get all the column that were updated. But I want to have them grouped as one when I register the changed column in the database. Is there a way to get a sequence number and store in a variable inside a trigger. The code that I was able to make keeps on getting PLS-00357.
CREATE OR REPLACE TRIGGER TRG_EMPLOYEE_CHANGED AFTER INSERT OR DELETE
OR UPDATE ON EMPLOYEE REFERENCING OLD AS old NEW AS new FOR EACH ROW
DECLARE
GROUPID NUMBER := SEQ_POPERATIONLOG_LOGSUBNO.NEXTVAL;
BEGIN
OPERATION('FIRST_NAME', GROUPID, :old.FIRST_NAME, :new.FIRST_NAME);
OPERATION('LAST_NAME', GROUPID, :old.LAST_NAME, :new.LAST_NAME);
OPERATION('ADDRESS', GROUPID, :old.ADDRESS, :new.ADDRESS);
OPERATION('TELEPHONE', GROUPID, :old.TELEPHONE, :new.TELEPHONE);
END;
A: Prior to 11g, the only supported syntax for getting a value from a sequence was:
DECLARE
GROUPID NUMBER ;
BEGIN
SELECT SEQ_POPERATIONLOG_LOGSUBNO.NEXTVAL
INTO GROUPID
FROM DUAL;
...
One alternative solution would be to use NEXTVAL in the first INSERT statement and CURRVAL (i.e. the most recently assigned value in this session) for the others.
A: If you are using Oracle 10g or older then you'd need to select the sequence next value from Oracle's dummy table DUAL.
CREATE OR REPLACE
TRIGGER TRG_EMPLOYEE_CHANGED
AFTER INSERT OR DELETE OR UPDATE
ON EMPLOYEE
REFERENCING OLD AS old NEW AS new
FOR EACH ROW
DECLARE
GROUPID NUMBER;
BEGIN
SELECT SEQ_POPERATIONLOG_LOGSUBNO.NEXTVAL
INTO GROUPID
FROM dual;
OPERATION('FIRST_NAME', GROUPID, :old.FIRST_NAME, :new.FIRST_NAME);
OPERATION('LAST_NAME', GROUPID, :old.LAST_NAME, :new.LAST_NAME);
OPERATION('ADDRESS', GROUPID, :old.ADDRESS, :new.ADDRESS);
OPERATION('TELEPHONE', GROUPID, :old.TELEPHONE, :new.TELEPHONE);
END;
A: I think I got the answer by using select into.
SELECT SEQ_X_LOGSUBNO.NEXTVAL INTO GROUPID FROM DUAL;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555270",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to redirect hostname to ec2 instance? I have this domain 'suaparte.org' and I have the website running in a EC2 here http://50.19.242.172:8080/SuaParte/ I would like to redirect 'suaparte.org' to http://50.19.242.172:8080/SuaParte/.
Amazon provied a public dns to my elastic ip : ec2-50-19-242-172.compute-1.amazonaws.com
I think it's just put this public dns in my hostname provider, but I wonder, how he gonna know to redirect to http://50.19.242.172:8080/SuaParte/ ?
And not to other project that I have deployed in my glassfish ?
A: DNS is a 'better' name for IP. Nothing more. With it you cannot specify port (in your case 8080) or contextPath (in your case SuaParte).
To do that you must install a http server on port 80 (default port for http protocol) on your server. And than when accessing http://50.19.242.172:80 will handle the redirect to http://50.19.242.172:8080/SuaParte/.
Other solution is to configure the glassfish to run on port 80 and then deploy your app as default (to contextPath /).
A: This is a general web server question and is not specific to Amazon EC2. It works pretty much the same there as on any other web server.
You have a couple options including:
*
*Change your web server to be listening on port 80 of 50.19.242.172 and point your DNS for suaparte.org and www.suaparte.org to resolve to 50.19.242.172. If you have multiple web sites on that server and that port, then you'll want to learn how to configure virtual hosts so that they each serve their own content depending on what hostname the browser is trying to access. Once you have virtual hosts, you may want to simply show the home page at "/" or you can redirect to the "/SuaParte/" path.
*Point DNS for suaparte.org and www.suaparte.org to a different web server (still running on port 80) that redirects the browser to port 8080, path /SuaParte/ on your EC2 box. The most convenient solution here would be if your domain registrar or DNS provider allows you to set up a redirect for free. You might find this under the DNS configuration settings of your provider.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555274",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: LINQ to SQL relationship doesn't update collections I'm having one issue with LINQ to SQL for Windows Phone (SQL Server CE).
I'm developing an personal finance app, and then I have the Account class and the Transaction class. Each Transaction class have a reference to the account it belongs to, so the Account class have a collection of transactions, in a one-to-many relationship. Then I have the repositories (AccountRepository and TransactionRepository) that expose methods to insert, delete, findbykey, and return all instances of each of this classes. The ViewModel have references to its repositories. OK, everything works just well, but, when I create a transaction, it doesn't appear in the Account.Transactions collection untill I stop the software and run it again.
Here's some pieces of the code, first, the model classes:
[Table]
public class Transaction : INotifyPropertyChanged, INotifyPropertyChanging
{
// {...}
[Column]
internal int _accountID;
private EntityRef<Account> _account;
[Association(Storage = "_account", ThisKey = "_accountID")]
public Account Account
{
get {return _account.Entity;}
set
{
NotifyPropertyChanging("Account");
_account.Entity = value;
if (value != null)
{
_accountID = value.AccountID;
}
NotifyPropertyChanged("Account");
}
}
// {...}
}
[Table]
public class Account : INotifyPropertyChanged, INotifyPropertyChanging
{
// {...}
private EntitySet<Transaction> _transactions;
[Association(Storage = "_transactions", OtherKey = "_accountID")]
public EntitySet<Transaction> Transactions
{
get { return this._transactions; }
set { this._transactions.Assign(value); }
}
public Account()
{
_transaction = new EntitySet<Transaction>(
new Action<Transaction>(this.attach_transaction),
new Action<Transaction>(this.detach_transaction)
);
}
private void attach_transaction(Transaction transaction)
{
NotifyPropertyChanging("Transactions");
transaction.Account = this;
}
private void detach_transaction(Transaction transaction)
{
NotifyPropertyChanging("Transactions");
transaction.Account = null;
}
// {...}
}
Then I have some repositories that implement a GetAll() method that returns an ObservableCollection. The repositories have a reference to the Context class that is created inside the ViewModel class and, like this:
public class AccountRepository
{
private MyContext _context;
public AccountRepository(ref MyContext context)
{
_context = context;
}
// {...}
public ObservableCollection<Account> GetAll()
{
return new ObservableCollection(_context.Accounts.Where([some paramethers]).AsEnumerable());
}
// {...}
}
My ViewModel initialize the repositories in the constructor and then expose methods with some few logic code to insert, delete, etc., each of this types.
public class MyViewModel : INotifyPropertyChanged, INotifyPropertyChanging
{
private MyContext _context;
private AccountRepository accountRepository;
private TransactionRepository transactionRepository;
public ObservableCollection<Account> AllAccounts;
public ObservableCollection<Transaction> AllTransactions;
public MyViewModel(string connectionString)
{
_context = new MyContext("Data Source=’isostore:/mydatabase.sdf’"); if (!db.DatabaseExists()) db.CreateDatabase();
accountRepository = new AccountRepository(ref _context);
transactionRepository = new TransactionRepository(ref _context);
// [Some other code]
LoadCollections();
}
// {...}
public void LoadCollections()
{
AllAccounts = accountRepository.GetAll();
NotifyPropertyChanged("AllAccounts");
AllTransactions = transactionRepository.GetAll();
NotifyPropertyChanged("AllTransactions");
}
public void InsertTransaction(Transaction transaction)
{
AllTransactions.Add(transaction);
transactionRepository.Add(transaction);
LoadCollections(); // Tried this to update the Accounts with newer values, but don't work...
}
// {...}
}
When the user create a Transaction, the page calls the InsertTransaction (Transaction transaction) method in the view model, that pass the transaction object to the repository. But the Transactions collection in the Account object doesn't get updated. Then I tried to call the LoadCollections() method to force a new query in the context, and try to somehow get a fresh account object, but it still without the recently created transaction. If I stop my app and start it again, the Accounts are up to date and have all transactions I've created in the last run within its transactions collection.
How can I update this Transactions collection at runtime?
Updating the question:
I had some feedback regarding to notifying the UI that the collection was changed.
I think it's a problem with the association between transactions and account. Once I create a transaction, it won't appear in it's account.Transactions collection until I dispose my context and create it again.
It may be some notify fault, but I DON'T think it is and I did some code to try to prove it, I'm not in my PC right now but I'll try to explain my test.
The code I did to prove it was something like this:
Account c1 = context.Accounts.Where(c => c.AccountID == 1).SingleOrDefault();
Transaction t1 = new Transaction() { Account = c1, {...} };
context.Transactions.InsertOnSubmit(t1);
context.SaveChanges();
c1 = context.Accounts.Where(c => c.AccountID == 1).SingleOrDefault();
// The transaction IS NOT in the c1.Transactions collection right NOW.
context.Dispose();
context = new MyContext({...});
c1 = context.Accounts.Where(c => c.AccountID == 1).SingleOrDefault();
// The transaction IS in the c1.Transactions after the dispose!
Account c2 = context.Where(c => c.AccountID == 2).SingleOrDefault();
t1 = context.Transactions.Where(t => t.TransactionID == x).SingleOrDefault();
t1.Account = c2;
context.SubmitChanges();
c1 = context.Accounts.Where(c => c.AccountID == 1).SingleOrDefault();
// The transaction still in the c1 collection!!!
c2 = context.Accounts.Where(c => c.AccountID == 2).SingleOrDefault();
// It should be in the c2 collection, but isn't yet...
context.Dispose();
context = new MyContext({...});
c1 = context.Accounts.Where(c => c.AccountID == 1).SingleOrDefault();
// The transaction is not in the c1.Transaction anymore!
c2 = context.Accounts.Where(c => c.AccountID == 2).SingleOrDefault();
// The transaction IS in the c2.Transactions now!
A: It would be great if a more complete code sample could be posted demonstrating the specific problem.
As far as getting Parent->Child one:many relationships working as you expect, this is a feature not implemented directly by L2S. Rather it is implemented in the DataContext. This is done in the Child.Parent property setter by having the child add itself to its parent EntitySet instance.
This mechanism works as long as you generate parent<->child relationships at run time by using the setter which maintains this binding.
By way of a code example, here is the property that is generated by the O/R designer in Visual Studio for assigning a parent entity type on the child for a one:many relationship:
[global::System.Data.Linq.Mapping.AssociationAttribute(Name="Account_Transaction", Storage="_Account", ThisKey="AccountId", OtherKey="AccountId", IsForeignKey=true)]
public Account Account
{
get
{
return this._Account.Entity;
}
set
{
Account previousValue = this._Account.Entity;
if (((previousValue != value)
|| (this._Account.HasLoadedOrAssignedValue == false)))
{
this.SendPropertyChanging();
if ((previousValue != null))
{
this._Account.Entity = null;
previousValue.Transactions.Remove(this);
}
this._Account.Entity = value;
if ((value != null))
{
value.Transactions.Add(this);
this._AccountId = value.AccountId;
}
else
{
this._AccountId = default(long);
}
this.SendPropertyChanged("Account");
}
}
}
Note that Transaction.Add and Transaction.Remove pieces... That is the management of the EntitySet<> on the parent item - it doesn't happen automatically within the L2S layer.
Yes, this is a lot of glue to write. Sorry. My recommendation would be that if you have a complex data model with lots of relationships, to model it using DBML and have VS spit out a data context for you. There are a couple of targetted changes that will need to be made to remove some of the constructors on that DataContext object, but 99% of what is spit out by the designer will just work.
-John Gallardo
Developer, Windows Phone.
A: 2011-10-07 - UPDATE:
This has really been bothering me since you pointed out how messy the solution was, even though it worked, so I dug further into a solution and have come up with a new one :) or rather, a modified version of your original one that I think does what you're looking for. I'm not sure what to put here in the answer, but I'll call out a couple of areas and then update the code sample on my blog with the latest version once I get my FTP issues worked out.
Account class - put your code back in for the onAttach and onDetatch methods (I made lambdas, but it's basically the same thing).
public Account()
{
_transactions = new EntitySet<Transaction>(
(addedTransaction) =>
{
NotifyPropertyChanging("Account");
addedTransaction.Account = this;
},
(removedTransaction) =>
{
NotifyPropertyChanging("Account");
removedTransaction.Account = null;
});
}
Account class - updated the Association attribute for the EntitySet:
[Association(
Storage = "_transactions",
ThisKey = "AccountId",
OtherKey = "_accountId")]
Transaction class - updated the Association attribute for the EntityRef to add the missing key and the IsForeignKey attribute:
[Association(
Storage = "_account",
ThisKey = "_accountId",
OtherKey = "AccountId",
IsForeignKey = true)]
Lastly, here are the update methods I'm testing with:
// test method
public void AddAccount()
{
Account c1 = new Account() { Tag = DateTime.Now };
accountRepository.Add(c1);
accountRepository.Save();
LoadCollections();
}
// test method
public void AddTransaction()
{
Account c1 = accountRepository.GetLastAccount();
c1.Transactions.Add(new Transaction() { Tag = DateTime.Now });
accountRepository.Save();
LoadCollections();
}
Note that I'm adding a Transaction to an Account - not setting the Account value of a Transaction when I save it. I think this, combined with adding the IsForeignKey setting is what was missing from your original solution attempt. Try this out and see if it works any better for you.
2011-10-05 - UPDATE:
OK- it looks like I missed something with my original answer. Based on the comment, I think that the issue has to do with a quirk related to Linq to SQL. When I made the following changes to my original project, it seemed to work.
public void AddTransaction()
{
Account c1 = accountRepository.GetLastAccount();
Transaction t1 = new Transaction() { Account = c1, Tag = DateTime.Now };
c1.Transactions.Add(t1);
transactionRepository.Add(t1);
accountRepository.Save();
transactionRepository.Save();
LoadCollections();
}
Basically, when adding a Transaction object, I had to add the new Transaction to the Transactions collection of the original Account object. I didn't think you had to do this, but it seemed to work. Let me know if this didn't work and I'll try something else.
Original answer:
I believe that this is a data binding quirk. I built out a sample that you can download from my blog, but the biggest change I made to the code you provided was to replace the ObservableCollection fields with properties:
private ObservableCollection<Account> _accounts = new ObservableCollection<Account>();
public ObservableCollection<Account> Accounts
{
get { return _accounts; }
set
{
if (_accounts == value)
return;
_accounts = value;
NotifyPropertyChanged("Accounts");
}
}
private ObservableCollection<Transaction> _transactions = new ObservableCollection<Transaction>();
public ObservableCollection<Transaction> Transactions
{
get { return _transactions; }
set
{
if (_transactions == value)
return;
_transactions = value;
NotifyPropertyChanged("Transactions");
}
}
I also removed the attach/detatch code as it's not really needed. Here's my Account constructor now:
public Account()
{
_transactions = new EntitySet<Transaction>();
}
I couldn't tell from your sample, but make sure that each table has a PK defined:
// Account table
[Column(
AutoSync = AutoSync.OnInsert,
DbType = "Int NOT NULL IDENTITY",
IsPrimaryKey = true,
IsDbGenerated = true)]
public int AccountID
{
get { return _AccountID; }
set
{
if (_AccountID == value)
return;
NotifyPropertyChanging("AccountID");
_AccountID = value;
NotifyPropertyChanged("AccountID");
}
}
// Transaction table
[Column(
AutoSync = AutoSync.OnInsert,
DbType = "Int NOT NULL IDENTITY",
IsPrimaryKey = true,
IsDbGenerated = true)]
public int TransactionID
{
get { return _TransactionID; }
set
{
if (_TransactionID == value)
return;
NotifyPropertyChanging("TransactionID");
_TransactionID = value;
NotifyPropertyChanged("TransactionID");
}
}
You can download my version of this app from http://chriskoenig.net/upload/WP7EntitySet.zip - just make sure you add an account before you add transactions :)
A: In LoadCollection() you are updating the properties AllAccounts and AllTransactions, but you are not notifying the UI that they have been changed. You can notify the UI by raising the PropertyChanged event after setting the properties - in the property setter is a good place to do this.
A: I had similar problem, and cause of that was recreating collections, like you do in LoadCollections(). However you call NotifyPropertyChanged(..collectionname..) which must ensure UI refreshing, but maybe just try to make like this:
private readonly ObservableCollection<Transaction> _allTransactions = new ObservableCollection<Transaction>();
public ObservableCollection<Transaction> AllTransactions
{ get { return _allTransactions; } }
// same for AllAccounts
public void LoadCollections()
{
// if needed AllTransactions.Clear();
accountRepository.GetAll().ToList().ForEach(AllTransactions.Add);
// same for other collections
}
This approach guarantee, that you UI always bound to same collection in memory and you not need use RaisePropertyChanged("AllTransaction") in any place in you code, since this property cannot be changed anymore.
I always use this approach for defining collection in View Models.
A: I noticed something else in the code that I want to raise.
public ObservableCollection<Account> AllAccounts;
public ObservableCollection<Transaction> AllTransactions;
Are both public variables. I wrote a small application to just test your question and I am pretty sure that those values should be properties instead. If you bind to them at least. I say this because of the following.
I wrote a small app with a property and a public variable:
public ObservableCollection<tClass> MyProperty { get; set; }
public ObservableCollection<tClass> MyPublicVariable;
With a small test UI
<ListBox ItemsSource="{Binding MyProperty}" DisplayMemberPath="Name" Grid.Column="0"/>
<Button Content="Add" Grid.Column="1" Click="Button_Click" Height="25"/>
<ListBox ItemsSource="{Binding MyPublicVariable}" Grid.Column="2" DisplayMemberPath="Name"/>
And a method that will add stuff to each of the variables:
public void AddTestInstance()
{
tClass test = new tClass() { Name = "Test3" };
MyProperty.Add(test);
MyPublicVariable.Add(test);
NotifyPropertyChanged("MyPublicVariable");
}
I found that the MyProperty updated the UI just fine but that even when I call NotifyPropertyChanged on the MyPublicVariable, the UI was not updated.
Hence, try to make AllAccounts and AllTransactions properties instead.
A: I've had similar issues tha happened because the DBML is not in sync with your database. Have you tried to delete your DBML and recreate it again?
A: Actually, the behavior you are seeing makes sense when you look at it technically.
LinqToSql, like most other ORMs, employs an IdentityMap to track loaded entities and changes to them. This is one of the reasons the default L2S models implement INotifyPropertyChanged, so the L2S engine can subscribe to these events and act accordingly.
I hope this clarifies what happens when you change a property of an entity. But what happens when you want to add an entity to the database? There are two options L2S could know you want to add it: You tell it explicitly (via DataContext.Table.InsertOnSubmit) or you attach it to an existing Entity that L2S tracks withs its IdentityMap.
I recommend you read the Object States and Change Tracking article on MSDN, as this will clarify your understanding.
public void LoadCollections()
{
AllAccounts = accountRepository.GetAll();
NotifyPropertyChanged("AllAccounts");
AllTransactions = transactionRepository.GetAll();
NotifyPropertyChanged("AllTransactions");
}
public void InsertTransaction(Transaction transaction)
{
AllTransactions.Add(transaction);
transactionRepository.Add(transaction);
LoadCollections(); // Tried this to update the Accounts with newer values, but don't work...
}
Albeit inefficient and probably not the best design, this can be made to work (it depends on the implementation of transactionRepository.Add). When you add a new Transaction to AllTransactions, L2S can't possibly figure out it needs to insert that object because it isn't in the tracked object graph. Correctly, you then call transactionRepository.Add, which probably calls InsertOnSubmit(transaction) and SubmitChanges() (the last part is important). If you now call LoadCollections (and your databinding is setup correctly!) you should see AllTransactions containing the new transaction.
As a final note, you should check out the concept of Aggregate Roots. In general, you have one Repository Implementation per Aggregate (Transactions and Accounts are fine).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555276",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Lines not visible on a KML file I have a set of points that are joined by using kml.linestring . But, I want to colour code those lines based on the speeds at those lines ( which I have available)> The problem is that my kml file, when rendered on google maps, doesn't render the lines at all :(
If I do the same thing for a different set of co-ordinates, which are polygons, it works totally fine. Infact, if I do not colour code the lines and just use the default colour, it renders the lines perfectly. But, I need the colour coding. I am attaching the code below:
public static void drawKML(File f) throws IOException
{
final Kml kml= KmlFactory.createKml();
final Document document = kml.createAndSetDocument().withName("Document.kml").withOpen(true);
final LineStyle style1=document.createAndAddStyle().withId("linestyleExample1").createAndSetLineStyle().withColor("ff000000");
final LineStyle style2=document.createAndAddStyle().withId("linestyleExample2").createAndSetLineStyle().withColor("ff008cff");
final LineStyle style3=document.createAndAddStyle().withId("linestyleExample3").createAndSetLineStyle().withColor("ff008000");
FileInputStream fstream=new FileInputStream(f);
DataInputStream in=new DataInputStream(fstream);
BufferedReader br=new BufferedReader(new InputStreamReader(in));
String line=br.readLine();
Placemark placemark1;
while(line!=null)
{
String[] alpha=line.split(" ");
double speed=Double.parseDouble(alpha[4])*3.6;
String description="";
description=description+"Speed="+speed+"\n";
if(speed>=0 && speed<=15) {
document.createAndAddPlacemark().withStyleUrl("#linestyleExample1").withDescription(description).createAndSetLineString().withExtrude(true).withTessellate(true).addToCoordinates(Double.parseDouble(alpha[1]), Double.parseDouble(alpha[0])).addToCoordinates(Double.parseDouble(alpha[3]),Double.parseDouble(alpha[2]));
logger.error("In black range");
}
else if(speed>15 && speed<=35) {
document.createAndAddPlacemark().withStyleUrl("#linestyleExample2").withDescription(description).createAndSetLineString().withExtrude(true).withTessellate(true).addToCoordinates(Double.parseDouble(alpha[1]), Double.parseDouble(alpha[0])).addToCoordinates(Double.parseDouble(alpha[3]),Double.parseDouble(alpha[2]));
logger.error("In orange range");
}
else {
document.createAndAddPlacemark().withStyleUrl("#linestyleExample3").withDescription(description).createAndSetLineString().withExtrude(true).withTessellate(true).addToCoordinates(Double.parseDouble(alpha[1]), Double.parseDouble(alpha[0])).addToCoordinates(Double.parseDouble(alpha[3]),Double.parseDouble(alpha[2]));
logger.error("In green");
}
//placemark1.createAndSetLineString().withExtrude(true).withTessellate(true).addToCoordinates(Double.parseDouble(alpha[1]), Double.parseDouble(alpha[0])).addToCoordinates(Double.parseDouble(alpha[3]),Double.parseDouble(alpha[2]));
line=br.readLine();
}
kml.marshal(new File(path/to/file));
}
This is how it looks:
This is how it should look:
Fragment from the faulty kml file ( which doesn't represent any points ) :
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:xal="urn:oasis:names:tc:ciq:xsdschema:xAL:2.0">
<Document>
<name>Document.kml</name>
<open>1</open>
<Style id="linestyleExample1">
<LineStyle>
<color>ff000234</color>
<width>0.0</width>
</LineStyle>
</Style>
<Style id="linestyleExample2">
<LineStyle>
<color>ff008cff</color>
<width>0.0</width>
</LineStyle>
</Style>
<Style id="linestyleExample3">
<LineStyle>
<color>ff006400</color>
<width>0.0</width>
</LineStyle>
</Style>
<Placemark>
<description>Speed=0.0
</description>
<styleUrl>#linestyleExample1</styleUrl>
<LineString>
<extrude>1</extrude>
<tessellate>1</tessellate>
<coordinates>78.48419,17.38463 78.48302,17.38328</coordinates>
</LineString>
</Placemark>
<Placemark>
<description>Speed=0.0
</description>
<styleUrl>#linestyleExample1</styleUrl>
<LineString>
<extrude>1</extrude>
<tessellate>1</tessellate>
<coordinates>78.48302,17.38328 78.48244,17.38264</coordinates>
</LineString>
</Placemark>
<Placemark>
<description>Speed=0.0
</description>
<styleUrl>#linestyleExample1</styleUrl>
<LineString>
<extrude>1</extrude>
<tessellate>1</tessellate>
<coordinates>78.48244,17.38264 78.48173,17.38204</coordinates>
</LineString>
</Placemark>
<Placemark>
<description>Speed=51.4415867904
</description>
<styleUrl>#linestyleExample3</styleUrl>
<LineString>
<coordinates>78.48173,17.38204 78.48068,17.38264</coordinates>
</LineString>
</Placemark>
<Placemark>
<description>Speed=51.4415867904
</description>
<styleUrl>#linestyleExample3</styleUrl>
<LineString>
<coordinates>78.48068,17.38264 78.47993,17.3829</coordinates>
</LineString>
</Placemark>
<Placemark>
<description>Speed=90.72
</description>
<styleUrl>#linestyleExample3</styleUrl>
<LineString>
<coordinates>78.47993,17.3829 78.47677,17.38331</coordinates>
</LineString>
</Placemark>
<Placemark>
<description>Speed=76.46400000000001
</description>
<styleUrl>#linestyleExample3</styleUrl>
<LineString>
<coordinates>78.47677,17.38331 78.47521,17.38359</coordinates>
</LineString>
</Placemark>
<Placemark>
<description>Speed=61.56000000000001
</description>
<styleUrl>#linestyleExample3</styleUrl>
<LineString>
<coordinates>78.47521,17.38359 78.47506,17.38353</coordinates>
</LineString>
</Placemark>
<Placemark>
<description>Speed=0.0
</description>
<styleUrl>#linestyleExample1</styleUrl>
<LineString>
<extrude>1</extrude>
<tessellate>1</tessellate>
Fragment from one which does represent it correctly :
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:gx="http://www.google.com/kml/ext/2.2" xmlns:kml="http://www.opengis.net/kml/2.2" xmlns:xal="urn:oasis:names:tc:ciq:xsdschema:xAL:2.0">
<Document id="feat_1">
<Style id="stylesel_0">
<LineStyle>
<color>ff000000</color>
<colorMode>normal</colorMode>
</LineStyle>
</Style>
<Style id="stylesel_1">
<LineStyle>
<color>ff008cff</color>
<colorMode>normal</colorMode>
</LineStyle>
</Style>
<Style id="stylesel_2">
<LineStyle>
<color>ff008cff</color>
<colorMode>normal</colorMode>
</LineStyle>
</Style>
<Style id="stylesel_3">
<LineStyle>
<color>ff008cff</color>
<colorMode>normal</colorMode>
</LineStyle>
</Style>
<Style id="stylesel_4">
<LineStyle>
<color>ff008cff</color>
<colorMode>normal</colorMode>
</LineStyle>
</Style>
<Style id="stylesel_5">
<LineStyle>
<color>ff008000</color>
<colorMode>normal</colorMode>
</LineStyle>
</Style>
<Style id="stylesel_6">
<LineStyle>
<color>ff008cff</color>
<colorMode>normal</colorMode>
</LineStyle>
</Style>
<Style id="stylesel_7">
<LineStyle>
<color>ff008cff</color>
<colorMode>normal</colorMode>
</LineStyle>
</Style>
<Style id="stylesel_8">
<LineStyle>
<color>ff008cff</color>
<colorMode>normal</colorMode>
</LineStyle>
</Style>
<Style id="stylesel_9">
<LineStyle>
<color>ff008cff</color>
<colorMode>normal</colorMode>
</LineStyle>
</Style>
<Style id="stylesel_10">
<LineStyle>
<color>ff008cff</color>
<colorMode>normal</colorMode>
</LineStyle>
</Style>
<Style id="stylesel_11">
<LineStyle>
<color>ff008cff</color>
<colorMode>normal</colorMode>
</LineStyle>
</Style>
<Style id="stylesel_12">
<LineStyle>
<color>ff008cff</color>
<colorMode>normal</colorMode>
</LineStyle>
</Style>
<Style id="stylesel_13">
<LineStyle>
<color>ff008000</color>
<colorMode>normal</colorMode>
</LineStyle>
</Style>
<Style id="stylesel_14">
<LineStyle>
<color>ff008000</color>
<colorMode>normal</colorMode>
</LineStyle>
</Style>
<Style id="stylesel_15">
<LineStyle>
<color>ff008cff</color>
<colorMode>normal</colorMode>
</LineStyle>
</Style>
<Style id="stylesel_16">
They are different as the second one has been generated using Python ( which generates a lot of linestyles first and then assigns them one by one to the points . )
A: The reason is that in the 'faulty' kml your linestyles have a explicit width definition of 0.0 Change it to a positive number (5.0 or so) and you'll see your lines or remove it completly to use the default width
Codewise I don't know the lib you are using but I would guess something like this should do the trick
final LineStyle style2=
document.createAndAddStyle()
.withId("linestyleExample2")
.createAndSetLineStyle()
.withColor("ff008cff")
.withWidth(5.0d);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555278",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: how to use google place api for my php application I'm trying to create a web page. When user starts typing in a textbox, an autocomplete city with state name list appears in suggested dropdown box like in google map.
I've got the api for google place autocomplete. But I am unable to implement it.
Can any one suggest me how to implement google place api?
API URL is: Google Place API Page
A: What i implemented is the below code and it gave me the solution that i wanted -
<html>
<head>
<style type="text/css">
body {
font-family: sans-serif;
font-size: 14px;
}
</style>
<title>Google Maps JavaScript API v3 Example: Places Autocomplete</title>
<script src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places" type="text/javascript"></script>
<script type="text/javascript">
function initialize() {
var input = document.getElementById('searchTextField');
var autocomplete = new google.maps.places.Autocomplete(input);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div>
<input id="searchTextField" type="text" size="50" placeholder="Enter a location" autocomplete="on">
</div>
</body>
</html>
A: You can use this jquery plugin
http://code.google.com/p/geo-autocomplete/
demo:
http://code.google.com/apis/maps/documentation/javascript/examples/places-autocomplete.html
A: Just click on the link, and do a CTRL + U, it gives you the source, then SELECT ALL, then PASTE IT, and it works.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555279",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Smartcard authentication for .NET I have a smartcard reader and a smartcard. I have installed drivers and it works as expected. I can use this card as windows logon or for remote desktop logon.
I'm building my app which should work only when the card is inserted and I need to call web services from my app which requires a certificate from the card.
Any suggestions on how do I do that? The web is full of examples for ASP.NET and I'm building Windows forms.
As a further note: Everything must work the same even if user logs on windows without the card. The card must me present for the app to work.
Thanks.
A: If the Smartcard driver supports the standard Windows CryptoAPI, it will export the certificates from the card into the personal store of the user. You can access those certificates using the X509Store class. When you access the certificate, the user will be prompted to insert the card and enter his PIN.
Note: Some smartcard drivers do not automatically export the certificates. Instead, they have a tool which the user can use to do this.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555281",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Binding FontSize of TextBlock in Validation.ErrorTemplate I declared a simple Validation.ErrorTemplate for TextBox as the following.
<Style TargetType="{x:Type TextBox}" BasedOn="{StaticResource {x:Type TextBox}}">
<Setter Property="Validation.ErrorTemplate">
<Setter.Value>
<ControlTemplate>
<DockPanel LastChildFill="True">
<TextBlock Text="!" DockPanel.Dock="Right"
FontSize="{TemplateBinding TextBox.FontSize}"
Foreground="Red"/>
<AdornedElementPlaceholder Name="adornerPlaceholder" />
</DockPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
I expect that the font size of the exclamation mark will be the same font(edited) size as TextBox, but it doesn't result in the expectation and always gets the default font size. Furthermore, I tried Binding using RelativeSource={RelativeSource Mode=TemplatedParent}, Path=FontSize, but it also cannot solve the problem. Why is this situation occurred? How can I make the the exclamation mark gets the same size as TextBox?
A: Why don't you bind to the AdornedElementPlaceholder?
<Style TargetType="{x:Type TextBox}" BasedOn="{StaticResource {x:Type TextBox}}">
<Setter Property="Validation.ErrorTemplate">
<Setter.Value>
<ControlTemplate>
<DockPanel LastChildFill="True">
<TextBlock Text="!" DockPanel.Dock="Right"
FontSize="{Binding ElementName=adornerPlaceholder, Path=AdornedElement.FontSize}"
Foreground="Red"/>
<AdornedElementPlaceholder Name="adornerPlaceholder" />
</DockPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
This is untested, but it should work :)
A: Another option is to wrap the TextBlock in a Viewbox, which automatically scales its height along with the adorned element:
<Style TargetType="{x:Type TextBox}" BasedOn="{StaticResource {x:Type TextBox}}">
<Setter Property="Validation.ErrorTemplate">
<Setter.Value>
<ControlTemplate>
<DockPanel LastChildFill="True">
<Viewbox DockPanel.Dock="Right"
Height="{Binding ElementName=adornerPlaceholder, Path=ActualHeight}"
Stretch="Uniform"
Margin="5 0">
<TextBlock Text="!" Foreground="Red" />
</Viewbox>
<AdornedElementPlaceholder Name="adornerPlaceholder" />
</DockPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
This would then work for any element being adorned, regardless of font size, any for any exclamation graphic (i.e. text, path, element, etc)
Positioning/layout can be tweaked with margin.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555282",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: WatiN firing KeyDown event for the wrong keyCode If you look at the code in WatiN.Core.Element.cs you see the following:
private static NameValueCollection GetKeyCodeEventProperty(char character)
{
return new NameValueCollection
{
{"keyCode", ((int) character).ToString()},
{"charCode", ((int) character).ToString()}
};
}
This is the code used to simulate the firing of client side events, for example when automating typing text into a text field. It seems to me that this code generates the wrong keyCodes.
Let's say that I type the letter "v" into a text box. (int)'v' returns 118. 118 is the keyCode for F7 not the keyCode for "v" which is 86.
Sure enough my application is detecting that F7 has been hit.
This just seems straightforwardly wrong. Am I missing something here - I can't believe that no one else would be seeing this issue if I weren't.
Thanks in advance,
Julian.
A: I think a couple things are happening here. Calling ((int)'[character]') is returning that character's decimal ASCII value. Lowercase v is 118. Uppercase V is 86.
Console.WriteLine("lowercase: " + ((int)'v').ToString());
Console.WriteLine("uppercase: " + ((int)'V').ToString());
Console.WriteLine("V in Keys Enumeration: " + ((int)System.Windows.Forms.Keys.V).ToString());
Looking through the call stack for WatiN.Core.Element.KeyPress it eventually gets down to call the following line of code in method SetValueWhenOnKeyPress in IEFireEventHandler.cs.
var newValue = _ieElement.GetAttributeValue("value") + ((char) int.Parse(addChar));
addChar is the keyCode item returned in GetKeyCodeEventProperty. newValue is what is being used to set the Element's value, thus when you do something like myTextField.TypeText('v') a lowercase v is typed in your textbox.
Note: WatiN 2.1 code was reviewed for this.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555289",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: WCF Service is slow after few iterations I am new to WCF Services. I have created a wsHTTPBinding WCF service.
While I am using the WCF Service in my Client application(application contains text box and submit button) it is very slow after few iterations (after six or seventh iteration).
I checked the web.config file. I increased the buffersize in server and client. But I'm still facing the same issue.
A: I would recommend enabling WCF trace logging which you can use to get the timings for each request, and possibly some visibility into what it is doing. If that lends no useful details, it would probably be easiest to just use a profiler to get the performance data for several requests.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555290",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I access PropertyChanged event from a static property? I have static Property a like this :
public static int AverageDiarrheaB
{
get { return averageDiarrheaB; }
set
{
averageDiarrheaB = value;
OnPropertyChanged("AverageDiarrheaB");
}
}
public static event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string name)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}
While running I am getting this error : An object reference is required for the non-static field, method, or property 'CareMapGlobals.OnPropertyChanged(string)'.
How to rectify this... please help
Thanks
Sandeep
A: Simple answer:
Remove 'static' from public static int AverageDiarrheaB and from public static event PropertyChangedEventHandler PropertyChanged;
Longer answer:
The key is in the name PropertyChanged... it applies to properties of objects.
You can only sensibly have property change events on properties attached to an object (e.g. class properties). Otherwise the "name" parameter would be meaningless as there is no object with that property name.
If you just want to share a single setting across all instances, you can have a static field that is accessed by a non-static setter and getter.
e.g.
private static int averageDiarrheaB
public int AverageDiarrheaB
{
get { return averageDiarrheaB; }
set
{
averageDiarrheaB = value;
OnPropertyChanged("AverageDiarrheaB");
}
}
If you do need static access to an entire object search for singleton patterns and access a single instance of an object that way instead.
But ignoring all that, this will work (tested):
... your code will "work" if you replace this with null and make the other changes shown to make OnPropertyChanged static as well:
private static int averageDiarrheaB;
public static int AverageDiarrheaB
{
get { return averageDiarrheaB; }
set
{
averageDiarrheaB = value;
OnPropertyChanged("AverageDiarrheaB");
}
}
public static event PropertyChangedEventHandler PropertyChanged;
public static void OnPropertyChanged(string name)
{
if (PropertyChanged != null)
{
PropertyChanged(null, new PropertyChangedEventArgs(name));
}
}
The consequences of consuming the static PropertyChanged event are that you will not have an object reference. Give it a try and see if it works "enough" for your purposes.
Given the extreme misuse of the PropertyChanged event in your code I would suggest using a new event name instead :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555291",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Why background image for body is not going to bottom in this jsfiddle example See this jsfiddle example http://jsfiddle.net/z7JBr/4/
this is css
body {background:url(http://digitaldaily.allthingsd.com/files/2007/06/iphone_34.jpg) no-repeat center bottom red}
A: You will need to give your body some height, since it doesn't have enough content to make it all the way to the bottom.
body {
background:url(http://digitaldaily.allthingsd.com/files/2007/06/iphone_34.jpg) no-repeat center bottom red;
height:500px;
}
A: @jitendra; put body, html{height:100%} in your body because your body have no height right now
A: I had a similar problem with the background image stopping before the bottom of the page. In my CSS I had put body{background-image:url(http://domain.com/image.jpg);} and it turned out that in another part of the CSS i had body{background:#fff;}. When I took this second part out it worked fine.
I know this is an old post but it comes top of Google search so I thought I'd try and help someone having the same problem!
A: Just wanted to mention that as well as what has been stated about the height you also need to make sure that your child divs, that will effectively be increasing the body's height, are not set to position absolute. I ran into this where some styles being set for mobil were not set inside a media query and it messed the background image up.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555294",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: flex not importing SQL based connections? I'm trying to include a database un flex4 (flashbuilder) project, i don't see data and SQL packages in the import? What might be the reason? Should i add external library?
import flash.data.SQLConnection;
import flash.data.SQLStatement;
import flash.events.SQLErrorEvent;
import flash.events.SQLEvent;
Description Resource Path Location Type
1172: Definition flash.data:SQLConnection could not be found. EyeVision1.mxml /EyeVision1/src line 28 Flex Problem
A: You can use those classes only in an AIR project, not in a web-based Flex project. AIR comes packaged with a SQLite database to which you can connect using these classes.
A Flex web-based application runs on the client not on a server, so if you want to access a database on the server you'll have to use a server side language to do it and pass the results to the Flex app on the client side. If you want to access a local database, well... you can't (except perhaps using HTML5 local storage and ExternalInterface).
A: You can connect the database directly from flex but this is not recommended because of the security reason.
You may try asSQL to do so.
Have a look on the following question:
Connecting any database directly from flex
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555295",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: NSNumber comparison with < (less) operator instead of compare some days ago I've read a post written by another user regarding comparisons between NSNumber objects using the < (less) operator.. He was getting wrong results and people told him that it was comparing the addresses of the NSNumber objects instead of their values... I've tried to reproduce the problem but there is something I'm missing:
int main (int argc, char*argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSMutableArray *arrayDistance = [NSMutableArray array];
[arrayDistance addObject:
[NSNumber numberWithInteger: 10]];
[arrayDistance addObject:
[NSNumber numberWithInteger: 20]];
[arrayDistance addObject:
[NSNumber numberWithInteger: 8]];
[arrayDistance addObject:
[NSNumber numberWithInteger: 9]];
int iMinor = 0;
int i;
for (i = 0; i < [arrayDistance count]; i++) {
if([arrayDistance objectAtIndex: i] < [arrayDistance objectAtIndex: iMinor])
{
iMinor = i;
}
}
NSLog(@"iMinor is %d", iMinor);
[pool release];
return 0;
}
The code above correctly returns 2, why? Shouldn't it be comparing the addresses instead of the values of the NSNumber objects within the arrayDistance array? Shouldn't it be necessary to get the integer value out of the NSNumber objects or use the compare method of the NSNumber objects?
Does the NSNumber class overload the < (less) operator in order to compare the actual values stored within the objects? If so, where is it written in the reference documentation?
I hope the question is clear. Thank you in advance for any help.
A:
The code above correctly returns 2, why? Shouldn't it be comparing the addresses instead of the values of the NSNumber objects within the arrayDistance array? Shouldn't it be necessary to get the integer value out of the NSNumber objects or use the compare method of the NSNumber objects?
It is comparing the addresses of the NSNumber objects, and yes, you should either get the underlying integer value or use -compare:.
What’s happening under the hood is that Lion uses tagged pointers for (a subset of) NSNumber instances that represent integers. Because of the tagged pointer representation, the addresses in your particular example end up having the same order as the underlying integers they represent.
If you print the actual addresses with
printf("%p\n", [arrayDistance objectAtIndex:i]);
you’ll get:
0xac3
0x14c3
0x8c3
0x9c3
Ignoring the least significant byte:
0xa = 10
0x14 = 20
0x8 = 8
0x9 = 9
As you can see, those addresses do map the underlying integer values.
Note, however, that this is an implementation detail that varies according to the target platform and can change in the future. You shouldn’t depend on it.
Does the NSNumber class overload the < (less) operator in order to compare the actual values stored within the objects? If so, where is it written in the reference documentation?
No, there is no operator overloading in Objective-C.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555296",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.