text stringlengths 8 267k | meta dict |
|---|---|
Q: Why is CGContextRef not an object? Wouldnt it make much more sense if CGContextRef was an actual object?
Now u need to give the context with it, everytime u want to add a path.
Wouldnt it be much nicer to say:
[context addPath:myPath];
instead of
CGContextAddPath(context,myPath);
Is it a struct or whats the deal here?
Anyone care to elaborate?
A: It might be easier from a programmer's point of view, but part of the reason that it is in C is for performance. When doing graphics intensive code, and rendering time matters (which is nearly always), the last thing you want to be doing is allocating lots of temporary objects. It's a tradeoff - performance for readability/maintainability.
As Martin Ullrich mentioned, there are some Objective-C wrappers around some of the Core Graphics stuff, but it's really a lot better to know what going on "under the hood" before using the Objective-C stuff (which will be easier, but slightly slower).
BTW this slowness I'm talking about is only really an issue when you are doing a lot of drawing, and you want (or need) to keep the FPS/responsiveness very good. If you're drawing hundreds of shapes and lines, for example, you'd want to use CG directly. If you're just drawing a handful of shapes/images/text, using the Obj-C wrappers will give only a negligible performance hit.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525931",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Force two nodes to occupy the same rank in Graphviz? Using ruby-graphviz, I've created a graph that looks like this (border added to emphasize rendering boundaries):
What I really want is for A and K to line up together at the top (or left, if rankdir="LR"). So I added an invisible node (call it X), and added invisible edges from X to A and K. And here's what I got:
X, XA, and XK have no labels, and style set to 'invis'.
X has height, width, and margin set to 0, and fixedsize set to true.
XA and XK have minlen, len, and penwidth set to 0.
But there's still that empty space at the top. Is there any way to get rid of it, short of cropping after the fact?
A: You do not need invisible nodes to achieve this.
This is the dot syntax to force the same rank for two nodes:
{rank=same; A; K;}
This is called a subgraph.
I don't know ruby-graphviz, I'm not sure how to create a subgraph - but there is an example on github:
c2 = g.subgraph { |c|
c[:rank => "same"]
c.mysite[:label => "\nexample.com\n ", :shape => "component", :fontname => "Arial"]
c.dotgraph[:label => "\ndotgraph.net\n ", :shape => "component", :fontname => "Arial"]
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525934",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Address of a static variable I am trying to do a simple class to unique ID conversion. I am thinking about adding a static method:
class A {
static int const *GetId() {
static int const id;
return &id;
}
};
Each class would then be identified by unique int const *. Is this guaranteed to work? Will the returned pointer really be unique? Is there any better simpler solution?
I have also thought about pointer to std::type_info:
class A {
static std::type_info const *GetId() {
return &typeid(A);
}
};
Is that better?
Edit:
I don't need to use the id for serialization. I only want to identify a small set of base classes and I want all subclasses of some class to have the same id
A: The address of static variable is guaranteed to be unique and the same in all translation units.
It is not a good idea because it requires you to add code to every class to be identified.
The pointers to type info objects are not guaranteed to be unique, but the type info objects themselves are guaranteed to compare as equal for a given class, and as unequal for distinct classes. This means you can use small wrapper objects that carry type info pointers, and the delegate the comparisions to the type info objects. C++11 has such a wrapper in the standard library, and if you don't have access to that, there is one in Andrei Alexandrescu's "Modern C++ Design", and therefore probably also in the Loki library, there is probably one in Boost, and there is one on my Wordpress blog – it's not like you to have invent one from scratch.
If, however, the id's are to be used for serialization, then you need id's that are valid across builds. And in that case you you need strings or UUIDs. I would go with UUIDs.
To associate a class with an UUID you can in general use a type traits class. Or if you're only doing Windows programming then you can use Visual C++'s language extensions for this. I think but I am not 100% sure that those language extensions are also implemented by g++ (in Windows).
Cheers & hth.
A: As I have noticed at least MSVC 2008 or 2010 optimizes the static variable, so that the following GetId function returns same address even for different classes.
static int const *GetId() {
static const int i = 0;
return &i;
}
Therefore address of uninitialized constant static variable may not be used for identification. The simplest fix is to just remove const:
static int *GetId() {
static int i;
return &i;
}
Another solution to generate IDs, that seems to work, is to use a global function as a counter:
int Counter() {
static int i = 0;
return i++;
}
And then define the following method in the classes to be identified:
static int GetId() {
static const int i = Counter();
return i;
}
As the method to be defined is always the same, it may be put to a base class:
template<typename Derived>
struct Identified {
static int GetId() {
static const int i = Counter();
return i;
}
};
And then use a curiously recurring pattern:
class A: public Identified<A> {
// ...
};
A: The address of the static int is guaranteed to be unique for each
function (and the same for every call to the same function). As such,
it can work very well as an id within a single execution of the code.
The address could conceivably change from one run to the next, and will
often change from one compilation to the next (if you've changed
anything in the code), so it is not a good solution for an external id.
(You don't say whether the id must be valid outside a single execution
or not.)
The address of the results of a typeid is not guaranteed to be the
same each time you call the function (although it probably will be).
You could use it to initialize a pointer, however:
static std::type_info const& GetId()
{
static std::type_info const* id = &typeid(A);
return id;
}
Compared to using int*, this has the advantage of providing additional
information (e.g. for debugging). Like int*, the identifier may be
different from one run to the next; A::GetId()->name() will point to
the same '\0' terminated string (although again the address might be
different) provided you compile with the same compiler. (As far as I
can tell, the standard doesn't guarantee this, but in practice, I think
you're safe.) Change compilers, however, and all bets are off.
The solution I've used in the past is something like:
static char const* GetId()
{
return "A"; // Or whatever the name of the class is.
}
This provides a unique identifier, easily compared, within a single
execution of the code, and a string value which can be used as an
external identifier, and which is guaranteed across all compilers. We
implemented this as a macro, which defined both the static function, and
a virtual function which returned it, e.g.:
#define DECLARE_IDENTIFIER(name) \
static char const* classId() { return STRINGIZE(name); } \
virtual char const* id() { return classId(); }
This results in a very fast (but limited) RTTI, and supports external
identifiers for serialization and persistency.
A: Yes, this will work. Each static local will be given distinct memory location at the time when the module is loaded and it will persist until the module is unloaded. Remember, static locals are stored in static storage that is distributed during compilation and they persist till the module gets unloaded, so they will have distinct memory locations.
A: The int* method would be unique, since a different static memory cell must be allocated for each static variable, and I'd guess it is simpler to understandthan the type_info idea.
A: Clearly pointers to different variables must have different values. Just watch out if you choose to derive a subclass of A. You need to decide what your policy is for id. If you did nothing then the subclass would have the same id.
A: Static variables are initialized before Heap & Stack memory so yeah it will be unique.
Quirky though.
A: In general, you really really want to avoid hacky things like this. If I really had to do this, I'd look at using some UUID system (there's a library in Boost for that, but I'm not very familiar with it), or some singleton that maintained a list of these objects for whatever purpose you need.
A: Because you will have to add this method to all classes that require a UID you may as well do this.
unsigned int getUID()
{
return 12;
}
The advantage of this is that the compiler will be able to use a jump table if you are using this for RTTI for switching on type, which will not be possible with two pointers because the jump table would be very sparse.
The (minor) disadvantage is you need to keep track of which identifiers have been taken.
A major disadvantage of the first method you presented is that the same numbers cannot be used to identify objects because the virtual getUID() method won't be able to take the address of the variable in another function's scope.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525942",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: Remove Non-English Characters from NSString (Obj-C) I have NSString like
Aavkar Complex, Opposite Gurukul, Drive-in Road, Ahmedabad,
àªà«àªàª°àª¾àª¤, India
so I want to consider only english characters and without
english characters are from above string so please give me any idea.
Thanks in advance.
A: Here is a little dirty example:
NSString *test = @"Olé, señor!";
NSMutableString *asciiCharacters = [NSMutableString string];
for (NSInteger i = 32; i < 127; i++) {
[asciiCharacters appendFormat:@"%c", i];
}
NSCharacterSet *nonAsciiCharacterSet = [[NSCharacterSet characterSetWithCharactersInString:asciiCharacters] invertedSet];
test = [[test componentsSeparatedByCharactersInSet:nonAsciiCharacterSet] componentsJoinedByString:@""];
NSLog(@"%@", test); // Prints @"Ol, seor!"
A: try this:-
NSString *emailRegEx = @"[A-Za-z]";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegEx];
//Valid email address
NSString *textString=@"gagdaksdhaksdhaskdhasldhasldalasàªà«àªàª°àª¾àª¤dhwheqweuqweuqwe";
NSString *textFinalString=@"";
for (int i=0; i<[textString length]; i++) {
NSString *text2string=[textString substringWithRange:NSMakeRange(i,1)];
NSLog(@"%@",text2string);
if ([emailTest evaluateWithObject:text2string] == YES)
{
NSLog(@"yesenglishCharacter");
textFinalString=[textFinalString stringByAppendingString:text2string];
}
else {
NSLog(@"noenglishCharacter");
}
}
NSLog(@"textFinalString%@",textFinalString);
A: Here is some sample code using NSRange's to do this for a textfield, although the code should be easily adaptable to use for an array of NSString's. Hope that Helps!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525951",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Using Camel Servlet I have been trying to get a basic example of a servlet endpoint to work in camel. My example is based on this:http://camel.apache.org/servlet-tomcat-example.html
When I try to run this in Jetty though I get the following exception: 'java.lang.IllegalStateException: No resource at org.apache.camel.component.servlet.CamelHttpTransportServlet/httpRegistry'
Here is my Web.xml
<!-- Camel servlet -->
<servlet>
<servlet-name>CamelServlet</servlet-name>
<servlet-class>org.apache.camel.component.servlet.CamelHttpTransportServlet</servlet-class>
<init-param>
<param-name>matchOnUriPrefix</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- Camel servlet mapping -->
<servlet-mapping>
<servlet-name>CamelServlet</servlet-name>
<url-pattern>/camel/*</url-pattern>
</servlet-mapping>
<!-- the listener that kick-starts Spring -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- location of spring xml files -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
And here is my applicationContext.xml:
<bean id="route" class="com.routes.smppRoute" />
<!-- the camel context -->
<camelContext xmlns="http://camel.apache.org/schema/spring" id="camel">
<routeBuilder ref="route" />
</camelContext>
The route simple takes the input and outputs it to the console
public class smppRoute extends RouteBuilder {
@Override
public void configure() throws Exception {
from("servlet:///").to("stream:out");
}
}
I am pretty sure I have all the dependencies in, here is the pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.fundamo</groupId>
<artifactId>fundamo-platform-smpp-camel</artifactId>
<version>1.0-SNAPSHOT</version>
<name>Camel Router Application</name>
<description>Camel project that deploys the Camel routes as a WAR</description>
<url>http://www.myorganization.org</url>
<packaging>war</packaging>
<repositories>
<repository>
<id>org.apache.camel</id>
<url>https://repository.apache.org/content/groups/snapshots-group</url>
</repository>
</repositories>
<dependencies>
<!-- Camel Dependencies -->
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-core</artifactId>
<version>2.7-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-spring</artifactId>
<version>2.7-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-stream</artifactId>
<version>2.7-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-servlet</artifactId>
<version>2.7-SNAPSHOT</version>
</dependency>
<!-- Spring Web -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>3.0.5.RELEASE</version>
</dependency>
<!-- logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.5.11</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
</dependency>
</dependencies>
<build>
<defaultGoal>install</defaultGoal>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<!-- plugin so you can run mvn jetty:run -->
<plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>7.2.2.v20101205</version>
<configuration>
<webAppConfig>
<contextPath>/</contextPath>
</webAppConfig>
<systemProperties>
<!-- enable easy JMX connection to JConsole -->
<systemProperty>
<name>com.sun.management.jmxremote</name>
<value />
</systemProperty>
</systemProperties>
<scanIntervalSeconds>10</scanIntervalSeconds>
</configuration>
</plugin>
</plugins>
</build>
A: Can you try to change the version to 2.8.1 instead of using the 2.7-SNAPSHOT ?
I just did some test on the camel-example-servlet-tomcat in the Camel trunk, it doesn't throw such a error.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525952",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: JSP - Image Button becomes an image after clicking on it I'm creating a jsp page that requires an image button to send a value to my servlet and subsequently become a static image after being clicked on.
Is there an easy way to do this without using additional libraries? How do I receive and manipulate the response object in the jsp page after my servlet has confirmed it has received the value from the jsp page? Is there a way to differentiate the different buttons clicked as well?
Thank you!
With much thanks,
A young and newbie programmer.
A: You may use JSTL <c:choose/> to compare a attribute value which is returned from the servlet's response.
Jsp page - page1.jsp
<c:choose>
<c:when test="${status=='ok'}">
<form method="post" action="your_servlet">
..other stuff
<input type="image" src="images/image1.jpg"/>
</form>
</c:when>
<c:otherwise>
<img src="images/image1.jpg"/>
</c:otherwise>
</c:choose>
In servlet you have to set status attribute and use getRequestDispatcher() to forward the request.
request.setAttribute("status","ok");
request.getRequestDispatcher("/page1.jsp").forward(request,response);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525955",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to format gridview content when doing binding? I am currently doing the data binding:
<asp:TemplateField HeaderText="Priority" SortExpression="priority">
<ItemTemplate>
<asp:Label Visible="true" runat="server" ID="priorityLabel" Text='<%# bind("numberTemplatePriority") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
However, I would like to get this value first: <%# bind("numberTemplatePriority") %>, which will bring an integer, an according to that value, I want to show an equivalent string. For example: if it is number 4, I want to show "Very Important".
I wouldn't like to modify the sql query since it is used in other parts of the application.
The GridView datasource is a dataset and "numberTemplatePriority" is one of its columns.
Thanks in advance.
A: Try,
<asp:Label
Visible="true"
runat="server"
ID="priorityLabel"
Text='<%# Eval("numberTemplatePriority").ToString()=="1" ? "Very Important" :
Eval("numberTemplatePriority").ToString()=="2" ? "Something" : "Nothing" %>'
/>
A: You can use RowDataBound event of the gridview.Try this.
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lbl = (Label)e.Row.FindControl("priorityLabel");
int number = Convert.ToInt32(lbl.Text);
if (number == 4)
{
lbl.Text = "Very Important";
}
}
}
Hope this helps
A: Give the following a try :
<%# (Eval("numberTemplatePriority") == "Very Important") ? Response.Write("Very Imprortant") : Response.Write("Not Important") %>
But I think you need to handle this kind of situations on the sql query. This kind of implementations are not so good idea. It will make it hard to maintain your application in a long term.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525958",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Twitter api - trigger on new post? I have never worked with the twitter api, so I have no idea if this is possible. What I want to do is to trigger a url everytime something new happens on a users timeline (?). Is this possible, and if so, how do I do it?
A: Yes, but it takes a bit of work. You need to use the twitter streaming API, specifically the follow option.
From twitter:
Example: Create a file called ‘following’ that contains, exactly and
excluding the quotation marks: “follow=12,13,15,16,20,87” then
execute:
curl -d @following https://stream.twitter.com/1/statuses/filter.json
-uAnyTwitterUser:Password.
Basically you pass a list of user ids you want to follow, open a long-lived connection, and twitter sends back to you anything that the user posts publicly. You can monitor this connection and do things when a user posts something.
You have another option, called a User Stream , which gets you way more information about when a user does anything, but it requires the user's approval, and a much more complex authentication process via oAuth. So I would only use that if you need it.
How you're going to be keeping a persistant connection open to twitter is something very much dependent on your programming language and software. In Python, I really like tweepy, but even for python there are several different libraries, or you can just use curl or pycurl and do it yourself like in the example above.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525962",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Trying to get SuperWebSocket server working under mono/c# I was using Nugget before (http://nugget.codeplex.com/), but when I upgraded to Chrome 14, it stopped working, and that's when I found this project: http://superwebsocket.codeplex.com/.
I've read this bit here: Is superwebsocket available in asp.net by default?, and I've also built the mono version of SuperSocket. Connecting with Chrome 14, and the websocket just shows as pending in Chrome.
I see a message like this in the server side logfile:
INFO 2011-09-22 23:44:03,924 17166ms uer - WebSocket Server - Session: 1a2dc865-9d02-468e-ac7b-26f3d0b96a2a/127.0.0.1:49261
New SocketSession was accepted!
But the WebSocketServer.NewSessionConnected event never fires. I do see the WebSocketServer.SessionClosed event firing however.
Anyone have any ideas why the new session connection event never fires, and/or why Chrome never receives any response from the socket server?
A: Which version of SuperWebSocket are you using?
The latest source support Chrome 14, but there is no drop for it for now.
So you should download source code by yourself.
Another problem is SuperSocket, SuperSocket 1.4 SP1 which SuperWebSocket base on has no MONO assemblies in release package, so you need build it by yourself.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525965",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Monotouch: How to get a localized string from sqlite DB I want to display a list of items from my sqlite DB in a tableView. These items need to be localized depending on the language selected on the phone.
As an example, if on of the items in the DB was "Hello", it should be displayed as "Hello" in english, "Hallo" in german and so on.
I already tried to store the complete (NSBundle.MainBundle.LocalizedString("Hello", "Hello")) and just storing the identifier for each string, but neither worked.
Any idea where I made a mistake?
Thanks in advance, BanZai
A: Problem solved, made a very stupid mistake. I filled the DB with already localized strings, so obviously the language matched with the original language, but after changing it, the content in the DB stayed the same, thx @Krumelur for trying to help
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525966",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Java 5.0 Compiler API? Is there a Java 5.0 equivalent to the Java 6.0 Compiler API? I'm trying to compile and jar some XmlBean schemas at runtime.
Thanks.
A: You can write the files to disk and call javac using System.exec()
Perhaps its time to updated to Java 6 or 7.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525969",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to check values are unique in JTable? I have a JTable which has two columns and 10 rows. When I read second column values from the JTable, I have to check whether those are unique values.
How to check?
A: You could use a Set to determine if duplicates are being added.
TreeSet set = new TreeSet();
TableModel tableModel = table.getModel() ;
for(int i=0; i<tableModel.getRowCount();i++){
Object obj = tableModel.getValueAt(i, 2);
if(!set.add(obj)){
//throw duplicate error
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525971",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Can't get minimize from CLPFD to work Me and a friend are writing a program which is supposed to solve a CLP problem. We want to use minimize to optimize the solution but it won't work, because it keeps saying that the number we get from sum(P,#=,S) is between two numbers (for example 5..7). We haven't been able to find a good way to extract any number from this or manipulate it in any way and are therefore looking for your help.
The problem seems to arise from our gen_var method which says that each element of a list must be between 0 and 1, so some numbers come out as "0..1" instead of being set properly.
Is there any way to use minimize even though we get a number like "5..7" or any way to manipulate that number so that we only get 5? S (the sum of the elements in a list) is what we're trying to minimize.
gen_var(0, []).
gen_var(N, [X|Xs]) :-
N > 0,
M is N-1,
gen_var(M, Xs),
domain([X],0,1).
find([],_).
find([H|T],P):- match(H,P),find(T,P).
match(pri(_,L),P):-member(X,L), nth1(X,P,1).
main(N,L,P,S) :- gen_var(N,P), minimize(findsum(L,P,S),S).
findsum(L,P,S):- find(L,P), sum(P,#=,S).
A: I've slightly modified your code, to adapt to SWI-Prolog CLP(FD), and it seems to work (kind of). But I think the minimum it's always 0!
:- use_module(library(clpfd)).
gen_var(0, []).
gen_var(N, [X|Xs]) :-
N > 0,
M is N-1,
gen_var(M, Xs),
X in 0..1 .
find([], _).
find([H|T], P):-
match(H, P),
find(T, P).
match(pri(_,L),P):-
member(X, L),
nth1(X, P, 1).
findsum(L,P,S) :-
find(L, P),
sum(P, #=, S).
main(N, L, P, S) :-
gen_var(N, P),
findsum(L, P, S),
labeling([min(S)], P).
Is this output sample a correct subset of the expected outcome?
?- main(3,A,B,C).
A = [],
B = [0, 0, 0],
C = 0 ;
A = [],
B = [0, 0, 1],
C = 1 ;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525972",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Can we get unique transaction id from app store I want to access transaction id or something unique id when the app is first purchased and downloaded from app store.
So that I can identify that user with that unique id, and send that id to my server.
Is this possible to get that from app store?
A: Previously you would use the device id, but that is now deprecated by Apple. I would recommend you simply generate a new GUID when the app is first launched, store that in the user defaults, and use that.
There isn't any way to access transaction information from your app.
A: You can get a unique transaction ID from an In-App-Purchase, but not from the original download or app purchase from the iTunes App store. Neither of these identify the user. Apple's privacy policy may prevent them from ever giving you this information from their app store data.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525973",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Hibernate @DiscriminatorValue not picked up I have the following hierarchy:
@Entity
@Table("changes")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "type", discriminatorType = DiscriminatorType.STRING)
class Change {
@Column(name="type", nullable=false, insertable=false, updatable=false)
@GeneratedValue
String _type;
@ManyToOne
@JoinColumn(name = "user_id")
User _user;
}
@Entity
class EmailChange extends Change {}
@Entity
class BillingChange extends Change {}
@Entity
class User {
@OneToMany(mappedBy = "_user", cascade = Array(Cascade.ALL))
List<EmailChange> _emailChanges;
@OneToMany(mappedBy = "_user", cascade = Array(Cascade.ALL))
List<BillingChange> _billingChanges;
}
I would expect _emailChanges to contain only rows where type = "EmailChange", and _billingChanges rows with type = "BillingChange". However this is not what actually happens - both end up containing rows of both types. Is there any way to force it to obey the polymorphic relationship?
A: You mapped it as SINGLE_TABLE, so all columns are going to a single table. OneToMany creates a foreign key to that table. The same table can't have different columns.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525974",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: CSS layout problem: tabs should overlap the frame I'm working on a template like this:
The as you can see the frame (3) has a glassy border which goes behind the tabs (1,2). But I don't know how to do this layout in CSS. I searched stackoverflow and found the following threads, but they didn't help:
*
*https://stackoverflow.com/questions/6649360/how-to-overlap-put-a-frame-layout-from-top-border-of-an-imageview
*CSS problem, creating tabs
The HTML code is something like this:
<div id="frame">
<nav>
<ul id="topnav">
<li>Tab1</li>
<li>Tab2</li>
<li>Tab3</li>
<li>Tab4</li>
<li>Tab5</li>
<li>Tab6</li>
<li>Tab7</li>
</ul>
</nav>
</div>
A: Try This
HTML :
<div id="frame">
<ul>
<li><a href="javascript:void(0);">Tab 01</a></li>
<li><a href="javascript:void(0);" class="active">Tab 02</a></li>
<li><a href="javascript:void(0);">Tab 03</a></li>
<li><a href="javascript:void(0);">Tab 04</a></li>
</ul>
</div>
<div id="frame2">Frame 02</div>
CSS :
#frame,#frame ul
{ height:30px;
background:#f0f0f0;
}
#frame ul li
{ height:30px;
float:left;
padding-right:2px;
}
#frame ul li a
{ position:relative;
height:30px;
display:block;
float:left; /* for IE6 bug */
background-color:#f00;
left:0;
top:0;
padding:0 4px;
color:#fff;
}
#frame ul li a:hover,#frame ul li a.active
{ height:40px;
}
#frame2
{ border:#000 1px solid;
padding:10px;
}
Please Check JSFIDDLE for Reference
A: I think you are looking for the z-index. An element with a higher z-index will appear above another element with a lower z-index. you can use something like this:
.tabSelected {
z-index: 99;
}
A: I would suggest having a look at jquery-ui which provides an example on the site of a tabbed element such as this, you can modify the design using the theme roller on the site to get the colours you want.
jquery ui tabs
A: If you're using CSS3, you could try using RGBA for the background colour of the frame - here's a couple of links:
*
*SO question/answer
*CSS Tricks article
RGBA will allow the divs to be slightly transparent while keeping the contents visible - just make sure the frame is slightly larger than the contents (so it can be seen) and set the background colour to match the glass effect.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525976",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to write fraction value using html? I want to write fraction value such as the picture below:
How do I write fraction value using html without using image?
NOTE: I don't want this 1 1/2 pattern but strictly just as the pic above
A: Check out the following:
span.frac {
display: inline-block;
text-align: center;
vertical-align: middle;
}
span.frac > sup, span.frac > sub {
display: block;
font: inherit;
padding: 0 0.3em;
}
span.frac > sup {border-bottom: 0.08em solid;}
span.frac > span {display: none;}
<p>7 <span class="frac"><sup>42</sup><span>⁄</span><sub>73</sub></span>.</p>
CodePen
A: You can use <sup> and <sub> elements in conjunction with the fraction slash entity ⁄
<sup>1</sup>⁄<sub>2</sub> is 1⁄2
UPDATE: I made this fiddle that shows a hyphenated fraction in HTML using a table.
<table>
<tbody>
<tr>
<td rowspan="2">1</td>
<td style="border-bottom:solid 1px">1</td>
</tr>
<tr>
<td>2</td>
</tr>
</tbody>
</table>
A: I think there is an easier way for doing this. Use the following HTML.
1 ½
Result is 1 ½
A:
.frac {
display: inline-block;
position: relative;
vertical-align: middle;
letter-spacing: 0.001em;
text-align: center;
}
.frac > span {
display: block;
padding: 0.1em;
}
.frac span.bottom {
border-top: thin solid black;
}
.frac span.symbol {
display: none;
}
1 <div class="frac">
<span>1</span>
<span class="symbol">/</span>
<span class="bottom">2</span>
</div>
A: Using MathML (Specification, Wikipedia):
<math>
<mrow>
<mn>1</mn>
<mfrac>
<mi>1</mi>
<mi>2</mi>
</mfrac>
</mrow>
</math>
A: Using pure html and with margin property of br you can work around
br {
content: "";
margin: -1%;
display: block;
}
<big>1</big><sup> <u><big>1</big></u></sup><br/> <sup> <big>2</big></sup>
A: The following code will be rendered just as the example in the question, and if the client does not support CSS it will be rendered as plain text, still readable as a fraction:
<p>1 <span class="frac"><sup>12</sup><span>/</span><sub>256</sub></span>.</p>
span.frac {
display: inline-block;
font-size: 50%;
text-align: center;
}
span.frac > sup {
display: block;
border-bottom: 1px solid;
font: inherit;
}
span.frac > span {
display: none;
}
span.frac > sub {
display: block;
font: inherit;
}
The middle <span> serves only for the clients who do not render CSS - the text is still readable as 1 12/256 - and that's why you should place a space between the integer and the fraction.
You may want to change the font-size, because the resulting element may be a little taller than the other characters in the line, or you may want to use a relative position to shift it a little to the bottom.
But the general idea, as presented here, may be enough for the basic use.
A: Try the following:
1<sup>1</sup>⁄<sub>2</sub>
This displays as:
11⁄2
A: Simple "inline" HTML
a
<span style="display:inline-flex;flex-direction:column;vertical-align:middle;">
<span>1</span>
<span style="border-top:1px solid">2</span>
</span>
b
CodePen
https://codepen.io/eyedean/pen/bGMqBaB
Screenshot
A: br {
content: "";
margin: -1%;
display: block;
}
<big>1</big><sup> <u><big>1</big></u></sup><br/> <sup> <big>2</big></sup>
A: Here is another method using newer CSS methods. This method also uses custom tags, but you can change these to <div class = "..."></div> if you're not fond of custom tags.
Copy the following to your CSS:
Use .fraction and .numer if you use classes instead
fraction {
display: inline-grid;
grid-template-columns: 1fr;
grid-template-rows: 1fr 1fr;
font-size: 0.8em; // You can change fraction size here. I recommend 0.5em ~ 0.8em
vertical-align: top;
}
numer {
border-bottom: 1px solid;
}
You can now use the tags like this:
Add 1 <fraction> <numer>1</numer> 2 </fraction> cups of flour into the bowl and stir.
Output
I'd also recommend using read-only formatting for screen-reader output:
CSS
read {
position: absolute;
font-size: 0;
}
HTML
1 <fraction> <read>and</read> <numer>1</numer> <read>over</read> 2 </fraction>
Screen-reader: "one and one over two..."
A: It's something like this:
1<sup>1</sup>⁄<sub>2</sub>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525977",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "72"
} |
Q: FB.init gives 'root undefined' or 'innerHTML' error I have written a Facebook website app that gives the possibility to push reactions that people give to news items to there Facebook wall. Everything works fine except in IE8.
When I visit the homepage with IE9 compatibility mode IE8 I get:
Unable to set value of the property 'innerHTML': object is null or undefined
When visit with authentic IE8 I get:
'root' is null or not an object
This is the Facebook code I have on that page:
<script src="http://connect.facebook.net/en_US/all.js"></script>
<div id="fb-root"></div>
<script>
FB.init({
appId : '${siteConfiguration.facebookAppId}',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
</script>
I have tried putting the script tags in the and the fb-root in the but I still get the error.
A: It was right in front of me!
FB quote: The best place to put this code is right before the closing </body> tag.
I placed it in the <head> tag.
A: Guess you need to reorder your code put the line
afer
so your code now will be
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
FB.init({
appId : '${siteConfiguration.facebookAppId}',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
</script>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525985",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Generate distribution from Maven project I want to build an application distribution with Maven. I have a module in my project which holds the main source code. I decided to build the application distribution from this module. I'm telling maven in the module's POM to copy all the configuration files and dependant libs to the target/ directory. My problem is that Maven keeps all the build related temporary dirs (like. classes, generated-sources, maven-archiver) in the target directory. I wan't to auto delete these at least during the install phase. How can i achive this? If i put the maven-clean-plugin to the end of the build it looks like Maven always deletes the whole target directory, no matter who i'm trying to exclude files what i'm trying to keep.
A: try this in your pom
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.2-beta-4</version>
<executions>
<execution>
<id>user_distribution</id>
<phase>package</phase>
<goals>
<goal>attached</goal>
</goals>
<configuration>
<descriptors>
<descriptor>src/main/assembly/dist.xml</descriptor>
</descriptors>
</configuration>
</execution>
</executions>
</plugin>
and here is the xml
<?xml version="1.0" encoding="UTF-8"?>
<assembly xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/xsd/assembly-1.1.1.xsd">
<id>dist</id>
<formats>
<format>zip</format>
</formats>
<files>
<file>
<source>target/${pom.artifactId}-${pom.version}.jar</source>
<outputDirectory>lib/</outputDirectory>
</file>
</files>
<fileSets>
<fileSet>
<directory>directory to be included</directory>
<outputDirectory>/</outputDirectory>
<includes>
<include>file name to be included</include>
</includes>
</fileSet>
<fileSet>
<directory>another directory to be included</directory>
<outputDirectory>/</outputDirectory>
</fileSet>
</fileSets>
</assembly>
A:
I'm telling maven in the module's POM to copy all the configuration
files and dependant libs to the target/ directory
How are you doing this?
Based on the question, it looks like you need to worry less about selectively deleting contents of target folder (which can be done by customizing maven clean plugin), but creating a distribution using maven assembly plugin (as pointed out by @Scorpion).
The latter allows you to bundle together all your project artifacts including the dependencies into zip or other formats, which can then be easily used by developers. You may want to decouple this from regular build by using a separate profile, so that the distribution is built only on need basis.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525990",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How can I create my own class of objects using SilverLight Can someone help me to resolve a question: How can I create my own class of objects (using SilverLight), which will consist of figures, such as a circle with 4 buttons: bottom, top, left and right inside the circle.
A: You just need to add a silverlight user control to your project and to define its content.
There's a tutorial here for SL2 but it's still relevant for SL4.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525991",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to obtain the total page count for a pdf in iTextSharp? I've created a class that extends PdfPageEventHelper to add a specific message at the end of the page. The problem is that this text need to be added only to the end of the PDF (if I have 3 pages this text need to be displayed only on the footer of the last page).
In the OnEndPage function of the PdfPageEventHelper class I use document.PageNumber to know what page I'm modifying, but how can I know if this page is the last one?
Thanks.
A: (writer.PageNumber - 1) is the last page.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525993",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: parameter count mismatch in parameterized query I am using quite a lot of parameterized queries in my code for performance reasons. In short, some of them work, some don't.
I initialize the query during construction of my database wrapper like this:
QString querystring = QString("SELECT somevalue FROM sometable "
"WHERE one_feature = :one_feature AND other_feature = :other_feature ");
myquery = QSqlQuery(db);
myquery.setForwardOnly(true);
myquery.prepare(querystring);
myquery is a QSqlQuery member variable of my database wrapper. Later on, in the function that wants to use this query, I do something like
int db_wrapper::fetch_some_value (int arg1, int arg2) {
myquery.clear();
myquery.bindValue(":one_feature", arg1);
myquery.bindValue(":other_feature", arg2);
qDebug() << "Bound values: " << myquery.boundValues();
bool OK = myquery.exec();
if (!OK) {
int number = myquery.lastError().number();
qDebug() << "db error " << number;
qDebug() << "db error " << myquery.lastError().text();
#ifdef USE_EXCEPTIONS
throw "Could not fetch some_value!";
#endif
}
// process data...
}
I always get the same error message/output:
Bound values: QMap((":one_feature", QVariant(int, 1) ) ( ":other_feature" , QVariant(int, 1) ) )
db error -1
db error " Parameter count mismatch"
terminate called after throwing an instance of 'char const*'
The exception is not surprising, but the parameter count mismatch is. The call to boundValues actually shows the right values and all, still I get this error message. I have similar queries that work just fine.
I tried substituting positional bind values, renamed the placeholders, used ? and positional bind values, all to no avail. Does anyone have an idea what the problem might be?
I use Qt 4.7.3 and SQLite 3.7.4-2
A: Usually this error means that the SELECT/UPDATE query itself is incorrect. You did not give the schema of the database so it's not possible to pinpoint which one. So one or more of somevalue, sometable, one_feature, or second_feature is not in the database/table.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525996",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Using open source database design as starting point for commercial application I'm designing an ecommerce solution, and have been researching various methodologies used by leading open source ecommerce solutions.
I realise that once I've set my features, and normailzed my database design, I may come up with something unique, but what claim do these open source solutions have on the outcome of my analysis?
I don't want to step on anyone's toes, or infringe any license, but the code will be bespoke, and really, only the models (I'm using ASP MVC) will have any resemblence to any other solution..
I'm sure someone will be able to chip in with some experience here..
Cheers in advance..
A: You really need to talk to a lawyer about this - and a lawyer who understands copyright in your particular country, at that.
Having said that....
In general, Open Source projects have licenses that protect the code, but not the concepts. So, if you see that an open source ecommerce solution includes a shopping cart, with a database table storing this cart, and you create your own shopping cart, with a similar table, but don't use their code, you're in the clear.
Even better - most Open Source projects allow and encourage you to use their software, and to extend it - though what happens with those extensions depends on the license. However, this doesn't appear to apply to you - you say you're only looking at the concepts, not building on top of someone else's codebase.
The bad news is that - depending on where you live - open source projects may not be your biggest intellectual property risk. Amazon famously patented "one-click" ordering, and could, theoretically, sue you if your solution includes "one-click" ordering.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525997",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Save state of dynamically added View The problem is that if I have an EditText in a layout.xml the View's state is saved e.g. on orientation change. When I add an EditText from code it doesn't happen.
TextView.setFreezesText() doesn't help.
A: So the answer is:
View.setSaveEnabled(boolean)
Its enabled by default, but as the doc says:
the view still must have an id assigned to it (via setId()) for its state to be saved
A: You should save your EditText content on your activity's onPause method which is called when you change the orientation of an activity.
Check out getPreferences method as well to save your activity's state when it is paused.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526004",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Spring Webflow 2.3.0 Samples unstartable... No Idea how to fix I'm currently evaluating Spring (with a focus on WebFlow) for future projects. After reading lots of docs and articles (most of which didn't help much) I downloaded the current release of Spring WebFlow (2.3.0 at the time of writing) and tried to get the samples running. Apart from solvable, yet frustrating, dependency- and classpath-issues, I hit the first roadblock with the config-files distributed with the samples. First of all, the webflow-config.xml of the booking-mvc-sample isn't even valid.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:webflow="http://www.springframework.org/schema/webflow-config"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/webflow-config
http://www.springframework.org/schema/webflow-config/spring-webflow-config.xsd">
<!-- Executes flows: the entry point into the Spring Web Flow system -->
<webflow:flow-executor id="flowExecutor">
<webflow:flow-execution-listeners>
<webflow:listener ref="securityFlowExecutionListener" />
</webflow:flow-execution-listeners>
</webflow:flow-executor>
<!-- The registry of executable flow definitions -->
<webflow:flow-registry id="flowRegistry" flow-builder-services="flowBuilderServices" base-path="/WEB-INF">
<webflow:flow-location-pattern value="/**/*-flow.xml" />
</webflow:flow-registry>
<!-- Plugs in a custom creator for Web Flow views -->
<webflow:flow-builder-services id="flowBuilderServices" view-factory-creator="mvcViewFactoryCreator"
development="true" validator="validator" />
<!-- Configures Web Flow to use Tiles to create views for rendering; Tiles allows for applying consistent layouts to your views -->
<bean id="mvcViewFactoryCreator" class="org.springframework.webflow.mvc.builder.MvcViewFactoryCreator">
<property name="viewResolvers" ref="tilesViewResolver"/>
<property name="useSpringBeanBinding" value="true" />
</bean>
<!-- Installs a listener to apply Spring Security authorities -->
<bean id="securityFlowExecutionListener" class="org.springframework.webflow.security.SecurityFlowExecutionListener" />
<!-- Bootstraps JSR-303 validation and exposes it through Spring's Validator interface -->
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>
</beans>
*
*cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'webflow:flow-executor'.
*cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'webflow:flow-registry'.
*cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'webflow:flow-builder-services'.
Changing http://www.springframework.org/schema/webflow-config/spring-webflow-config.xsd to http://www.springframework.org/schema/webflow-config/spring-webflow-config-2.3.xsd removes the validation errors from Eclipse but the SAXParser still complains at startup.
Is there any way around it? Can someone help me out with a working config or point to a working tutorial (either a correct one if it's the samples fault or one that shown me how to setup SWF correctly if I'm doing it wrong)?
Right now I'm not far from dumping SWF from our list of possible frameworks as "not running out of the box" and - looking at the userbase and prevalence of Spring, this is somehow hard to believe.
Thanks a lot.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526008",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to make $('#some-id') return the same object as getElementById('some-id')
Possible Duplicate:
How to get a DOM Element from a JQuery Selector
I have a JavaScript library that takes one of parameters as
element: document.getElementById('file-uploader')
And it works well, though I try to use jQuery instead and error happens then.
element: $('#file-uploader')
I suppose these return different objects so how can I make it with jQuery but return an object of the same kind as if it were returned by getElementById method?
A: Try -
$('#file-uploader')[0] //or $('#file-uploader').get(0)
This will return the 'naked' JavaScript DOM object, the same as
document.getElementById('file-uploader')
would return. The example above will only return the first element of the matched set, but in a situation where you're searching by id that should be fine.
A: Try:
$('#file-uploader')[0]
It should be equiv to:
document.getElementById('file-uploader')
A: you have to use either [0] or .get(0) to return the dom object instead of the jquery:
$('#file-uploader')[0];
or
$('#file-uploader').get(0);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526010",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: gdata SetAuthenticationToken() - 403 forbidden I am just trying to get list of Albums in a web app using following c# code.
For AccessToken, I wen to OAuthPlaygound and generated an accessToken
with Picasa in scope using valid consumer key and password which relevant to my web application.
Issue :When I execute following code, I get 403 forbidden error along with message as "Invalid Token" error on last line if I use SetAuthenticationToken() option.
However, if I use setUserCredentialss(), it works. Could anyone please
help me in this? Is it that token generated using OAuth Playground
doesn't work here? Or to use client library token should also be geenrated using it? Is there any workaround?
PicasaService service = new PicasaService("codesamples.google.com");
service.SetAuthenticationToken(accessToken); //Doesn't works
//service.setUserCredentials("myUsername", "myPassword"); //Works
AlbumQuery query = new AlbumQuery(PicasaQuery.CreatePicasaUri(username));
PicasaFeed feed = service.Query(query);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526012",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Slow performance on migrating from .Net 3.5 to .Net 4.0 My application was running pretty well on .Net Framework 3.5 SP1, have no issues with it. Recently we have converted the application to .Net Framework 4.0, we are encountered lot of performance problems and some functional inconsistency.
We are using in our project:
*
*WPF Toolkit
*Addin-Express components
*Our own custom components
Slow on application start-up, ListView/Combobox performance was pretty slow, in my scenario it is taking 10-12 sec time to respond on selecting list view item. Application running down performance on long run.
I am surprised that after converting the entire application to .Net 3.5 running pretty good on performance/functional without any code changes.
Could anybody tell me what was caused these issues or what are the best practices for migrating to 4.0 ?
--
Raavi
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526015",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ASP.Net MVC 3 Configuration i want to ask about ASP.Net Configuration. i have a project that use ASP.Net MVC3. and i use membership in my project. in my database server, there's 2 database for my project.
*
*aspnetdb, contains aspnet_membership, aspnet_user, aspnet_roles, etc (i use asp.net Configuration)
*mydatabase, its for my project database.
now my boss told me that he want to host my project in public and told me to use only one database. so i have to move aspnetdb to mydatabase. how can i do it without making new table in mydatabase ?
thanks
A: By default the ASP.NET membership provider uses a built-in connectionString named LocalSqlServer which is something like this:
<add name="LocalSqlServer"
connectionString="Data Source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true"
providerName="System.Data.SqlClient"/>
and when you use the Membership for first time (or when you use the web configuration manager tool), the aspnetdb.mdf will be created automatically. For first step, you can remove this connectionString from web.config by clear command:
<connectionStrings>
<clear/>
<!-- your other connectionStrings -->
</connectionStrings>
and also, you must change the connectionString for membershipProvider (and also roleProvider if you use it) in web.config file:
<membership userIsOnlineTimeWindow="20">
<providers>
<clear />
<add
connectionStringName="YourSpecifiedConnectionString" // your connectionString here
name="AspNetSqlMembershipProvider"
type="System.Web.Security.SqlMembershipProvider"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="false"
requiresUniqueEmail="false"
maxInvalidPasswordAttempts="500"
minRequiredPasswordLength="1"
minRequiredNonalphanumericCharacters="0"
passwordAttemptWindow="10"
applicationName="/" />
</providers>
</membership>
<roleManager enabled="true">
<providers>
<clear/>
<add connectionStringName="YourSpecifiedConnectionString" // your connectionString here
name="AspNetSqlRoleProvider"
applicationName="/"
type="System.Web.Security.SqlRoleProvider, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
</providers>
</roleManager>
For configure the database to use ASP.NET built-in membership provider, you can use regsql tool
which can be founded here:
C:\Windows\Microsoft.NET\Framework\(version that you are using. mine is v4.0.30319)\
In this folder, find the aspnet_regsql.exe file and run it. A helpful wizard will be shown and
help you step by step to configure new database. And about your final issue: You haven't to apply any change
to your edmx file! The EF works with tables you supplied to it, and membershipProvider do its job with
tables that ASP.NET supplied to it! Well done, Good job!
A: You have to add those tables to your own database. It's quite easy. Just use the aspnet_regsql tool to export the database schema to a SQL file and run that file in your own database.
Instruction:
http://www.xdevsoftware.com/blog/post/Install-ASPNET-Membership-Provider-on-a-Shared-Hosting-Company.aspx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526018",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Disable screen window in sipp When we execute the sipp tool that time it is showing the different types of screen and statistics for calls.
Is it possible to disable the screens and statistics while executing the sipp tool? Because I used to get that screen and statistics in a text file after calls are executed. So I don't want that screen window while executing the sipp tool.So that I'm asking is there any way to do it?. If anyone know about this please let me know.
Thanks in advance.
A: Try the option that runs SIPp in background mode.
-bg : Launch SIPp in background mode.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526024",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: BlackBerry - MDS simulator init calls I debug my BlackBerry apps on device emulator, using the MDS simulator for access to the web.
Today I ran a Wireshark trace to catch my app's calls. I saw 2 calls made by the MDS simulator before my traffic started, and hope someone can explain them to me.
*
*http://www.blackberry.net/go/mobile/mds/http/mappings.xml
*http://www.blackberry.net/go/mobile/mds/http/mappings2prop.xsl
They seem to return some settings possibly for the simulator.
What are these calls for?
I also wonder if these calls are somehow related to the poor performance of the MDS simulator that I deal with regularly - will the MDS simulator continue to work if this server does not respond?
Hope this makes sense to one of the BB experts here - thx.
A: Well, I have noticed this before, from my opinion i think it's a kind of request for blackberry server to open a port according to the proxy setting. Or it maybe as a log for connections. That is just my opinion I'm not an expert ...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526025",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: UIView frame is set wrongly, view got {nan, nan} origin. This is part of my code.
NSLog(@"fr: %@", NSStringFromCGRect(frame_)); NSLog(@"org: %@",
NSStringFromCGPoint(frame_.origin)); // cell.frame = frame_; [cell
setFrame: frame_];
NSLog(@"c: %@", cell); NSLog(@"c frame: %@",
NSStringFromCGRect(cell.frame));
And the printouts are surprising. Anyone got any idea on this? help and thanks.
[657:707] fr: {{350, 600}, {175, 300}}
[657:707] org: {350, 600}
[657:707] c: <JXUIGridViewCell: 0xf62d3c0; frame = (nan nan; 175 300); tag = 4010; animations = { position=<CABasicAnimation: 0x15b4a0>; bounds=<CABasicAnimation: 0x15b540>; }; layer = <CALayer: 0xf62d400>>
[657:707] c frame: {{nan, nan}, {175, 300}}
A: I was actually looking for an answer for this very problem as well. But came up short.
But it turns out, that if you at any point set the origin of a view to nan, then it will stick. Thus it can never be changed again.
Solution: Never set origin of view to nan.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526029",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Trigger to update another field in same table I want to run a trigger when I update a certain field on the database, so it updates another field (basically we have 2 different unique IDs for each record, so when one is changed, we need to update the other too - yay!)
CREATE OR REPLACE TRIGGER trigger_name ON table AFTER
UPDATE AS
UPDATE table A
SET unique_to_update = NVL(
(SELECT b.unique_to_update_from
FROM table b
WHERE B.other_unique_id = A.unique_id_to_match
), 0);
I have no idea if this works (scared to test it, quite frankly, since I'm certain it'll break things) and even if it did, it'd run on every single update of that table - not just the one field that I wanted.
Any help would be much appreciated, thank you!
A: Test anything before putting it in production.
Something like this shoud be your trigger:
CREATE OR REPLACE TRIGGER trigger_name
BEFORE UPDATE of unique_id_to_match
ON table
FOR EACH ROW
AS
BEGIN
select
NVL(
(SELECT b.unique_to_update_from
FROM table b
WHERE B.other_unique_id = :new.unique_id_to_match
), 0)
into :new.unique_to_update
FROM dual;
END;
A: 5000 rows x 900 columns is not so big :)
I was afraid it has 10M of rows :)
OK start
create temporary table tmp_my_important_columns on commit delete rows
as
select unique_id_to_match, unique_to_update_from,
other_unique_id , unique_to_update
from table where rownum < 1;
second
CREATE OR REPLACE TRIGGER trigger_before_upd_stmt
BEFORE UPDATE
ON table
AS
BEGIN
insert into
tmp_my_important_columns
select unique_id_to_match, unique_to_update_from,
other_unique_id , unique_to_update
from table;
END;
third,
CREATE OR REPLACE TRIGGER trigger_name
BEFORE UPDATE of unique_id_to_match
ON table
FOR EACH ROW
AS
BEGIN
select
NVL(
(SELECT b.unique_to_update_from
FROM tmp_my_important_columns b
WHERE B.other_unique_id = :new.unique_id_to_match
), 0)
into :new.unique_to_update
FROM dual;
END;
Comments:
*
*After an update, if you update the same rows again, without commit
(which deletes the tmp table), you'll get problems. So, or you commit
after update, or you can add an after update trigger(without for each row) that deletes all, from tmp table, but this is somehow ugly.
*You can add indexes on the temporary table.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526035",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: jQuery image preload from cache There are a lot of pre-load script examples available on stack overflow but is there a way to check if the browser already has the image preloaded in it's cache and if it is then do not initiate/overtake the image pre-loading with the .load() function and just let the browser put in the image?
A: I don't think so, but more importantly if your browser already has the image, it won't try to reload it anyways (it will just ask the server for the headers and see that the image hasn't changed).
If you want, you can put 'far futures expires' headers on the images, so the browser doesn't even try to check the server and just assumes any images it has in its cache are okay. This would effectively do what you asked.
I think Yahoo says it better than I can:
Browsers (and proxies) use a cache to reduce the number and size of
HTTP requests, making web pages load faster. A web server uses the
Expires header in the HTTP response to tell the client how long a
component can be cached. This is a far future Expires header, telling
the browser that this response won't be stale until April 15, 2010.
Expires: Thu, 15 Apr 2010 20:00:00 GMT
If your server is Apache, use the ExpiresDefault directive to set an
expiration date relative to the current date. This example of the
ExpiresDefault directive sets the Expires date 10 years out from the
time of the request.
ExpiresDefault "access plus 10 years"
Keep in mind, if you use a far future Expires header you have to
change the component's filename whenever the component changes. At
Yahoo! we often make this step part of the build process: a version
number is embedded in the component's filename, for example,
yahoo_2.0.6.js.
So basically, you can put the header Expires: Thu, 31 Dec 2030 0:00:00 GMT and the browser won't go looking for the image again for another 29 years or so : ). Of course this means if you change the images, you'll have to rename them.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526038",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Develop Android's application for all the versions i'm developing an android application and i don't know how to make it compatible with all the versions. In eclipse i select only one API level, and in androidManifest i tried to put minSdk and MaxSdk covering all the version, but it crashes on some OS with different version.
How can i make it compatible with all the versions? Can you help me?
A: Do you really need to support all versions? Check out this chart, which the Android team updates monthly, and tells you what percentage of devices are running which Android versions. As you can see, 97% of devices are on Android 2.1+
I recommend supporting only Android 2.1+ (API level 7) if you can.
Android Platform Versions
A: I'd say that you'll make life really hard for yourself by attempting to make your application work on antiquated Android versions (and by that I mean 1.5 and 1.6). As Sky mentioned, only target Android 2.1 and above.
Can you please specify what exception is being thrown when you attempt to run the application on a different version of the OS?
Here's my application's definition in the manifest.
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="10">
Defining it that way does not guarantee that your application will work on Froyo, Gingerbread and Gingerbread_MR1. Here's an example, I can't use requestSingleUpdate() from the LocationManager class in my application because it was only added in API level 9 (and I intend my application to work in API level 8!).
You need to ensure that you use functionality that is in API level 8 and below. Does that make sense?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526039",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to check if date of file > local file in PHP? I download a small image from a site with PHP locally to cache it, but I would like to be able to check later on if the file has been changed on the external site since it was downloaded. How?
A: You can check the last modification time on the files:
if (filemtime($filename1) > filemtime($filename2)) {
// do something
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526043",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: regex for a particular date format I want to have a regex for a date format, Example: 01-Jan-2011
I have written ^[0-9]{1,2}-[a-zA-Z]{3}-[0-9]{4} but does not check for all the valid dates like 50-AAA-2011 will also be considered as valid.
I am using Live Validation lib in javascript
My code
var sayDate = new LiveValidation('date');
sayDate.add( Validate.Format, { pattern: /^[0-9]{1,2}-[a-zA-Z]{3}-[0-9]{4}/i });
Please help!
A: How about:
^(0?[1-9]|[1-2][0-9]|3[0-1])-(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)-[1-2][0-9]{3}$
This will still allow 31-feb-2011 so to check a date actually exists you'll probably need to use something other than a regex
A: Well clearly if you want only Jan-Dec to be validated, you need to specify it in the RegEx. And then you have to validate whether the date potion iscorrect. And then whether that date is actually valid for the given month or year and there are so many other cases. I believe RegEx is not the solution for this. Have you tried using Date.parse something like Datejs?
A: Trying to validate a date format using regex is actually a lot more complex than it sounds. You can do basic validation quite easily, but there's always that bit more to do to get it perfect.
I would suggest instead using either a date picker control, which can do the validation for you (and also gives you the bonus of a nice shiny user interface feature), or else one of the existing Javascript libraries which can handle dates for you.
For date picker controls, there are any number of jQuery options. For date handling libraries, I would suggest looking up date.js.
Hope that helps.
A: You can validate the syntax of the date via JavaScript regular expressions. You can check the semantics using the Date object, like so:
function ValidateCustomDate(d) {
var match = /^(\d{1,2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{4})$/.exec(d);
if (!match) {
// pattern matching failed hence the date is syntactically incorrect
return false;
}
var day = parseInt(match[1], 10); // radix (10) is required otherwise you will get unexpected results for 08 and 09
var month = {
Jan: 0,
Feb: 1,
Mar: 2,
Apr: 3,
May: 4,
Jun: 5,
Jul: 6,
Aug: 7,
Sep: 8,
Oct: 9,
Nov: 10,
Dec: 11
}[match[2]]; // there must be a shorter, simpler and cleaner way
var year = parseInt(match[3], 10);
var date = new Date(year, month, day);
// now, Date() will happily accept invalid values and convert them to valid ones
// 31-Apr-2011 becomes 1-May-2011 automatically
// therefore you should compare input day-month-year with generated day-month-year
return date.getDate() == day && date.getMonth() == month && date.getFullYear() == year;
}
console.log(ValidateCustomDate("1-Jan-2011")); // true
console.log(ValidateCustomDate("01-Jan-2011")); // true
console.log(ValidateCustomDate("29-Feb-2011")); // false
console.log(ValidateCustomDate("29-Feb-2012")); // true
console.log(ValidateCustomDate("31-Mar-2011")); // true
console.log(ValidateCustomDate("31-Apr-2011")); // false
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526047",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Dojo: click on the tab I need to attach onClick event to tab, not to its content. For example, viewing the example, I want the event firing when I click "Drinks" tab.
The following code results in firing event when I click on tab's content, so it is not what I need:
<div
dojoType="dijit.layout.ContentPane"
href="test.php"
onClick="alert(1);"
>
</div>
Attaching event to tab container results in firing event when click both tabs and tab content.
A: You want to connect to the event onShow. Take a look at the "Event Summary" heading in the reference documentation:
http://dojotoolkit.org/api/dijit/layout/ContentPane
<div dojoType="dijit.layout.ContentPane" href="test.php" onShow="console.log('I'm being shown')"></div>
A: maybe you can write a something like this :
dojo.connect(
dojo.byId("myTab"),
"onclick",
function(){
alert('click');
}
);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526052",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: jQuery UI Drop/Drag data from sql are not draggable/droppable I'm playing around with jQuery UI Drop/Drap using the Photo Manager example provided by jqueryui.com. What I'm trying to achieve is to it as a photo manager but with data auto generated from an sql database. I've managed to fill the draggable <div> with data from the database and images can be dropped in the droppable <div> like in the example and so i'm storing that data back in the database (different table) so the next time the users relog or refresh the page they will be able to see the images that have been dropped in the droppable <div>, so far so good. The problem is that the data generated for the droppable <div> aren't draggable, only the images that have been dropped from the draggable <div> without refresing the page are draggable and droppable back to draggable <div>.
jquery ui code
$(function() {
var $available_for_share = $( "#available-for-share" ),
$currently_sharing = $( "#currently-sharing" );
// let the available_for_share items be draggable
$( "li", $available_for_share ).draggable({
cancel: "a.ui-icon", // clicking an icon wont initiate dragging
revert: "invalid", // when not dropped, the item will revert back to its initial position
containment: $( "#sharing" ).length ? "#sharing" : "document", // stick to demo-frame if present
helper: "clone",
cursor: "move"
});
// let the available_for_share be droppable as well, accepting items from the currently-sharing
$available_for_share.droppable({
accept: "#currently-sharing li",
activeClass: "custom-state-active",
drop: function( event, ui ) {
currently_sharing( ui.draggable );
}
});
// let the currently-sharing be droppable, accepting the available_for_share items
$currently_sharing.droppable({
accept: "#available-for-share > li",
activeClass: "ui-state-highlight",
drop: function( event, ui ) {
available_for_share( ui.draggable );
}
});
function available_for_share( $item ) {
var arr = {};
arr['list_id'] = list_id();
arr['share_with'] = $item.attr('id');
$.post('<?= site_url() ?>/lists/js_share_with', arr,function(str){
str = $.parseJSON(str);
if(str['status'] == 0){
info_bar(str['status'],str['msg']);
} else {
info_bar(str['status'],str['msg']);
$item.fadeOut(function() {
var $list = $( "ul", $currently_sharing ).length ?
$( "ul", $currently_sharing ) :
$( "<ul class='available-for-share ui-helper-reset'/>" ).appendTo( $currently_sharing );
$item.find( "a.ui-icon-trash" ).remove();
$item.appendTo( $list ).fadeIn();
});
}
})
}
function currently_sharing( $item ) {
var arr = {};
arr['list_id'] = list_id();
arr['stop_sharing'] = $item.attr('id');
$.post('<?= site_url() ?>/lists/js_stop_sharing', arr,function(str){
str = $.parseJSON(str);
if(str['status'] == 0){
info_bar(str['status'],str['msg']);
} else {
$item.fadeOut(function() {
$item
.appendTo( $available_for_share )
.fadeIn();
});
info_bar(str['status'],str['msg']);
}
})
}
HTML
<div id="sharing" class="col3 center">
<h2>Share this list</h2>
<span style="font-size:0.8em;">Drag and drop at the bottom box the images you want to share.</span>
<br />
<? if (is_array($available)) : ?>
<div class="ui-widget ui-helper-clearfix">
<hr>
<span style="font-size:0.8em;">available for sharing</span><br />
<ul id="available-for-share" class="available-for-share ui-helper-reset ui-helper-clearfix ui-state-default">
<? foreach ($available as $k) : ?>
<li id="<?= $k['imageID'] ?>" class="ui-widget-content ui-corner-tr">
<img src="http://somedomain/images/<?= $k['imageID'] ?>_64.jpg" alt="<?= $k['imageName'] ?>" width="52" height="52" />
</li>
<? endforeach ?>
</ul>
<span style="font-size:0.8em;">shared with</span><br />
<div id="currently-sharing" class="ui-widget-content ui-state-default ui-droppable">
<? if (is_array($currently_sharing_with)) : ?>
<ul class="available-for-share ui-helper-reset">
<? foreach ($currently_sharing_with as $k) : ?>
<li id="<?= $k['imageID'] ?>" class="ui-widget-content ui-corner-tr ui-draggable" style="display: list-item;">
<img src="http://somedomain/images/<?= $k['imageID'] ?>_64.jpg" alt="<?= $k['imageName'] ?>" width="52" height="52" />
</li>
<? endforeach ?>
</ul>
<? endif ?>
</div>
</div>
<? else : ?>
<p>No images</p>
<? endif ?>
</div>
The jquery code is inside a <script> and it runs right after the database data have been retrieved.
A: Found the solution, i had to make $currently_sharing draggable too, it was only droppable.
// let the $currently_sharing items be draggable
$( "li", $currently_sharing ).draggable({
cancel: "a.ui-icon", // clicking an icon won't initiate dragging
revert: "invalid", // when not dropped, the item will revert back to its initial position
containment: $( "#sharing" ).length ? "#sharing" : "document", // stick to demo-frame if present
helper: "clone",
cursor: "move"
});
A: Try using livequery plugin, http://docs.jquery.com/Plugins/livequery . May be you need to use live function for newly added elements.
$( "li", $available_for_share ).livequery(function(){
$(this).draggable({
cancel: "a.ui-icon",
revert: "invalid",
containment: $( "#sharing" ).length ? "#sharing" : "document",
helper: "clone",
cursor: "move"
});
});
do the same for other functions as well
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526058",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Java XML Library that keeps attributes in order? Is there any java xml library that can create xml tags with attributes in a defined order?
I have to create large xml files with 5 to 20 attributes per tag and I want the attributes ordered for better readability. Attributes which are always created should be at the beginning, followed by common attributes and rarely used attributes should be at the end.
A: Here's an easy way to create a custom outputter based on jdom:
JDOM uses XmlOutputter to convert a DOM into text output. Attributes are printed with the method:
protected void printAttributes(Writer out, List attributes, Element parent,
NamespaceStack namespaces) throws IOException
As you see, the attributes are passed with a simple list. The (simple) idea would be to subclass this outputter and override the method:
@Override
protected void printAttributes(Writer out, List attributes, Element parent,
NamespaceStack namespaces) throws IOException {
Collections.sort(attributes, new ByNameCompartor());
super.printAttributes(out, attribute, parent, namespaces);
}
The implementation of a comparator shouldn't be that difficult.
A: I'm not aware of any such library.
The problem is that the XML information model explicitly states that the order the attributes of a tag are irrelevant. Therefore, any in-memory XML representation that goes to the effort of preserving the ordering will more memory than is necessary and/or implement the attribute set/get methods suboptimally.
My advice would be to implement the ordering of attributes in the presentation of your XML content; e.g. in your XML editor.
I should point out that my Answer answers the Question as written - about "keeping the attributes in order". This could mean:
*
*preserving the order of insertion, or
*keeping in attributes sorted according to some ordering rule; e.g. ascending order.
From your comment below that you really just want to output the attributes in sorted order. This is a simpler problem, and can be addressed by customizing the code that serializes a DOM. Andreas_D explains how you can do this with JDOM, and there may be other options.
The other point is that something is a bit broken if the order of attributes in the input to a tool makes a significant difference to how it behaves. Because the order of XML attributes is supposed to be non-significant ...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526062",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: DOM Tree rendering consequence I wonder how is it important for DOM tree element to be on the right place?
<style> should be inside <head></head>
<div> should be inside <body>
<body> should be inside <html>
For example:
$(document).ready(function () {
$("body").css("display", "none").before("<p>Loading...</p>");
});
It turns out to be that after document download we cover and put in front of it a kind of a block, that informs about page loading.
What reaction browsers can show to such construction? I checked it in Firefox 6, IE 9 - no problems!
A: The problem here is that if your DOM does not conform to a standard, there is no standard way defined for how the layout should be handled by the web browser.
Therefore the browsers are free to render the webpage as they wish; which makes it harder for you to design a webpage that displays consistently across allllllll web browsers.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526063",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Which parameters should I declare as sql placeholders? Should I use a placeholder for every parameter even if it a parameter is always same? And how about nulls? Should I use placeholders for them also?
I'm interested in avoiding preparing and enable caching of the query. I'm using mysql, php and pdo but I think this is the same also with other databases. Security is not a deal because the parameters in the question are hard coded.
Case 1: Should I use a placeholder for visibility or is hard coded value 1 better?
select * from table where visibility=1 and product=:id
Case 2: Should I use a placeholder for null? (and is it the same for both cases?)
select * from t1 where color is null
update t1 set color=null where product=:id
A: if parameters are hardcoded, there is no use for the placeholders at all.
Query caching is enabled by mysql by default, so, you have no worry about it.
So, if there are really no dynamically changed parameters, there is no use in preparing and executing. Just use PDO query method.
However, the question from your title, Which parameters should I declare as sql placeholders? is muhch more interesting.
in terms of that clumsy PDO library, you have to use placeholders for data only.
but in terms of creating SQL queries dynamically, you have to use appropriate placeholders for every variable part of query.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526068",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to sync many small files between two far away sites with limited slow network? Can I use git to accelerate this work? How to sync many small files between two far away sites with limited slow network, and site B have old copy of site A. Can I use git to accelerate this work?
Usually I like use winrar to add site A data to pakage and robocopy to site B, but this way waste old copy on site B.
If use robocopy directly, the speed will awfull slow since so much small files.......
Now I know git can transfer files diffs with compress. Should I create a empty git repostitory on site B, and send to site A. Then add two site data to their git repo separately ? But I think the two git repository can't only transfer diff files when push back to site B. There must have a first whole copy transfer of site A git repo, isn't it? It's not a daily backup work, just one time.
How to only transfer diff files with most speed and compress.....
Other software and suggestion is welcome, like caculate two site data's MD5 and compare to find out diff files, then pakage and compress to transfer.....
Thank you....
Thanks. Since my data in on win2003 both sites, Should I install cygwin for tar rsync and gzip command? I try cygwin1.7, but the gzip is 1.4 and have not --rsyncable option.....
Just tar | rsync will compare and compress?
I read some windows cwrsync article, seems I have to install on rsync server and client,.....
A: rsync is more suitable for synchronizing files by transferring compressed deltas.
A: Tar, gzip (with --rscynable) and rsync are your friends:
tar cf - /siteA | gzip -c --rsyncable > A.tar.gz
rsync -a A.tar.gz siteB:/somewhere
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526072",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: concating fields with null values ill start of by saying "Yes, i know my table does not conform with 1NF."
i am working with something old, and can not change it.
so please, no comments about that.
now, to the problem:
select title,address,zip,city, concat(telefon1,',',telefon2,',',telefon3) as phone
the problem with this is, that it works fine until one of the columns in concat is null or empty.
if it is, then i get a Null result for the phone column.
if all three have values, everything works as expected.
how can i overcome this problem ?
A: Try this:
SELECT title,address,zip,city,CONCAT(
COALESCE(telefon1,''), ',',
COALESCE(telefon2,''), ',',
COALESCE(telefon3,'')) as phone
A: Wrap each telefon column in ifnull(...,'') to turn null into blank.
select ...,
concat(ifnull(telefon1,''),',',ifnull(telefon2,''),',',ifnull(telefon3,'')) as phone
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526073",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Haven't ECMA5 (recent JavaScript) any built-in function for copying objects? I need something like Ext.apply in Node.js. The most obvious way is to define my own:
function simplestApply(dst, src1) {
for (var key in src) if (src.hasOwnProperty(key))
Object.defineProperty(dst, key, Object.getOwnPropertyDescriptor(src, key));
}
But isn't there any built-in function for the same purpose?
A: This is the fastest way, but it doesn't copy the functions.
JSON.parse(JSON.stringify(obj))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526074",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How can I use more than one set of constraints on a single domain class in Grails? I need to choose a set of validation rules at save time. Ideally I would like to be able to define more than one set of constraints in the domain class:
class Account {
...
static constraints = { ... }
static constraints2 = { ... }
}
I know I can do my own validation in code (account.errors.rejectValue(...) etc) but I am looking to save some time by using the built in Grails validation if possible.
A: This is what Command Objects are for.
The reason you can't just swap out validation is that the validation also helps define the database structure, like setting a field to be non-null, or non-blank, or having a specific length. Turning off "non-null", for example, could break the database structure.
Command objects, on the other hand, are designed to have their own unique set of validation rules. It's not the cleanest method (now you are tracking the same structure in more than one situation), but it's better in a lot of ways.
*
*It allows you to securely accept input parameters without worrying that something that shouldn't be processed gets set.
*It creates cleaner controllers, since the validation logic can all be handled within the Command Object, and not sprinkled through the controller method.
*They allow you to validate properties that don't actually exist on the object (such as password verification fields).
If you think you really need multiple sets of constraints, you are most likely either a) over-complicating the domain object to represent more information than it really should (maybe break it up into several one-to-one related objects), or b) incorrectly setting the constraints in the first place.†
In my experience, usually it's a that happens when you feel the need to swap out constraints.
† That being said, it can (rarely) make sense. But Command objects are the best solution in this situation.
A: you can use the validator constraint, see: http://www.grails.org/doc/latest/ref/Constraints/validator.html
within one validator constraint you can perform more checks than one and return diffrent error codes, e.g.
static constaints = {
name: validator { value, obj ->
if (value.size() > 10)
return [invalid.length]
else if (value.contains("test"))
return [invalid.content]
return true
}
in message.properties
domainClass.propName.invalid.content = ...
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526076",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to best pull off nested clickable elements? I have a situation that looks something like this
<div class="x" href="foo">
<div class="y" href="bar"></div>
<div class="z"></div>
<div class="y" href="baz"></div>
<a href="#">fooz</a>
</div>
x is a badge that should be clickable. The problem is that the badge also contains links that also should be clickable. In addition y and z are clickable. Unfortunately clicking the child links only leads to the outter x being pressed. How should I best handle something like this?
A: This doesn't work and it's not valid html, because nested a-elements are not allowed. For a solution more information is needed.
A: I think that you should not place <a> tags into another <a>. The solution here would be either using javascript, and event bubbling or you should separate the links and place/style them in a way where you see one integral badge. In the html you would actually build it from separated elements.
Personally I would go for the javascript way, as it is much more straightforward.
A: Continuing from my previous comment (assuming my understanding of your scenario was correct), here is your solution: http://jsfiddle.net/chricholson/7yzxQ/12/
It involves using stopPropagation to prevent the click being detected up the tree structure http://api.jquery.com/event.stopPropagation/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526077",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: django model polymorphism with proxy inheritance My Discount model describes common fields for all types of discounts in the system. I have some proxy models which describe concrete algorithm for culculating total. Base Discount class has a member field named type, which is a string identifing its type and its related class.
class Discount(models.Model):
TYPE_CHOICES = (
('V', 'Value'),
('P', 'Percentage'),
)
name = models.CharField(max_length=32)
code = models.CharField(max_length=32)
quantity = models.PositiveIntegerField()
value = models.DecimalField(max_digits=4, decimal_places=2)
type = models.CharField(max_length=1, choices=TYPE_CHOICES)
def __unicode__(self):
return self.name
def __init__(self, *args, **kwargs):
if self.type:
self.__class__ = getattr(sys.modules[__name__], self.type + 'Discount')
super(Discount, self).__init__(*args, **kwargs)
class ValueDiscount(Discount):
class Meta:
proxy = True
def total(self, total):
return total - self.value
But I keep getting exception of AttributeError saying self doesnt have type. How to fix this or is there another way to achieve this?
A: Your init method needs to look like this instead:
def __init__(self, *args, **kwargs):
super(Discount, self).__init__(*args, **kwargs)
if self.type:
self.__class__ = getattr(sys.modules[__name__], self.type + 'Discount')
You need to call super's __init__ before you will be able to access self.type.
Becareful with calling your field type since type is also a python built-in function, though you might not run into any problems.
See: http://docs.python.org/library/functions.html#type
A: call super(Discount, self).__init__(*args, **kwargs) before referencing self.type.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526088",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Capturing additional mouse buttons Is there a way to capture presses of additional mouse buttons if mouse has more that 2 of them? According to MSDN WM_XBUTTONDOWN is sent for 2 additional buttons only. I need a solution which will work for any mouse, so using features of special mouse drivers is prohibited. I've found in DirectInput documentation enum Mouse_Device which contains constants describing up to 8 buttons. Can be DirectInput used for this?
A: What about raw input via the WM_INPUT message?
There's a decent explanation of how it works here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526091",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Push notification in c# web application project I have used json to get better performance for my data result of any search in textbox.
I want include Push notification feature ,to show instant update It may be from any browser or any other IP.
It takes notification from server and show instant update without reloading the web page.
A: You can poll data from server with an interval or you might use some async methods like
node.js or signalR. Mr Hanselman has some great posts about them.
http://www.hanselman.com/blog/AsynchronousScalableWebApplicationsWithRealtimePersistentLongrunningConnectionsWithSignalR.aspx
http://www.hanselman.com/blog/InstallingAndRunningNodejsApplicationsWithinIISOnWindowsAreYouMad.aspx
https://github.com/SignalR/SignalR
A: You have to pull in intervals your server for new data.
Setup a timer with the setinterval function and call a server function via ajax to look for new data.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526093",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Rails Admin vs Active Admin : Rails Admin generation tools
Possible Duplicate:
Rails Admin vs. ActiveAdmin
I'm aware that there is already another question about this, but it was not so useful to me. I'm looking for an Admin generation tool for Rails and, apart from personal taste, I ca'nt decide whether use Rails Admin, Active Admin or other tools. HAve you had any experience with them? Can you suggest which you prefer, giving tech explanaitions and feedbacks?
A: I haven't tried Rails Admin, but Active Admin is pretty nice.
Active Admin is flexible in the sense that it lets you customize the admin panel at great length, but requires a little bit of Rails (and Ruby) knowledge, and a few conventions here and there.
There is a nice video cast on Active Admin on this website active admin @ railscast.com
I personally prefer to manage objects directly from the front page (Authorization, Sessions, etc...), but all in all it depends what you intend to do for a website. For an e-commerce solution, having an admin panel is useful, but on the other hand I find it overkill for a blog ;).
hope it helps!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526099",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: asp.net MVC3 custom route for Doddle Report I am using doodle report which outputs quick reports in pds, html and xls formats. It is working fine as shown in the documentation link below:
http://doddlereport.codeplex.com/wikipage?title=Web%20Reporting
Now i need to be able to pass an ID value to the controller so report is generated dynamically.
the default route is as follows:
return routes.MapRoute("DoddleReport",
"{controller}/{action}.{extension}",
new { controller = defaultAction, action = defaultAction },
new { extension = new ReportRouteConstraint() }
which outputs the following url localhost/Report/ReadMeters.htm when using the following
actionlink @Html.ActionLink("HTM", "ReadMeters", new{ extension = "htm"})
I have tried to add a new route in global.asax that will accept an ID parameter as follows:
routes.MapRoute("DoddleReportExtension",
"{controller}/{action}.{extension}/id",
new { controller = "Report", action = "Index" },
new { extension = new ReportRouteConstraint(),
id = UrlParameter.Optional
}
);
and passing the value using actionlink:
@Html.ActionLink("View", "ReadMeters", new { id = ViewBag.ID, extension = "htm" }
but this is outputting url localhost/Report/ReadMeters.htm?id=19
this does not work and i get the following error:
Server Error in '/' Application.
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /Report/ReadMeters.htm
Any Ideas how to fix this please? This is my first MVC project and so far have relied on the default routing mechanisms for other areas of the project but got stuck on this one.
Your help is appreciated, thanks
A: I know I'm late here, but I'm the author of DoddleReport and just wanted to say that this issue has been resolved in the latest source and NuGet package. It also supports MVC Areas.
Hope the project has been helping you!
A: you could do something like this ...
routes.MapRoute("DoddleReportExtension",
"{Controller}/{Action}/{Extension}/{id}/",
new { controller = Report, action = Index,Extension=new ReportRouteConstraint(), id=UrlParameter.Optional });
and then you can send the extension and the id to ActionResult..
public ActionResult showItem(string Extension)
{
//view stuff here.
}
public ActionResult showItem(string Extension, int id)
{
//view stuff here
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526101",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: mootools className undefined I really don't understand why that piece of code won't work :
$$('.nav_contact').addEvent('click', function(){
if (this.getStyle('color') != '#ffc000') {
this.tween('color','#ffc000');
alert(this.className);
$$('.navigation').getElements('a').each(function(a) {
alert(a.className);
if (a.className != 'nav_contact') {
a.tween('color','#b2b1af');
}
});
}
});
here is the related HTML :
<nav class="navigation">
<ul>
<li><a class="nav_foo">Portfolio</a></li>
<li><a class="nav_bar">Services</a></li>
<li><a class="nav_contact">Contact</a></li>
</ul>
</nav>
This is supposed to highlight the clicked button and to somehow hide the other ones. The problem is that I can't get elements className soon as I enter the each. The alert gives me "undefined".
Anybody ?
A: this will be hard to scale / pattern as is.
consider something like this:
(function() {
var navItems = $$(".navigation a");
document.getElements("a.nav_contact").addEvent("click", function() {
var self = this;
if (this.getStyle('color') != '#ffc000') {
this.tween('color', '#ffc000');
navItems.each(function(a) {
// more scalable - change all but the current one w/o special references.
if (a != self) {
a.tween('color', '#b2b1af');
}
return;
// or check if it has an implicit class name...
if (!a.hasClass("nav_contact"))
a.tween('color', '#b2b1af');
// or check if the only class name is matching...
if (a.get("class") != 'nav_contact')
a.tween('color', '#b2b1af');
});
}
});
})();
jsfiddle: http://jsfiddle.net/dimitar/V26Fk/
To answer your original question though. Even though CURRENTLY mootools returns a proper element object, it will not always be the case. Do not assume it will be and ALWAYS use the api to get properties of the object, eg. element.get("class") vs el.className - it does the browser differences mapping as well. same for value, text etc - just discipline your self to use the API or you wont be able to upgrade to mootools 2.0
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526102",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Route mappings are broken suddenly. How to fix? Route mappings for my MVC app are broken suddenly.
Here are route mappings
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}", // URL with parameters
new { controller = "Home", action = "Index" } // Parameter defaults
);
}
Here is controller code
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public string Login()
{
return "Login";
}
}
I can access Index view by using http://localhost:49637/ but I cannot access Login view via http://localhost:49637/Login. If I try to access Login view via http://localhost:49637/Home/Login, it works.
A: You have no route that matches - 'http://localhost:49637/Login' as your only route looks for both a controller and an action value, and you are only passing one value, so MVC is attempting to route you to a 'Login' controller that does not exist. I haven't tested this, but adding something like this should fix your problem-
routes.MapRoute(
"Login",
"Login",
new { controller = "Home", action = "Login" }
);
Remember that asp.net MVC will use the first matching route it finds, so you'll need to place this route above the 'default' route in your RegisterRoutes function.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526105",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to send an email which exactly looks in the outlook express how i see in my web browser? In my web browser this shows correctly. But when i send it to Gmail or Outlook it does not show correctly nor it show in the center alignment layouts. (many other newsletter i receive they fit it exactly in the center).
HTML to send:
<form target="theFrame" >
<DIV class=contents style="width:527px;">
<DIV class=contents_body style="padding-left:150px;">
Why you are not padding, in Outlook? And showing full texts in 100% width?
</DIV>
</DIV>
</form>
<iframe name='theFrame'></iframe>
A: This is because email clients are based on older versions of html and will not render the same as a browser.
If you have a look at online services such as email on acid or litmus you can test how your email will look in various email clients prior to sending.
Keep your email template basic and favour old style table layouts.
How about a spacer image?
<DIV class=contents style="width:527px;">
<img src="yoururl/img/spacer.gif" width="150px" align="left" />
<DIV class=contents_body style="padding-left:150px;">
Why you are not padding, in Outlook? And showing full texts in 100% width?
</DIV>
</DIV>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526107",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: FTP Request Header Format I want to know the difference in the ftp request header for an ipv4 server and ipv6 server.
can anyone give the header format for those ipv4 and ipv6?
thanks in advance,
Ramulu Ponnam
A: Do you mean HTTP? FTP just sends one-line commands, not full headers like HTTP.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526112",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Load Wordpress post content into DIV using AJAX I posted a question a couple of days ago on how to Scroll to Single Post in a custom Wordpress template that I'm developing. What I need in the nut shell is to load a single post into a defined DIV when a particular link is clicked and then scroll down to that DIV holding the newly loaded content. Considering the dynamic content nature of Wordpress or that of any other CMS, the URL of that link cannot be an absolute one.
Unfortunately, there wasn't any concrete answer around at that point of time, so I decided to snoop around a little bit. And since the main issue was loading the content in dynamically, I decide to zoom in on how I can do it with AJAX on Wordpress:
So far, I have gotten a slight idea from a great post (Loading WordPress posts with Ajax and jQuery) by Emanuele Feronato. He basically stores the post ID in the rel attribute of the clickable link and then calls it. Well, there are a few other steps to make this work, but the reason I'm only mentioning the post ID right now is because it seems it's the only part of the equation that isn't right; the post ID loads into the link's rel attribute but fails to load into the .load function.
Just to give you a better idea of what I've gotten in my markup so far:
THE AJAX/JQUERY IN HEADER.PHP
$(document).ready(function(){
$.ajaxSetup({cache:false});
$(".trick").click(function(){
var post_id = $(this).attr("rel");
$("#single-home-container").html("loading...");
$("#single-home-container").load("http://<?php echo $_SERVER[HTTP_HOST]; ?>/single-home/",{id:post_id});
return false;
});
});
INDEX.PHP
<?php get_header();?>
<!--home-->
<div id="home">
<!--home-bg-->
<img class="home-bg" src="<?php bloginfo('template_url');?>/images/home-bg.jpg" />
<!--home-bg-->
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<a class="trick" rel="<?php the_ID(); ?>" href="<?php the_permalink();?>">
<div class="box element col<?php echo rand(2,4); ?>" id="<?php $category = get_the_category(); echo $category[0]->cat_name; ?>">
<?php the_post_thumbnail(); ?>
<span class="title"><?php the_title(); ?></span>
<span class="ex"><?php the_excerpt(); ?></span>
</div>
</a>
<?php endwhile; endif; ?>
</div>
<!--home-->
<div id="single-home-container"></div>
SINGLE-HOME.PHP (THIS IS A CUSTOM TEMPLATE)
<?php
/*
Template Name: single-home
*/
?>
<?php
$post = get_post($_POST['id']);
?>
<!--single-home-->
<div id="single-home post-<?php the_ID(); ?>">
<!--single-home-bg-->
<div class="single-home-bg">
</div>
<!--single-home-bg-->
<?php while (have_posts()) : the_post(); ?>
<!--sh-image-->
<div class="sh-image">
<?php the_post_thumbnail(); ?>
</div>
<!--sh-image-->
<!--sh-post-->
<div class="sh-post">
<!--sh-cat-date-->
<div class="sh-cat-date">
<?php
$category = get_the_category();
echo $category[0]->cat_name;
?>
- <?php the_time('l, F jS, Y') ?>
</div>
<!--sh-cat-date-->
<!--sh-title-->
<div class="sh-title">
<?php the_title();?>
</div>
<!--sh-title-->
<!--sh-excerpt-->
<div class="sh-excerpt">
<?php the_excerpt();?>
</div>
<!--sh-excerpt-->
<!--sh-content-->
<div class="sh-content">
<?php the_content();?>
</div>
<!--sh-content-->
</div>
<!--sh-post-->
<?php endwhile;?>
<div class="clearfix"></div>
</div>
<!--single-home-->
Just for the record: When the post ID failed to load, I tried installing that particular Kubrick theme used in Emanuele Feronato's demo and made the necessary changes according to his guide but nothing worked.
Does anyone have any idea what's going on or if there is any other way to dynamically load the post ID into the .load function?
A: Instead of using:
var post_id = $(this).attr("rel");
you should directly fetch the href. They're both the same.
var post_id = $(this).attr("href");
This helps with 2 things:
*
*Less markup in your HTML
*You stay away from using rel as a data attribute, which is not a very wise choice nowadays with HTML5. (read here)
A: Well, by a stroke of luck and some coffee with cigarettes, I managed to resolve the issue:
Here's what I did:
1. Test if post ID is captured in the rel attribute and loaded properly in the post_id variable
I inserted an alert call back on the AJAX / JQUERY snippet to see if the post ID was even loading into the post_id variable right. This is how it looked like:
$(document).ready(function(){
$.ajaxSetup({cache:false});
$(".trick").click(function(){
var post_id = $(this).attr("rel");
alert(post_id);
$("#single-home-container").html("loading...");
$("#single-home-container").load("http://<?php echo $_SERVER[HTTP_HOST]; ?>/single-home/",{id:post_id});
return false;
});
});
So when I clicked on the link, the call back gave the accurate post ID associated with the post. This kinda isolated the problem right down to the URL defined in the .load() function. It seemed that the post ID was just not sufficient to load the post into defined DIV.
2. Change link's rel attribute from post ID to post permalink
I decided that since the post ID was clearly not working I would instead use the post's permalink tag in the link's rel attribute. This is how it link's rel looked like previously:
<a class="trick" rel="<?php the_ID(); ?>" href="<?php the_permalink();?>"></a>
And this is how it looks like now:
<a class="trick" rel="<?php the_permalink ?>" href="<?php the_permalink();?>"></a>
3. Edit .load() function URL / value
Following on from there, I had to make a change to the AJAX / JQUERY snippet so that it will not use the post ID anymore:
$(document).ready(function(){
$.ajaxSetup({cache:false});
$(".trick").click(function(){
var post_link = $(this).attr("rel");
$("#single-home-container").html("loading...");
$("#single-home-container").load(post_link);
return false;
});
});
As you can see from the above, I've taken the link's rel attribute value (which is now the post's permalink) and thrown it into the post_link variable. This enables me to simply take that variable and place it into the .load() function, replacing http://<?php echo $_SERVER[HTTP_HOST]; ?>/single-home/",{id:post_id} which obviously didn't work.
VOILA! Problem solved.
Though I have yet to test this, I believe that using the permalink in this instance actually cuts out the need to change the permalink structure in Wordpress as instructed by Emanuele Feronato in his post.
So if anyone has the intent to dynamically load Wordpress posts into a defined DIV, you can probably try this out!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526113",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "28"
} |
Q: Django jquery form submissions returning 500 I am trying to do a modelform submission is Django with jquery and I am getting a 500 server response and not sure how to proceed.
This is my js:
function addUpdate(e) {
e.preventDefault();
var form = jQuery(e.target);
jQuery.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: form.serialize(),
dataType: 'json',
success: function(){
$('<p>Been Added</p>').insertBefore("div.tr-list");
}
});
};
jQuery("form#tr-form").submit(function(e){
addUpdate(e);
});
This is my form:
<input class="nidden" type="button" id="tr-trigger" value="Add Resource" />
<form class="absolute" id="tr-form" action="{% url topic_resource_create topic.person.user topic.slug %}" method="POST">{% csrf_token %}
<div id="tr-wrapper">
{{ tr_form.as_p }}
<input id="tr-submit" type="submit" value="Submit" />
<input type="reset" value="Reset" />
</div>
</form>
This is my view:
def tr_create_xhr(request, slug):
if request.method == "POST":
form = TopicResourceForm(request.POST)
try:
r = Resource.objects.get(url=form.cleaned_data['resource'])
except Resource.DoesNotExist:
r = Resource.objects.create(url=form.cleaned_data['resource'], rtype=form.cleaned_data['rtype'])
r.save()
form.resource = r
topic = Topic.objects.get(person__user=request.user, slug__iexact=slug)
form.topic = topic
if form.is_valid():
form.save()
response = serializers.serialize('json', form)
if request.is_ajax():
return HttpResponse(response, content_type="application/javascript")
else:
return HttpResponseRedirect("../..")
I am not sure if they view logic is correct because I get a 500 server error everytime i try and post to the url. I have a couple other similar form submissions that are giving me the same error.
A: Firebug should show you the actual error. However, in this case it seems likely that the problem is in your serialization code. You can't call serializers.serialize on a form - that makes no sense at all. The serializers work on a queryset.
What you need to do is get the object returned from saving the form, wrap that in a list, and then serialize it:
obj = form.save()
response = serializers.serialize('json', [obj])
However you also have some issues with the flow through your view - there's no object if the form is not valid, for example.
A: usually means can't find jquery files. look at the source of your html header. should be something like this and if you follow the link you should see the jquery script.
<script type="text/javascript" src="/static/js/jquery-1.6.2.js"></script>
your base template would have something like this
<script type="text/javascript" src="{{ STATIC_URL }}js/jquery-1.6.2.js"></script>
You may also find the documentation on static files useful.
A: Maybe it is because of csrf-protection? Symptoms are very similar.
https://docs.djangoproject.com/en/1.3/ref/contrib/csrf/
So you can try to add {% csrf_token %} somewhere between <form> and </form> tags.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526114",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Callbacks over Callbacks I want to put markers on a map. The source is a json request, which returns cities.
I've got a function (sencha) that returns the records (asynchronous) and a function (google maps api) that returns the lng, lat for specific cities (asynchronous) and a method (google maps), that puts markers on the map.
The result should be a marker on the map at the location calculated by google with a caption retrieved from the record.
load records
offers = App.stores.offers.load({
callback: function(records, operation, success){...}
})
get location
geocoder = new google.maps.Geocoder();
geocoder.geocode(
{'address': adress},
function(results, status) {...}
}
and set the marker
marker = new google.maps.Marker({
map: map,
position: loc,
title: text
});
What I wan't to do is, load the record, loop over each record, find out about location of the city and put a marker there.
synchronous I would do:
records = App.stores.offers.load();
for (var i=0; i < records.length; i++) {
setMarker( map, getLocation(records[i].data["city"]), cords[i].data["text"]);
}
What's the right way to put it together with the asynchronous functions?
A: I don't really know what does the App.stores.offers.load function do exactly but I'll assume its callback function arguments contain loading results in records variable. In this case loop through records inside callback function and for each call geocode, and on geocode's callback place markers (nothing wrong with this).
EDIT: this is untested and probably not most efficient but should work:
offers = App.stores.offers.load({
callback: function(records, operation, success){
if (success) {//or sth like this
var complete;
for (var i = 0; i < records.length; i++) {
complete = false;
geocoder.geocode( {'address': records[i].adress},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
title: results[i].text,
position: results[0].geometry.location
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
complete = true;
});
while (!complete);
}
}
}
});
A: In the end I implemented it with extjs / sencha. The second problem I run in to was the restrictions on the google maps service (I had a lot of quota exceeded exceptions). So it's not exactly the answer to the question. So I marked the other answer as correct, because it's closer to the question. Here the code I had in the end anyway, may it help someone.
App.stores.offers = new Ext.data.Store({
model: 'Offer',
(...)
listeners: {
load: function(store, records, success){
this.addEvents( "refresh_locations", "locations_updated" );
for (var i=0; i < store.data.length; i++) {
store.fireEvent("refresh_locations", store , store.getAt(i), "load" );
}
},
refresh_locations: function(store, record, method){
if (record.get("location") == null || record.get("location") == ""){
Ext.Ajax.request({
url: 'api/partner2sport/find_location',
params: {
"city" : record.get("place")
},
success: function(response, options) {
db_check = Ext.decode(response.responseText)["success"];
if (db_check){
var latlngStr = Ext.decode(response.responseText)["location"].replace(/\(|\)/g,"").split(",",2)
var lat = parseFloat(latlngStr[0]) - (Math.random() / 100);
var lng = parseFloat(latlngStr[1]) - (Math.random() / 100);
var latlng = new google.maps.LatLng(lat, lng);
record.set("location", latlng);
}else{
geocoder = new google.maps.Geocoder();
geocoder.geocode(
{
'address': record.get("place")
},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
record.set("location", results[0].geometry.location);
Ext.Ajax.request({
url: 'api/partner2sport/set_location',
params: {
"city" : record.get("place"),
"location": record.get("location")
}
});
}
}
);
}
},
failure: function(response, options) {
console.log("bad request");
}
});
}
},
(...)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526115",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Npgsql does not commit transaction after failed command I'm using Npgsql 2.0.11 under .NET 4.0 to modify a PostgreSQL 9.0 database. The program makes many modifications to the database, all within a single transaction.
Just before committing, I run SELECT statement, which sometimes fails (eg. with a timeout). I swallow the exception and go ahead and commit the transaction anyway. There is no error, so it appears as if everything worked, but in actual fact the database was not modified at all!
My guess is that the failed SELECT rolled back the entire transaction. Can I either prevent this (ie. have the transaction still committed) or at least detect this situation and throw an exception, so the user knows the commit failed?
I know that in this specific case I could just move the SELECT outside the transaction, but I'm more concerned about solving this for the general case. Having a commit not commit is a pretty serious problem and I want to make sure it doesn't go undetected.
A: I know nothing about Npgsql, but I can speak to the behavior of PostgreSQL. When any error occurs within a PostgreSQL transaction, the transaction is marked invalid until it is closed. (Their term is "aborted", which I think is misleading.) Furthermore, and this is IMHO insane, if you COMMIT an invalid transaction, it "succeeds" but has the same effect as ROLLBACK. You can observe this in the psql REPL; it will print ROLLBACK in response to your COMMIT command, but it won't signal an error.
You can create a SAVEPOINT right before your final SELECT. If it fails, then ROLLBACK to the savepoint name; that will get you out of the invalid state and allow you to commit the previous part of the transaction.
A: I ended up writing a little wrapper method that tries to execute a trivial statement as part of the transaction right before committing, which is effective in detecting the problem.
public static void CommitTransaction(NpgsqlConnection conn, NpgsqlTransaction tran)
{
using (var command = new NpgsqlCommand("SELECT 1", conn, tran))
{
try
{
command.ExecuteScalar();
}
catch (NpgsqlException ex)
{
if (ex.Code == "25P02")
throw new Exception("The transaction is invalid...");
throw;
}
}
tran.Commit();
}
The fix is either of Morg.'s or Ryan Culpepper's answers: either run the statement outside of the transaction or create a SAVEPOINT beforehand and ROLLBACK to it on error.
A: Having something fail within a transaction and yet the transaction complete wouldn't be very transactional right ?
So basically, if it may fail and you don't care about it, don't put it in the transaction with that which must not fail.
Use transactions as they're meant to be used and you won't have any issues ;)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526116",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: duplicate s in seam's pages.xml Using seam, in pages.xml I can catch the value of a query string parameter and put it in a backing bean like so:
<page view-id="/my/page.xhtml" >
<param name="myParam" value="#{myActionBackingBean.param}" />
<action execute="#{myActionBackingBean.doAction()}" />
</page>
As far as I've read, this will also take the value out of the backing bean and put it back in the query string over a redirect (i.e. defines a two-way binding).
In the project I'm working on, we have a few pages with duplicate params, like this:
<page view-id="/my/page.xhtml" >
<param name="myParam" value="#{myActionBackingBean.param}" />
<param name="myParam" value="#{myDifferentBackingBean.param}" />
<action execute="#{myActionBackingBean.doAction()}" />
</page>
This seems to compile and run fine, but eclipse has started reporting an error (since a recent update, possibly a plugin update) that "Value myParam is not unique" for the second param name.
*
*Are duplicate param tags like this invalid as suggested by eclipse?
*What is the most likely behaviour to expect in the second case?
*Is there another way to get the value of a query string parameter into two beans (could it be done using an <action> to copy from one to the other with EL, for example)
I have a lot of seam and EL to learn so I'm grateful for any good sources if these questions seem naive.
A: Probably the best way to do so is to create another bean just to keep your information and simply bind it to it.
Then you can inject it into myActionBackingBean and myDifferentBackingBean.
Otherwise you can copy it from one to another during the @Create method.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526124",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Optimising a lot of inserts with JDBC and MySQL I have to perform a large number of inserts (in this instance 27k) and I want to find an optimal to do this. Right now this is the code that I have. As you can see I'm using prepared statement and batches and I'm executing every 1000 ( I have also tried with a lesser number such as 10 and 100 but the time was again way to long). One thing which is omitted from the query is that there is an auto-generated ID if it is of any matter to the issue:
private void parseIndividualReads(String file, DBAccessor db) {
BufferedReader reader;
try {
Connection con = db.getCon();
PreparedStatement statement = null;
statement = con.prepareStatement("INSERT INTO `vgsan01_process_log`.`contigs_and_large_singletons` (`seq_id` ,`length` ,`ws_id` ,`num_of_reads`) VALUES (?, ?, ?, ?)");
long count = 0;
reader = new BufferedReader(new FileReader(logDir + "/" + file));
String line;
while ((line = reader.readLine()) != null) {
if(count != 0 && count % 1000 == 0)
statement.executeBatch();
if (line.startsWith(">")) {
count++;
String res[] = parseHeader(line);
statement.setString(1, res[0]);
statement.setInt(2, Integer.parseInt(res[1]) );
statement.setInt(3, id);
statement.setInt(4, -1);
statement.addBatch();
}
}
statement.executeBatch();
} catch (FileNotFoundException ex) {
Logger.getLogger(VelvetStats.class.getName()).log(Level.SEVERE, "Error opening file: " + file, ex);
} catch (IOException ex) {
Logger.getLogger(VelvetStats.class.getName()).log(Level.SEVERE, "Error reading from file: " + file, ex);
} catch (SQLException ex) {
Logger.getLogger(VelvetStats.class.getName()).log(Level.SEVERE, "Error inserting individual statistics " + file, ex);
}
}
Any other tips regarding what might be changed in order to speed up the process. I mean a single insert statement doesn't have much information - I'd say no more than 50 characters for all 4 columns
EDIT:
Okay following the advice given I have restructured the method as follows. The speed up is immense. You could even try and play with the 1000 value which might yield better results:
private void parseIndividualReads(String file, DBAccessor db) {
BufferedReader reader;
PrintWriter writer;
try {
Connection con = db.getCon();
con.setAutoCommit(false);
Statement st = con.createStatement();
StringBuilder sb = new StringBuilder(10000);
reader = new BufferedReader(new FileReader(logDir + "/" + file));
writer = new PrintWriter(new BufferedWriter(new FileWriter(logDir + "/velvet-temp-contigs", true)), true);
String line;
long count = 0;
while ((line = reader.readLine()) != null) {
if (count != 0 && count % 1000 == 0) {
sb.deleteCharAt(sb.length() - 1);
st.executeUpdate("INSERT INTO `vgsan01_process_log`.`contigs_and_large_singletons` (`seq_id` ,`length` ,`ws_id` ,`num_of_reads`) VALUES " + sb);
sb.delete(0, sb.capacity());
count = 0;
}
//we basically build a giant VALUES (),(),()... string that we use for insert
if (line.startsWith(">")) {
count++;
String res[] = parseHeader(line);
sb.append("('" + res[0] + "','" + res[1] + "','" + id + "','" + "-1'" + "),");
}
}
//insert all the remaining stuff
sb.deleteCharAt(sb.length() - 1);
st.executeUpdate("INSERT INTO `vgsan01_process_log`.`contigs_and_large_singletons` (`seq_id` ,`length` ,`ws_id` ,`num_of_reads`) VALUES " + sb);
con.commit();
} catch (FileNotFoundException ex) {
Logger.getLogger(VelvetStats.class.getName()).log(Level.SEVERE, "Error opening file: " + file, ex);
} catch (IOException ex) {
Logger.getLogger(VelvetStats.class.getName()).log(Level.SEVERE, "Error reading from file: " + file, ex);
} catch (SQLException ex) {
Logger.getLogger(VelvetStats.class.getName()).log(Level.SEVERE, "Error working with mysql", ex);
}
}
A: You have other solutions.
*
*Use LOAD DATE INFILE from mySQL Documentation.
*If you want to do it in Java, use only one Statement that inserts 1000 values in 2 order :
"INSERT INTO mytable (col1,col2) VALUES (val1,val2),(val3,val4),..."
But I would recommend the 1st solution.
A: The fastest way to do what you want to do is to load directly from the file (http://dev.mysql.com/doc/refman/5.5/en/load-data.html).
There are some problems with loading from a file - firstly, the file needs to be readable by the server, which often isn't the case. Error handling can be a pain, and you can end up with inconsistent or incomplete data if the data in your file does not meet the schema's expectations.
It also depends on what the actual bottleneck is - if the table you're inserting to has lots going on, you may be better using a combination of insert delayed (http://dev.mysql.com/doc/refman/5.5/en/insert-delayed.html).
The official line on speeding up inserts is here: http://dev.mysql.com/doc/refman/5.5/en/insert-speed.html
A: Depending on the structure of your data you have a potential bug in your "execute batch every 1000 iterations" logic.
If the frequency of lines beginning with ">" is low, then you could have an instance where the following happens (loading for lots of unnecessary executeBatch calls:
line in data file events in program
-----------------------------------------------------------
> some data (count=999)
> some more data (count=1000)
another line (execute batch, count=1000)
more unprocessed (execute batch, count=1000)
some more (execute batch, count=1000)
So I would move the if(count != 0 && count % 1000 == 0) inside the if (line.startsWith(">")) block.
Note, I'm note sure whether this can happen in your data or how much of a speed-up it would be.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526126",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Issue With android ListView I have added a listadapter which contains a checkbox, imageview, two textviews and a button to a listview. The problem is when I click on single checkbox for selecting more than one is getting selected. Below is my code for the Adapter. Please tell me any thing wrong in the code.
package com.mgm.schannel.lazylist;
import java.util.ArrayList;
import java.util.List;
import com.mgm.schannel.R;
import com.mgm.schannel.fonts.FontUtil;
import com.mgm.schannel.parser.inbox.Child;
import com.mgm.schannel.parser.inbox.Messages;
import com.mgm.schannel.ui.inboxActivity;
import android.content.Context;
import android.graphics.Color;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.CompoundButton.OnCheckedChangeListener;
public class InboxAdapter extends BaseAdapter {
public ArrayList<Object> getSelectedItems() {
return selectedItems;
}
private ArrayList<Object> selectedItems;
private inboxActivity activity;
private List<Object> data;
private static LayoutInflater inflater = null;
private TextView MessageCount;
FontUtil fontsList;
private boolean showMoveButton;
int positionItem;
public TextView getMessageCount() {
return MessageCount;
}
public InboxAdapter(inboxActivity a, List<Object> results, FontUtil fontslist) {
activity = a;
data = results;
fontsList = fontslist;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
showMoveButton = false;
selectedItems = new ArrayList<Object>();
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
Object inboxObject = data.get(position);
positionItem = position;
if(convertView == null)
vi = inflater.inflate(R.layout.inboxlist, null);
Button btnmove = (Button)vi.findViewById(R.id.btnmovehere);
if(position % 2 == 0)
{
vi.setBackgroundColor(Color.parseColor("#ebebeb"));
}
else
{
vi.setBackgroundColor(Color.parseColor("#f4f4f4"));
}
if(inboxObject instanceof Messages)
{
ImageView imgicon = (ImageView)vi.findViewById(R.id.inboxicon);
imgicon.setImageResource(R.drawable.message);
TextView text = (TextView)vi.findViewById(R.id.txtCaption);
text.setTextSize(16.f);
text.setTextColor(Color.BLACK);
text.setTypeface(fontsList.getTitilliumMaps29L002());
text.setText(((Messages)inboxObject).getSender());
text = (TextView)vi.findViewById(R.id.txtMessage);
text.setTextSize(10.f);
text.setTextColor(Color.BLACK);
text.setTypeface(fontsList.getTitilliumMaps29L002());
text.setText(((Messages)inboxObject).getMessage());
btnmove.setVisibility(View.INVISIBLE);
CheckBox cbSelected = (CheckBox)vi.findViewById(R.id.chkSelection);
cbSelected.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if(buttonView.isChecked())
{
getSelectedItems().add(data.get(positionItem));
}
}
});
}
else if(inboxObject instanceof Child)
{
TextView text = (TextView)vi.findViewById(R.id.txtCaption);
text.setTextSize(14.f);
text.setTextColor(Color.BLACK);
text.setTypeface(fontsList.getTitilliumMaps29L002());
Log.e("Folder Name", ((Child)inboxObject).getFolderName());
text.setText(((Child)inboxObject).getFolderName());
ImageView imgicon = (ImageView)vi.findViewById(R.id.inboxicon);
imgicon.setImageResource(R.drawable.folder);
text = (TextView)vi.findViewById(R.id.txtMessage);
text.setVisibility(View.GONE);
if(showMoveButton)
{
btnmove.setVisibility(View.VISIBLE);
}
else
{
btnmove.setVisibility(View.INVISIBLE);
}
CheckBox cbSelected = (CheckBox)vi.findViewById(R.id.chkSelection);
cbSelected.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if(buttonView.isChecked())
{
getSelectedItems().add(data.get(positionItem));
}
}
});
}
return vi;
}
public void showMove(boolean value) {
showMoveButton = value;
}
}
A: You are always referencing the same exact checkbox object. You need to reference a different one each time, or create a new checkbox each time.
CheckBox cbSelected=(CheckBox)vi.findViewById(R.id.chkSelection);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526131",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Sprint Samsung Galaxy s2 - Activity has leaked IntentReceiver - Are you missing a call to unregisterReceiver() I have not seen this error on the Droid Bionic, Droid 3, Motorola Photon 4g, HTC Evo 3d, and the Thunderbolt.
This sample application will throw a "leaked IntentReceiver" error by following these steps:
*
*Somehow aquire a Sprint Samsung Galaxy s2 Epic Touch 4g (the one with the 4.52" screen)
*Launch application
*Press "Launch Activity Two" button
*Open menu, then open the sub menu (Food) - NOTE: You don't need to click on an option, simply viewing the submenu is sufficient
*Press the phone's back button to close the submenu and menu.
*Press the phone's back button again to return to ActivityOne - eclipse will print the error below.
If you simply open the menu and select a single option item (not a submenu) then press the back button you will not see the error.
So my question is: Where is this registered IntentReceiver coming from, and how can I unregister it?
Thank you for your time.
# AndroidManifest.xml (Target version is 2.3.3)
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.test" android:versionCode="1" android:versionName="1.0">
<uses-sdk android:minSdkVersion="10" />
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".ActivityOne" android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".ActivityTwo"></activity>
</application>
</manifest>
# one.xml (layout for ActivityOne)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="Hello this is activity one" />
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/launch_activity_two"
android:text="Launch Activity Two" />
</LinearLayout>
# two.xml (layout for ActivityTwo)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hello this is activity Two. The only way to leave is by pressing the back button on your phone. If you open a submenu (press menu button then select a submenu) - then press the back button on your phone there will be an exception thrown." />
</LinearLayout>
# menu/menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/food" android:title="Food">
<menu>
<item android:id="@+id/food_is_good" android:title="Food is good" />
<item android:id="@+id/food_is_delicious" android:title="Food is delicious" />
<item android:id="@+id/food_is_bad" android:title="Food is bad" />
</menu>
</item>
<item android:id="@+id/doggies_are_cuddly" android:title="Doggies are cuddly" />
</menu>
# ActivityOne
public class ActivityOne extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.one);
// launches activity two
Button button = (Button)findViewById(R.id.launch_activity_two);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), ActivityTwo.class);
startActivity(intent);
}
});
Log.v("Samsung Galaxy sII", "Created Activity One");
}
}
# ActivityTwo
public class ActivityTwo extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.two);
Log.v("Samsung Galaxy sII", "Created Activity Two");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
Log.v("Samsung Galaxy sII", "Creating options menu");
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.food_is_bad:
Log.v("Samsung Galaxy sII", "Food is bad");
return true;
case R.id.food_is_good:
Log.v("Samsung Galaxy sII", "Food is good");
return true;
case R.id.food_is_delicious:
Log.v("Samsung Galaxy sII", "Food is delicious");
return true;
case R.id.doggies_are_cuddly:
Log.v("Samsung Galaxy sII", "Doggies are cuddly");
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
09-23 00:46:09.210: VERBOSE/Samsung Galaxy sII(28668): Created Activity Two
09-23 00:46:11.791: VERBOSE/Samsung Galaxy sII(28668): Created Activity Two
09-23 00:46:12.705: VERBOSE/Samsung Galaxy sII(28668): Creating options menu
09-23 00:46:19.120: ERROR/ActivityThread(28668): Activity com.test.ActivityTwo has leaked IntentReceiver com.android.internal.view.menu.MenuDialogHelper$1@4052c470 that was originally registered here. Are you missing a call to unregisterReceiver()?
09-23 00:46:19.120: ERROR/ActivityThread(28668): android.app.IntentReceiverLeaked: Activity com.test.ActivityTwo has leaked IntentReceiver com.android.internal.view.menu.MenuDialogHelper$1@4052c470 that was originally registered here. Are you missing a call to unregisterReceiver()?
09-23 00:46:19.120: ERROR/ActivityThread(28668): at android.app.LoadedApk$ReceiverDispatcher.<init>(LoadedApk.java:756)
09-23 00:46:19.120: ERROR/ActivityThread(28668): at android.app.LoadedApk.getReceiverDispatcher(LoadedApk.java:551)
09-23 00:46:19.120: ERROR/ActivityThread(28668): at android.app.ContextImpl.registerReceiverInternal(ContextImpl.java:858)
09-23 00:46:19.120: ERROR/ActivityThread(28668): at android.app.ContextImpl.registerReceiver(ContextImpl.java:845)
09-23 00:46:19.120: ERROR/ActivityThread(28668): at android.app.ContextImpl.registerReceiver(ContextImpl.java:839)
09-23 00:46:19.120: ERROR/ActivityThread(28668): at android.content.ContextWrapper.registerReceiver(ContextWrapper.java:318)
09-23 00:46:19.120: ERROR/ActivityThread(28668): at com.android.internal.view.menu.MenuDialogHelper.show(MenuDialogHelper.java:97)
09-23 00:46:19.120: ERROR/ActivityThread(28668): at com.android.internal.policy.impl.PhoneWindow.onSubMenuSelected(PhoneWindow.java:808)
09-23 00:46:19.120: ERROR/ActivityThread(28668): at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:867)
09-23 00:46:19.120: ERROR/ActivityThread(28668): at com.android.internal.view.menu.IconMenuView.invokeItem(IconMenuView.java:532)
09-23 00:46:19.120: ERROR/ActivityThread(28668): at com.android.internal.view.menu.IconMenuItemView.performClick(IconMenuItemView.java:122)
09-23 00:46:19.120: ERROR/ActivityThread(28668): at android.view.View$PerformClick.run(View.java:9238)
09-23 00:46:19.120: ERROR/ActivityThread(28668): at android.os.Handler.handleCallback(Handler.java:587)
09-23 00:46:19.120: ERROR/ActivityThread(28668): at android.os.Handler.dispatchMessage(Handler.java:92)
09-23 00:46:19.120: ERROR/ActivityThread(28668): at android.os.Looper.loop(Looper.java:130)
09-23 00:46:19.120: ERROR/ActivityThread(28668): at android.app.ActivityThread.main(ActivityThread.java:3691)
09-23 00:46:19.120: ERROR/ActivityThread(28668): at java.lang.reflect.Method.invokeNative(Native Method)
09-23 00:46:19.120: ERROR/ActivityThread(28668): at java.lang.reflect.Method.invoke(Method.java:507)
09-23 00:46:19.120: ERROR/ActivityThread(28668): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:907)
09-23 00:46:19.120: ERROR/ActivityThread(28668): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:665)
09-23 00:46:19.120: ERROR/ActivityThread(28668): at dalvik.system.NativeStart.main(Native Method)
A: onCreateOptionsMenu(Menu menu) is called every time the options menu is displayed. I did have some strange effects with this too and now use onPrepareOptionsMenu(Menu menu) instead of this which is just called once for the activity, maybe this helps to get around this issue.
Maybe the Android version installed on S2 calls the method again for the sub menu and somehow leaks a registered IntentReceiver through this, as in this case the menu would get created twice.
A: Check your menu for errors. There are several ways of getting this error on SG2. Often the error is correct even if it's ignored on several devices. Overall, doing something in the menuhandling that causes the normal handling of the menu to end will give you this error. Launching activities from onOptionsItemSelected on items that has submenus for instance.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526136",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I check for an int in a variadic list? I've got a method that can take a variable number of arguments.
I'm using variadic commands to get the arguments and store them in an NSMutableDictionary.
The problem is, if I send an int to the method, I get a crash, because NSMutableDictionaries can't store an int.
What I want to do is make the method check if one of the arguments is an int, and if it is, turn it into an NSNumber before I put it in the dictionary.
But I can't for the life of me find out how to check for an int.
[I know one answer would be "don't send an int to the method, only send NSNumbers!" Problem is, that places an obligation on the caller of the method that can't be determined from the method description alone.]
A: The type of arguments in variadic lists cannot be checked. It has to be specified by some other way.
For instance, NSLog() uses the format argument to get type information: %@ for an object, %d for an integer value or %f for a floating point value.
A: I recently came across the concept "Type Encodings" in Apple doc. This is done using @encode() compiler directive. Doc says that, "When given a type specification, @encode() returns a string encoding that type".
So, sing @encode() and typeof() and strcmp() we can find the type of the variable that is passed. typeof() returns the type of the variable. For example, @encode(int) returns "i" and consider a variable named var is an integer variable, then typeof(var) would return int. In this case, @encode(int) and @encode(typeof(var)) would return "i" only. We can check for the equality of the strings using strcmp() method.
if (strcmp(@encode(typeof(variable)), @encode(int)) == 0) {
// The varibale is an "int"
// @encode(int) returns "i"
// @encode(float) returns "f"
// @encode(double) returns "d"
} else if (strcmp(@encode(typeof(variable)), @encode(NSObject *)) == 0) {
// The varibale is an "object"
// @encode(NSObject *) returns "@"
// You can use anything in the place of NSObject in the above line
// @encode(NSString *) or @encode(UIButton *) will also return "@"
}
There is list give for all the Objective-C type encodings. You can check for the string encodings of the other types in the above Apple doc link.
Application of the above concept in variadic functions: It will be almost impossible to use the above type encoding concept to variadic finctions with different kind of arguments, as we get each argument from va_arg() method only after specifying the type as the argument. So, we are trying to get the argument to find its type from va_arg() method which itself requires the type to return the argument. Bit annoyoing!
A: Edit: this isn't working. I thought it was, but now I'm getting crashes I don't understand. If I figure it out, I'll come edit this more. Here's what I wrote before, which is wrong. Again, this is not working:
I think I found the answer to this: Key-Value Coding.
With Key-Value Coding, I can set up an instance variable of type id,
and then dynamically identify the actual contents of the variable. I
can put anything in it, even an int, and Key-Value methods will
identify it for me. But what's even more awesome is that if I
retreive the contents of a variable using Key-Value Coding, and the
variable turns out to be an int, Key-Value Coding automatically turns
it into an NSNumber for me.
I will attempt to demonstrate.
The main thing is to set up accessor statements for the variable I
want to access. So, for this example, let's say the variable is
called "identifyMe."
//in the interface:
@property (copy) id accessIdentifyMe;
//in the implementation:
@synthesize accessIdentifyMe = identifyMe;
Now "identifyMe" is Key-Value Compliant. We're good to go.
All I have to do is take the items in the variadic list, pass them
into identifyMe one by one, and use Key-Value methods to identify the
contents. Like so:
/*...assume all the following is happening inside a loop that
counts through
the variadic list. I'll call the variadic list "variadicList."
First, I take
the current variadic item and put it into identifyMe, declaring it
as type
"id"*/
identifyMe = va_arg(variadicList, id);
/*Now I use a Key-Value method to check if identifyMe holds an
NSNumber. If it
holds an int, it will automatically be returned as an NSNumber,
you'll recall, so
querying for an NSNumber is functionally the same as querying for
an int.
Outside the loop I've set up a handy boolean called foundANumber
in which to
store the results of the query:*/
foundANumber = [[self valueForKey:@"identifyMe"]
isKindOfClass:[NSNumber class]];
That's given me the ability to separate the numbers from the objects.
With that done, I can put the objects directly into my dictionary, and
put the numbers into an NSNumber before I put them in the dictionary.
And what this means at the other end, when calling this method from
another object, is that I can call this method and put an int in the
parameter list and not worry about causing a crash. Yay.
Here's the reason this isn't working: KVC isn't magic. I thought it had some super special way of determining the type of a variable, but it doesn't. It just looks at the type declared in the accessor methods, and it can't independently verify any more than that. Darn.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526144",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: What method is called when UIScrollView has reached its maximumZoomScale? Theres a wide UIScrollView (let's call it wideScroll) and inside it, smaller UIScrollViews (call them singleScrollViews). And there is a UIView in each SingleScrollView, which contains two different UIImageViews.
I need to use the scrolling delegates for the wideScroll, and zooming delegates for the singleScrollViews.
How I do this is, I use UIScrollView delegates in wideScroll class, and when a zooming event happens, I return the pointer of the desired singleScrollView's UIView in the method;
-(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
//here i determine "int someint" according to current page.
SingleScrollView *b = (SingleScrollView *)[wideScrollView viewWithTag:someint];
return ((UIView *)[b viewWithTag:WRAPPERVIEW_TAG]);
}
When I do this, the zooming of individual singleScrollViews work fine except one thing, which is,
when singleScrollView reaches its maximumZoomScale, the zooming ends, but before "scrollViewDidEndZooming" method is called, "scrollViewDidZoom" is called one last time and set the content offset of UIView to (0,0), making the image scroll to top left.
On the contrary, when I zoom in without reaching maximumZoomScale, the UIView stays where it is zoomed, not scrolling to top or anything else.
Also, the "-(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView" method is called thrice when I reach maximumZoomScale while zooming.
Any Ideas?
Workaround:
I set the maximumzoomscale to 2.01 and when singleScrollView.ZoomScale is > 2.00, i set it back to 2.00 in the beginning of the ScrollViewDidZoom delegeta method.
A: Take a look at the photoscroller sample example. And you need to implement viewForZooming individually for each single scrollview. That's the better approach of implementation.And override layoutSubview method and set the centre of your imageview in it based on your scrollview zoom scale
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526147",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Wix: Assigning a property a value from a dialogue control Could someone please show me a simple example of assigning a value to a property that was supplied by a user from a dialogue edit control.
A: <Control Id="ServiceName" Type="Edit" X="20" Y="73" Width="200" Height="18" Property="SERVICENAME"></Control>
You can get value of the property like: Value=[SERVICENAME].
A: Look at WiX Tutorial article: New Link in a Chain, it explains how to add user registration page.
User Interface Revised section contains other examples on how you can customize UI with WiX.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526148",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Easy rule to read complicated const declarations? For reading complex pointer declarations there is the right-left rule.
But this rule does not mention how to read const modifiers.
For example in a simple pointer declaration, const can be applied in several ways:
char *buffer; // non-const pointer to non-const memory
const char *buffer; // non-const pointer to const memory
char const *buffer; // equivalent to previous declartion
char * const buffer = {0}; // const pointer to non-const memory
char * buffer const = {0}; // error
const char * const buffer = {0}; // const pointer to const memory
Now what about the use of const with a pointer of pointer declaration?
char **x; // no const;
const char **x;
char * const *x;
char * * const x;
const char * const * x;
const char * * const x;
const char * const * const x;
And what is an easy rule to read those declarations?
Which declarations make sense?
Is the Clockwise/Spiral Rule applicable?
Two real world examples
The method ASTUnit::LoadFromCommandLine uses const char ** to supply command line arguments (in the llvm clang source).
The argument vector parameter of getopt() is declared like this:
int getopt(int argc, char * const argv[], const char *optstring);
Where char * const argv[] is equivalent to char * const * argv in that context.
Since both functions use the same concept (a vector of pointers to strings to supply the arguments) and the declarations differ - the obvious questions are: Why do they differ? Makes one more sense than the other?
The intend should be: The const modifier should specify that the function does not manipulate strings of this vector and does not change the structure of the vector.
A: The const modifier is trivial: it modifies what precedes it, unless
nothing precedes it. So:
char const* buffer; // const modifies char
char* const buffer; // const modifies *
, etc. Generally, It's best to avoid the forms where nothing precedes
the const, but in practice, you're going to see them, so you have to
remember that when no type precedes the const, you have to logically
move it behind the first type. So:
const char** buffer;
is in fact:
char const** buffer;
, i.e. pointer to pointer to const char.
Finally, in a function declaration, a [] after reads as a * before.
(Again, it's probably better to avoid this misleading notation, but
you're going to see it, so you have to deal with it.) So:
char * const argv[], // As function argument
is:
char *const * argv,
a pointer to a const pointer to a char.
A: (Trying to focus on other aspects of the question)
The rule of thumb for const declarations is to read them from right to left and const modifies the next token. Exception: At the beginning of a declaration const modifies the previous token.
There is a rationale behind this exception - for elementary declarations const char c looks for some people more natural than char const c - and it is reported that a precursor form of const char c predates the final const rule.
getopt
int getopt(int argc, char * const argv[], const char *optstring);
or
int getopt(int argc, char * const * argv, const char *optstring);
Which means that argv is a pointer to const vector of pointers to non-const strings.
But one would expect following declaration:
int getopt(int argc, char const * const * argv, const char *optstring);
(pointer to const vector to const strings)
Because getopt() is not supposed to change the strings referenced via argv.
At least char ** (as used in main()) automatically converts to char * const * argv.
Clang
ASTUnit::LoadFromCommandLine(..., const char **argv, ...);
Which means that argv is a pointer to a non-const array of pointers to const strings.
Again one would expect const char * const *argv for the same reason as above.
But this is more noticeable because char ** does not convert to const char **, e.g.
int main(int argc, char **argv) {
const char **x = argv; // Compile error!
return 0;
}
yields a compile error, where
int main(int argc, char **argv) {
char * const *x = argv;
return 0;
}
and
int main(int argc, char **argv) {
const char * const *x = argv;
return 0;
}
do not.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526152",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "50"
} |
Q: How can i use sql database query?
Hello. I am new to android. In my application there is three tables category , product and quality in spinner. when i select perticular category , product related to that category would be display in product category. How can i do this? Please help me.
A: Manisha, I am assuming this database is local (sqlite3) and hence you would need to implement DatabaseHelper class.
Refer this tutorial for details
http://www.screaming-penguin.com/node/7742
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526160",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: JSON, HighCharts/HighStock, DBSlayer - Data display I have a MySQL database with some price data in it I would like to display using HighCharts/HighStock yet I'm not sure how I can actually go about getting this data from MySQL (via DBslayer as the JSON layer) and display in high charts (the example I found on their site isnt helpful and searching around there are no good tuts).
So essentially the system looks like this:
MySQL <---> DBSlayer Service <---> JSON Requests to DBSlayer <---> Web page with charts - send query to DBSLayer
The MySQL View which DBSlayer queries in a nutshell looks like this:
DATE TIME | Symbol1 | Price 1 | Symbol2 | Price 2 | Price3
2011-09-01| ABC | 12.3 | XYZ | 67.8 | 0.0852
Or a better example is the returned JSON from a query to DBSlayer:
{"RESULT" : {"HEADER" : ["id" , , "authorID" , "msgDate" , "obj_obj" , "obj_subj" , "obj_diff" , "subj_pos" , "subj_neg" , "subj_diff" , "pos_lex" , "neg_lex" ] ,
"ROWS" : [["4e0f1c393bfbb6aa4b7278c2" , "27" , "2011-06-30 13:59:47" , 0.0275171 , 0.972483 , -0.944966 , 0.993814 , 0.00618577 , 0.987628 , 1 , 0 ] ,
["4e0f1c393bfbb6aa4b7278c3" , "36324" , "2011-06-30 13:59:31" , 0.364953 , 0.635047 , -0.270095 , 0.0319281 , 0.968072 , -0.936144 , 3 , 1 ] ,
["4e0f1c393bfbb6aa4b7278c4" , "12134" , "2011-06-30 13:59:28" , 0.0112589 , 0.988741 , -0.977482 , 0.857735 , 0.142265 , 0.715469 , 1 , 1 ] ] ,
"TYPES" : ["MYSQL_TYPE_VAR_STRING" , "MYSQL_TYPE_VAR_STRING" , "MYSQL_TYPE_DATETIME" , "MYSQL_TYPE_DOUBLE" , "MYSQL_TYPE_DOUBLE" , "MYSQL_TYPE_DOUBLE" , "MYSQL_TYPE_DOUBLE" , "MYSQL_TYPE_DOUBLE" , "MYSQL_TYPE_DOUBLE" , "MYSQL_TYPE_DOUBLE" , "MYSQL_TYPE_LONG" } , "SERVER" : "db-webPrices"}
How should I deploy this to High Charts? Should I use Node.js to wrap the query first (there are Node.js to DBSlayer libs however they dont work with the newest version of Node.js.
How would I use JQuery to get this data and format for a HighStock chart like this one: http://www.highcharts.com/stock/demo/multiple-series/gray
The basic HighCharts Demo using a CSV file as a data source looks like this:
$(function() {
var seriesOptions = [],
yAxisOptions = [],
seriesCounter = 0,
names = ['DJI', 'SENTIMENT', 'GOOG', 'GS', 'SENTIMENT-Z', 'DJI-Z'],
colors = Highcharts.getOptions().colors;
$.each(names, function(i, name) {
$.get(name +'.csv', function(csv, state, xhr) {
// inconsistency
if (typeof csv != 'string') {
csv = xhr.responseText;
}
// parse the CSV data
var data = [], header, comment = /^#/, x;
$.each(csv.split('\n'), function(i, line){
if (!comment.test(line)) {
if (!header) {
header = line;
}
else {
var point = line.split(';'), date = point[0].split('-');
x = Date.UTC(date[2], date[1] - 1, date[0]);
if (point.length > 1) {
// use point[4], the close value
data.push([
x,
parseFloat(point[4])
]);
}
}
}
});
seriesOptions[i] = {
name: name,
data: data,
yAxis: i
};
// create one y axis for each series in order to be able to compare them
yAxisOptions[i] = {
alternateGridColor: null,
gridLineWidth: i ? 0 : 1, // only grid lines for the first series
opposite: i ? true : false,
minorGridLineWidth: 0,
title: {
text: name,
style: {
color: colors[i]
}
},
lineWidth: 2,
lineColor: colors[i]
};
// As we're loading the data asynchronously, we don't know what order it will arrive. So
// we keep a counter and create the chart when all the data is loaded.
seriesCounter++;
if (seriesCounter == names.length) {
createChart();
}
});
});
// create the chart when all data is loaded
function createChart() {
chart = new Highcharts.StockChart({
chart: {
renderTo: 'container',
alignTicks: false
},
rangeSelector: {
selected: 1
},
title: {
text: null
},
xAxis: {
type: 'datetime',
maxZoom: 14 * 24 * 3600000, // fourteen days
title: {
text: null
}
},
yAxis: yAxisOptions,
series: seriesOptions
});
}
});
</script>
<script type="text/javascript" src="js/themes/gray.js"></script>
Any examples/code would be greatly appreciated!
Cheers!
A: If you view the source of the demo page you provided, you can see how it's done with CSV data. A JSON result is even easier to use.
Update: The documentation shows you more info on how your data should look.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526166",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Issue communicating via RS232 - VB.net dll / Delphi win32 exe I have a Delphi program that communicates with a vb.net dll that I created. The vb.net dll communicates with a Fluke scope meter via an RS232 connection. I have created a program that communicates correctly via RS232, giving me the anticipated value. Though, when I package this up as a dll and access the dll from my Delphi program I always receive a value of "1", rather than the value I was expecting (most cases a value in and around 240).
I know that my delphi program is definitely communicating correctly with the dll and that my dll is definitely communicating with the scope meter. It is just the value that is returned which is the issue! Hopefully I have simply done something very silly here, but I can't see it and it is starting to drive me mad!
Here is my vb.net code:
Public Interface IFlukeComm
Function GetReading(ByVal Command As String, ByVal PortNum As Integer) As String
Function Test() As String
End Interface
Public Class FComm : Implements IFlukeComm
Private WithEvents moRS232 As Rs232
Dim InvokeRequired As Boolean
Dim TxResult As String
Private Sub OpenCom(ByVal PortNum As Integer)
Dim sTx As String
moRS232 = New Rs232()
Try
With moRS232
.Port = PortNum
.BaudRate = 1200
.DataBit = 8
.StopBit = Rs232.DataStopBit.StopBit_1
.Parity = Rs232.DataParity.Parity_None
.Timeout = 1500
End With
moRS232.Open()
moRS232.Dtr = True
moRS232.Rts = True
moRS232.EnableEvents()
moRS232.PurgeBuffer(Rs232.PurgeBuffers.TxClear Or Rs232.PurgeBuffers.RXClear)
sTx = "PC 9600"
sTx += ControlChars.Cr
moRS232.Write(sTx)
moRS232.Close()
Catch ex As Exception
End Try
End Sub
Private Sub moRS232_CommEvent(ByVal source As Rs232, ByVal Mask As Rs232.EventMasks) Handles moRS232.CommEvent
If (Mask And Rs232.EventMasks.RxChar) > 0 Then
TxResult = source.InputStreamString
End If
End Sub
Public Function GetReading(ByVal Command As String, ByVal PortNum As Integer) As String Implements IFlukeComm.GetReading
OpenCom(PortNum)
Threading.Thread.Sleep(500)
With moRS232
.Port = PortNum
.BaudRate = 9600
.DataBit = 8
.StopBit = Rs232.DataStopBit.StopBit_1
.Parity = Rs232.DataParity.Parity_None
.Timeout = 1500
End With
moRS232.Open()
moRS232.Dtr = True
moRS232.Rts = True
moRS232.EnableEvents()
Command += ControlChars.Cr
moRS232.Write(Command)
Threading.Thread.Sleep(500)
moRS232.Close()
If TxResult <> "" Then
'moRS232.Read(10)
Dim sRead As String = moRS232.InputStreamString
Return sRead
Else
Return "Invalid"
End If
End Function
Public Function Test() As String Implements IFlukeComm.Test
Return "Success"
End Function
End Class
Here is my Delphi code:
procedure TfrmLauncher.btnM1UNClick(Sender: TObject);
begin
ShowMessage(GetMeasurements('QM 11',cmbM1PC.ItemIndex + 1));
end;
function TfrmLauncher.GetMeasurements(strType : string; iPort : Integer) : string;
var
IFC : IFlukeComm;
begin
IFC := CreateComObject(CLASS_FComm) as IFlukeComm;
Result := IFC.GetReading(strType,iPort);
end;
A: TxResult = source.InputStreamString
Dim sRead As String = moRS232.InputStreamString
I don't use VB.net, but it looks as if you may be attempting to read the receive buffer twice. Does InputStreamString permit this, or does it empty on read?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526171",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Extremely slow rendering of Reportviewer in ASP.Net MVC I have been looking for a solution for doing reporting in ASP.Net MVC, and I did come across a solution by Rai Kaimal Rendering an RDLC directly to the Response stream in ASP.NET MVC. Everything works just fine, but the localReport.Render() function takes extremely long to render the page (40 seconds for 2 very simple pages - the same reports executes in 2 seconds from a winforms solution). Any help would be appreciated. If there's no way to speeding up the report, I'm interested in knowing how other developers handle the reporting in a ASP.Net MVC solution.
Here is my code:
public ActionResult CustomerReport()
{
var localReport = new LocalReport
{
ReportPath = Server.MapPath("~/Reports/CustomerReport.rdlc")
};
var reportDataSource = new ReportDataSource("Customers", _repository.GetAll( ));
localReport.DataSources.Add(reportDataSource);
const string reportType = "PDF";
string mimeType;
string encoding;
string fileNameExtension;
//The DeviceInfo settings should be changed based on the reportType
//http://msdn2.microsoft.com/en-us/library/ms155397.aspx
const string deviceInfo = "<DeviceInfo>" +
" <OutputFormat>PDF</OutputFormat>" +
" <PageWidth>8.5in</PageWidth>" +
" <PageHeight>11in</PageHeight>" +
" <MarginTop>0.5in</MarginTop>" +
" <MarginLeft>1in</MarginLeft>" +
" <MarginRight>1in</MarginRight>" +
" <MarginBottom>0.5in</MarginBottom>" +
"</DeviceInfo>";
Warning[] warnings;
string[] streams;
//Render the report
byte[] renderedBytes = localReport.Render(
reportType,
deviceInfo,
out mimeType,
out encoding,
out fileNameExtension,
out streams,
out warnings);
return File(renderedBytes, mimeType);
}
A: Placing <trust legacyCasModel="true" level="Full"/> inside <system.web> tag in web.config did it for me. I'm in ASP.NET Webforms though. More details here
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526172",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: iPhone:UIWebview Gradient background starts-over when scrolling down the content When I apply the gradient background to uiwebview custom html content it only applies to visible area , when scroll down the content the gradient starts again from top color value again, any ideas?
[customHtml appendString:[NSString stringWithFormat:@"%@ ", @" <body style='background-color:#4b95bf; background-image:-webkit-gradient(linear, left top, left bottom, from(#55aaee), to(#003366));'>"]];
A: Use
background-attachment:fixed;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526176",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: SQL query syntax error I got a syntax error on this query, but I don't know what I'm doing wrong.
UPDATE `jos_planning2_rosters` r
LEFT JOIN jos_planning2_rosters_setup s ON r.id = s.roster_id
LEFT JOIN jos_planning2_workplaces w ON s.workplace_id = w.id
WHERE r.roster_state =1
AND s.card_id IS NULL
AND s.type_id = '2'
AND r.roster_date >= DATE( NOW()) SET s.card_id = '1', s.type_id = '1'
WHERE s.type_id = '2', s.card_id IS NULL, r.id = '8';
A: You have two WHERE clauses in your query.
A: Are you trying to do this, the query is a mess:
UPDATE s
SET s.card_id = '1',
s.type_id = '1'
From jos_planning2_rosters_setup s
INNER JOIN jos_planning2_rosters r ON r.id = s.roster_id
WHERE r.roster_state = 1
AND s.card_id IS NULL
AND s.type_id = '2'
AND r.roster_date >= GetDate()
AND r.id = '8';
A: Try it without those backticks around jos_planning2_rosters.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526177",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
} |
Q: SmsManager keeps retrying to send SMS on HTC Desire In my app I need to send SMS, so I use the following code
final String SMS_REQUEST_OK = "SMS_REQUEST_OK";
String m_sms_message = String.format("sample text");
String m_dest_number = "some number";
Intent SMSInfo = new Intent(SMS_REQUEST_OK);
SMSInfo.putExtra("msg", m_sms_message);
SMSInfo.putExtra("num", m_dest_number );
PendingIntent sentPI = PendingIntent.getBroadcast(m_context, 0,
SMSInfo, PendingIntent.FLAG_CANCEL_CURRENT);
m_context.registerReceiver(new BroadcastReceiver(){
@Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode()){
case Activity.RESULT_OK:
Toast.makeText(m_context, String.format(
m_context.getResources().getString(R.string.sms_success),
arg1.getExtras().getString("msg"),
arg1.getExtras().getString("num")),
Toast.LENGTH_LONG).show();
break;
default:
Toast.makeText(m_context, String.format(
m_context.getResources().getString(R.string.sms_error),
arg1.getExtras().getString("msg"),
arg1.getExtras().getString("num")),
Toast.LENGTH_LONG).show();
break;
}
}
}, new IntentFilter(SMS_REQUEST_OK));
SmsManager.getDefault().sendTextMessage(
m_dest_number,
null,
m_sms_message,
sentPI,
null);
I expect it to try to send SMS one time, and then show Toast message with result of this operation. It works fine if SMS is sent successfully, however if it's not it keeps retrying to send it, judging on lots of Toast messages (it occurs on HTC Desire (S), testing it on Samsung doesn't get this behaviour - Toast with error is shown once).
So - is it how SmsManager should behave and how to avoid it (so that it try to send SMS only one time)?
edit I forgot to mention - it happens if getResultCode() returns 133404, haven't tested it on other errors
edit2 According to this, 133404 is htc-specific error, which means temporary failure and device will retry automatically, untill, eventually, proper result code is received and broadcast is sent. However, no SmsManager-documented broadcast is received within resonable time. So the question remains - is there a way to stop this retry attempts?
A: Just to summarize what I've found out: according to android documentation, expected behaviour of sendTextMessage() is only one attempt to send message, and broadcasting result afterwards. However, some HTC devices keep retrying to send message, broadcasting "temporary error" code after each attempt. So if app is only checking whether result code is "successfull" or not (as lots of sms applications on android market seem to do), it will mark message as unsent and stop listenning to it (which suits expected behaviour of sendTextMessage() function), which may lead to marking message unsent, when actually it was sent successfully in later attempt.
What's worse is that documented code might never be sent - so, if you get one of HTC "temporary codes" (133404 or 133179, there might be more however) message status is indetermined - it might be sent some time later, or might never be sent. So as it seems to me you can only determine message status by keeping listening for broadcast until you get proper result code (which may never be sent), or judging on delivery broadcast.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526179",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Reconciling outputs of jconsole and top I am trying to look at memory management in Java. I have a program that creates a large collection (~500MB). I run java without any special arguments. Once this collection goes out of scope, I invoke the garbage collector using System.gc(). From jconsole, I can see that the heap memory in use is dramatically reduced. The same cannot be said of the RES output of the top linux command.
My only interpretation is that once the JVM gets hold of memory, it does not release it to the system as long as it is running. Is this correct?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526181",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Git ssl error on windows I keep getting the following error when attempting to clone a git repository using ssl on windows:
error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed
The ssl certificate hierarchy is trusted (the issuer certificate is added to Trusted Root Certificate Authorities) and I can browse to the hosting site (a private instance of Gitorious) without ssl errors. I've tried cloning on Windows 7 and on Windows Server 2008 and it's failed both times.
Anyone got any ideas?
A: Git Apparently not take certificates saved in windows, you have to specify what editing the path to the certificate file .gitconfig
gitconfig location:
C:\Program Files (x86)\Git\etc
Add the line (replace with the path to file and yourCertificate.ctr with the name to your certificate):
.
.
.
[help]
format = html
[http]
sslVerify = true
sslCAinfo = C:/Program Files (x86)/Git/bin/curl-ca-bundle.crt
sslCAinfo = [route]/yourCertificate.crt
[sendemail]
smtpserver = /bin/msmtp.exe
[diff "astextplain"]
.
.
.
and try again..
A: The location of http.sslcainfo is stored in "C:\ProgramData\Git\config".
It is not altered when uninstalling/reinstalling git.
I recently had to change it from
sslCAInfo = C:/Program Files/Git/mingw64/ssl/certs/ca-bundle.crt
to
sslCAInfo = C:/Users/kristof/AppData/Local/Programs/Git/mingw64/ssl/certs/ca-bundle.crt
Also see issue:
Configure http.sslcainfo in Git for Windows' own system-wide config #531
https://github.com/git-for-windows/git/issues/531
A: Make sure to add to your Git global config file:
http.sslcainfo=/bin/curl-ca-bundle.crt
Your msysgit instance needs to know where to look for the CA certificates in order to validate them.
See more settings in this SO answer or in "Cannot get Http on git to work".
A: If all else fails, you can set the environment variable GIT_SSL_NO_VERIFY to true. However, it is hopefully possible to resolve the issue in another way. WARNING: This exposes you to SECURITY RISKS, as you can no longer trust that you're talking to the server you think you're talking to.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526182",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: How could I display a crosshair cursor with x-y coordinates when hovering over an image? I have an image inside a div on which users can click.
Is there a way to display the coordinates of the cursor when hovering over that image in realtime? I know that to display a crosshair cursor, the cursor type has to be set: cursor: crosshair- but how could I display those coordinates as well?
A: Try:
$(function () {
$('#hover-img')
// show the coordinates box on mouseenter
.bind('mouseenter', function () {
$('#coordinates').show();
})
// hide it on mouseleave
.bind('mouseleave', function () {
$('#coordinates').hide();
})
// update text and position on mousemove
.bind('mousemove', function (evt) {
$('#coordinates').html(
(evt.pageX - this.offsetLeft) + '/' + (evt.pageY - this.offsetTop)
).css({
left: evt.pageX + 20,
top: evt.pageY + 20
})
});
});
Note: see the » demo for the html-elements used.
A: <html>
<head>
<script>
function onMouseOver(Sender,e){
var x = e.x - Sender.offsetLeft;
var y = e.y - Sender.offsetTop;
document.getElementById('coord').innerHTML = x+"-"+y;
}
</script>
</head>
<body>
<img src="image.jpg" onmousemove="onMouseOver(this,event)">
<span id='coord'></span>
</body>
</html>
A: With jQuery you can do:
<script language="text/javascript">
$('#your_image').mouseover(function(e){
var x = e.pageX - this.offsetLeft;
var y = e.pageY - this.offsetTop;
alert("X: " + x + " Y: " + y);
});
</script>
A: <html>
<head>
<script type="text/javascript">
function getAbsoluteOffset(htmlelement) {
var offset={x:htmlelement.offsetLeft,y:htmlelement.offsetTop};
while(htmlelement=htmlelement.offsetParent)
{
offset.x+=htmlelement.offsetLeft;
offset.y+=htmlelement.offsetTop;
}
return offset;
}
function image_onmouseout(ev) {
document.getElementById("mouseinfo").innerHTML="Mouse outside of image";
}
function image_onmousemove(ev) {
var offset=getAbsoluteOffset(this);
document.getElementById("mouseinfo").innerHTML=
"Coordinates in page: (x: "+ev.clientX+",y:"+ev.clientY+")"+
"<br/>"+
"Coordinates in image: (x: "+(ev.clientX-offset.x)+",y:"+(ev.clientY-offset.y)+")";
}
</script>
</head>
<body>
<div style="width:400px;height:400px;background:red;">
<img src="image.png"
onmouseout="image_onmouseout.call(this,event);"
onmousemove="image_onmousemove.call(this,event);" />
</div>
<span id="mouseinfo">Mouse outside of image</span>
</body>
</html>
example: http://jsfiddle.net/HWMtc/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526186",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: When to remove TFS 2010 automatically created Workspaces Since almost one year we are running CI builds on our build machine. And the TFS creates a new workspace (ws) for each build, meanwhile we have many ws'.
So my questions (I didn't find a hint in the docs, though):
*
*Should we remove these "stale" ws' manually?
*Or is there any automatism in the TFS, so that it can handle or reuse these ws' somewhen? - Maybe configurable?
Thanks in advance.
A: These workspaces seem worthless, I wouldn't know how to make any use for them.
Using TF-Sidekicks (the "Workspace"-sidekick) & entering in the search criteria the name of the build-server it is possible to get a list of all those, now useless, workspaces.
We do this every one to two weeks, usually as part of the end-of-iteration cleanup.
I suspect that it shouldn't be hard to implement a console-app do this, I just haven't gotten round to investigate it. I could support in that, if you like.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526188",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Empty Popup window for datagridcell I'm using a Popup (System.Windows.FrameworkElement.Popup) to display a note to the user if e.g.
he exceeds the maximum string length in a text box.
I'm using the PlacementTarget property to assign a frameworkElement to make sure that the Popup is displayed near the corresponding control and not near to the mouse pointer.
Everything is working fine for a normal textBox, but using a popup in a datagrid poses a problem.
Using the popup with PlacementTarget = theDataGrid is working but the popup is displayed at the left upper corner of the datagrid
(with Placement = PlacementMode.Left) but I want to display the popup near the cell that triggers the display of the popup.
Now I am using the following code to determine the corresponding DataGridCell:
static DataGridCell TryToFindGridCell(DataGrid grid, DataGridCellInfo cellInfo)
{
DataGridCell result = null;
DataGridRow row = (DataGridRow)grid.ItemContainerGenerator.ContainerFromItem(cellInfo.Item);
if (row != null)
{
int columnIndex = grid.Columns.IndexOf(cellInfo.Column);
if (columnIndex > -1)
{
DataGridCellsPresenter presenter = VisualTreeHelperMethods.GetVisualChild<DataGridCellsPresenter>(row);
result = presenter.ItemContainerGenerator.ContainerFromIndex(columnIndex) as DataGridCell;
}
}
return result;
}
which seems to work fine, but using the DataGridCell (which is a FrameworkElement in contrast to DataGridCellInfo) has the effects, that
*
*the popup is displayed at the correct location, near the DataGridCell
*but is empty
Can anybody help or explain why the popup is empty?
For now I stick to displaying the popup with PlacementTarget = theDataGrid which is however a bit unsatisfactory.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526190",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: keeping focus on iframe at all times with jquery I've got an HTML page with an header, a footer, a simple menu and a large iframe (yeah, i know it's sad..)
I need to keep the focus on the iframe at all times (there are keypress events on it), even when clicking on the external parts of the page...
The catch is that i can't access any of the content of the iframe (external site)
How can i accomplish this ? i've been thinking about something like this:
function setFoc(){
$('#IFRAMEID').focus();
}
setInterval('setFoc()',200)
but i don't like it, it's a really ugly thing to do...
thankssss !
SOLVED: see example here http://jsfiddle.net/GrqkT/1/
A: Setting click event handler to the body should do the trick.
$("body").click(function(){
$('#IFRAMEID').focus();
});
It really depeneds on what element are there outside the iframe.
Maybe it would be better to rewrite event handlers and send them to iframe?
EDIT:
It won't override other handlers.
See example in fiddle here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526191",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: refer to html-button in ExtJS file In a jsp file, a form is created wherein a button is specified.
I am using ExtJS 4.
I need to get reference of the html-button in ExtJS file.
On click of this html-button, display the Ext components(grid panel) on the page.
I tried using Ext.DomQuery but no luck. Please provide pointers
Also posted at ExtJS4 forums http://www.sencha.com/forum/showthread.php?148205-refer-to-html-button-in-ExtJS-script&p=652122
Thanks,
-Divya
code snippet below:
report.jsp
<%@ page import="java.util.*" %>
<%@ page import="java.io.PrintWriter" %>
<%
some java code
%>
<link rel="stylesheet" type="text/css"
href="../js/extjs4/resources/css/ext-all.css" />
<link rel="stylesheet" type="text/css" href="../js/extjs4/shared/example.css" />
<script type="text/javascript" src="../js/extjs4/bootstrap.js"></script>
<script type="text/javascript" src="../js/extjs4_scripts/report/reportPanel.js">
</script>
<form name="reportpage" id="prcr" method="post" action="url">
<table>
<tr>
<td>
<input id=\"osSubmitButton\" type=\"button\" name=\"submitRelease\" value=\"Submit\">
</td>
</tr>
</table>
</form>
reportPanel.js
Ext.Loader.setConfig({enabled: true});
Ext.Loader.setPath('Ext.ux', '../extjs4/ux/');
Ext.require([
'Ext.DomQuery.*',
'Ext.data.*',
'Ext.grid.*',
'Ext.tree.*',
'Ext.util.*',
'Ext.toolbar.Paging',
'Ext.ux.grid.FiltersFeature',
'Ext.tip.QuickTipManager'
]);
Ext.onReady(function() {
Ext.tip.QuickTipManager.init();
var btn=Ext.query("#osSubmitButton");
btn.on("click", function(){
console.info("clicked");
relstore.load();
reportPanel.setVisible(true);
});
});
A: Since you know the id of the button you can just call Ext.get.
Ext.get('osSubmitButton').on('click', ...);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526192",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Does System.Threading.Timer rely on system time being correct? I have a service which runs a job every 30 minutes based on a System.Threading.Timer. The timer is setup with an interval as usual and fires the job off asynchronously.
Last night the time on the server it resides on decided to reset itself to something completely different to the actual time & date. Subsequently, my jobs did not run every 30 minutes - infact they completely stopped.
However, upon resetting the time this morning the next 30 minute task ran itself (30 minutes later) and then ALL of the other tasks ran themselves at the same time as if they had been queuing all night.
Can anyone shed any light on this?
EDIT: As an update - using the other timer (System.Timers.Timer) and exactly the same thing happened. Time changes to something completely different, service then stops completing its tasks until the time is subequently reset in the morning and then 30mins later it runs ALL of the tasks which should have run every 30 mins since the time changed!
A: I can't replicate a scenario that results in this.
Using this code
class Program
{
private static Timer timer;
private static readonly Stopwatch stopwatch = new Stopwatch();
static void Main(string[] args)
{
timer = new Timer(Tick);
stopwatch.Start();
timer.Change(30000, Timeout.Infinite);
Console.ReadLine();
}
private static void Tick(object obj)
{
stopwatch.Stop();
Console.WriteLine(stopwatch.Elapsed.Seconds);
}
}
I start the app, change my local computer time to 20 seconds in the future. The Tick method is still called 30 seconds after I started the app. The stopwatch says 30 and my mobilephone timer says 30.
A: I think that's because the Timer queues callbacks for execution by thread pool threads and maybe it schedules the callback for an actual time in the future and not an interval.
@GertArnold's answer is correct you should use System.Timers.Timer instead because it raises the Elapsed event, based on the value of the Interval property.
A: Since you tried all relevant built-in options regarding timers only the following options are left:
*
*use Sleep - this is something I see as bad practice BUT in your specific case should solve the problem desribed
*find some 3rd-party timer library and test it with your rather special cicumstances...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526199",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: how to set an OnTouchListener for a PopupWindow? Here's my code that shows a PopUp when the button is touched and dismisses it, when the user releases his finger.
But I need to know weather the user had just released his finger or did he slide into the popup and release his finger from there.
In my code this doesn't really work, since I guess the popup doesn't get focus without the user releasing his finger. Is there a way to fix it?
Thanks!
LinearLayout LinLay = new LinearLayout(this);
ImageView ivg = new ImageView(this);
ivg.setImageResource(R.drawable.icon);
LinLay.addView(ivg);
final PopupWindow pw = new PopupWindow(LinLay, 100, 100, true);
final Button bt2 = (Button)findViewById(R.id.button2);
bt2.setOnTouchListener(new OnTouchListener(){
@Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN )
{
pw.showAtLocation(bt2, Gravity.CENTER, 0, 0);
}
else if(event.getAction() == MotionEvent.ACTION_UP )
{
pw.dismiss();
}
return true;
}
});
ivg.setOnTouchListener(new OnTouchListener(){
@Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_UP )
{
showToast(); /// doesn't work! :)
}
return true;
}
});
}
public void showToast()
{
Toast.makeText(this, "AAA!", 500).show();
}
A: To use imageview and imageview onclick() to display showpopoup() window
im = new ImageView(this);
im.setImageResource(R.drawable.btn);
im.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
showPopup(R.layout.popup_example);
}
});
and
private void showPopup(int resourses) {
final LayoutInflater inflate = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflate.inflate(resourses, null, false);
ViewGroup viewgroup = (ViewGroup) view
.findViewById(R.id.buttonContainer);
LinearLayout layout = new LinearLayout(this);
view.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View arg0, MotionEvent arg1) {
mPopup.dismiss();
return true;
}
});
mPopup = new PopupWindow(view, 160, LayoutParams.FILL_PARENT, true);
mPopup.setAnimationStyle(android.R.style.Animation_InputMethod);
mPopup.showAtLocation(view, Gravity.LEFT, 0, 10);
}
A: obviously ,it does not work. message send as follow:
ACTION_DOWN
*
*activity :dispatch touch event
*activity :onUserInteraction
*layout :dispatch touch event
*layout :onInterceptTouchEvent
*button :onTouch(action_down)
ACTION_UP
*
*activity :dispatch touch event
*layout :dispatch touch event
*layout :onInterceptTouchEvent
*button: ontouch..
so you can see the method can only be transfer to up view.
imageview is the same level to the button..
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526200",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: MySQL syntax error in selecting multiple columns with the WHERE delimiter? I have a rather simple query to work with my ajax app, but it gives the following error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'desc, price FROM products WHERE id='asfasfasf1'' at line 1
I'm stumbled by this as I simply can't see the syntax error anywhere:
echo json_encode($this->query("SELECT name, desc, price FROM products WHERE id='".$id."';"), JSON_FORCE_OBJECT);
query() is as follows:
function query($query){
$link = mysql_connect($this->host, $this->username, $this->password);
$connected = mysql_select_db($this->database, $link);
if(!$connected){
die("Error: selecting database.");
}
$q = mysql_query($query);
if(!$q){
return "Error: ".mysql_error();
}
$result = mysql_fetch_assoc($q);
return $result;
}
Naturally, this is inside an object, but that shouldn't have anything to do with it. All the fields are correct, database can be connected to since the query() is used multiple times with other code and works well. Please help.
A: desc is a keyword in SQL (for sorting in descending order.) If you're going to use it as a column name, try quoting it:
$this->query("SELECT name, `desc`, price FROM products WHERE id='".$id."';")
See the MySQL manual on reserved words for an almost identical example, and more details on how to deal with keywords.
Or you could just rename your column to "description", say. Much as quoting is the "right" solution, it's generally helpful to avoid using reserved words as column names if you can.
A: There's a good chance id has to be in double quotes, not single ones.
BTW, be careful with this sort of thing because it makes SQL injection attacks really easy.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526207",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Ruby Mysql - Failed to allocate memory error I have a large MySQL table of about 4 million rows, which I want to process with a ruby script. At the moment, when I run the script I get a "failed to allocate memory (NoMemoryError)". The query runs but the error pops up once I try to loop through the resultset. Can I allocate more memory to the ruby heap space?
Currently, I am thinking of saving the resultset to a large file and the processing that file in chunks.
Any suggestion on an alternative course of action?
Thanks all,
s
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526208",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to add Pushpin Onclick Event? I am using the below code to disaply multiple pushpins from an XML file. I would like to know how I setup an tap event for each pushpin that will pass a value
foreach (var root in Transitresults)
{
var accentBrush = (Brush)Application.Current.Resources["PhoneAccentBrush"];
var pin = new Pushpin
{
Location = new GeoCoordinate
{
Latitude = root.Lat,
Longitude = root.Lon
},
Background = accentBrush,
Content = root.Name
};
BusStopLayer.AddChild(pin, pin.Location);
}
}
A: What you have is pretty close, try this:-
foreach (var root in Transitresults)
{
var accentBrush = (Brush)Application.Current.Resources["PhoneAccentBrush"];
var pin = new Pushpin
{
Location = new GeoCoordinate
{
Latitude = root.Lat,
Longitude = root.Lon
},
Background = accentBrush,
Content = root.Name,
Tag = root
};
pin.MouseLeftButtonUp += BusStop_MouseLeftButtonUp;
BusStopLayer.AddChild(pin, pin.Location);
}
}
void BusStop_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
var root = ((FrameworkElement)sender).Tag as BusStop;
if (root != null)
{
// You now have the original object from which the pushpin was created to derive your
// required response.
}
}
A: From MSDN page for PushPin events you can see that Tap event is available and so you can register a handler:
pin.Tap += args => { /* do what you want to do */ };
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526211",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Sending mail with PHP Imap I could retrieve mails from Gmail server on localhost using PHP Imap, but I could not send one. I already try with functions imap_mail() and mail() Could you tell me how? or any thing is required such as mail server?
Thanks!
A: Nearly nobody uses or supports sending mail with IMAP. Use SMTP to send mails out.
A: Here is a tutorial with some helpful comments, about specifying novalidate-cert (although I agree with cweiske).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526215",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Detecting a bad item inserted into a std::set Say I have a custom type in my set, and the set/ordering only makes sense if all items have the same value on some property... if an item with a different value is inserted the model is screwed up and I want to protect this.
I thought maybe the comparison function might be a place we could test this (as an assert or exception) to either flag the problem and/or prevent the item getting inserted. e.g on TypeName, operator<() always returns false if the important attribute isn't equal.
Is this reasonable?
A: I guess putting it in the comparator could have issues as you've not got any guarantees when it's going to be called. Perhaps some mythical implementation stores items in a list when the number of items is small and doesn't call the comparator until later?
Probably the simplest approach would be to wrap the std::set in a protective outer class that performed these assertions.
class MySet {
private:
std::set<myFunkyType> myType;
public:
void insert(myFunkyType type) {
assert(!type.isFunky(), "funk violation");
// and so on
}
// all other members other than insertion or mutation just delegate to the
// underlying set
}
A: If your std::set is an implementation detail of a custom class then it should be up to your class's public member functions to ensure that invalid elements aren't inserted in your set. Otherwise, if you need a data structure to pass a collection of your objects around use a std::map instead, provide your class with a key generating function and put your error detection code there.
Remember that set elements, as map keys, should be immutable with respect to their ordering; basing ordering on mutable state smells bad.
A: The operator< idea sounds a bit fishy. It would merely mean that such elements are ordered last. x is the largest element iff x<y==false for all y, and x<x==false must always hold. But if that's acceptable to you, it's OK.
A: When in your op< you detect that you can not establish a strict weak ordering, the only reasonable thing is to throw an exception. Any kind of insert, or possible other return from op< will likely break the internal constraints of the set.
Wrapping is IMHO not really necessary, since the behaviour of your wrapped insert() would probably be the same (that is, throw an exception).
The only thing that might make wrapping more attractive is any uncertainty about whether your standard library implementation is good enough to be able to cope with a throwing comparator. I doubt that many standard library implementations are strong on exception safety at that operation.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526217",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do I know if a table is an array? I'm developing a simple optimized JSON function. Lua uses tables to represent arrays but in JSON I need to recognize between them. The code below is used:
t={
a="hi",
b=100
}
function table2json(t,formatted)
if type(t)~="table" then return nil,"Parameter is not a table. It is: "..type(t) end
local ret=""--return value
local lvl=0 --indentation level
local INDENT=" " --OPTION: the characters put in front of every line for indentation
function addToRet(str) if formatted then ret=ret..string.rep(INDENT,lvl)..str.."\n" else ret=ret..str end end
addToRet("{")
lvl=1
for k,v in pairs(t) do
local typeof=type(v)
if typeof=="string" then
addToRet(k..":\""..v.."\"")
elseif typeof=="number" then
addToRet(k..":"..v)
end
end
lvl=0
addToRet("}")
return ret
end
print(table2json(t,true))
As you can see in JSON reference an object is what is called a table in Lua and it's different from an array.
The question is how I can detect if a table is being used as an array?
*
*One solution of course is to go through all pairs and see if they only have numerical consecutive keys but that's not fast enough.
*Another solution is to put a flag in the table that says it is an array not an object.
Any simpler/smarter solution?
A: The simplest algorithm to differentiate between arrays/non-arrays is this one:
local function is_array(t)
local i = 0
for _ in pairs(t) do
i = i + 1
if t[i] == nil then return false end
end
return true
end
Explanation here: https://web.archive.org/web/20140227143701/http://ericjmritz.name/2014/02/26/lua-is_array/
That said, you will still have issues with empty tables - are they "arrays" or "hashes"?
For the particular case of serializing json, what I do is marking arrays with a field in their metatable.
-- use this when deserializing
local function mark_as_array(t)
setmetatable(t, {__isarray = true})
end
-- use this when serializing
local function is_array(t)
local mt = getmetatable(t)
return mt.__isarray
end
A: Here is more simplest check based on Lua specific #len function mechanism.
function is_array(table)
if type(table) ~= 'table' then
return false
end
-- objects always return empty size
if #table > 0 then
return true
end
-- only object can have empty length with elements inside
for k, v in pairs(table) do
return false
end
-- if no elements it can be array and not at same time
return true
end
local a = {} -- true
local b = { 1, 2, 3 } -- true
local c = { a = 1, b = 1, c = 1 } -- false
A: No there is no built-in way to differentiate, because in Lua there is no difference.
There are already existing JSON libraries, which probably already do this (eg. Lua CJSON.
Other options are
*
*leave it up to the user to specify what type the argument is, or as what type he'd want to have it treated.
*have arrays explicitly declared by arranging the __newindex such that only new numerical and subsequent indices are allowed to be used.
A: @AlexStack
if not t[i] and type(t[i])~="nil" then return false end
This code is wrong, if fails when one of the elemets is false.
> return isArray({"one", "two"})
true
> return isArray({false, true})
false
I think the whole expression can be changed to type(t[i]) == nil but it still will fail in some scenarios because it will not support nil values.
A good way to go, I think, is trying with ipairs or checking whether #t is equal to count, but #t returns 0 with objects and count will be zero with empty arrays, so it may need an extra check at the beginning of the function, something like: if not next(t) then return true.
As a sidenote, I'm pasting another implementation, found in lua-cjson (by Mark Pulford):
-- Determine with a Lua table can be treated as an array.
-- Explicitly returns "not an array" for very sparse arrays.
-- Returns:
-- -1 Not an array
-- 0 Empty table
-- >0 Highest index in the array
local function is_array(table)
local max = 0
local count = 0
for k, v in pairs(table) do
if type(k) == "number" then
if k > max then max = k end
count = count + 1
else
return -1
end
end
if max > count * 2 then
return -1
end
return max
end
A: You can simply test this (assuming t is a table):
function isarray(t)
return #t > 0 and next(t, #t) == nil
end
print(isarray{}) --> false
print(isarray{1, 2, 3}) --> true
print(isarray{a = 1, b = 2, c = 3}) --> false
print(isarray{1, 2, 3, a = 1, b = 2, c = 3}) --> false
print(isarray{1, 2, 3, nil, 5}) --> true
It tests if there is any value in the "array part" of the table, then checks if there is any value after that part, by using next with the last consecutive numeric index.
Note that Lua does some logic to decide when to use this "array part" and the "hash part" of the table. That's why in the last example the provided table is detected as an array: it is dense enough to be considered an array despite the nil in the middle, or in other words, it is not sparse enough. Just as another answer here mentions, this is very useful in the context of data serialization, and you don't have to program it for yourself, you can use Lua underlying logic. If you would serialize that last example, you could use for i = 1, #t do ... end instead of using ipairs.
From my observation in Lua and LuaJIT implementation, the function next always looks up the array part of the table first, so any non array index will be found after the whole array part, even though after that it doesn't follow any particular order. I'm not sure if this is a consistent behaviour across different Lua versions, though.
Also, it's up to you to decide if empty tables should be treated as arrays as well. In this implementation, they are not treated as arrays. You could change it to return next(t) == nil or (#t > 0 and next(t, #t) == nil) to do the opposite.
Anyway, I guess this is the shortest you can get in terms of code lines and complexity, since it is lower bounded by next (which I believe is either O(1) or O(logn)).
A: Thanks. I developed the following code and it works:
---Checks if a table is used as an array. That is: the keys start with one and are sequential numbers
-- @param t table
-- @return nil,error string if t is not a table
-- @return true/false if t is an array/isn't an array
-- NOTE: it returns true for an empty table
function isArray(t)
if type(t)~="table" then return nil,"Argument is not a table! It is: "..type(t) end
--check if all the table keys are numerical and count their number
local count=0
for k,v in pairs(t) do
if type(k)~="number" then return false else count=count+1 end
end
--all keys are numerical. now let's see if they are sequential and start with 1
for i=1,count do
--Hint: the VALUE might be "nil", in that case "not t[i]" isn't enough, that's why we check the type
if not t[i] and type(t[i])~="nil" then return false end
end
return true
end
A: If you want fast, simple, non-intrusive solution that will work most of the times, then I'd say just check index 1 - if it exists, the table is an array. Sure, there's no guarantee, but in my experience, tables rarely have both numerical and other keys. Whether it's acceptable for you to mistake some objects for arrays and whether you expect this to happen often depend on your usage scenario - I guess it's not good for general JSON library.
Edit: For science, I went to see how Lua CJSON does things. It goes through all pairs and checks if all keys are integers while keeping the maximum key (the relevant function is lua_array_length). Then it decides whether to serialize the table as an array or object depending on how sparse the table is (the ratio is user controlled) i.e. a table with indices 1,2,5,10 will probably be serialized as an array while a table with indices 1,2,1000000 will go as an object. I guess this is actually quite good solution.
A: I wrote this function for pretty printing lua tables, and had to solve the same problem. None of the solutions here account for edge cases like some keys being numbers but others not. This tests every index to see if it's compatible with being an array.
function pp(thing)
if type(thing) == "table" then
local strTable = {}
local iTable = {}
local iterable = true
for k, v in pairs(thing) do
--if the key is a string, we don't need to do "[key]"
local key = (((not (type(k) == "string")) and "["..pp(k).."]") or k)
--this tests if the index is compatible with being an array
if (not (type(k) == "number")) or (k > #thing) or(k < 1) or not (math.floor(k) == k) then
iterable = false
end
local val = pp(v)
if iterable then iTable[k] = val end
table.insert(strTable, (key.."="..val))
end
if iterable then strTable = iTable end
return string.format("{%s}", table.concat(strTable,","))
elseif type(thing) == "string" then
return '"'..thing..'"'
else
return tostring(thing)
end
end
A: This is not pretty, and depending on how large and cleverly-deceptive the table is, it might be slow, but in my tests it works in each of these cases:
*
*empty table
*array of numbers
*array with repeating numbers
*letter keys with number values
*mixed array/non-array
*sparse array (gaps in index sequence)
*table of doubles
*table with doubles as keys
function isarray(tableT)
--has to be a table in the first place of course
if type(tableT) ~= "table" then return false end
--not sure exactly what this does but piFace wrote it and it catches most cases all by itself
local piFaceTest = #tableT > 0 and next(tableT, #tableT) == nil
if piFaceTest == false then return false end
--must have a value for 1 to be an array
if tableT[1] == nil then return false end
--all keys must be integers from 1 to #tableT for this to be an array
for k, v in pairs(tableT) do
if type(k) ~= "number" or (k > #tableT) or(k < 1) or math.floor(k) ~= k then return false end
end
--every numerical key except the last must have a key one greater
for k,v in ipairs(tableT) do
if tonumber(k) ~= nil and k ~= #tableT then
if tableT[k+1] == nil then
return false
end
end
end
--otherwise we probably got ourselves an array
return true
end
Much credit to PiFace and Houshalter, whose code I based most of this on.
A: At least in luajit 2.1.0-beta3 (where I tested it), I reliably get sorted iteration with pairs() for numerical indices, therefore this should also work and could be a bit faster than https://stackoverflow.com/a/25709704/7787852
Even if the Lua reference manual says explicitly that the iteration order of pairs cannot be relied upon.
local function is_array(t)
local prev = 0
for k in pairs(t) do
if k ~= prev + 1 then
return false
end
prev = prev + 1
end
return true
end
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526223",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "20"
} |
Q: reverse link list using recursion I am trying to reverse a link list using recursion. I have written a function "reverse(node* ptr) for this
I am getting output as 40 40 20 while i expect output to be 40 , 20 , 10.
below is the code posted.
class list {
//some code;
void reverse()
{
node* temp = new node;
temp =first;
reverse(temp);
temp =NULL;
delete temp;
}
void reverse(node* ptr) {
if(ptr->next != NULL)
{
ptr =ptr->next;
reverse(ptr);
}
cout << ptr->data << endl;
}
// some code;
};
int main()
{
list ll;
ll.insert(18);
ll.insert(20);
ll.insert(40);
ll.display();
ll.reverse();
return 0;
}
please suggest what I am doing wrong here.
Thanks
A: Before even talking about the linked list, there is a major problem with your code:
void reverse()
{
node* temp = new node;
temp =first;
reverse(temp);
temp =NULL;
delete temp;
}
You allocate space for a node and then change what it is pointing to, to first. This means the memory you allocated will be leaked. Not only that but you then set it to NULL and then try to free it. You can't free NULL!
I believe you simply meant:
void reverse()
{
reverse(first);
}
Simple. On to the linked list:
if(ptr->next != NULL)
{
ptr =ptr->next;
reverse(ptr);
}
You set ptr to the next element so when reverse() returns it will be one element ahead. I believe you meant:
if(ptr->next != NULL)
{
reverse(ptr->next);
}
A: You should get rid of the line ptr =ptr->next;.
The main objective is to print all the nodes that come after the current node before printing value of the current node. So simply a call to reverse(ptr->next) followed by a cout<<ptr->data<<endl should suffice, since the first call takes care of all nodes after ptr. There is no need to advance the pointer as we want to print the current node at the end.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526226",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Which is the fastest performing way to avoid n+1 issues and why? I'm looking to add some utility methods to help avoid a lot of n+1 issues in a legacy application.
The common pattern is this:
select a.* /* over 10 columns */
from [table-A] a
where /* something */
Retrieved into a collection of ClassA record instances
Then the sub-instances are lazy retrieved:
select b.* /* over 10 columns */
from [sub-table-B] b
where b.ParentId = @ClassA_ID
This results in an n+1 selects issue. Mostly this isn't a major problem as only a couple of ClassA instances are being retrieved on an infrequently hit page, but in an increasing number of places this n+1 issue causes the pages to become too slow as the application has scaled.
I'm looking to replace a part of the existing data access code of this application so that the ClassA instances and ClassB instances are retrieved together.
I think there are 3 ways this could be done:
1) Get the ClassA instances as we do now, then get the ClassB instances in one aggregated call:
select b.*
from [sub-table-B] b
where b.ParentId in ( /* list of parent IDs */ )
This is two separate DB calls, and the query plan of the dynamic SQL will not be cacheable (due to the list of IDs).
2) Get the ClassB instances with a sub query:
select b.*
from [sub-table-B] b
inner join [table-A] a
on b.ParentId = a.[ID]
where /* something */
This is also two DB calls, and query against [table-A] has to be evaluated twice.
3) Get all together and de-dupicate the ClassA instances:
select a.*, b.*
from [table-A] a
left outer join [sub-table-B] b
on a.[ID] = b.ParentId
where /* something */
This is just one DB call, but now we get the contents of [table-A] repeated - the result set will be larger and the time sending the data from the DB to the client will be more.
So really this is 3 possible compromises:
*
*2 DB calls, no query caching
*2 DB calls, complex query evaluated twice
*1 DB call, significantly larger result set
I can test these three patterns for any one parent-child pair of tables, but I have loads of them. What I want to know is which pattern is consistently quicker? More importantly why? Is one of these compromises an obvious performance-killer?
What do existing mechanisms like Linq, EF and NHibernate use?
Is there a 4th way that's better than all 3?
A: I think EF and L2S use your third approach - there is definitly just one db call.
Normally more db roundtrips take more time than less db roundtrips with bigger resultsets.
Maybe there are some edge cases where you have massive data in table A and the bigger resultset increases transfer time to the clien too much.
But thats mainly a question of latency and bandwith between db server and client.
A 4th way might be to write a stored proc which returns more than one resultset. One for each table you query with just the records you need. That fits to your 1st approach but reduced to one roundtrip. But that would complicate things a bit and is not as flexible as the other approaches.
A: In my opinion, "which is the fastest way" depends on the latency and bandwidth to your database server, and also how big are your resultsets.
In a scenario where latency is the bottleneck (ADSL network?), and if your resultsets are not huge, you better have send one single query to your server. Bandwidth used will be bigger, due to the fact [table-A] record are sent multiple times, but globally speaking this might be the fastest way to get your data to the client.
A: Most modern databases (Oracle for sure if you use parameterised queries) will cache the query evaluation and you will encounter very little hit on them.
Some ORMs like Django's will allow you to create a custom query and return only partial results that you need to render the page. This is a good approach - if you see a DB hotspot optimise it, but otherwise leave ORM to do its bidding.
Remember, hardware is cheap (two days of consultant's work cost the same as a server upgrade), regardless what your finance manager says.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526227",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: ExtJS 4 - How to display template having width greater than the width of combo-box?
I have a combo-box in which the values are being displayed in a template.
Now, I want the width of the template to be more than that of combo-box and hence I am using matchFieldWidth:false as mentioned at the link - ExtJS ComboBox dropdown width wider than input box width?
But when I do so, then in the list of values there is no scrollbar displayled due to which the user is able to see only the first two values. The complete list gets displayed as soon as matchFieldWidth:false is removed, but then the width of template is reduced to that of combo-box which is not what is wanted.
Below is my code:
xtype: 'combo',
id: 'testId',
name: 'testName',
displayField: 'vslCd',
valueField: 'vslCd',
fieldLabel: 'Vessel Code',
store: storeVesselCodeVar,
matchFieldWidth: false,
queryMode: 'remote',
listConfig: {
loadingText: 'Loading...',
width: 400,
autoHeight:true,
getInnerTpl: function () {
return '<table><tr><td height="5"></td></tr><tr valign="top"><td>Vessel Code:{vslCd}</td></tr><tr><td height="2"></td></tr><tr valign="top"><td>Vessel Name:{vslNm}</td></tr><tr><td height="5"></td></tr></table>';
}
}
Could anyone please suggest that what can be the reason behind this and how to resolve this? Attached is a screenshot related to the problem.
I am using this ExtJS4 and IE9.
A: This appears to be a bug in Ext 4.0.2a. When 'matchFieldWidth' is set to 'false', the dropdown list is not sized at all.
see Picker.js#alignPicker:
if (me.matchFieldWidth) {
// Auto the height (it will be constrained by min and max width) unless there are no records to display.
picker.setSize(me.bodyEl.getWidth(),
picker.store && picker.store.getCount() ? null : 0);
}
// note: there is no other occurence of setSize in this method
if 'matchFieldWidth' is false, picker.setSize is never called and the picker (= dropdown) is never seized.
A possible fix is to call setSize in any case, and just not apply a width if matchFieldWidth=true.
picker.setSize(me.matchFieldWidth ? me.bodyEl.getWidth() : null,
picker.store && picker.store.getCount() ? null : 0);
Note: setSize() will apply the configured maxWidth resp. maxHeight if the passed value is 'null'.
It's probably better to apply the patch without modifying the Ext source.
Ext.require('Ext.form.field.Picker', function() {
var Picker = Ext.form.field.Picker;
Picker.prototype.alignPicker = Ext.Function.createSequence(
Picker.prototype.alignPicker, function(width, height) {
if(this.isExpanded && !this.matchFieldWidth) {
var picker = this.getPicker();
picker.setSize(null, picker.store &&
picker.store.getCount() ? null : 0);
}
})
});
A: I have been able to resolve this issue by adding height to the template. Here is the final code:
xtype: 'combo',
id: 'testId',
name: 'testName',
displayField: 'vslCd',
valueField: 'vslCd',
fieldLabel: 'Vessel Code',
store: storeVesselCodeVar,
matchFieldWidth: false,
queryMode: 'remote',
listConfig: {
loadingText: 'Loading...',
width: 400,
height:300,
autoHeight:true,
getInnerTpl: function () {
return '<table><tr><td height="5"></td></tr><tr valign="top"><td>Vessel Code:{vslCd}</td></tr><tr><td height="2"></td></tr><tr valign="top"><td>Vessel Name:{vslNm}</td></tr><tr><td height="5"></td></tr></table>';
}
}
Hope this helps someone.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526232",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Manipulating Form.Action I have to use Form.Action to redirect to a script that will be picking up values from my page. It is worth noting that this script is external.
My issue is that I also want the button that is clicked and has the Action hooked up to it, to also complete some functionality in the code behind first.
Is there anyway I can either :
In the buttons click event handler, can I set the Form.Action and then call something such as Form.Submit?
OR
Set up the Form.Action in advance and then somehow have the button posting back before the action takes place.
If this is not possible, any pointers in the correct direction with how I can achieve this would be appreciated.
A: If the page does not need to do validation/processing on server side when user clicks the button then you can do it like,
In ASPX:
<asp:Button ID="btnSubmit" runat="server"
OnClientClick="$('form').get(0).setAttribute('action', 'ScriptActionUrl'); $('form').submit();"
Text="Submit">
</asp:Button>
If there is something to be processed/validated on server-side then do it like,
In ASPX:
<asp:Button ID="btnSubmit" runat="server" OnClick="btnSubmit_Click" Text="Submit">
</asp:Button>
In Page-behind-code:
protected void btnSubmit_Click(object sender, EventArgs e)
{
Page.Validate(); //Do Validation or some other processing
if(Page.IsValid)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), Guid.NewGuid().ToString(), "$('form').get(0).setAttribute('action', 'ScriptActionUrl'); $('form').submit();", true);
}
}
A: Is this a form that you care what the submitted form does? If all that must be done is for it to submit you can build the POST submitted data inside your button click event and send it off without ever redirecting the user and continue processing your code.
There is useful documentation on one way to do it here though there are several ways to do it.
Typically you would build your POST data with a builder then send it off. Here is an example:
// Create a new WebClient instance to send the data with
WebClient myWebClient = new WebClient();
// Collection to hold our field data
NameValueCollection postValues = new NameValueCollection();
// Add necessary parameter/value pairs to the name/value container.
postValues.Add("LoginName", tbLoginName.Text);
postValues.Add("Password", tbPassword.Text);
// Send off the message
byte[] responseArray = myWebClient.UploadValues("http://website.com", postValues);
// Decode and display the response.
tbResponse.Text = Encoding.ASCII.GetString(responseArray);
This code is just a mock up but it should point you in the right direction if this is the path you want to take.
A: You could do what you need to do in the code behind and then call Server.Transfer(string url,bool preserveFormVariables); to move the request to another page to handle.
You can then use Request.Form at the other page to get out the values you need.
A: This is quite possible by setting the PostBackUrl property for any button control (like asp.net button or link button). For a proof of concept do the following:
*
*Create an asmx web service project; Add one webmethod called SayHello. It will accept one argument - Username and return Hello <Username> to the calling client.
*Run this web service. Assume its url is something like http://localhost:6107/DemoAsmx/demo.asmx
*Open another VS instance. Create a normal web project. Add a aspx page. Add one textbox. Set its id to Username
*Add a button to the page. Set it PostbackUrl property to http://localhost:6107/DemoAsmx/demo.asmx/SayHello
*Run the web project. Now Enter a name in the textbox, and click the button. You will see the xml response from the asmx web service.
This can be done via javascript also. I hope this helps.
A: Since the page needs to submit to the page not under your control I would recommend creating a web service tied to the button click. Using code like the following you can create javascript events that occur before the page submits:
btnSubmit.Attributes.Add("onclick", "javascript:functionName()")
Replace functionName with the name of the function you are making your web service call in. This has the added ability to cancel the form's submission based upon the web service's results by doing:
return false;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526238",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: how to get source and destination latitude and longitude? hi all how to implement code for getting latitude and longitude when we enter the location address (i mean when i enter from address and to address into auto complete Textview.then i will get the latitude and longitude for from address and to address).so help me solve the problem.
A: You are looking for reverse Geo coding concept. And it is well explained here.
http://mobiforge.com/developing/story/using-google-maps-android
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<com.google.android.maps.MapView
android:id="@+id/mapView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:enabled="true"
android:clickable="true"
android:apiKey="0l4sCTTyRmXTNo7k8DREHvEaLar2UmHGwnhZVHQ"
/>
</RelativeLayout>
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.MapView.LayoutParams;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
public class MapsActivity extends MapActivity
{
MapView mapView;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mapView = (MapView) findViewById(R.id.mapView);
LinearLayout zoomLayout = (LinearLayout)findViewById(R.id.zoom);
View zoomView = mapView.getZoomControls();
zoomLayout.addView(zoomView,
new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
mapView.displayZoomControls(true);
}
@Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526240",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Add values to exsisting of a hash how can one insert additional values to an exsisting key of a hash in R.
h=hash()
h[key1] = "value1"
. ???
h[key1] = exsisting values + "value2" = c(values(h),"value2")
??
A: First of all it may be useful to indicate why you want to use hash in the first place. Standard R contains a dataformat list which is also a key - value store. Unless there is a very specific need to use a different system, the system with list is well documented and has many useful functions like lapply which may not exist for your package.
You seem to want to create what is called a multimap in C++. There is no need to use hash for that, you can do it by nesting lists Eg:
h<-list()
h[['key1']]<-list("value1")
h[['key1']]<-list(unlist(h[['key1']]),'value2')
str(h)
List of 1
$ key1:List of 2
..$ : chr "value1"
..$ : chr "value2"
If your values have the same datatype you don't even need the nested list:
h<-list()
h[['key1']]<-"value1"
h[['key1']]<-c(h[['key1']],'value2')
str(h)
List of 1
$ key1: chr [1:2] "value1" "value2"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526244",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-4"
} |
Q: jQuery .animate() not doing anything in IE8 I have a div of text (#text-write), each character of which is spanned. The div is absolutely positioned inside a relatively positioned container div (#typetext). Here's the effect intended:
*
*Animate inner div (#text-write) to opacity 0 for 400ms.
*Animate each span inside inner div one after the other to opacity 1 for 400ms each.
*Pause for 5 seconds.
*Go back to 1.
I simply can't make this work in IE8. It works in IE7 and below, IE9, other major and obscure (that i know of) browsers. I've been pulling my hair trying out everything I found on the net (add layout to the absolutely positioned inner div, play with filter, try fade, etc.) for the last 5 or so hours.
The logic is running (I tried inserting an alert in the recursive call, and IE8 does the alert for each spanned letter and in the exact timing, even the pause), no errors in console, either.
But nothing is happening to the opacity. It does not even disappear. It just stays there.
Can you help?
jQuery(function() {
// span each letter in text
var textType = jQuery('#text-write').remove().text(), textTypeLength = textType.length,
fadeSpeed = 400, fadePause = 5000,
textSpanned = '';
for (i=0;i<textTypeLength;i++) textSpanned += '<span>' + textType.charAt(i).replace(' ',' ') + '<\/span>';
jQuery('#typetext').append('<div id="text-write">'+ textSpanned + '<\/div>');
// fade phrase logic
function fadeType(){
var letters = jQuery('#text-write span').animate({opacity: 0}, fadeSpeed),
i=0;
(function(){
jQuery(letters[i++]).animate({opacity: 1}, fadeSpeed, arguments.callee);
})();
}
// make it happen
fadeType();
setInterval(function(){fadeType();},fadePause + fadeSpeed + (textTypeLength*fadeSpeed));
});
A: i found the answer over at http://api.jquery.com/fadeTo/#dsq-cite-119679059
the <span> elements i wanted to animate were of course inline. displaying them as inline-block finally did it for ie8. thanks much jeko, who found the solution over at http://www.devcomments.com/IE-8-fadeTo-problem-with-inline-elements-to65024.htm
posting here for anyone else out there who may need it and not waste as much time as i had.
A: As an addition, I was using animate to move items around with percentages. IE does not support percents. I switched animate from percentages to pixels and it worked just fine.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526251",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: stored procedure using like (MySQL) How can I use the LIKE statement in stored procedures (MySQL) ?
I tried both but I still get errors:
..WHERE Des_Articolo LIKE '%nome_art%';
..WHERE Des_Articolo LIKE'%',nome_art,'%';
nome_art is declared as
CREATE PROCEDURE ric_art (IN nome_art VARCHAR(100) , OUT msg VARCHAR(100))
Many thanks Roberto
A: Use CONCAT to concatenate strings:
WHERE Des_Articolo LIKE CONCAT('%', nome_art, '%');
Note: This type of query is slow. If performance is an issue, you may want to consider an alternative approach such as full-text searching.
A: you can use:
..Where Des_Articolo like CONCAT('%',nome_art,'%');
Bun Leap_kh
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526252",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: VB6's Boolean data type equivalent in MIDL Which MIDL data type is equal to the VB6's Boolean type?
A: According to MSDN Boolean is available in MIDL.
A: Finally I tried Boolean (as @Sohnee suggested), VARIANT_BOOL (thanks to @Alex K.) and BOOL.
The Boolean type was not recognized by VB6's Object Browser. The VARIANT_BOOL is the exact equivalent to a VB6's Boolean data type. The BOOL was recognizes as Long data type in VB6.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526254",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Unknown reference to __dlopen in dlopen dlopen is located in libdl.a but when I link my application against libdl.a , gcc linker throw this error : unknow reference to __dlopen called in dlopen
Should I import another .a?
A: You should be able to use the shared library libdl.so with
gcc -ldl ...
if you don't have a strong requirement on using the static version.
A: When I try to compile statically a dlopen mockup program, gcc (Archlinux/gcc version 4.6.1 20110819 (prerelease)) tells me:
$ gcc test.c -ldl -static
/tmp/ccsWe4RN.o: In function `main': test.c:(.text+0x13):
warning: Using 'dlopen' in statically linked applications requires
at runtime the shared libraries from the glibc version used for linking
and indeed, when I ran this script in /usr/lib/
for i in *.a;
do
echo $i;
readelf -a $i | grep __dlopen;
done
I saw:
libc.a
16: 0000000000000080 69 FUNC GLOBAL DEFAULT 1 __dlopen
000000000000 002300000001 R_X86_64_64 0000000000000000 __dlopen + 0
35: 0000000000000000 0 NOTYPE GLOBAL DEFAULT UND __dlopen
so as per the first line, libc.a does define your missing symbole.
In my system, gcc test.c -ldl -static is enough to make the application run, but
gcc <file> -static -ldl -lc
should fix the problem in your system.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526255",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.