text stringlengths 8 267k | meta dict |
|---|---|
Q: StringLength Mvc As you know there is a property called [StringLength] in model of mvc. I have a variable which is an int and I want to restrict it to maximum 4 characters. I need something like [IntLength]. Can you help me?
[Display(Name="Credit card number:")]
[RegularExpression(@"\d{4}")]
public int BookingCardNumberFirstFour { get; set; }
<%: Html.TextBoxFor(model => model.BookingCardNumberFirstFour, new {style="width:40px;"}) %>
A: You can use the range attribute.
[Range(0,9999)]
public int myInt { get; set;}
if you want them to enter exactly 4 digits use the regular expression attribute.
[RegularExpression(@"\d{4}")]
public int myInt {get; set;}
<%: Html.EditorFor(model => model.BookingCardNumberFirstFour, new {style="width:40px;"}) %>
<%: Html.ValidationMessageFor(model => model.BookingCardNumberFirstFour) %>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527310",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: android camera (froyo) doesnt include static method open() I must be the first to face this problem because I can't find even a single thread about it.
Today I wanted to start on the camera aspect of my application needs.
I read up some documentation
my manifest looks like this:
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
I wrote this in the manifest ABOVE <application> and underneath <manifest>
What im doing is; I have created a new class.
using eclipse as my IDE.
I then declare a field:
Camera _camera;
In the constructor(just to test)
I tried to do:
_camera = Camera.open();
I got an error.
I use my real phone to test the app, because I have no webcam or anytihng for the simulator to use. And the simulator gives me a memory error when I tell it to have a camera.
Anyway, upon finding out why I can't use Camera.open (I included the package: android.graphics.Camera;) Because that is what eclipse included for me when i used to organize imports function.
I looked into the android.jar that eclipse attached for me. Contained in a folder thingy called Android 2.2 -> android.jar
I searched for android.graphics and took a peek in the content of Camera.class
It turns out that my Camera class only has these methods:
Camera()
applyToCanvas()
dotWithNormal()
finalize()
getMatrix()
restore()
rotateX()
rotateY()
rotateZ()
save()
translate()
I intentionally let the parameters out because they are of no importance.
To get to the actual question: Why?
Why is there no open() method, no release() method? and whatever else im missing.. '
Thanks for reading.
Todays lesson: Don't be a smart **s. I was indeed 950% sure I included that specific package. But it was the wrong package. derp. Thanks fo notifying me. Issue is solved.
A: You are using the wrong Camera.
android.graphics.Camera - A camera instance can be used to compute 3D transformations and generate a matrix that can be applied, for instance, on a Canvas.
android.hardware.Camera - The Camera class is used to set image capture settings, start/stop preview, snap pictures, and retrieve frames for encoding for video. This class is a client for the Camera service, which manages the actual camera hardware.
A: You are using a wrong Camera class. Use this one http://developer.android.com/reference/android/hardware/Camera.html
You are using Camera from android.graphics.Camera I suppose you need the one from android.hardware.Camera
A:
(yes im 950% sure I have included the package:
android.graphics.Camera;)
You are looking for android.hardware.Camera.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527311",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can I convert datetime to date, truncating the times, leaving me the dates? I have a field that's in datetime format when date would be better and more consistent with the rest of the database, so I want to convert. The time part is all 00:00:00 anyway.
How can I do this in MySQL?
Thanks.
A: Cast it as a DATE:
select DATE(my_date_time)
That will truncate the time from it, leaving only the date part.
A: If you want this in a SELECT-Statement, just use the DATE Operator:
SELECT DATE(`yourfield`) FROM `yourtable`;
If you want to change the table structurally, just change the datatype to DATE (of course only do this if this doesn't affect applications depending on this field).
ALTER TABLE `yourtable` CHANGE `yourfield` `yourfield` DATE;
Both will eliminate the time part.
A: when using change we have to repeat the same name again for the field.now we can use MODIFY to alter the filed type.
ALTER TABLE `yourtable` MODIFY `yourfield` DATE;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527315",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "22"
} |
Q: Document filter is not working in Java? In text field more than 10 characters na, it has to show an error. For that i used document filter:
JTextField field = (JTextField) txtFld;
AbstractDocument document = (AbstractDocument) field.getDocument();
document.setDocumentFilter(new DocumentSizeAndUppercaseFilter(10));
So this is my document filter coding. I registered the textfield through document filter. But nothing has happening here. How to use document filter?
DocumentSizeAndUppercaseFilter class which has the error msg.
A: Without seeing the code for DocumentSizeAndUppercaseFilter I would suspect that you havn't implemented (/override) the DocumentFilter's replace method:
@Override
public void replace(DocumentFilter.FilterBypass fb, int offset,
int length, String text, AttributeSet attrs)
throws BadLocationException {
....
}
Screenshot from the code below:
Example implementation of DocumentSizeAndUppercaseFilter:
static class DocumentSizeAndUppercaseFilter extends DocumentFilter {
private final int max;
public DocumentSizeAndUppercaseFilter(int max) {
this.max = max;
}
@Override
public void insertString(DocumentFilter.FilterBypass fb, int offset,
String text, AttributeSet attr)
throws BadLocationException {
if (fb.getDocument().getLength() + text.length() < max)
super.insertString(fb, offset, text.toUpperCase(), attr);
else
showError();
}
@Override
public void replace(DocumentFilter.FilterBypass fb, int offset,
int length, String text, AttributeSet attrs)
throws BadLocationException {
int documentLength = fb.getDocument().getLength();
if (documentLength - length + text.length() < max)
super.replace(fb, offset, length, text.toUpperCase(), attrs);
else
showError();
}
private void showError() {
JOptionPane.showMessageDialog(null, "Too many characters entered");
}
}
Example main:
public static void main(String[] args) {
JTextField firstName = new JTextField();
AbstractDocument d = (AbstractDocument) firstName.getDocument();
d.setDocumentFilter(new DocumentSizeAndUppercaseFilter(10));
JFrame frame = new JFrame("Test");
frame.add(firstName);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200, 60);
frame.setVisible(true);
}
A: Start with something simple.
The section from the Swing tutorial on Implementing a Document Filter has a working example that does half of what you want.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527323",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Associating AutoComplete TextBox to Xml with WP7 Is there a way to create an autocomplete textBox using data from a xml file with WP7?
A: Yes, you read the XML file and use that data as the ItemsSource for the AutoCompleteBox.
It's not possible to pass raw XML, or the path to the file, to the AutoCompleteBox and have it automatically work out what to display.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527324",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: check all values in table or object i would like make somethings:
<?php
$a = array();
for ($i =0; $i<15; $i++){
$a[$i] = '111';
}
foreach ($a as $ok){
//if all values in $a == 111 : {
echo "all is 111"
} else {
echo "no";
}
}
?>
LIVE: http://codepad.org/RdvhK0VD
is function in PHP for this? i must each values check separately?
A: You can use array_count_values which will return an associative array of values and their frequencies.
If array_count_values($a) returns an array of length 1 and its key is '111', then $a contains only '111'.
$arr2 = array_count_values($a);
$key = '111';
if( count($arr2) == 1 && array_key_exists($key, $a) )
{
// $a contains only $key
}
A: <?php
$a = array();
for ($i =0; $i<15; $i++)
{
$a[$i] = '111';
}
$flag=true;
foreach ($a as $ok)
{
if ( $a != 111 )
{
$flat=true;
}
}
if(flag===true)
{
echo "all is 111"
} else {
echo "no";
}
?>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527330",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Binding JSON to nested Grails Domain Objects I'm developing a RESTful interface which is used to provide JSON data for a JavaScript application.
On the server side I use Grails 1.3.7 and use GORM Domain Objects for persistence. I implemented a custom JSON Marshaller to support marshalling the nested domain objects
Here are sample domain objects:
class SampleDomain {
static mapping = { nest2 cascade: 'all' }
String someString
SampleDomainNested nest2
}
and
class SampleDomainNested {
String someField
}
The SampleDomain resource is published under the URL /rs/sample/ so /rs/sample/1 points to the SampleDomain object with ID 1
When I render the resource using my custom json marshaller (GET on /rs/sample/1), I get the following data:
{
"someString" : "somevalue1",
"nest2" : {
"someField" : "someothervalue"
}
}
which is exactly what I want.
Now comes the problem: I try to send the same data to the resource /rs/sample/1 via PUT.
To bind the json data to the Domain Object, the controller handling the request calls def domain = SampleDomain.get(id) and domain.properties = data where data is the unmarshalled object.
The binding for the "someString" field is working just fine, but the nested object is not populated using the nested data so I get an error that the property "nest2" is null, which is not allowed.
I already tried implementing a custom PropertyEditorSupport as well as a StructuredPropertyEditor and register the editor for the class.
Strangely, the editor only gets called when I supply non-nested values. So when I send the following to the server via PUT (which doesn't make any sense ;) )
{
"someString" : "somevalue1",
"nest2" : "test"
}
at least the property editor gets called.
I looked at the code of the GrailsDataBinder. I found out that setting properties of an association seems to work by specifying the path of the association instead of providing a map, so the following works as well:
{
"someString" : "somevalue1",
"nest2.somefield" : "someothervalue"
}
but this doesn't help me since I don't want to implement a custom JavaScript to JSON object serializer.
Is it possible to use Grails data binding using nested maps? Or do I really heave to implement that by hand for each domain class?
Thanks a lot,
Martin
A: Since this question got upvoted several times I would like to share what I did in the end:
Since I had some more requirements to be implemented like security etc. I implemented a service layer which hides the domain objects from the controllers. I introduced a "dynamic DTO layer" which translates Domain Objects to Groovy Maps which can be serialized easily using the standard serializers and which implements the updates manually. All the semi-automatic/meta-programming/command pattern/... based solutions I tried to implement failed at some point, mostly resulting in strange GORM errors or a lot of configuration code (and a lot of frustration). The update and serialization methods for the DTOs are fairly straightforward and could be implemented very quickly. It does not introduce a lot of duplicate code as well since you have to specify how your domain objects are serialized anyway if you don't want to publish your internal domain object structure. Maybe it's not the most elegant solution but it was the only solution which really worked for me. It also allows me to implement batch updates since the update logic is not connected to the http requests any more.
However I must say that I don't think that grails is the appropriate tech stack best suited for this kind of application, since it makes your application very heavy-weight and inflexbile. My experience is that once you start doing things which are not supported by the framework by default, it starts getting messy. Furthermore, I don't like the fact that the "repository" layer in grails essentially only exists as a part of the domain objects which introduced a lot of problems and resulted in several "proxy services" emulating a repository layer. If you start building an application using a json rest interface, I would suggest to either go for a very light-weight technology like node.js or, if you want to/have to stick to a java based stack, use standard spring framework + spring mvc + spring data with a nice and clean dto layer (this is what I've migrated to and it works like a charm). You don't have to write a lot of boilerplate code and you are completely in control of what's actually happening. Furthermore you get strong typing which increases developer productivity as well as maintainability and which legitimates the additional LOCs. And of course strong typing means strong tooling!
I started writing a blog entry describing the architecture I came up with (with a sample project of course), however I don't have a lot of time right now to finish it. When it's done I'm going to link to it here for reference.
Hope this can serve as inspiration for people experiencing similar problems.
Cheers!
A: It requires you to provide teh class name:
{ class:"SampleDomain", someString: "abc",
nest2: { class: "SampleDomainNested", someField:"def" }
}
I know, it requires different input that the output it produces.
As I mentioned in the comment earlier, you might be better off using the gson library.
A: Not sure why you wrote your own json marshaller, with xstream around.
See http://x-stream.github.io/json-tutorial.html
We have been very happy with xstream for our back end (grails based) services and this way you can render marshall in xml or json, or override the default marshalling for a specific object if you like.
Jettison seems to produce a more compact less human readable JSON and you can run into some library collision stuff, but the default internal json stream renderer is decent.
If you are going to publish the service to the public, you will want to take the time to return appropriate HTTP protocol responses for errors etc... ($.02)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527331",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "39"
} |
Q: Simulate click event in AS3 Is there any way to simulate a click event in AS3? I'm trying this:
element.dispatchEvent(new MouseEvent(MouseEvent.MOUSE_DOWN, true, false));
But click event isn't trigger it.
A: You must dispatch a MouseEvent.CLICK event.
element.dispatchEvent(new MouseEvent(MouseEvent.CLICK, true, false));
A: If you are listening for MouseEvent.CLICK then dispatch MouseEvent.CLICK. You are now dispatching MouseEvent.MOUSE_DOWN
element.dispatchEvent(new MouseEvent(MouseEvent.CLICK));
A: To simulate a CLICK event you need first to dispatch:
element.dispatchEvent(new MouseEvent(MouseEvent.MOUSE_DOWN, true, false));
followed by a:
element.dispatchEvent(new MouseEvent(MouseEvent.MOUSE_UP, true, false));
On the MOUSE_UP event the handler will then issue a click event (if the mouse is OVER the element, so you may need to set the mouse_x and mouse_y variables in the dispatched event.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527337",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How can we save a file with date? How can we save file with current date?
Date date11 = Calendar.getInstance().getTime();
DateFormat formatter =new SimpleDateFormat("d/M/yyyy");
String date1 =formatter.format(date11);
FileWriter fw = new FileWriter("C:\\InjectionExcel"+ date1 +".csv");
date1 given is current date. But this code is not working. Where am I mistaking?
A: A file name can't contain any of the following characters in Windows:
\ / * ? " < > |
Your problem is caused by attempting to use / as file name. It will be interpreted as path separator. For example, if the current day is 23 and the directory C:\InjectionExcel23 does not exist, then you will get something like the following exception (which you should initially have reported in your question!):
java.io.IOException: The system cannot find the path specified
Unrelated to the concrete problem, the way how you created the today's date is clumsy. You're generating all that unnecessary Calendar overhead. Just use new Date().
Date date11 = new Date();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527355",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Return string array in C++ function I am new to C++.
For a school project I need to make a function which will be able to return a string array.
Currently I have this in my header:
Config.h
string[] getVehicles(void);
Config.cpp
string[] Config::getVehicles(){
string test[5];
test[0] = "test0";
test[1] = "test1";
test[2] = "test2";
test[3] = "test3";
test[4] = "test4";
return test;}
Obviously this does not work but that's the idea of what I am trying to do.
In Java this would be the way to do it. I've tried googling my problem but I didn't come across any answers that were clear to be honest.
A: Maybe it is better to use a vector in this case, but this is not a correct answer for the question. The reason why it doesn't work is that the variable test just exists in the scope of your function.
So you have to manage the memory on your own. Here is an example:
string* getNames() {
string* names = new string[3];
names[0] = "Simon";
names[1] = "Peter";
names[2] = "Dave";
return names;
}
In this case you return a pointer of the position in the heap. All the memory in the heap has to free manually. So it is now your work to delete the memory, if you don't need it anymore:
delete[] names;
A: In C++ you don't use an array, but a std::vector instance. Arrays in C++ must have a compile-time fixed length while std::vector instances can change their length at runtime.
std::vector<std::string> Config::getVehicles()
{
std::vector<std::string> test(5);
test[0] = "test0";
test[1] = "test1";
test[2] = "test2";
test[3] = "test3";
test[4] = "test4";
return test;
}
std::vector can also grow dynamically, so in a C++ program you will find more often something like
std::vector<std::string> Config::getVehicles()
{
std::vector<std::string> test; // Empty on creation
test.push_back("test0"); // Adds an element
test.push_back("test1");
test.push_back("test2");
test.push_back("test3");
test.push_back("test4");
return test;
}
Allocating dynamically an array of std::string is technically possible but a terrible idea in C++ (for example C++ doesn't provide the garbage collector that Java has).
If you want to program in C++ then grab a good C++ book and read it cover to cover first... writing Java code in C++ is a recipe for a disaster because the languages, despite the superficial braces similarity, are very very different in many fundamental ways.
A: Try this
#include <iostream>
#include <string>
using namespace std;
string * essai()
{
string * test = new string[6];
test[0] = "test0";
test[1] = "test1";
test[2] = "test2";
test[3] = "test3";
test[4] = "test4";
cout<<"test et *test\t"<<&test<<' '<<*(&test)<<'\n';
return test;
}
main()
{
string * toto;
cout<<"toto et *toto\t"<<&toto<<' '<<*(&toto)<<'\n';
toto = essai();
cout<<"**toto\t"<<*(*(&toto))<<'\n';
cout<<"toto\t"<<&toto<<' '<<*(&toto)<<'\n';
for(int i=0; i<6 ; i++)
{
cout<<toto[i]<<' '<<&toto[i]<<'\n';
}
}
For example, in my computer, the result is
toto et *toto 0x7ffe3a3a31b0 0x55dec837ae20
test et *test 0x7ffe3a3a3178 0x55dec9ddd038
**toto test0
toto 0x7ffe3a3a31b0 0x55dec9ddd038
test0 0x55dec9ddd038
test1 0x55dec9ddd058
test2 0x55dec9ddd078
test3 0x55dec9ddd098
test4 0x55dec9ddd0b8
0x55dec9ddd0d8
Getting addresses and contents of addresses could help you to understand that an array in c++ is really rudimentary : it offers no methods and you could access an index without allocating memory (the value 6 in the loop).
Your first example show a direct allocation of a local array (test), so you can't return it (the local array dies), in this example, the local variable dies also but there is always a variable that access at this part of allocated memory, the function, and then the variable that receive the result of the function, so the variable test is dead after the calling of the function but the memory is still allocated. Regards.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527356",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "27"
} |
Q: Tween does NOT repeat indefinitely I am trying to animate a hexagon spinning like a wheel indefinitely:
function rotateCW(e:TweenEvent = null):void{
var hexRot:Tween = new Tween(this, "rotationZ", None.easeNone, 0, 360, 2, true);
hexRot.addEventListener(TweenEvent.MOTION_FINISH, rotateCW);
}
For some strange reason the animation stops after a random amount of repetitions. It varies anything from between 2 and 600 times before it stops.
I've got a whole bunch of different events firing all over the place in my application, is it possible that this might cause the MOTION_FINISH event to either not fire or not get caught?
Thanks!
A: First of all you should define hexRot and listen to its MOTION_FINISH outisde of your function. By doing like you do, every hexRot stays in memory since it has a listener attached to it.
This may not solve your problem but it will be a cleaner way to write things and you will be less vulnerable to strange behaviors.
private var hexRot:Tween;
/**
*Run only once
*/
function init():void {
hexRot = new Tween(this, "rotationZ", None.easeNone, 0, 360, 2, true);
hexRot.addEventListener(TweenEvent.MOTION_FINISH, rotateCW);
}
function rotateCW(e:TweenEvent = null):void{
hexRot.start();
}
A: The flash Garbage collector has cleaned up your hexRot-variable, so the animation stopped. To fix this, use the solution Kodiak has provided :) When the variable is globally declared, it won't get collected as long as you don't put anything new in the variable.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527364",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can't Understand Weird C Runtime Error. Need Help? I am trying to master the GObject Library. So I tried to make a simple Gtk+ Custom Widget by inheriting from GtkHBox. I can't figure out what the problem is or even where the problem is so I'll have to paste the entire code. Here is the code:
notetab.h
#ifndef NOTETAB_H
#define NOTETAB_H
G_BEGIN_DECLS
#define PRO_NOTE_TAB(obj) GTK_CHECK_CAST(obj, pro_note_tab_get_type (), ProNoteTab)
#define GTK_CPU_CLASS(klass) GTK_CHECK_CLASS_CAST(klass, pro_note_tab_get_type(), ProNoteTabClass)
#define GTK_IS_CPU(obj) GTK_CHECK_TYPE(obj, pro_note_tab_get_type())
typedef struct _ProNoteTab ProNoteTab;
typedef struct _ProNoteTabClass ProNoteTabClass;
struct _ProNoteTab
{
GtkWidget hbox;
GtkObject parent_instance;
GtkLabel label;
GtkButton cbtn;
};
struct _ProNoteTabClass
{
GtkHBoxClass parent_class;
};
GtkType pro_note_tab_get_type(void);
GtkWidget* pro_note_tab_new(void);
G_END_DECLS
#endif
notetab.c
#include "common.h"
#include "notetab.h"
GtkType pro_note_tab_get_type()
{
GtkType pro_note_tab_type = 0;
if (!pro_note_tab_get_type)
{
static const GtkTypeInfo pro_note_tab_info =
{
"ProNoteTab",
sizeof(ProNoteTab),
sizeof(ProNoteTabClass),
(GtkClassInitFunc) NULL,
(GtkObjectInitFunc) NULL,
NULL,
NULL,
(GtkClassInitFunc) NULL
};
pro_note_tab_type = gtk_type_unique(GTK_TYPE_WIDGET, &pro_note_tab_info);
}
return pro_note_tab_type;
}
GtkWidget* pro_note_tab_new(void)
{
return GTK_WIDGET(gtk_type_new(pro_note_tab_get_type()));
}
Now the program compiles perfectly fine. But the error I get at runtime is:
GTK_CRITICAL**: IA__gtk_type_new : assertion GTK_TYPE_IS_OBJECT(type) failed
GTK_CRITICAL**: IA__gtk_container_add : assertion GTK_IS_WIDGET(widget) failed
What am I doing wrong? Or even I what in the world is this error about?
A: According to the docs, gtk_type_unique is "deprecated and should not be used in newly-written code".
Use g_type_register_static instead. More so if you are trying to master GObject, not old Gtk+.
Anyway, I'd say that your error is due to some of the NULL function pointers you are setting, some are probably not optional, but this is poorly documented.
A: For one, the pro_note_tab_type variable in pro_note_tab_get_type() really looks like it should be static.
A: That must be the problem
if (!pro_note_tab_get_type)
{
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527371",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to split a string on the first occurrence of one of multiple substrings in JavaScript? Given strings
s1 = "abcfoodefbarghi"
and
s2 = "abcbardefooghi"
How can I split s1 into "abc" and "defbarghi"
and s2 into "abc" and "defooghi"
That is: split a string into two on the first occurrence of either one of strings "foo" or "bar"
I suppose this could be done with s.split(/regexp/), but what should this regexp be?
A: Use a Regular Expression in this way:
var match = s1.match(/^([\S\s]*?)(?:foo|bar)([\S\s]*)$/);
/* If foo or bar is found:
match[1] contains the first part
match[2] contains the second part */
Explanation of the RE:
*
*[\S\s]*? matches just enough characters to match the next part of the RE, which is
*(foo|bar) either "foo", or "bar"
*[\S\s]* matches the remaining characters
Parentheses around a part of a RE creates a group, so that the grouped match can be referred, while (?:) creates a non-referrable group.
A: str.replace(/foo|bar/,"\x034").split("\x034")
idea is replace the first occurrence with a special(invisible) String, and then split against this string.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527374",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: RegEx problem with IE7 when trying validate Email address I am wondering an annoying problem with Email Validation using regex.
I'm using this regex to validate email address on a web page:
^\s*[a-zA-Z0-9_\+-]{1,63}(\.[a-zA-Z0-9_\+-]{1,63})*@(?=[a-zA-Z0-9-\.]{0,255}\.?\s*$)[a- zA-Z0-9-]{1,63}(\.[a-zA-Z0-9-]{1,63}){0,126}\.([a-zA-Z]{2,63})\.?\s*$
Now this works allright with IE8 --> and latest Mozilla and Opera version for example.
I already read about this article: http://blog.stevenlevithan.com/archives/regex-lookahead-bug
But even I was using .* with ?= I could not get it working. Any RegEx guru have ideas what I'm doing wrong.
I also tried this:
^\s*[a-zA-Z0-9_\+-]{1,63}(\.[a-zA-Z0-9_\+-]{1,63})*@(?=.*[a-zA-Z0-9-\.]{0,255}\.*?\s*$)[a- zA-Z0-9-]{1,63}(\.[a-zA-Z0-9-]{1,63}){0,126}\.([a-zA-Z]{2,63})\.*?\s*$
But with no success.
A: Is the space in the last group of
@(?=[a-zA-Z0-9-\.]{0,255}\.?\s*$)[a- zA-Z0-9-]{1,63}
right after the - intentional? This probably won't work with a conservative engine.
A: I got this regex and it seems to do the job right:
const string myRegex = @"^(([\w-]+\.)+[\w-]+|([a-zA-Z]{1}|[\w-]{2,}))@"
+ @"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\."
+ @"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
+ @"([a-zA-Z]+[\w-]+\.)+[a-zA-Z]{2,4})$";
A: Have you tried removing the lookahead altogether? I agree with @Gerben that it serves no purpose in your regex:
^\s*[a-zA-Z0-9_\+-]{1,63}(\.[a-zA-Z0-9_\+-]{1,63})*@[a-zA-Z0-9-]{1,63}(\.[a-zA-Z0-9-]{1,63}){0,126}\.([a-zA-Z]{2,63})\.?\s*$
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527375",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: VirtualBox error while using Vagrant I want to use Vagrant to create a virtual machine for a development environment. I am getting an error when it tries to install the virtual machine into VirtualBox. The output of VBoxManage import is below. My colleague is able to run this command without any problem. I am on Mac OS X 10.6.8 and he is on Debian.
Does anyone have an idea of the meaning of this error?
20:41:26:haitran:vagrant $ vagrant up
[default] Box ubuntu1104 was not found. Fetching box from specified URL...
[default] Downloading with Vagrant::Downloaders::HTTP...
[default] Downloading box: http://dl.dropbox.com/u/7490647/talifun-ubuntu-11.04-server-amd64.box
[default] Extracting box...
[default] Verifying box...
[default] Cleaning up downloaded box...
[default] Importing base box 'ubuntu1104'...
The VM import failed! Try running `VBoxManage import` on the box file
manually for more verbose error output.
21:06:54:haitran:vagrant $ VBoxManage import ~/.vagrant.d/boxes/ubuntu1104/box.ovf
0%...10%...20%...30%...40%...50%...60%...70%...80%...90%...100%
Interpreting /Users/haitran/.vagrant.d/boxes/ubuntu1104/box.ovf...
OK.
Disks: vmdisk1 41943040000 -1 http://www.vmware.com/interfaces/specifications/vmdk.html#streamOptimized box-disk1.vmdk -1 -1
Virtual system 0:
0: Suggested OS type: "Ubuntu_64"
(change with "--vsys 0 --ostype <type>"; use "list ostypes" to list all possible values)
1: Suggested VM name "talifun-ubuntu-11.04-server-amd64"
(change with "--vsys 0 --vmname <name>")
2: Number of CPUs: 1
(change with "--vsys 0 --cpus <n>")
3: Guest memory: 360 MB
(change with "--vsys 0 --memory <MB>")
4: Network adapter: orig NAT, config 2, extra slot=0;type=NAT
5: CD-ROM
(disable with "--vsys 0 --unit 5 --ignore")
6: IDE controller, type PIIX4
(disable with "--vsys 0 --unit 6 --ignore")
7: IDE controller, type PIIX4
(disable with "--vsys 0 --unit 7 --ignore")
8: SATA controller, type AHCI
(disable with "--vsys 0 --unit 8 --ignore")
9: Hard disk image: source image=box-disk1.vmdk, target path=/Users/haitran/VirtualBox VMs/talifun-ubuntu-11.04-server-amd64/box-disk1.vmdk, controller=8;channel=0
(change target path with "--vsys 0 --unit 9 --disk path";
disable with "--vsys 0 --unit 9 --ignore")
0%...
Progress state: VBOX_E_FILE_ERROR
VBoxManage: error: Could not create the clone medium '/Users/haitran/VirtualBox VMs/talifun-ubuntu-11.04-server-amd64/box-disk1.vmdk' (VERR_GENERAL_FAILURE)
VBoxManage: error: Details: code VBOX_E_FILE_ERROR (0x80bb0004), component Appliance, interface IAppliance, callee
Context: "ImportAppliance" at line 793 of file VBoxManageAppliance.cpp
A: Seems the question has been sitting here for a while, so maybe you already solved the problem. We're also using Vagrant and run into a strange problem where the box was corrupted.
For us this caused the provisioning to fail on a given laptop, but work on all the others. There was no clear indication of the failure, besides the provisioning process just froze.
Have you checked the sha1-sum or similar, to verify that you have exactly the same box file downloaded as your colleague? All the disk image files are cached under ~/.vagrant.d/boxes, so you could compare the checksums under that directory, right after import.
A: It looks like you haven't downloaded the box yet, so vagrant is doing it's best to find the original location of the box.
Try downloading the box manually
vagrant box add ubuntu1104 http://dl.dropbox.com/u/7490647/talifun-ubuntu-11.04-server-amd64.box
Also try turning up the logging
$ VAGRANT_LOG=DEBUG vagrant up
http://docs-v1.vagrantup.com/v1/docs/debugging.html
Lastly, try a different box image. It may have an newer/older version of virtual box guest editions installed. Could explain why your colleague has no issues with it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527384",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Bluetooth Automatic Connection with Paired Devices I am new here and I have read a lot of your post, and still don't find the solution of my problem.
I am writing an App for Android 2.2 using Bluetooth to connect to an End-Device.
I have a list of Paired Devices and I can connect my Android-Tablet with each of my already known devices.
What I want to do, is to connect with an End-Device automatically as soon as the Android-Tablet (Master in the whole communication, by the way) detects that one of the known Paired-Devices is in range.
One possibility is to constantly poll and try to see who is near me, but that would cost a lot of battery life, and if I go in range with one of the End-Devices and my Android-Tablet is not in the middle of the Polling-Process, I would not get the automatic connection; I would have to wait until the next Polling-Cycle.
Is there any solution to the problem?
I would the whole thing to work like the BT-Headsets and my handy :-/
Thanks for your answers and hope we can deal with it!
A: I am not sure whether this solution works or not. The idea is get all the paired devices and loop through it and try to connect using the MAC address of that device
String macAddress;
for (BluetoothDevice device : pairedDevices) {
BluetoothSocket bluetoothSocket = null;
try {
if (bluetoothSocket == null || !bluetoothSocket.isConnected()) {
bluetoothSocket = device.createRfcommSocketToServiceRecord(MYUUID);
mBluetoothAdapter.cancelDiscovery();
if(!bluetoothSocket.isConnected()){
bluetoothSocket.connect();
}
if (bluetoothSocket.getInputStream() != null && bluetoothSocket.getOutputStream() != null) {
macAddress = device.getAddress();
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527386",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Tool to capture every event details from other applications Is it possible to create a Windows application to capture all event details (control type,event type,window etc) triggered from different types of applications (winform, wpf, silverlight, etc)
I tried the "record" tool in "white framework".
http://white.codeplex.com/wikipage?title=Recorder&referringTitle=Home
But this tool is not detecting every events in my application.Iam looking for developing similar kind of application.
If it is possible please give some guidance.I need this for automating the testing of some applications. Thanks.
A: It depends on the application you want to automate. If it's Win32, WinForms or WPF you might look at Windows UI Automation.
Also it depends on what kind of events your are talking about. Which event is missing from the White recording tool?
Update: The best Tool to see/discover the kind of UI Automation events you can record from a third party application is Inspect.exe (formerly called UISpy.exe).
In there you can record actions/events and browse through the element tree with all available properties. My experience is: if you can't see it there, you can't automate it with UI Automation.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527390",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to get same server response data for two different application? I'am using LVL to get server response data. I want to know if I can get the same server response data for my two different applications and if so, what changes I have to do in LVL to make it possible?
A: This can only happen if you are using the same SALT for both your applications. I am also modifying LicenseCheckerCallback to return userid, packagename and versioncode to the application. I then store it for local usage. The good part is that I can now do activation checks once. But I have to do it again when the version number is upgraded. And ofcourse I check the local storage first for a valid activation before asking LVL to check.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527400",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: execute inline script from Ajax request On my application homepage, I built a 'widgets' system. The source of the widgets is generated server side, and pushed to the client through Ajax.
Ext.Ajax.request({
url: '/get-widgets',
success: function( response ) {
var boxes = Ext.decode( response.responseText );
Ext.each( boxes, function( box ) {
box.id = 'cell-' + box.cell;
var element = Ext.DomHelper.append( 'canvas', {
tag: 'div',
id: box.id,
cls: 'widget size-' + ( box.size || '11' ),
children: [{
tag: 'div',
cls: 'title',
html: box.title
}, {
tag: 'div',
cls: 'main',
html: box.body
}]
}, true );
});
}
});
The problem is, that some widgets have some inline Javascript in their body, that needs to be executed. This works perfectly in Firefox, but does not in Chrome.
Is there a flag or something you need to activate for the inline code to be executed?
A: Found out the Ext.Element::update() method features a flag to scan for and execute inline scripts. I changed my code as follows to utilize this method:
var element = Ext.DomHelper.append( 'canvas', {
tag: 'div',
id: box.id,
cls: 'widget size-' + ( box.size || '11' ) + ' ' + ( box.cls || '' ) + ' ' + ( box.type || '' ),
children: [{
tag: 'div',
cls: 'title',
html: box.title
}, {
id: box.id + '-body',
tag: 'div',
cls: 'main'
}]
}, true );
Ext.get( box.id + '-body' ).update( box.body, true );
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527403",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: edit rich:extendedDataTable using rich:modalPanel I have a <code>rich:extendedDataTable</code>. Each row has a a4j:commandLink as below.
Table Page:
<a4j:commandLink
id="editlink" oncomplete="#{rich:component('editPanel')}.show()"
reRender="editPanel">
<f:setPropertyActionListener value="#{archive}"
target="#{archiveOrderBean.currentOrder}" />
<f:setPropertyActionListener value="#{row}"
target="#{archiveOrderBean.currentRow}" />
<h:graphicImage value="/images/edit.png"
style="border:0;vertical-align: top;" />
</a4j:commandLink>
On click of the the link the rich:modalPanel is populated with the values of the selected row. The content of the selected row is fetched correctly, but when the data in the modalpanel is edited, the value is not being reflected in the bean.
Bean Getter and Setter:
<code>public ArchiveOrderModel getCurrentOrder() {
return currentOrder;
}
public void setCurrentOrder(ArchiveOrderModel currentOrder) {
this.currentOrder = currentOrder;
}
</code>
ModalPanel Page : below contents are included in the <code>rich:modalPanel</code> and <code>h:form</code>
<h:panelGrid columns="1">
<a4j:outputPanel>
<h:panelGrid columns="2">
<h:outputText value="Name" />
<h:outputLabel value="SL_#{archiveOrderBean.currentOrder.structureId}" />
<h:outputText value="Client" />
<h:inputText value="#{archiveOrderBean.currentOrder.customer}" style="width:200px"/>
<h:outputText value="DateCreated" />
<h:outputText value="#{archiveOrderBean.currentOrder.date}" style="width:200px" />
<h:outputText value="Description" />
<h:inputText value="#{archiveOrderBean.currentOrder.version}" style="width:200px" />
<h:outputText value="Order Desription" />
<h:inputText value="#{archiveOrderBean.currentOrder.orderType}" style="width:200px" />
</h:panelGrid>
<rich:message showSummary="true" showDetail="false" for="price" />
</a4j:outputPanel>
<a4j:commandButton value="Update"
action="#{archiveOrderBean.updateStruct}"
reRender="auftragListNew"
oncomplete="if (#{facesContext.maximumSeverity==null}) #{rich:component('editPanel')}.hide();" >
</a4j:commandButton>
</h:panelGrid>
Can Any one please help me out for this. I just need to know how the modalPanel values can be updated back to bean.
A: The problem was that the a4j:commandButton was not correctly placed inside the h:form. I could now find the updated values
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527407",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Response to DELETE method request sent using node.js never arrives I have node.js server which acts like a proxy. It recieves localhost requests and forward them to web service on another domain. GET, POST and PUT requests work just fine.
But I have a problem with DELETE method request. It causing "Gateway Timeout - In read" error. But web service on another domain recieves this request and executes appropriate DB sql to delete requested item. Moreover, if I send the same request using Fiddler for example, I receive an actual response.
Here is how my node.js http.request options look like:
{
"host": "some.domain",
"port": 443,
"path": "/paht/item/id",
"method": "DELETE",
"headers": {
"Host": "some.domain",
"Content-Type": "application/json; charset=utf-8"
}
}
A: smthin to do with firewall/spyware setting (check routers firewall) I had the same thing where my app worked on one pc and not on another...
A: Answering to my own question:
Nodejs adds Transfer-Encoding: chunked header to such DELETE request. And this header was causing described problem.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527408",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: what is the best way to update status bar message? May i know which is the best way to update a statusbar message in MDI application.I have come across this code for displaying the message in status bar of parent form from child form but i want to update the message based on user's action.
In parent form
private void Form1_Load(object sender, EventArgs e)
{
FrmShiftManagement newMDIChild = new FrmShiftManagement();
newMDIChild.MdiParent = this;
this.LayoutMdi(MdiLayout.Cascade);
newMDIChild.Show();
StatusMessage.Text = "Ready";
//toolstriplabel1.Alignment = ToolStripItemAlignment.Right;
}
public void ShowStatus(string status)
{
this.StatusMessage.Text = status;
Application.DoEvents();
}
In Child form
((FrmTRMS)this.MdiParent).ShowStatus("Item(s) Saved");
This code is working fine when the data is saved or any action performed..Now how can i set parent form original message back to the status bar once the data is saved or deleted.
A: You could do this:
string oldMsg = "";
public void ShowStatus(string status)
{
oldMsg = this.StatusMessage.Text;
this.StatusMessage.Text = status;
this.StatusMessage.Invalidate(); // To force status bar redraw
this.StatusMessage.Refresh();
}
public void RestoreStatus()
{
this.StatusMessage.Text = oldMsg;
}
and use RestoreStatus() on child form close or whenever you please.
A: I have got the solution w.r.to display message from child form to parent form in statusbar..I have gone through this link..http://www.codeproject.com/KB/cs/pass_data_between_forms.aspx
its very helpful.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527409",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: JQuery Mobile Dropdown List Positioning I am using jQuery Mobile and am having an issue with the margin added to the top of a drop down list element.
I am trying to align a drop down list next to a text input, but the top of the inputs appear out of line.
Here is a sample: http://jsfiddle.net/f6Prp/
What I want is the drop down list to be flush to the top, along with the text box. No matter what style I add, I can not seem to affect the position of the drop down.
Any help would be much appreciated.
Thanks,
Chris.
A: The ui-btn class defines a top margin. You can disable it with the following style:
.ui-select .ui-btn {
margin-top: 0px;
}
Note that the above will affect all select boxes, which might not be what you want. In that case, you can use a more restrictive selector.
You can find the updated fiddle here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527412",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Use Python bottle server to receive FileEntity of a POST request from Android On Android phone, I used setEntity() to put the FileEntity to the POST request.
HttpPost post = new HttpPost(uri);
FileEntity reqEntity = new FileEntity(f, "application/x-gzip");
reqEntity.setContentType("binary/octet-stream");
reqEntity.setChunked(true);
post.addHeader("X-AethersNotebook-Custom", configuration.getCustomHeader());
post.setEntity(reqEntity);
When using bottle, tried this but it is not working
f = request.body
gzipper = gzip.GzipFile( fileobj= f )
content = gzipper.read()
The content will be an empty string. So I tried to look at request.forms and request.files. Both of them have no key and value.
request.files.keys()
request.forms.keys()
When searching, I read about the entity: "a request MAY transfer entity" and the entity has entity-header and entity-value. So it may be something like file-content = e.get(entity-header).
A: Using that code, the phone send file using chunked encoding. Because py-bottle does not support chunked enconding, the solution here is rewrite the android to send file as body of POST request.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527413",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: java & phpseclib, RSA and OAEP? I am encrypting in Java using Cipher.getInstance("RSA/ECB/OAEPWITHSHA-512ANDMGF1PADDING") and setEncryptionMode(CRYPT_RSA_ENCRYPTION_OAEP) in phpseclib, but the phpseclib is not decrypting the data correctly.
It worked perfectly when I used RSA/ECB/PKCS1Padding in Java, and setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1) in phpseclib.
Here are the supported ciphers in Java: http://download.oracle.com/javase/6/docs/technotes/guides/security/SunProviders.html#SunJCEProvider
Are none of those ciphers compatible with phpseclib's OAEP implementation?
A: The problem lies in the size of the keys used, had me puzzled for a while as well.
To use OAEP safely, you have to use >=2048 bit RSA keys.
Also, make sure you run
$rsa->setHash('sha512');
$rsa->setMGFHash('sha512');
before setEncryptionMode() on the PHP side.
edit: it seems 1024 keys won't work correctly even with sha256, so I've modified my answer to only include the safe 2048+ bits route.
A: You'd probably have to do $rsa->setHash('sha512'); By default sha1 is used.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527414",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Where to obtain the apache JavaHL subversion binding library? I can find the API-docs for JavaHL 1.6 at http://subversion.apache.org/docs/javahl/1.6/ . However I can't find any pointer to a jar+native binary (win32) package, or maven resource. Where do you obtain these artifacts?
A: There seems no obvious way to retrieve them directly (searched in some Maven repos). JavaHL (win32) is part every current eclipse version with subversive in it. So technically, the following would work:
*
*Install in a fresh Eclipse installation the plugin Subversive.
*Include there the (optional) library JavaHL.
*At the end, you will find the library files in the directory plugins/org.polarion.eclipse.team.svn.connector.javahl16.win32_<version-nr>
Perhaps this workaround helps you, but I am interested in the "real" solution as well.
A: You can use the WANDisco SVN client installation, which installs the native libraries and 'paired' JAR file. See the accepted answer to my question here, which I'm going to suggest this as a duplicate of. (Although this question is older, I think the answer to the later one is more correct, so I see it as better that this is a duplicate of that if it makes any difference!)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527416",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Navigation text overlapping in wordpress Im using the whiteboard theme for wordpress.
My navigation is aligned to the right hand side of my header, however the navigation text is overlapping, the two inks in the navigation overlap each other on the header. any idea why?
#nav-primary {
clear: both;
width: 100%;
padding: 0 10px;
}
#nav-primary ul,
#nav-primary li {
list-style: none;
}
#nav-primary a {
position: absolute;
right: 0;
padding: 10px;
width: auto;
/*bottom: auto;*/
}
A: It seems that position: absolute is doing you no favours here. Try removing this.
You also might be inheriting undesirable styles from your basic list style, but without seeing the whole CSS file we won't be able to determine that.
A: try using z-index:99; or create a relative div id if you are using position absolute.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527419",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can i use one HttpURLConnection download many pictures from one website? My app should download many pictures from one website,the number is more than 200.So if i put this below code in a for(int i = 0; i++ ; i < 200),it looks not nice,the connection should connect and disconnect every time.
So anybody have some good suggestions?
URL imageUrl = new URL(url);
conn = (HttpURLConnection)(imageUrl.openConnection());
conn.connect();
InputStream is = conn.getInputStream();
BitmapFactory.Options ops = new BitmapFactory.Options();
ops.inSampleSize = inSample;
bitmap = BitmapFactory.decodeStream(is, null, ops);
is.close();
conn.disconnect();
A: URLConnection pooling happens behind the scenes. You don't have to worry about it yourself.
A: Since each image have a separate url, connection have to open and closed. There are no alternatives for this code.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527422",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is there focus and lost-focus event on black berry sdk? I am very new developer for black berry environment. Is there a focus and lost-focus event for the controls which are currently selected or deselected?
Please give me some like or example.
Thank you.
A: If you are writing your own custom field, or want to catch the events of your Screen class(es), then you would override the virtual Field.onFocus() and Field.onUnfocus() methods.
If you want to catch focus events of other fields, then you have to implement the FocusChangeListener interface and then call the Field.setFocusChangeListener() method of those fields.
A: Yes, these are Field.onFocus(int direction) and Field.onUnfocus(). Check the API for details.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527424",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Listing data from 3 different but associated table into one dropdown (using linq-to-sql and mvc3) i ve 3 tables in my database : item,group,groupdetail;
in table item there are 2 fields : id,item_name (bigint"long",string)
in table group there are 2 fields : id,group_name (bigint,string)
in table group_details there are 3 fields : id,group_id,item_id (bigint,bigint,bigint)
group_id is nullable cause some items have no groups.
what i want to do is listing the names of groups where the items that has a group "group_name" ordered by item_id and also in the same list i wanna show the item names which has no group and both of them should be ordered by item_id
i can also fill dropdowns with jquery if required for this action but i'm brain freezed with listing part.
controller
var data = from guru in dataContext.group_details select guru;
var itemsWithoutGroup = data.Where(c => c.group_id == null).OrderBy(c => c.item_id).Where(c => c.item_id == c.item.id).Select( c=>c.item.item_name);
var groups = data.Where(c => c.group_id != null).OrderBy(c => c.item_id).Where(c => c.group_id == c.group.id).Select( c=>c.group.group_name);
var grandlist = // i wanna do smt here to list both in one dropdown ordered by item_id
view
@Html.DropDownList("GroupDetails", new SelectList((System.Collections.IEnumerable)ViewData["GroupDetailedList"], "id", "item_id"))
EDIT:
To be more specific about it..
Group-1
Group-2
Item-9
Group-3
Item-15
Group-4
So this is how the dropdown should look like! Items with no groups should be listed too with the item groups and be ordered by item_id..
A: The statement i would use is:
var groupswithItems = (from groupdetail in group_details select groupdetail.group_id
join group in groups groupdetail.group_id equals group.id
orderby groupdetail.item_id
select new SelectListItem {Text= group.name, Value= group.id.ToString() }).ToList()
var itemswithotgroups = (from item in items orderby item.id select new SelectListItem { Text= item.name, Value= item.id.ToString() }).ToList()
ViewBag.Combined = groupswithItems.union(itemswithotgroups);
This would give you the list from all groups that are in group detail (those contain items i presume) and convert it to object that Dropdownlist can handle
@Html.DropDownList("GroupDetails", ViewBag.groups as List<SelectListItem>))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527426",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Spring Mvc 3 hasErrors is always false I have following class,
public class MarketPlace {
@NotEmpty(message="This Template Name is required")
@Size(max=50)
private String templateName;
public String getTemplateName() {
return templateName;
}
}
With the following post method,
@RequestMapping(value = "/PublishApplication.htm", method = RequestMethod.POST)
public String PublishForm(@Valid MarketPlace m, BindingResult result, Map model) {
if (result.hasErrors()) {
return "PublishApplication";
}
return "PublishApplication";
}
But hasErrors is always false? why?
Is I need any further configuration?
A: You have to set annotations "On" in your spring-servlet by adding this: <mvc:annotation-driven/>
Don't forget to include also the namespace "mvc". It'll look something like this:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
add xlmns:mvc:
xmlns:mvc="http://www.springframework.org/schema/mvc
add to xsi:schemaLocation:
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
A: Only add this to your spring XML to enable annotation support to controllers:
<mvc:annotation-driven/>
it should work after that
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527431",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: What base resolution to design for with Android? I am new to designing interfaces for Android. (I have gone through the Multiple Screens section in the Developer Guide.) What base resolution are you designing your screens for?
A: That is based on your app is for phone, or tablet, or both. Currently when designing layout for phone's app, there are three most basic resolution:
- 320dip x 480dip (normally 320px x 480px phone)
- 320dip x 533dip (normally 480px x 800px phone)
- 320dip x 569dip (normally 480px x 854px phone)
So when you design layout for phone's app, please remember:
1. Always use dip for width, height and sp for text size
2. A layout fit 320dip x 480dip screen will fit the other two
3. match_parent, wrap_content, gravity... are powerful Android XML layout attributes
4. Choose the orientation (landscape, portrait) carefully, normally an app requires only one orientation
The same goes for tablet's app, choose the most normal screens and create layout for the smallest one, and stretch the layout on bigger one.
But for both tablet and phone, you should use dimens.xml to store layout values. Reference here: http://developer.android.com/guide/topics/resources/more-resources.html#Dimension
Good luck with Android nightmare :)
A: Dont design for specific screen resolution!
Design for a range of devices either small screen, Medium screen or large screen.
Following are generic irrespective of your screen size.
Best layout is LinearLayout and RelativeLayout.
Bes metrics for Views 'dp' and for fonts 'sp'
Hope this helps!
A: I recommend base resolution for 320x480 pixel screen as this is supported by most number of devices. But you need to provide assets for hdpi (High Density), mdpi (medium density), ldpi (low density), xhdpi (xtra high density) specially images, buttons etc.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527440",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do I use a Less than or greater than symble in the WHERE statement with a SUM feature I want it to list the records if the total number of Yes's are less than 5.
I am getting an error:
An aggregate may not appear in the WHERE clause unless it is in sub query contained in a HAVING clause or select list , and the column being aggregated is an outer reference
I want to list students who are in WCM103, and have attended less than 5 classes.
A: Would something like:
WITH att
AS (SELECT studentID,
SUM(CASE WHEN attStatus = 'Yes' THEN 1 ELSE 0 END) as att_count
FROM attendance
GROUP BY studentID)
SELECT *
FROM Attendance a
INNER JOIN Student s USING (studentID)
INNER JOIN att USING (studentID)
WHERE att.att_count < 5
AND a.unitcode = 'SIT103';
work for you?
You could select the columns from STUDENT and ATTENDANCE you need etc.
EDIT: I don't have a SQL interface in front of me tody so some of the SQL might need tweaking.
David, in light of the new info, try the following:
WITH att
AS (SELECT unitcode,
studentID,
SUM(CASE WHEN attStatus = 'Yes' THEN 1 ELSE 0 END) as att_count
FROM attendance
WHERE attdate < TO_DATE('07/08/2011', 'DD/MM/YYYY')
GROUP BY unitcode,
studentID)
SELECT *
FROM Student s
INNER JOIN att USING (studentID)
WHERE att.unitcode = 'SIT103'
AND att.att_count < 5;
I have SQL*Plus running again now. I just ran:
CREATE TABLE student (
studentid NUMBER,
student_name VARCHAR2(30)
);
CREATE TABLE attendance (
studentid NUMBER,
unitcode VARCHAR2(10),
attdate DATE,
attstatus VARCHAR2(5)
);
INSERT INTO student VALUES (2106,'Jo Bloggs');
INSERT INTO student VALUES (2108,'Jo Schmoe');
INSERT INTO attendance VALUES (2106, 'SIT103', TO_DATE('05/06/2011', 'DD/MM/YYYY'), 'No');
INSERT INTO attendance VALUES (2106, 'SIT103', TO_DATE('07/07/2011', 'DD/MM/YYYY'), 'Yes');
INSERT INTO attendance VALUES (2106, 'SIT103', TO_DATE('10/05/2011', 'DD/MM/YYYY'), 'Yes');
INSERT INTO attendance VALUES (2108, 'SIT203', TO_DATE('05/05/2011', 'DD/MM/YYYY'), 'Yes');
WITH att
AS (SELECT unitcode,
studentID,
SUM(CASE WHEN attStatus = 'Yes' THEN 1 ELSE 0 END) as att_count
FROM attendance
WHERE attdate < TO_DATE('07/08/2011', 'DD/MM/YYYY')
GROUP BY unitcode,
studentID)
SELECT studentid,
student_name,
unitcode
FROM Student s
INNER JOIN att USING (studentID)
WHERE att.unitcode = 'SIT103'
AND att.att_count < 5;
and got:
STUDENTID STUDENT_NAME UNITCODE
2106 Jo Schmoe SIT103
Which is correct isn't it?
A: To use having, you have to have a group by clause, the group by is then executed and the having acts as a filter after the query has been aggregated.
Not sure you want to do a sum, without seeing the data in the tables but you should be able to do a count of the number of yes in the attendance table and then the having will list those that meet the criteria
Try something like this (oracle SQL syntax)
SELECT s.studentname, count(*)
FROM student s, attendance a
WHERE s.studentid=a.studentid
AND a.class='SIT108'
AND a.status='Y'
GROUP BY s.studentname
HAVING COUNT(*)<5
or with ANSI syntax
SELECT s.studentname, count(*)
FROM student s
LEFT INNER JOIN attendance a
ON s.studentid=a.studentid
WHERE a.class='SIT108'
AND a.status='Y'
GROUP BY s.studentname
HAVING COUNT(*)<5
You can omit the count(*) on the top line as well if you just want a list of names
SELECT s.studentname
FROM student s
LEFT INNER JOIN attendance a
ON s.studentid=a.studentid
WHERE a.class='SIT108'
AND a.status='Y'
GROUP BY s.studentname
HAVING COUNT(*)<5
Add whatever additional where clauses or joins you need
A: Try replacing WHERE with HAVING as in the following:
SELECT *
FROM Attendance AS a INNER JOIN
Student AS s ON a.studentID = s.studentID
HAVING (SUM(CASE WHEN attStatus = 'Yes' THEN 1 ELSE 0 END) < 5)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527441",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to detect Chrome Inspect Element is running or not? Is there any way to detect whether the Chrome Inspect Element window is running?
For example if the user clicks "Inspect Element" in Chrome, the window shows a Hello World alert.
Is that possible?
A: UPDATE This no longer works. The property console.profiles has been removed in Chrome 29.
The only solution that's left is checking the difference between window.outerHeight and window.innerHeight as suggested by @Gerben. There is a library devtools-detect based on this method which adds devtoolschange to the window object.
Alternatively, there is an effort in progress to create a Chrome extension using a more robust detection method, see this Google Group.
Here's how they check if DevTools are open in the first challenge of Discover DevTools interactive course:
function () {
console.profile();
console.profileEnd();
if(console.clear) { console.clear() };
return console.profiles.length > 0;
}
A: window.onresize = function(){
if((window.outerHeight-window.innerHeight)>100)
alert('hello');
}
In action: http://jsbin.com/ediquk/
Note that it seems like the resize event gets fired twice, so you should check whether you alerted the use already.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527442",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "24"
} |
Q: Css in Javascript I would like to display a status message in javascript and would like to include some css to that staus message.Can anyone help me out with this?
Now I have two css classes named Available and Not available for the available I need to apply the Available css class and for not available I need to append the NotAvailable css class.
Here is my javascript code:
function OnSuccess(response) {
var mesg = $("#mesg")[0];
switch (response.d) {
case "true":
mesg.style.color = "green";
mesg.innerHTML = "Available";
break;
case "false":
// mesg.style.color = "red";
mesg.innerHTML = "Not Available";
break;
case "error":
// mesg.style.color = "red";
mesg.innerHTML = "Error occured";
break;
}
}
function OnChange(txt) {
$("#mesg")[0].innerHTML = "";
}
This is my Css:
.Available
{
position: absolute;
width: auto;
margin-left: 30px;
border: 1px solid #349534;
background: #C9FFCA;
padding: 3px;
font-weight: bold;
color: #008000;
}
.NotAvailable
{
position:absolute;
width:auto;
margin-left:30px;
border:1px solid #CC0000;
background:#F7CBCA;
padding:3px;
font-weight:bold;
color:#CC0000;
}
A: mesg.addClass('Available');
mesg.removeClass('NotAvailable');
and vice versa.
A: You can use .addClass(cssClassName) adn .removeClass(cssClassName) method in jquery.
Something like this:
switch (response.d) {
case "true":
mesg.removeClass('NotAvailable').addClass('Available');
mesg.innerHTML = "Available";
break;
case "false":
mesg.removeClass('Available').addClass('NotAvailable');
mesg.innerHTML = "Not Available";
break;
case "error":
mesg.removeClass('Available').addClass('NotAvailable');
mesg.innerHTML = "Error occured";
break;
}
I have used removeClass(cssClass) and then addClass(className) because you are using same element to change class.
Also you can try .toggleClass(cssClassName)
A: It's easier than you think. You just need to change those innerHTML lines to:
mesg.html("<div class='Available'>Available</div>");
mesg.html("<div class='Available'>Not Available</div>");
.html() is just jQuery's more compatible way of setting the innerHTML. And html really means html... so you can do anything there you can do in a regular web page!
A: jQuery also has a .css() function. Maybe that will do the trick?
Or do you want to add a class to your mesg? in that case: $("#mesg").addClass("classOfYourChoice");
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527447",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: flashlike javascript framework or simple html5 solution I am kind of new to javascript/html5. normally I would do that kind of stuff inside flash/as3. but since the iPad doesn't support that I need to switch the horse...
I want to build a website where words are floating in position and size and if the mouse comes over one word it should draw some lines to all the other words. are there any frameworks one could use? the whole should look like a tag cloud with lines between the tags.
A: Raphael is a good JS replacement for Flash. It's a vector graphics based library.
A: Take a look at EaselJs from Grant Skinner. The approach he used is similar to Flash display list and timeline.
Here are some example:
https://github.com/mikechambers/ExamplesByMesh/tree/master/HTML5/EaselJS/follow
http://www.mikechambers.com/blog/2011/01/24/easeljs-example-follow-drone/
http://gskinner.com/blog/archives/2010/12/easel-js-simplifies-working-with-canvas-in-html5.html
A game Grant did:
http://www.pirateslovedaisies.com/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527448",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Ruby on Rails 3 Tutorial by Michael Hartl - Lesson 3 Static Pages Problem the system-created page http://localhost:3000/pages/home shows up fine. but when i change the content of the file home.html.erb and reload the page in the browser and view the source code, i see the content from my home.html.erb file gets added under the automatically created content. so basically there are two pages in the source code. anyone knows what causes that?
my application.html.erb:
<!DOCTYPE html>
<html>
<head>
<title>SampleApp</title>
<%= stylesheet_link_tag :all %>
<%= javascript_include_tag :defaults %>
<%= csrf_meta_tag %>
</head>
<body>
<%= yield %>
</body>
</html>
my home.html.erb
<!DOCTYPE html>
<html>
<head>
<title>Ruby on Rails Tutorial Sample App | Home</title>
</head>
<body>
<h1>Sample App</h1>
...
</body>
</html>
A: Your application.html.erb is fine, but home.html.erb is used to include only what's inside <body> tag. So, in your case it must contain only the
<h1>Sample App</h1>
...
part.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527454",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to get the Android device screen size from the adb command line? I need a way to detect device screen size and density with adb.
If there is no solution, where can I get the complete list of all existing android device with their screen size and density ?
A: LCD density is in the build.prop:
adb shell getprop ro.sf.lcd_density
And the resolution is availble in the dumpsys of the input activity:
# windows
adb shell dumpsys window | find "DisplayWidth"
# linux
adb shell dumpsys window | grep DisplayWidth
It works on all the devices I've tested with (2.2, 2.3.3, 2.3.4, 4.0.3; Acer Liquid E, HTC Wildfire S, HTC Incredible S, Motorola Atrix 4G, Samsung Galaxy Note, Samsung Galaxy Nexus), as well as the emulator, although the emulator's outputs are too clean to serve as a good example for parsing.
A: Using dumpsys
dumpsys window displays
shows something like this:
Display: mDisplayId=0
init=1080x1920 480dpi cur=1080x1920 app=1080x1920 rng=1080x1005-1920x1845
layoutNeeded=false
another way:
dumpsys display
also shows some interesting stuff like:
mDefaultViewport=DisplayViewport{valid=true, displayId=0, orientation=0, logicalFrame=Rect(0, 0 - 1080, 1920), physicalFrame=Rect(0, 0 - 1080, 1920), deviceWidth=1080, deviceHeight=1920}
and last but not least:
dumpsys power
will display something like
Electron Beam State:
mPrepared=false
mMode=2
mDisplayLayerStack=0
mDisplayWidth=1080
mDisplayHeight=1920
mSurfaceVisible=false
mSurfaceAlpha=0.0
that you could easily use to grep for mDisplayWidth and mDisplayHeight
A: To get required info from ADB, the following command executed from the command line will return a lot of useful properties about the connected devices
> adb shell getprop
To filter through these properties
on Unix use grep like
> adb shell getprop | grep density
on Windows use find like
> adb shell getprop | findstr "density"
Returned value looks like
[ro.sf.lcd_density]: [240]
for screen size put display instead of density
A: You can also access the WindowManager through ADB:
$ adb shell wm
usage: wm [subcommand] [options]
wm size [reset|WxH]
wm density [reset|DENSITY]
wm overscan [reset|LEFT,TOP,RIGHT,BOTTOM]
To get the screen resolution:
$ adb shell wm size
Physical size: 2880x1600
To get the screen the density:
$ adb shell wm density
Physical density: 320
You can also override the density by adding the new density:
$ adb shell wm density 160
A: Work is Good:
dumpsys window | grep Display
return: Display: init=320x480 cur=320x480 app=320x480 rng=320x295-480x455
A: ANDROID:/ # dumpsys window | grep mGlobalConfiguration
mGlobalConfiguration={1.0 ?mcc?mnc [en_US] ldltr sw720dp w1920dp h532dp 160dpi
So resolution is 1920x720
A: You can get screen dimensions with this code:
public int getScreenHeight() {
return getDisplay().getHeight();
}
private Display getDisplay() {
return ((WindowManager) getContext().getSystemService(
Context.WINDOW_SERVICE)).getDefaultDisplay();
}
public int getScreenWidth() {
return getDisplay().getWidth();
}
Once you have the Display in the code above you can use DisplayMetrics to get the density. DisplayMetrics will also give you absolute display with and height.
A: If you need to get the current status of range of Android device available in the market with it Screen Sizes and Densities Click here
This data is based on the number of Android devices that have accessed Android Market within a 7-day period ending on the data collection date
A: Look at the output of adb shell dumpsys. The screen size shows up there several times, along with lots of other information.
... although now I'm in the office, while it works on my phone, it's absent from the Galaxy tablet. Darn.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527459",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "78"
} |
Q: Consuming WCF service in objective C I m new to iPhone programming.
What I want to do authenticate a user in iPhone using webservice. For instance
I Have a WCF webservice that I want to consume in my objective C code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Runtime.Serialization;
using MobileKpi.Business;
namespace MobileKpi.Services
{
[ServiceContract]
public interface IUploadData
{
[OperationContract]
[WebInvoke(UriTemplate = "UploadUserSessionData/", Method = "POST")]
string UploadUserSessionData(SessionXML pstrXML);
}
[DataContract(Namespace = "", Name = "UserLogin")]
public class UserLogin
{
string user = "";
string pass = "";
[DataMember(Name = "userName")]
public string userName
{
get { return user; }
set { user = value; }
}
[DataMember(Name = "password")]
public string password
{
get { return pass; }
set { pass = value; }
}
}
}
I want to access its two data members user and password . How can I do it in Objective C.
Any solutions Or Sample Code.
A: One place you could start is reviewing the code in the answer of this SO question. It shows how to send JSON but you could tweak it to work with XML instead. In your code, you don't show how you expect UserLogin to be sent to the service. You could add it as a parameter as follows:
[ServiceContract]
public interface IUploadData
{
[OperationContract]
[WebInvoke(UriTemplate = "UploadUserSessionData/", Method = "POST")]
string UploadUserSessionData(SessionXML pstrXML, UserLogin credentials);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527461",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Texture loading I am using libgdx and I am loading all my textures as shown below,
Texture objTexture=new Texture(Gdx.files.internal("imagename"));
This code was inside my ApplicationListener. But, I want to load all my images at the start of my game. I don't want to load them inside of ApplicationListener. I have tried accessing texture object outside the scope of OpenGL and failed. Can anyone suggest me on this?
A: I think that the soonest you can load those textures (it involves uploading them into the VRAM, so I guess that the Graphics module has to be initialized and all the GL stuff done) is in the create function of the ApplicationListener.
Also, you may consider using the new AssetManager to manage your resources. Or write a simpler asset manager.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527466",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Visual Studio : Search Uncommented Code only Is there any way to restrict the Find/Search to uncommented lines only ?
(Maybe using regex would be a good lead)
A: Lets say, if you need to search all occurrences of an uncommented text "VPEntity" then try using the following regular expression in Find in files after selecting the Use RegEx option
^((?!//|/\*).)*VPEntity
Hope it works for you
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527468",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Error when using Impersonation with Powershell and Exchange 2007 from C# I'm using a Windows system service to create a mailbox in Ecxhange 2007 using Powershell. As it's running as a system service I'm wrapping the powershell call using impersonation (using advapi32.dll) to run it as a user with the appropriate exchange permissions, however, I'm receiving the following error message.
Cannot load Windows PowerShell snap-in Microsoft.Exchange.Management.PowerShell.Admin because of the following error: The type initializer for 'Microsoft.Exchange.Data.Directory.Globals' threw an exception.
There is a Microsoft KB article (KB943937) describing this issue and the fix is to install exchange SP1 RU1, but I am currently running SP3 RU1. I am using the -DomainController parameter as specified in the KB article but I'm still receiving the same error.
If I run the service as the user that I am impersonating the code runs fine so I don't think it's a problem with the code. I've tried running this on Windows XP and Server 2008 with the same problem.
Calling System.Security.Principal.WindowsIdentity.GetCurrent().Name before the powershell code I can see that the impersonation is working correctly.
Has anyone come across this before?
A: For anyone coming across this in the future, the problem was with where the impersonation was starting.
You have to start the impersonation after adding the snapin but before creating the runspace.
RunspaceConfiguration rsconfig = RunspaceConfiguration.Create();
PSSnapInException snapInException = null;
PSSnapInInfo info = rsconfig.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.Admin", out snapInException);
BeginImpersonation();
myRunspace = RunspaceFactory.CreateRunspace(rsconfig);
See this article for the full source code.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527469",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to grab multiple (int) from title I'm using $intVariable=(int)$_GET[var1];
to output and select a variable in mysql records i.e /myfile.php?cat=5 selects different results.
I am dealing with a dropdown from SQL so need to output a list based on selected ID's.. so I need to have something like /myfile.php?var1=X&var2=Y
I'm actually using a bit of JavaScript too, so unsure whether it's PHP or JS I need to adjust to grab another variable.
This code + some PHP currently outputs the selected ID of my selection in the title bar..
function reload(form)
{
var val=form.cat.options[form.cat.options.selectedIndex].value;
self.location='myfile.php?var1=' + val ;
}
How do I achieve this multi tier structure getting 2 variables from the title, so I can use multiple variable to assign in my MYSQL selects. have tier dropdown lists
A: Actually what you need is both PHP and javascript i think. You should pass another variable
function reload(form)
{
var val=form.cat.options[form.cat.options.selectedIndex].value;
var val2 = //get the value for var 2
self.location='myfile.php?var1=' + val +'&var2='+ val2 ;
}
and then get it in php
$intValue2= (int)$_GET['var2']
and use it for mysql
A: Not really sure what exact answer your looking for, but to fix your function to add more vars:
function reload(form)
{
var val=form.cat.options[form.cat.options.selectedIndex].value;
self.location='myfile.php?var1=' + val + '&var2=' + val2;
}
In general:
what your setting there is the GET parameters in the URL, so for example to set the variables "name" and "age" you would do:
http://www.example.com?name=bob&age=17
Where name is bob and age is 17
The other way people do it is through html arrays, so:
http://www.example.com?people[]=bob&people[]=fred
On the php side, $_GET['people'] will return an array with the two strings bob and fred.
If your using javascript to construct the url, you need to js to create a url like the one above, I'm guessing it should return
self.location='myfile.php?var1='+val+'&var2='+val2
When your reloading the form, to retain the selected drop down, you need to do one of two things
JS: Recommended
$('#mySelect').val(val2)
or in the php
if($optionvalue == $val2){$selected = "selected"}
echo "<option value=\"$optionvalue\" $selected>myoption</option>"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527470",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Eclipse plugin for exporting svn diff to JAR I'm looking for SVN plugin, which can export diff files between 2 revisions to runnable jar file.
So I will give it to another man, who just run it on test/production server, and jar automatically will update project with exported diff files.
It's easy to write command tool like I need, but I'm looking for Eclipse plugin.
A: If I'm reading this right my issue is similar to yours.
Back in Eclipse 3.2 (ish) in the synchronize perspective, you could select locally changed files, then do File > Export and choose JAR, and it would select the files for you. Now it doesn't.
If you want just the text diff, it's easy. Just use the create patch option.
If you want to create a jar containing the changed files - which I find useful for recording the changes for a chunk of work, or saving the alterations to a branch when I want to work on another, then its possible but unnecessarily laboured. (Works with Indigo)
Exporting changes in eclipse Synchronize view:
*
*Select all of them in the synchronize view
*Right Click and choose Show In > Project Explorer
*In the Project Explorer that appears, all the files should be selected. Some may be collapsed in their parent package. Use the + to make sure they are all visible and selected.
*right click in the Project Explorer and choose Export > Java > Jar File, or drag the files into an explorer window if you want them in a flat directory.
A: What you want is just not possible (at least, not using SVN / text diffs).
SVN/diff work with text files. The result with diff is a excerpt with only the lines changed in a file (in this class a .java source file). These files cannot even be compiled because they are not java code (even if the lines themselves are).
What you may do is use svn log to check which files have changed, retrieve the associated .class files and use them to patch the server. Do not know if there is any tool that makes that automatically, though (and it is complicated as often the .class files are not commited into subversion).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527475",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to make html page by link name I am building a page for produce name "product.aspx"
I have display some products in this page with hyperlink.
Now I want, when I click my product (such as pen) then it automatically makes an html page name pen.html with some information.
When I click clock then it automatically makes an html page name clock.html with some information.
How can I do this?
I am using asp.net C# 3.5.
A: You can use a Literal to crete your html page
in frontend ypu can add Literal
so in backend code you can create a html page by adding text to the literal
eg.
var productdata = datasource;
ltrProduct.text ="<head><title>"+productdata.title+"</title></head><body></body></html>";
A: Rather than actually creating a physical file for these products, its best to have a Web Form called something like "Product.aspx" which you pass a querystring to like:
/Product.aspx?product=Pen
This can then be URL Rewritten to something like:
/Product/Pen.aspx
You can then use this query string to return data like:
Dim cmd as new sqlcommand("SELECT Name, Price FROM Products WHERE FileName=@FileName", Conn)
cmd.CommandType = CommandType.StoredProcedure
cmd.parameters.AddWithValue("@FileName", Request.QueryString("product"))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527476",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ie6 frame or mode for ie 7/8/9? Very backwards question really, but we have a legacy system which only works with ie6, and no-other browser.
Theres not much chance of this system being renewed anytime soon unfortunately and having to support ie6 for an entire dept is really holding up some of our dev work.
Is there any chrome-like ie6 frame available or any modes in ie7/8/9 or anything that I dont know of that will allow us to upgrade the browsers and run a web app that only runs under ie6?
Sorry for the horribly backwards question... no-one likes ie6 especially when it stands in the way of progres.
Cheers
A: IE6 is the only significant version of IE for which there isn't a backward compatibility mode. The irony is that it is probably the version for which it was most needed (the requirement for IE6 compatiblity with internal web apps has been one of the biggest reasons given for corporations refusing to upgrade from it)
You can simulate IE5 using the 'quirks mode', and IE7/IE8 compatibility modes are available in later versions, but there has never been an IE6 compatibility mode.
There are a few options open to you:
Firstly, you could take an upgrade path that doesn't involve upgrading IE. If your next corporate browser is Firefox, Chrome, Safari or Opera, you can quite happily leave IE6 on the machine to be used as required.
Alternatively, you could install a VM running its own copy of Windows and IE6. With adequate configuration, it should be possible to make this pretty much transparent to the user; they would click an icon and get IE6, and not even necessarily need to know it's running in a VM. This would require the host machine to be reasonably powerful though, so it may not be an option if it means upgrading a lot of hardware.
You might be able to do something similar on a cheaper budget using a remote desktop; ie you would have one or more dedicated machines running IE6, which users could log into remotely. If most people only use your IE6 web app for a limited amount of time, you could get away with doing this with relatively low resources.
There is an application called IETester, which allows you to install virtually all versions of IE alongside each other, and run them in tabs within the same window. This might be worth trying out. However, if you're doing this for a live application, beware that IETester does have a tendency to crash relatively frequently. This isn't an issue for it's main purpose (testing that a site works in different versions of IE), but if you're trying to use it to do real work, it could get irritating very quickly.
Finally, you could bite the bullet and at least try to find out why the application in question only works in IE6. There are a number of possible reasons for this, and some of them are indeed unresolvable. However there are some reasons which may appear on first glance to only work in IE6, but might actually be possible to get working in later versions of IE.
For instance, IE6 has appalingly bad security, and a lot of old IE6-specific web apps exploited this. Newer browsers have disabled most of these security holes, but you can configure IE7/8/9 to re-activate some of them (on local intranet sites only, of course!) to allow older code to continue working. This particularly applies to sites which use ActiveX plugins. These can often be made to work in later versions of IE, despite claims to the contrary.
Not all apps can be fixed, but it might be worth your time to investigate fully exactly what it is about your app that stops it working in later IEs. If it can't be done then at least you'll know for sure, but if it is something simple, you'll be kicking yourself if you only find out later.
A: You could create a virtual machine with IE6, and only use it for that one app that needs IE6. There are many VM solutions, use the one that fits you best - e.g. VirtualBox, VMWare, QEMU, Microsoft Virtual PC.
Then, for the rest of the work, you can proudly march into the 21st century with a decent browser.
A: Although it really depends on what you mean by 'only works with ie6', there is a way to force IE to use a certain 'document compatibility' as Microsoft terms it.
Its done via a meta tag in the document that 'only works with ie6'.
Here is a URL from Microsoft that describes the process:
http://msdn.microsoft.com/en-us/library/cc288325(v=vs.85).aspx
The meta tag is X-UA-Compatible.
This will force IE to render the document in whatever IE version you set it to. So for IE6, you would have to add the following to the document bodies that only work with IE6:
<meta http-equiv="X-UA-Compatible" content="IE=5" >
The above method should force (for example) IE8 to render the frame in IE5 mode.
Best of luck.
Quick update: Turns out there is no IE=6, but IE=5. I would give that a shot.
A: Another option is to use IETester.
This will allow you to natively run IE6, IE7, IE8 and IE9 all within one Windows Operating System.
Its a bit mickey mouse, but if you can teach your staff to use this for this specific product, it should do the trick.
http://www.my-debugbar.com/wiki/IETester/HomePage
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527477",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to deal with Java Polymorphism in Service Oriented Architecture What is the path of least evil when dealing with polymorphism and inheritance of entity types in a service-oriented architecture?
A principle of SOA (as I understand it) is to have entity classes as mere data constructs, lacking in any business logic. All business logic is contained in narrow-scoped, loosely-coupled services. This means service implementations are as small as possible furthering the loose coupling, and means the entities avoid having to know about every behaviour the system may perform on them.
Due to Java's quite baffling decision to use the declared type when deciding which overloaded method to use, any polymorphic behaviour in the service implementations is instead replaced with a series of conditionals checking object.getClass() or using instanceof. This seems rather backward in an OOPL.
Is the use of conditionals the accepted norm in SOA? Should inheritance in entities be abandoned?
UPDATE
I definitely mean overloading and not overriding.
I define SOA to mean that behaviour of the system is grouped by use case into interfaces, and then the logic for these is implemented in one class per interface, generally. As such an entity class (say Product) becomes nothing more than a POJO with getters and setters. It absolutely should not contain any business logic related to a service, because then you introduce one focal point of coupling whereby the entity class needs to know about all business processes that may ever operate on it, completely negating the purpose of a loosely-coupled SOA.
So, being that one should not embed business process-specific behaviour in an entity class, one cannot use polymorphism with these entity classes - there is no behaviour to override.
UPDATE 2
The above behaviour is more simply explained as an overloaded path is chosen at compile-time, and an overridden path at run-time.
It'd be bad practice to have a subclass of your service implementation for each subtype of the domain model class it's acting on, so how do people get around the overloading-at-compile-time issue?
A: You can avoid this problem by designing the business logic in different classes based on the entity type, based on single responsibility principle it would be the best way to go when you place business logic in a service layer and use a factory to create logic implementation, for example
enum ProductType
{
Physical,
Service
}
interface IProduct
{
double getRate();
ProductType getProductType();
}
class PhysicalProduct implements IProduct
{
private double rate;
public double getRate()
{
return rate;
}
public double getProductType()
{
return ProductType.Physical;
}
}
class ServiceProduct implements IProduct
{
private double rate;
private double overTimeRate;
private double maxHoursPerDayInNormalRate;
public double getRate()
{
return rate;
}
public double getOverTimeRate()
{
return overTimeRate;
}
public double getMaxHoursPerDayInNormalRate;()
{
return maxHoursPerDayInNormalRate;
}
public double getProductType()
{
return ProductType.Service;
}
}
interface IProductCalculator
{
double calculate(double units);
}
class PhysicalProductCalculator implements IProductCalculator
{
private PhysicalProduct product;
public PhysicalProductCalculator(IProduct product)
{
this.product = (PhysicalProduct) product;
}
double calculate(double units)
{
//calculation logic goes here
}
}
class ServiceProductCalculator implements IProductCalculator
{
private ServiceProduct product;
public ServiceProductCalculator(IProduct product)
{
this.product = (ServiceProduct) product;
}
double calculate(double units)
{
//calculation logic goes here
}
}
class ProductCalculatorFactory
{
public static IProductCalculator createCalculator(IProduct product)
{
switch (product.getProductType)
{
case Physical:
return new PhysicalProductCalculator ();
case Service:
return new ServiceProductCalculator ();
}
}
}
//this can be used to execute the business logic
ProductCalculatorFactory.createCalculator(product).calculate(value);
A: It took me a while from reading this to work out what you were really asking for.
My interpretation is that you have a set of POJO classes where when passed to a service you want the service to be able to perform different operations depending on the the particular POJO class passed to it.
Usually I'd try and avoid a wide or deep type hierarchy and deal with instanceof etc. where the one or two cases are needed.
When for whatever reason there has to be a wide type hierarchy I'd probably use a handler pattern kind of like below.
class Animal {
}
class Cat extends Animal {
}
interface AnimalHandler {
void handleAnimal(Animal animal);
}
class CatHandler implements AnimalHandler {
@Override
public void handleAnimal(Animal animal) {
Cat cat = (Cat)animal;
// do something with a cat
}
}
class AnimalServiceImpl implements AnimalHandler {
Map<Class,AnimalHandler> animalHandlers = new HashMap<Class, AnimalHandler>();
AnimalServiceImpl() {
animalHandlers.put(Cat.class, new CatHandler());
}
public void handleAnimal(Animal animal) {
animalHandlers.get(animal.getClass()).handleAnimal(animal);
}
}
A:
Due to Java's quite baffling decision to use the declared type when
deciding which overloaded method to use
Whoever gave you that idea? Java would be a worthless language if it were like that!
Read this: Java Tutorial > Inheritance
Here's a simple test program:
public class Tester{
static class Foo {
void foo() {
System.out.println("foo");
}
}
static class Bar extends Foo {
@Override
void foo() {
System.out.println("bar");
}
}
public static void main(final String[] args) {
final Foo foo = new Bar();
foo.foo();
}
}
The Output is of course "bar", not "foo"!!
A: I think there is a confusion of concerns here. SOA is an architectural way to solve interaction between components. Each component within a SOA solution will handle a context within a larger domain. Each context is a domain of it self. In other words, SOA is something that allows for lose coupling in between domain contexts, or applications.
Object Orientation in Java, when working in this kind of an environment, will apply to each domain. So hierarchies and rich domain objects modelled using something like domain driven design will live on a level below the services in a SOA solution. There is a tier between the service exposed to other contexts and the detailed domain model which will create rich objects for the domain to work with.
To solve each context/applications architecture with SOA will not provide a very good application. Just as solving the interaction between them using OO.
So to try to answer the bounty question more specifically:
It's not a matter of engineering around the issue. It's a matter of applying the correct pattern to each level of design.
For a large enterprise ecosystem SOA is the way I would solve interaction in between systems, for example HR system and payroll. But when working with HR (or probably each context within HR) and payroll I would use the patterns from DDD.
I hope that clears the waters a bit.
A: Having thought about this a bit more I've thought on an alternative approach that makes for a simpler design.
abstract class Animal {
}
class Cat extends Animal {
public String meow() {
return "Meow";
}
}
class Dog extends Animal {
public String bark() {
return "Bark";
}
}
class AnimalService {
public String getSound(Animal animal) {
try {
Method method = this.getClass().getMethod("getSound", animal.getClass());
return (String) method.invoke(this, animal);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public String getSound(Cat cat) {
return cat.meow();
}
public String getSound(Dog dog) {
return dog.bark();
}
}
public static void main(String[] args) {
AnimalService animalService = new AnimalService();
List<Animal> animals = new ArrayList<Animal>();
animals.add(new Cat());
animals.add(new Dog());
for (Animal animal : animals) {
String sound = animalService.getSound(animal);
System.out.println(sound);
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527481",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
} |
Q: How to inspect if javascript/jquery is loaded in the DOM? no examples this time. I am a bit new to javascript. What is the best option to inspect if a certain javascript is loaded in the DOM? Let's say now I applied colourbox to my site, but still its not working, so what I want to see if it is a problem with javascript or somewhere else.
Also, what is the best tool to inspect on a certain javascript online. Let's say I want to do something similar to: http://muthemes.com/yield/ - a javascript slider with borders from left and right, that starts with text "Advertising projects, graphic design jobs, architecture assignments". I really do not understand which script is loaded for this. Can you please share some wisdom with me in order not to create such post's in the future. Thanks! I will appreciate very much.
A: for Firefox: Firebug. Chrome, Opera and IE have similar build-in functions (just press F12 / search for "developer console" on google).
This tools provide a console, detailed error-messages, debugging tools, dom- and css-inspectors and a lot of other useful stuff to make inspectinig and debugging a website very easy.
just install/open and play around to get used to this tools. they're almost self-explaining. For more information, there are a lot of wikis and good tutorials out there in the www - just ask google for help.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527483",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Emacs Word-Reordering Completion Style I'm missing one piece in Emacs' already superbly unique completion system (completion-styles and completion-styles-alist), namely word and sub-word-reordering a la google search.
As an example, file-write should complete to write-file if no other style finds a completion. Word-separating characters could for-example be matched using the regular expression "\\s_".
Even cooler and more general would be if applied the Damerau-Levenshtein Edit Distance (D) to words instead of letters. The completion candidates could the be sorted on increasing distance D, meaning closest match first.
My plan is quite clear on how to implement this and an implementation of D already exists. I ask anyway so I don't reinvent the wheel yet another time:
Has anybody implemented such a completion style already?
A: Per --
You cannot do what you want with vanilla Emacs (well, you can use Lisp to code whatever you need -- but you cannot do what you want not out of the box).
Icicles gives you exactly what you want. It's called "progressive completion", and the idea is similar to using a pipeline of grep commands.
*
*Nutshell view of progressive completion (and chipping away the non-elephant)
*Progressive completion
You can also use LevenShtein matching for completion with Icicles, and combine that with progressive completion to match the words in any order.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527484",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Programmatically select the login item's hide option in Mac I need to create a cocoa application, that run in back ground. I used lssharedFilelist to write an an application this was successful and the application is added to the login item in my Mac. My problem is to done the hide option check-box automatic selection. Is any method for do the above problem using any program such as lssharedFilelist, any other. If anybody know please Help Me. Thanks in advance.
A: You can achieve this using a single line of AppleScript:
osascript -e 'tell application "System Events" to make new login item with properties {path: "/path/to/application", hidden: True} at end'
Set hidden's value to True/False depending on whether or not you want the checkbox checked/unchecked, respectively.
Not sure of a Cocoa-esque way to do this, sorry.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527487",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: CodeIgniter htaccess subfolder problem I want a second website in my domain inside the folder test
www.mydomian.com/test
Apache server running on linux.
But when I load it in my navigator styles, images, helpers can't be found.
My htaccess is like this:
RewriteEngine On
RewriteBase /test
RewriteCond %{REQUEST_URI} ^system.*
RewriteCond $1 !^(index\.php|images|robots\.txt)
RewriteCond %{REQUEST_URI} ^application.*
RewriteRule ^(.*)$ /test/index.php?/$1 [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]
Thank you in advance
I have tried what you said, placing the htaccess file you gave me in the test folder and the other one in the root directory, it didn't work.
Other options?
A: Try adding a .htaccess file into your test folder instead.
I use this .htaccess content:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?/$1 [L]
In the folder test I would place another .htaccess, with almost the same content:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /test/index.php?/$1 [L]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527491",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Modal view does not redisplay? I'm developing an app that needs to pick up a JPEG from a web site on start-up.
The splash screen displays, then the app attempts to get a web address from a file. If the file is missing I open a modal view (as UIModalPresentationFormSheet) that has a text view for the user to type in an address - the address is then saved to a file.
The user taps the OK button, and an attempt is made to get the JPEG. If the address was wrong, or the JPEG is not on the web server, the modal dialog must re-open so the user can change the web address to the correct one.
The splash screen view controller contains these methods:
- (void)openAddressDialog
{
serverView *viewController = [[serverView alloc]init];
[viewController setServerAddress:[businessLogic serverAddress]];
[viewController setDelegate:self];
[viewController setModalPresentationStyle:UIModalPresentationFormSheet];
[self presentModalViewController:viewController animated:YES];
}
Interestingly, when I called the openAddressDialog method from the viewDidLoad method the modal view did not appear. I had to move it to the viewDidAppear method. So presumably the view has to be in a particular state before it will entertain modal views.
- (void)closeDialog:(UIViewController *)dialogController:(Boolean)actionRequired
{
// If action required, get the server address from the dialog
if (actionRequired)
{
serverView *viewController = (serverView *)dialogController;
NSString *address = [[viewController serverAddress]copy];
[businessLogic setServerAddress:address];
[self dismissModalViewControllerAnimated:YES];
if (![logoImage image])
{
[logoImage setImage:[businessLogic eventLogo]];
if (![logoImage image])
{
[self openAddressDialog];
}
}
}
else
{
exit(0);
}
}
This is the delegate method called back from the modal view when the user has touched OK or Cancel. The actionRequired param indicates that OK was tapped. And if so, the new server address is picked up from the modal view, and the modal view is dismissed. An attempt is made to get the JPEG from the new address (in a business rules class), and if still no file can be found, the first method shown above (openAddressDialog) is called again so the user can correct the address again.
The modal view appears fine the first time, but will not reappear if the user entered the wrong address. Does this have something to do with me attempting to represent the modal view so quickly after dismissing it?
I'm quite new to iPad development, so would appreciate any advice.
One other thing, which demonstrates my inexperience of C++ perhaps, is ... if I declare a private method in the m file, let's call it
- (void) methodB
and that method calls another private method, let's call it
- (void) methodA
methodA must be defined earlier in the m file than methodB. If I also want methodA to call methodB I reach an impasse. The only way around that I am aware of is to declare methodB in the h file - which makes it public. How do I code this scenario so the outside world can see neither of the methods?
A: if use to create nib to serverView then do like this
serverView *viewController = [[serverView alloc]initWithNibName:@"serverView" bundle:nil];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527493",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to generate reports for Android Automation I have a Robotium test cases that I would like to run nightly using automation tool, however I am not sure if it can be done without manually running it through Eclipse first. Is there a build script that would enable me to run the Robotium test cases automatically on nightly basis. Ideally this test cases would run directly on the device as we want to test compatibility across different Android OS Platform.
How can I run the test cases automatically? Is there any build script for Android out there that would enable me to do what I need to do?"
A: No you have to use the java io to generate report and store it in the android and after the report is generated you just have to pull the file out.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527494",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How good is NVCC at code optimizations? How well does NVCC optimize device code? Does it do any sort of optimizations like constant folding and common subexpression elimination?
E.g, will it reduce the following:
float a = 1 / sqrtf(2 * M_PI);
float b = c / sqrtf(2 * M_PI);
to this:
float sqrt_2pi = sqrtf(2 * M_PI); // Compile time constant
float a = 1 / sqrt_2pi;
float b = c / sqrt_2pi;
What about more clever optimizations, involving knowing semantics of math functions:
float a = 1 / sqrtf(c * M_PI);
float b = c / sqrtf(M_PI);
to this:
float sqrt_pi = sqrtf(M_PI); // Compile time constant
float a = 1 / (sqrt_pi * sqrtf(c));
float b = c / sqrt_pi;
A: The compiler is way ahead of you. In your example:
float a = 1 / sqrtf(2 * M_PI);
float b = c / sqrtf(2 * M_PI);
nvopencc (Open64) will emit this:
mov.f32 %f2, 0f40206c99; // 2.50663
div.full.f32 %f3, %f1, %f2;
mov.f32 %f4, 0f3ecc422a; // 0.398942
which is equivalent to
float b = c / 2.50663f;
float a = 0.398942f;
The second case gets compiled to this:
float a = 1 / sqrtf(c * 3.14159f); // 0f40490fdb
float b = c / 1.77245f; // 0f3fe2dfc5
I am guessing the expression for a generated by the compiler should be more accurate than your "optmized" version, but about the same speed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527496",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How to populate Radio button and Check box from database? I have Radio button on my page.I am saving the radio button value in database as 1 or 0 format. My question is when I want to populate the radio button how should i do?
Please can anyone help me
EDIT:
DataTable dt = DataAccess.GetHRInfo(userId);
if((int)dt.Rows[0]["Active"] > 0)
{
optIsActiveYes = 1;
...
Can i assign a value like this?
A: Considering that you already know how to store value to db I made assumption that you able to read it from DB as well, so:
Radio button will be checked when value is 1, otherwise reseted, event you'are read wrong value like 2 or -1
EDIT: Update to a comment
DataTable dt = DataAccess.GetHRInfo(userId);
int activeValue;
// by default false
bool optIsActiveYes = false;
if (dt.Rows[0]["Active"] != null
&& Int32.TryParse(dt.Rows[0]["Active"].ToString(), out activeValue))
{
optIsActiveYes = activeValue == 1;
}
A: Ok It was my mistake . . You can simply use
if(radioButton1Value == 1)
radioButton1.Checked = true;
:)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527502",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to use f:loadbundle with facelets Using f:loadbundle when using jsp as the view description language for an JSF application is pretty straight forward.
I want to know where to put this f:loadbundle when i am using facelets
A: Except from the way the taglibs are declared, it's really not different from JSP.
<!DOCTYPE html>
<html lang="en"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets">
<f:loadBundle basename="com.example.i18n.text" var="text" />
<head>
<title>Facelets page</title>
</head>
<body>
<h:outputText value="#{text['some.key']}" />
</body>
</html>
This also applies to all other tags/components. The only major difference is that you need to declare the taglib in a XML namespace instead of an old fashioned JSP <%@taglib %> thingy.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527503",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Is it possible to reuse a CryptVerifySignature() hash object? MSDN says that after CryptVerifySignature() you cannot reuse HCRYPTHASH object to try hashing more data, instead it says you need to recreate it with CryptDestroyHash() and CryptCreateHash(). Reusing really fails.
Anyone is familiar with a hack that can save these calls, or it is really impossible?
A: I imagine the HCRYPTHASH data structure is more flexible than just being used to call with CryptVerifySignature(). It's designed to operate on a (possibly discontinuous) stream of data (via CryptHashData()), which means it stores some state within it on the hash's current values. Therefore, once you've used it on a stream (even partial) the state is irrevocably altered, so you can't use it on another stream.
I guess they could've provided a reset function for the HCRYPTHASH structure... but they didn't!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527509",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can i use CLUTO package from C#? I am wondering whether there are some C#-specific builds of CLUTO package for using its APIs directly from C# project.
As i understand, you need to include ".h" file, provided with the package, to make it work.
That's a problem.
Edit: adding reference to Cluto: http://glaros.dtc.umn.edu/gkhome/views/cluto
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527514",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Variable calculation time I want to calculate a string once (basicaly a concatenation) in a variable using the result of my report's query and then submit it to my subreports.
But for the moment it's calculated in this order (let say operation A is my variable calculation and operation B is my subreport's call) :
A B A B A B ...
And what I'm looking for is A A A ... B B B (here every Bs have in parameter the last calculation of A).
Is there a solution which solve my problem like this (I guess it's a calculation time problem) ?
Thanks.
A: To change when a variable is calculated, you can use the resetType and incrementType attributes.
If you want it to only be calculated once (at the beginning of the report), set incrementType="Report". You will also have to change the variableExpression to an initialValueExpression.
Example:
<variable name="var1" class="java.lang.String" incrementType="Report">
<initialValueExpression><![CDATA[$F{foo}+$F{bar}]]></initialValueExpression>
</variable>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527521",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Python - List of dictionary to list of list of dictionary I have this kind of list of dictionary
[
{'word': u'live', 'sequence': 1L, 'part': 1L},
{'word': u'school', 'sequence': 2L, 'part': 1L},
{'word': u'job', 'sequence': 1L, 'part': 2L},
{'word': u'house', 'sequence': 2L, 'part': 2L},
]
That I'd like to transform into this kind of list of list of dictionary
[
[
{'word': u'live', 'sequence': 1L, 'part': 1L}
{'word': u'school', 'sequence': 2L, 'part': 1L},
],
[
{'word': u'job', 'sequence': 1L, 'part': 2L},
{'word': u'house', 'sequence': 2L, 'part': 2L},
],
]
Based on the key part and ordered on sequence
How can I do that ?
A: Since itertools can be confusing, here's how you can do it:
>>> import pprint
>>> import itertools
>>> l = [
... {'word': u'live', 'sequence': 1L, 'part': 1L},
... {'word': u'school', 'sequence': 2L, 'part': 1L},
... {'word': u'job', 'sequence': 1L, 'part': 2L},
... {'word': u'house', 'sequence': 2L, 'part': 2L},
... ]
>>> l2 = [sorted(list(g), key=lambda x:x["sequence"])
... for k, g in itertools.groupby(l, key=lambda x:x["part"])]
>>> pprint.pprint(l2)
[[{'part': 1L, 'sequence': 1L, 'word': u'live'},
{'part': 1L, 'sequence': 2L, 'word': u'school'}],
[{'part': 2L, 'sequence': 1L, 'word': u'job'},
{'part': 2L, 'sequence': 2L, 'word': u'house'}]]
This assumes that l is already sorted by the part key, if not, use
>>> l2 = [sorted(list(g), key=lambda x:x["sequence"])
... for k, g in itertools.groupby(sorted(l, key=lambda x:x["part"]),
... key=lambda x:x["part"])]
A: sorted() (or list.sort()) and itertools.groupby().
A: Group the parts using a dictionary:
import collections
dictlist = [
{'word': u'live', 'sequence': 1L, 'part': 1L},
{'word': u'school', 'sequence': 2L, 'part': 1L},
{'word': u'job', 'sequence': 1L, 'part': 2L},
{'word': u'house', 'sequence': 2L, 'part': 2L},
]
dd = collections.defaultdict(list)
for d in dictlist:
dd[d['part']].append(d)
dd.values()
To ordered by sequence, just used sorted with a sort key specified:
[sorted(dd[k], key=lambda x: x['sequence']) for k in dd]
Overall, this produces:
[[{'part': 1L, 'sequence': 1L, 'word': u'live'},
{'part': 1L, 'sequence': 2L, 'word': u'school'}],
[{'part': 2L, 'sequence': 1L, 'word': u'job'},
{'part': 2L, 'sequence': 2L, 'word': u'house'}]]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527523",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to Construct the Shared Access Signature URL using C#? Unable to generate signature (sig) part in the shared Access Signature while constructing URL to request list blob storage. Can anyone please provide a c# code to create sas?
A: This: http://msdn.microsoft.com/en-us/library/microsoft.windowsazure.storageclient.sharedaccesspolicy.aspx gives an example of how to create a shared access signature through the C# storage API.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527525",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to get a Part of the Directory path in a batch file I have a BAT file in a directory
D:\dir1\dir2\getpath.bat
when i run the bat with the below code it prints
D:\dir1\dir2\
i want only the path D:\dir1\
The directory structure is not fixed , need the complete directory path other than the current directory in which BAT file resides.
@echo off
SET SUBDIR=%~dp0
ECHO %SUBDIR%
tried using delims in a for loop but it didnt help.
A: @echo off
setlocal
SET SUBDIR=%~dp0
call :parentfolder %SUBDIR:~0,-1%
endlocal
goto :eof
:parentfolder
echo %~dp1
goto :eof
A: @echo off
SET MYDIR=%cd%
cd %MYDIR%\..
SET MYPARENTDIR=%cd%
cd %MYDIR%
A: If it's the parent directory of the directory your script resides in you want, then try this:
@echo off
SET batchdir=%~dp0
cd /D "%batchdir%.."
echo %CD%
cd "%batchdir%"
(untested, please comment if there are problems)
Note that this will, of course, change nothing if your batch resides in your drive root (as in F:\) ;) If you'd like a special output if that's the case, you should test %CD% against %batchdir% before the echo.
EDIT: Applied patch, see comment by @RichardA
A: A single line of code does it :-)
If you want the trailing back slash, then
for %%A in ("%~dp0.") do @echo %%~dpA
If you don't want the trailing back slash, then
for %%A in ("%~dp0..") do @echo %%~fA
A: %~dp0 returns the full drive letter and path of the current batch file. This can be used in a FOR command to obtain portions of the path:
When run from C:\dir1\dir2\dir3\batch.bat
FOR %%V IN ("%~dp0..\") DO @ECHO %%~dpV
returns C:\dir1\dir2\
This can be extended to continue higher up the path:
FOR %%V IN ("%~dp0..\..\") DO @ECHO %%~dpV
returns C:\dir1\
Source: Microsoft info on batch parameters
A: You almost had it right. Using %~dp0 grabs the Drive+Full path to your .bat so it will return the folder which your bat file is located in as well.
Since the active directly will be the directory your bat is run from, all you'll need to do is:
@echo off
CD ..
SET SUBDIR=%CD%
ECHO %SUBDIR%
If putting this in a bat script to verify, throw in a PAUSE on a newline to see your output.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527529",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: lambda Expression as a property I have a working setup which is not strongly typed and relies on reflection.
I have a class, say
class Person{
public string FirstName {get ; set;}
public string LastName {get; set;}
public int Age {get; set;}
...
// some more public properties
}
and
class CellInfo {
public string Title {get; set;}
public string FormatString {get; set;}
}
and I have a dictionary like this
Dictionary<string, CellInfo> fields = new Dictionary<string, CellInfo>();
fields.Add("FirstName", new CellInfo {Title = "First Name", FormatString = "Foo"});
fields.Add("LastName", new CellInfo {Title = "Last Name", FormatString = "Bar"});
It's a simple dictionary with property Names and some info about them.
I pass the dictionary to another module that processes Person instances and I do
Dictionary<string, CellInfo> fields = SomeMethodToGetDictionary();
foreach(Person p in someCollection)
{
foreach(var field in fields)
{
object cellValue = type(Person).GetProperty(field.Key).GetValue(p, null);
// use cellValue and info on field from field.Value somewhere.
...
}
}
This method of passing the string for field name and using reflection works, but I was wondering if there is a strongly-typed method of doing this.
What I had in mind was having a property that stored a linq expression, something like this
fields.Add("FirstName", new CellInfo
{
Title = "First Name",
FormatString = "Foo",
EvalExpression = p => p.FirstName
});
and during usage, somehow use the EvalExpression on a person object and get the property value. I have no clue where to begin or what the syntax would be like to have a property like this that's evaluateable. I'm new to function delegates and expression trees that I don't even know the right keywords to search for. Hope my description is clear; if not, let me know and I'll details as necessary.
Any assistance would much appreciated.
A: Use a delegate:
class CellInfo {
public string Title {get; set; }
public string FormatString {get; set; }
public Func<Person, object> EvalExpression { get; set; }
}
Then your lambda input will work...
A: You can try something like this to not have to code the property names as strings if this is what you mean by saying strongly typed:
class CellInfo<T>
{
public string Title { get; set; }
public string FormatString { get; set; }
public Func<T, object> Selector { get; set; }
}
Dictionary<string, CellInfo<Person>> dict = new Dictionary<string, CellInfo<Person>>();
dict.Add("LastName", new CellInfo<Person> { Selector = p => p.LastName });
dict.Add("Age", new CellInfo<Person> { Selector = p => p.Age });
foreach (Person p in someCollection)
{
foreach (var cellInfo in dict)
{
object value = cellInfo.Value.Selector(p);
}
}
A: I think a delegate is what you need. Something like this:
public delegate string EvalExpressionDelegate (Person);
class CellInfo
{
public string Title {get; set;}
public string FormatString {get; set;}
public EvalExpressionDelegate EvalExpression = null;
}
fields.Add("FirstName", new CellInfo
{
Title = "First Name",
FormatString = "Foo",
EvalExpression = p => p.FirstName
});
A: (Your question is clear but long. Trim the initial stuff.)
This is how ASP.NET MVC uses reflection and lambda expressions for creating field names on the HTML inputs, etc. So you could have a look at the source code for that matter.
In simple terms, you have to cast your expression to Member expression and get the name. Easy:
MemberExpression memberExpression = EvalExpression.Body as MemberExpression;
if (memberExpression == null)
throw new InvalidOperationException("Not a memberExpression");
if (!(memberExpression.Member is PropertyInfo))
throw new InvalidOperationException("Not a property");
return memberExpression.Member.Name; // returns FirstName
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527536",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Bind DataGrid to a Matrix I have a 'matrix' object like follows:
public class Matrix
{
public Dictionary<string, string> PropertyBags { ... }
// Sample Property Bag: [{"Column A", "A"}, {"Column B", "B"}]
public List<PropertyBags Row { ... }
}
I wonder what's a practical solution for displaying my objects in WPF DataGrid?
Thanks.
A: Yep, you can do it in code behind of a Grid View. The idea is to bind a custom data set to a grid.DataSource property and then add columns dynamically, see examples by links below.
Also the second link provides an good example using Dependency Property which bound to a ItemsSource of a grid in XAML, also DP has OnPropertyChangedCallback provided so each time you update a data set by new value:
*
*PropertyChanged get raised which automaticalli trigger an callback
*In callback you are populating grid.DataSource by a new data items
*UI get updated because in XAML grid has
Links to the examples:
*
*WPF Dynamically Generated DataGrid
*Binding a ListView to a Data Matrix
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527550",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Why would some code that should work NOT work and then START working with nothing changed? xCode4 First question here and can I start by saying how much help this site has been to me and how much I like the way it is laid out! Can anyone help me with this..
Yesterday I had an issue with a simple bit of code in xcode4. It was just loading a view from a view controller as part of an if statement. Being a bit new to iphone development I assumed it was my problem and spent hours trying to figure it out without any luck.
Later that evening a buddy came over and had a look (by this stage I had gone back to my original code with the original issue) he suggested trying the code outside the 'if' statement. So I just copied the few lines to before the 'if' and commented out the if statement. Lo and Behold... it worked as it should!
After a couple of 'undo's i ran it again in its original form and... it worked again! I didn't change a thing! THREE HOURS! I could cry!
Anyone know why? Is there some kind of cache in xcode that gets a bit cranky and if so how do I reset / clear it? during my three hours I closed xCode, cleaned several times, shut down the imac more than once...
A: Well, not sure if you tried clearing the Build from the build menu - but that's often been an issue for me in previous times. Always try doing this first.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527556",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to Duplicate Database Table in C#? See this Code:
switch(someString)
{
case "11":
Con1_1.ConnectionString = conStr;
Con1_1.Open();
Dapt1_1 = new SqlDataAdapter("SELECT * From StdList", Con1_1);
Dapt1_1.Fill(Dset1_1, "StdList");
count = Dset1_1.Tables["StdList"].Rows.Count - 1;
break;
case "12":
Con1_2.ConnectionString = conStr;
Con1_2.Open();
Dapt1_2 = new SqlDataAdapter("SELECT * From StdList", Con1_2);
Dapt1_2.Fill(Dset1_2, "StdList");
count = Dset1_2.Tables["StdList"].Rows.Count - 1;
break;
}
i want to use a database table that can duplicated for 2 cases. please help me to do that.
can i use only one Table in Database for 2 cases or more? or i have to define as many as Table that i need?
A: If I understand you correctly you want to get one set of records from a table if your someString is '11' and a different set of records from a different table if the value of someString is '12'?
If the structure of the records in both tables are the same you could simply add a field (eg 'SchoolClass' to the first table structure to differentiate the records, storing the appropriate value of someString in the column for each record. Then you only need one table - put all the records in that table. To access it the do the following:
Con1_1.ConnectionString = conStr;
Con1_1.Open();
Dapt1_1 = new SqlDataAdapter("SELECT * From StdList WHERE SchoolClass = '" + someString + "'", Con1_1);
Dapt1_1.Fill(Dset1_1, "StdList");
count = Dset1_1.Tables["StdList"].Rows.Count - 1;
A: Ok, I got you.
add two more column in a table, those for class and school. then
you can filter by class and school. But all details will be stored on one table
Con1_1.ConnectionString = conStr;
Con1_1.Open();
Dapt1_1 = new SqlDataAdapter("SELECT * From StdList WHERE class= '" + m_class+ "' AND school='"+m_school+"'", Con1_1);
Dapt1_1.Fill(Dset1_1, "StdList");
count = Dset1_1.Tables["StdList"].Rows.Count - 1;
A: Your schema proposal and code makes very little sense.
I would recommend that you use a schema that is something like this:
#Students
. Id
. ClassId
. Name
. Family
. Phone
. Etc...
#Classes
. Id
. ClassName
. More info you might want about a class...
Then you build a method in style with:
public DataTable GetStudentsByClass(int classId)
{
//Set the connection string to the database and open the connection
Con1_1.ConnectionString = conStr;
Con1_1.Open();
//Execute the SQL query
databaseAdapter = new SqlDataAdapter("SELECT * From Students WHERE ClassId = " + classId, Con1_1);
//Declare a datatable to fill
DataTable students;
//Fill the datatable with the results
databaseAdapter.Fill(students, "Students");
//Return the filled datatable
return students;
}
public int GetStudentsInClassCount(int classId)
{
//Here you can reuse the previous method to get the count, a more optimal way would be to use the SQL count though.
return GetStudentsByClass(classId).Rows.Count;
}
To use it you just do it like this:
DataTable students = GetStudentsByClass(1);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527557",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to find the best posts based on their ratings and the time of posting? I have a Posts table with a lot of posts submitted at various times, and every post has a rating with it. For question's sake let's say I have all the required details in the Posts table itself (i.e.contents, ratings, created_at etc are in the Posts table).
I need an algorithm to sort the Posts intelligently based on their ratings and how recently they've been posted.
I'm using MySQL backend, so a query would be appropriate.
A: Asking Google really isn't that hard. the first hit seems to be really good, the second one even is a topic on SO about this, leading to a great article about Bayesian rating which seems to be what you're looking for.
The rest is simple maths - by the Bayesian rating you can easily decide which posts are the best. to take the time into account, simply divide the rating by the minutes since the post was created (for example) and the result is a good rating that take the creation-time into account.
A: If I understand you could try:
SELECT * FROM Posts
ORDER BY ratings DESC, created_at
With this you get higher rating posts on the top and, if rating is the same, the older post comes first.
A: This query gives you highest ratings first, then created_at:
SELECT *
FROM yourposttable
ORDER BY ratings DESC,
created_at DESC;
Update
Your comments suggest you want some kind of weighted algorithm. Follow Oezis links above, they lead to some good pages covering that topic.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527558",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Conversion of float to String is adding a lot of numbers var myNumber:Number = 1.8;
trace(myNumber);
The above gives "1.7999999999999998"
conversion of String(myNumber) also gives "1.7999999999999998"
This only happens with certain numbers. If (myNumber == 1.4) it doesn't give me this problem.
I've checked with the debugger and the values are correct both before and after the trace or String conversion. However, the string itself is incorrect.
Any help would be greatly appreciated.
A: Due to the way floating point values are stored they rarely ever represent the exact value you put in. Read up on the way floating point values are stored if you are interested but you can solve your problem by rounding to the decimal place you would like to see outputted.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527559",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Refreshing profile documents in XPages I created a profile document in Lotus Notes that saves a boolean value. Then I created an XAgent that returns the value as plain text (either true or false). The problem is: when I changed the value of the profile document in the Lotus Notes client, the changed value is not returned by the XAgent even though I tried refreshing the XAgent page, closing the browser or using a different browser. The change appears only when I restart the HTTP task ('tell http restart') in the server. Is there a way to always get the fresh document profile values immediately? I've been searching for hours how to programatically clear the web server cache or the like but to no avail. I know that profile documents are not supposed to be changed frequently, but I;m doing this for testing's sake.
Please help me.
Thank you very much! :D
A: Are you using an actual "Profile" document like this ?
Call workspace.EditProfile("Interest Profile", session.UserName)
Profile documents have been around for very long time, and their usage was intended to be quite simple, and not designed for regular updating. It has since been mis-interpreted as the general "scratch pad" for processes.
Generally, I do not recommend their usage because Domino cache's profile documents irrespective of HTTP, and they are more awkward to manage. This is especially difficult when you have replicas floating around on other servers.
So, the alternative is to use normal documents, and access them via a regular getdocumentByKey method. This allows you to manage them directly, which in turn makes it easier to maintain.
A: For performance reasons, the Domino http (and XPages) engine caches pages and documents. And this includes profile documents.
One workaround that would work is to update the profile document not though the Notes Client, but via a Web Agent. This way, the HTTP engine is running the agent, so it should be able to recognize that the profile has changed and that its cache needs to be rebuilt.
Another workaround would be - if this is an Xpages only solution - to use scoped variables and properties files to store the information.
Other than that, the only "solution" I can think of, is to re-implement "profile documents" with "regular" documents and views.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527560",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is checking savedInstanceState for null in onCreate a good way to tell if the device was rotated? There's stuff I'd like to do in my Activities' onCreate() method only if they're constructed the first time, not when the device was rotated (on configuration changes). Currently I'm checking the savedInstanceState parameter passed into onCreate() for this. If it's null, then it's the first time the Activity starts, else there was only a rotation.
Is this a good and reliable way to tell this? Are there alternatives to this?
A: I don't know of a better solution. Romain Guy describes the same approach (checking savedInstance state or other objects you pass for null).
In the new activity, in onCreate(), all you have to do to get your
object back is to call getLastNonConfigurationInstance(). In
Photostream, this method is invoked and if the returned value is not
null, the grid is loaded with the list of photos from the previous
activity:
private void loadPhotos() {
final Object data = getLastNonConfigurationInstance();
// The activity is starting for the first time, load the photos from Flickr
if (data == null) {
mTask = new GetPhotoListTask().execute(mCurrentPage);
} else {
// The activity was destroyed/created automatically, populate the grid
// of photos with the images loaded by the previous activity
final LoadedPhoto[] photos = (LoadedPhoto[]) data;
for (LoadedPhoto photo : photos) {
addPhoto(photo);
}
}
}
When I am lazy to do this, I just disable recreating the Activity on orientation change. As described at How do I disable orientation change on Android?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527561",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Why can't I take the address of a return value? I've split some code into two files, it was working before. In one file I have a function which has an out value parameter which is a pointer to a pointer.
I'm filling this parameter with a call to a getter and dereferencing it:
foo(&bar());
however I get an error saying ''&' requires an l-value'. I understand what this error means, but I thought I would be able to do this because it's a pointer and so does represent the original 'thing'.
Is it something to do with the fact that the actual pointers memory location could change, even though it would point to the right thing? but why did it work before when it was in the same file and not now?
Thanks in advance!
A: Well, you need an lvalue, i.e. something that can be assigned to. You can't assign to the return value of a function.
You need to do something like this:
temp = bar();
foo(&temp);
A: Using &, you aren't dereferencing, but referencing. To derefrence, use * instead: foo(*(bar()));.
And if you do want to reference it, put the result of bar() in a temporary variable:
x = bar();
foo(&x);
A: Assuming foo takes a pointer-to-int, try:
foo((int[]){bar()});
A: I guess bar() is:
type *bar () { return member_pointer; }
which returns the pointer member_pointer by value, hence not an l-vlaue.
If you want to modify the value member_pointer in foo(), you need:
type **bar () { return &member_pointer; }
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527562",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Serialization in .NET - deserialization in Android is there any way how to be able to serialize object in .NET and deserialize it in Android APK? I have tried WOX, but it is available only for pure Java (Android misses some imports). Is could be some custom serialization, but how to write it?
Thanks
A: Your best option is XML serialization. Takes more space than binary but being open you can do all you need to do on the Android side.
A: I don't know .NET but I'm sure there is a way to serialize .NET objects to JSON, just googled this: http://json.codeplex.com/ There are also libs for JSON for Android. Here is an example of parsing a JSON object on Android: http://www.androidcompetencycenter.com/2009/10/json-parsing-in-android/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527564",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to load web view in dialoge in android I am trying to load web view in to dialog. I am usuing the following code.
final TextView seeMonthlyBill = (TextView) parentLayout
.findViewById(R.id.my_ac_my_service_timewarnercable_link);
seeMonthlyBill.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Dialog dialog = new Dialog(getActivity());
WebView wb = new WebView(getActivity());
wb.getSettings().setJavaScriptEnabled(true);
wb.loadUrl("http://www.google.com");
wb.setWebViewClient(new HelloWebViewClient());
dialog.setCancelable(true);
dialog.setContentView(wb);
dialog.setTitle("WebView");
dialog.show();
}
});
I want to open web view on the click on a text view. When i am clicking on the text view dialog is opening without the webview. Can any please help me to solve this issue.
Thanks in advance.
A: Use a XML layout containing a Webview.
Then call dialog.setContentView(R.layout.web_dialog)
Set up the webview afterwards like so:
WebView wv = (WebView) findViewById(R.id.webview);
"R.id.webview" being the ID in the XML Layout file.
Dialog Layout example:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<WebView
android:id="@+id/webview"
android:scrollbars="vertical"
android:scrollbarAlwaysDrawVerticalTrack="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
</LinearLayout>
Your code modified:
final TextView seeMonthlyBill = (TextView) parentLayout
.findViewById(R.id.my_ac_my_service_timewarnercable_link);
seeMonthlyBill.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Dialog dialog = new Dialog(getActivity());
dialog.setContentView(R.layout.web_dialog)
WebView wb = (WebView) dialog.findViewById(R.id.webview);
wb.getSettings().setJavaScriptEnabled(true);
wb.loadUrl("http://www.google.com");
wb.setWebViewClient(new HelloWebViewClient());
dialog.setCancelable(true);
dialog.setTitle("WebView");
dialog.show();
}
});
A: @Override
protected Dialog onCreateDialog(int id) {
// TODO Auto-generated method stub
Dialog dialog = new Dialog(yourActivity.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
setDialogView(dialog,id);
return dialog;
return super.onCreateDialog(id);
}
private void setDialogView(final Dialog dialog,final int id) {
// TODO Auto-generated method stub
dialog.setContentView(R.layout.layoutContainingWebview);
final WebView mWebView = (WebView)dialog.findViewById(R.id.WebviewId);
mWebView.getSettings().setBuiltInZoomControls(true);
mWebView.getSettings().setDefaultZoom(WebSettings.ZoomDensity.FAR);
mWebView.setBackgroundColor(Color.TRANSPARENT);
mWebView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_INSET);
mWebView.loadUrl("url");
mWebView.setWebViewClient(new MyWebViewClient());
dialog.setTitle("Feedback"); // for Feedback
}
private class MyWebViewClient extends WebViewClient {
@Override
//show the web page in webview but not in web browser
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl (url);
return true;
}
TO show call showDialog(1);
A: Set webview's height and width and it will work.
A: What i would recommend is creating an activity with a webview layout and anything else you want to add to it.
And when you register it in the android manifest use this tage.
<activity android:theme="@android:style/Theme.Dialog">
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527568",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: VirtualPathProvider Not Working on Hosting Environment My .Net project works fine on Local IIS7 (Windows 7 IIS7 x86). But it does not work on hosting environment (W2008 Server x64 IIS7). I can fully control hosting environment. But I could not locate the error. When working locally I can access the USer Controls in the DLL via VirtualPathProvider, but i receive error
The file '/TarimWeb/TarisApp/TarisUI/CariBanka.ascx' does not exist.
on hositng environment.
I can provide any information, but i do not know what my helper would need to know.
Thank you!
A: So, I totally forgot that "PreCompiled Web Sites" cannot use VirtualPathProviders.
I found a work around @ http://sunali.com/2008/01/09/virtualpathprovider-in-precompiled-web-sites/
It DID work for me too...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527571",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to achieve embedded custom tags in asp.net? I found this example:
<telerik:RadDatePicker
ID="RadDatePicker1"
runat="server">
<DateInput Width="100%"></DateInput>
<Calendar
CellAlign="Center"
CellVAlign="Middle"
DayNameFormat="FirstLetter"
FirstDayOfWeek="Default"
MonthLayout="Layout_7columns_x_6rows"
Orientation="RenderInRows"
TitleAlign="Center"
UseColumnHeadersAsSelectors="False"
ShowRowHeaders="False">
</Calendar>
<DatePopupButton
CssClass="radPopupImage_Default"
BorderColor="#D0E1F2"
BorderStyle="Solid"
BorderWidth="1px" />
My assumption is that inside the RadDatePicker there is a DateInput object, Calendar Object and DatePopupButton object.
I would like to have my own custom control that allows access to an inner object e.g.
<jonno:textbox id="txt1" runat="server"><FieldConfig fieldName="Input1"/></jonno:textbox>
Ideally I don't want the FieldConfig class to be a visual class but it's ok if it is.
How can I achieve this?
A: The embedded custom tags are properties of your control. To enable setting them in markup, you need to decorate your control and properties with the following attributes:
*
*Control: ParseChilden, PersistChildren
*Properties: PersistenceMode
Example from a control I use that does something similar:
/// <summary>
/// Control that will conditionally show one of two views
/// </summary>
[ParseChildren(true)]
[PersistChildren(true)]
public class EditingView : CompositeControl
{
#region private fields
private View _displayView = new View();
private View _editView = new View();
#endregion
#region properties
/// <summary>
/// The view that will be rendered in display mode
/// </summary>
[PersistenceMode(PersistenceMode.InnerProperty)]
public View DisplayView
{
get
{
return _displayView;
}
set
{
_displayView = value;
}
}
/// <summary>
/// The view that will be rendered in editing mode
/// </summary>
[PersistenceMode(PersistenceMode.InnerProperty)]
public View EditView
{
get
{
return _editView;
}
set
{
_editView = value;
}
}
/* Implementation details hidden */
}
Look the attributes up on msdn to read up on what they do exactly. The above should do what you need it to do though.
In markup I can then simply assign the two views:
<ctl:EditingView runat="server">
<DisplayView>
blah blah
</DisplayView>
<EditView>
blah blah edit
</EditView>
</ctl:EditingView>
THe only difference is that my properties are still WebControls and take more child controls. It shouldn´t matter though, as long as you set your attributes right.
Menno
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527573",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can you connect a Flex UI to a Unix backend server? Im working on a project with the following basic needs:
*
*Need to invoke a Flex Webapp in a new Tab from another Webapp in Java/Jsp
*This Flex UI must be connected to a unix backend to show the backend operations on the UI
*The unix backend server has telnet operations and SSO
Is this possible? how?
Any further help on getting that Java Api
Using it as Adobe Air will require use of a server rite... I wanna do it without any extra server. Just the UI and the backend Unix server.
A: You'll need some kind of middleware solution (java based api) that flex can call over the web. Either that or use Flex as a local application (Adobe Air) which can run more OS specific commands
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527576",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to get Javascript to work on the WP-Ecommerce Javascript for product entry? We have installed version of Wordpress (3.2.1) and WP e-commerce (3.8.6.1) and I have noticed that in the product editor (within the admin interface) has a lot of gadgets that no longer work and I believe it has to do with a Javascript conflict.
The gadgets that no longer work are:
*
*Not all the list of media buttons above the product entry page are visible
*The only media button that is visible should launch the media browser in a thickbox; however it does not do this, it simply opens the media browser in the same window and is pretty un-usable for non-tech savvy people.
*The Visual tab button is not selectable at all, only HTML is selectable
*The "Howdy {user}" message and all the other drop-downs is usually a drop-down menu; but this no longer works.
These bugs do not appear on other pages, and only on the product editor page.
I have attempted to:
*
*Comment out every JS file inside /wp-e-commerce/wpsc-admin/admin.php and seeing if it makes any difference
*Use Firebug to go through and disable each JS file as and where possible to see what effect it has.
However, I am still unable to find where the problem is, or how to fix it.
I am using a clean install of Wordpress and the latest download of WP-Ecommerce. The only plugin active is WP-Ecommerce
Any help on this would be great. Thanks.
A picture of the issues are below.
[IMAGE REMOVED FOR SECURITY PURPOSES]
Update: 23 Sep @ 13:15 BST
The admin.js file I refer to is in:
/wpsc-admin/js/admin.js
In the admin.js file, Chrome's Developer Tools are complaining of an error:
jQuery("a.thickbox").livequery(function(){
tb_init(this);
admin.js:458 Uncaught ReferenceError: tb_init is not defined
});
Also, it reports these errors:
post-new.php:997 Uncaught ReferenceError: switchEditors is not defined
post-new.php:998 Uncaught ReferenceError: switchEditors is not defined
I also believe the /wpsc-admin/includes/display-item-functions.php file has something to do with the bug/issue.
If I comment out the following all the Javascript suddenly works.
function wpsc_filter_delete_text( $translation, $text, $domain ) {
// If I comment this out the JS works.
// If left uncommented the JS does not work
/*
if ( 'Delete' == $text && isset( $_REQUEST['post_id'] ) && isset( $_REQUEST["parent_page"] ) ) {
$translations = &get_translations_for_domain( $domain );
return $translations->translate( 'Trash' ) ;
}
return $translation;
*/
}
I am going to continue my investigation to see where the problem is.
A: I believe I have resolved the problem.
Whilst the above solution does work, it creates a problem where other gadgets like the variations will not work anymore as intended.
After a lot of trial and error and pulling of hair, I upgraded to the latest version (3-8-7-rc1) and tried again, this does work but isn't ideal for all instances/occasions.
Apparantly, according to the forum thread I created on the Getshopped website, it is a memory allocation issue. If you view the source of the Edit Product page, you’ll see that it’s suddenly cut off when outputting the 'Product Download' metabox.
Anyway, upgrading seems to have solved the problem for now.
Thanks.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527581",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Escaping issue in maxscript I have some issues with the edittext of maxscript and string escaping.
First, I want to escape the string written in an edittext (accents and simple quotes). The purpose is to feed this string to a mysql query.
Then I’d like to limit the number of characters per line in the edittext, force line breaks when the visual width is reached.
Are those things possible in a simple way ? I do not want to parse all the charcaters in the string and insert line breaks or espace the special characters manually.
Thnaks for any help
A: Escaping the original string is easy:
-- origString = string from text box
substituteString origString "\\" "\\\\"
substituteString origString "\"" ""\\\"
For mySQL I'd probably do this for inverted commas:
substituteString origString "\"" "'"
Also if you wanted to escape TAB characters etc this would work:
substituteString origString (bit.intAsChar 9) "<TAB HERE>"
Check out http://www.asciitable.com for character numbers.
But remember the string will be stored with the escape characters, so if you read the string you will display escape characters as well.
What is this being used for?
Are you trying to display the results on a web page from mySQL?
As for line breaks I don't think there's a way to get the string per line of a Maxscript EditText box. However you could use a .Net text box in your Maxscript UI and read it that way.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527584",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is there such a thing as a reverse foreign key? In MySQL, is there a way to specify that a.column cannot exist in b.column - a reverse foreign key?
In other words:
# Would not return any rows ever
SELECT * FROM a
INNER JOIN b ON a.column = b.column;
# Would fail
INSERT INTO a
SELECT * FROM b;
# Would not insert any rows
INSERT IGNORE INTO a
SELECT * FROM b;
A: No there is no such thing.
You would need to do that in a trigger:
DELIMITER $$
CREATE TRIGGER bi_a_each BEFORE INSERT ON a FOR EACH ROW
BEGIN
DECLARE forbidden_key INTEGER;
SELECT id INTO forbidden_key FROM b WHERE b.id = NEW.acolumn LIMIT 1;
IF forbidden_key IS NOT NULL THEN
SELECT * FROM error_insertion_of_this_value_is_not_allowed;
END IF;
END $$
DELIMITER ;
A: To a point, if you want "can be in A or B, but not both"
This is the "super key/sub type" pattern
Create a new table AB that has a 2 columns
*
*SomeUniqueValue, PK
*WhichChild char(1), limited to 'a' or 'b'
There is also a unique constraint on both columns
Then
*
*Add a WhichChild column to tables A and B. In A, it is always 'a'. In B, always 'b'
*Add foreign keys from A to AB and B to AB on both columns
Now, SomeUniqueValue can be in only A or B.
Note: in proper RDBMS you'd use check constraints or computed columns to restrict WhichChild to 'a' or 'b' as needed. But MySQL is limited so you need to use triggers in MySQL. However, this is simpler then testing table B for each insert in A etc
A: Try to create a trigger and throw an error from it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527587",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Flash Player interface problem I am facing an interface freeze issue with Flash Projector running a flex state based application. A Flash Projector exe was generated from a standalone flash player ver 10.2. The target machine on which the problem occuresd has 10.3.
Basically "screen freeze" means that the user interface is running as usual on Flash Player, but it's not responding to any user input (like button presses). But if we alt-tab to another application, the state changes in the Flash player. There is display with buttons on the screen, but touching the buttons or doing anything else - it did not respond. Rebooting the computer fixes the problem.
Can you suggest why this is happening? Is there any known bug in Flash Player.
The problem is this is being hard to reproduce on the developer workstation as it doesn't happen always. But it happens quite often on the target machine running an Intel Atom N270. What debugging steps can you suggest?
Problem : http://www.youtube.com/watch?v=z25oV9QWRyk
A: Have you tried publishing the projector in 10.1 or a version of Flash newer than 10.2? If you are able to publish it as a SWF first, you can use the stand-alone projector exe (downloadable here) to load and create a projector from it.
According to this Adobe bug issue (registration required), version 10.1 was supposed to have resolved this, but it sounds like it may have reappeared in 10.2.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527595",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Axis2 : When to use Modules in Axis2 Webservices I am pretty new to webservices . We need to develop a web service using Axis2 .
Please tell me when to use Modules Concept , when using Axis2 .
Could anybody Please tell me a scenario where this Modules would be useful ??
A: Modules/handlers are extension points of axis2 - and they can be used to execute common logic that needs to be executed across all your services.
Modules have the concept of being 'available' and 'engaged'. 'Availability' means the module is present in the system, but has not been activated, i.e., the handlers included inside the module have not been used in the processing mechanism. When a module is 'engaged' it becomes active and the handlers get placed in the proper phases. The handlers will act in the same way. Usually a module will be used to implement a WS-* functionality such as WS-Addressing, WS-Security.
For example, if you want to audit all the requests coming to all your services - you can write an audit module for that - which will intercept all your requests.
Another example is the Rampart. Rampart is an axis2 module which implements WS-Security specification. Once you engage rampart module to your service, it will intercept all requests coming to that service and will process the security headers.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527599",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Elegant way of getting gray scale pixels from a scanned image I will have scanned images with gray toned handwriting on white background.
What is the elegant way of selecting, and getting pixels of gray level(non-white) contigous areas?
Which image processing library should i use?
So far i research for a class and method in Leptonica, but found method names like: seedfill, i do not want to fill the area i want to get pixel coordinates that make the contigous area.
So can you also share class name with library name?
Thanks for reading and possible response.
A: You could use OpenCV. Maybe the findContours function is what you want.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527603",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to use multiple places in Spring viewresolver? this is how I define the loaction of my jsp files:
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
But I have too many JSP files in one folder at the moment...I changed my directiory structure to this:
/WEB-INF/jsp/city/*.jsp
/WEB-INF/jsp/weather/*.jsp
How must I change my viewresolver so that both places are found?
Ask for more info if needed.
A: Don't change it at all, just return qualified view names, e.g.
"city/tokyo" or "weather/partlyCloudy"
A: I'm sure the Sean Patrick Floyd answer is a better way to do this, but if you are not willing to use that technique, define two view resolvers, one with the prefix "/WEB-INF/jsp/city" and the other with the prefix "/WEB-INF/jsp/weather".
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527607",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to install FFMPEG on windows server..? Thanks in advance..
I would like to install ffmpeg on my windows server.
My php version is 5.2.3.
i followed and copied the avcodec.dll and
avformat.dll files to system32 folder.and i copied ffmpeg file into php5\ext folder.Then i added tha extension php_ffmpeg in ini file extension.
and also ffmpex.exe in c:/ffmpeg folder.
i give the full rights of that all files.
But ffmpeg still not working.
Anyone guide me which thing i missed.....
Thanks...
A: I did not use as an extension as my server was 64bit. If you like to use exec(), then you can use like following example:
$cmd = "c:/wamp/www/ffmpeg.exe -i c:/wamp/www/a.mpg -sameq -ar 22050 c:/wamp/www/b.mpg";
$test = exec($cmd);
Source: http://ffmpeg.zeranoe.com/builds/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527609",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Disable JVM Hot Swap We are instrumenting byte code and we use Eclipse for software development.
We now have to following problem: when debugging, Eclipse is replacing our instrumented code with the compiled code using hot swap since it detects that it was changed.
In Eclipse I did not find any way to disable the feature: in the Hot Code Replace settings section I only see ways to enable/disable warnings.
As already answered we can disable auto build but I wanted to ask if there is a way (an option) to tell the JVM to disable the hot swap feature?
We could just start the JVM with the option disabled and we should not care about Eclipse or any other IDE/debugger swapping the code.
A: I have looked and thought and looked again at your problem, as far as I can tell in hotspot at the VM level there is no easy way to disable this feature.
It looks like the hotswap code is deep within the JVMTI (JVM tool interface), and if I read the code right can only really be controlled if you are embedding the JVM.
It just looks like its not going to be possible without patch the JVM
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527613",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: How to update the alarm ringing time While updating calendar events? I'm trying to set alarm for calendar events that are inserted through my application. I have also set alarm for events(i.e) when calendar event notification shows, Alarm also sounded. Now, if I update the event time, I must get the alarm time also be updated from old time to new time. How to make out this?
Any help is highly appreciated and Thanks in advance...
A: Does android have any 'foreign key' type relationship between Events and their Reminders in its calendar content provider? I think there it is, and can help you. The link below is from android calendar app's source, and it is related to edit event activity, used in editing and inserting events. in save() method, used in this class, you can find how android itself saves events, and stores them, I think it would help.
click to see android calendar src code
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527614",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: uibutton not allowing uiscrollview to scroll hi i have uiscrollview and uipage control and in uiscrollview i have buttons (custom buttons)
and the coading is as follows
bodyView = [[UIScrollView alloc]initWithFrame:CGRectMake(0,
0,
320,
415)];
bodyView.userInteractionEnabled = YES;
bodyView.pagingEnabled = YES;
bodyView.contentSize = CGSizeMake(640,self.bodyView.frame.size.height);
bodyView.showsHorizontalScrollIndicator = NO;
bodyView.scrollEnabled = YES;
bodyView.showsVerticalScrollIndicator = NO;
bodyView.scrollsToTop = NO;
bodyView.delegate = self;
bodyView.canCancelContentTouches = NO;
bodyView.delaysContentTouches = NO;
[self.view addSubview:self.bodyView];
pageControl=[[UIPageControl alloc]initWithFrame:CGRectMake(0,425,320,10)];
pageControl.numberOfPages = kNumberOfPages;
pageControl.currentPage = 0;
pageControl.userInteractionEnabled=YES;
pageControl.multipleTouchEnabled=YES;
[pageControl addTarget:self action:@selector(changePageNavigation) forControlEvents:UIControlEventTouchUpInside];
[pageControl addTarget:self action:@selector(changePageNavigation) forControlEvents:UIControlEventValueChanged];
[self.view addSubview:pageControl];
[self.view bringSubviewToFront:bodyView];
- (void)createIcons{
buttonCustom = [self createDynamicCustomButtons:CGRectMake(12, 103, 65, 65)
image:[UIImage imageFromPath:TKBUNDLE(@"Images.bundle/Images/HomeScreen/pharmacy.png")]
tag:1];
[bodyView addSubview:buttonCustom];
labelCustom = [self createDynamicCustomLabels:CGRectMake(12,185, 80, 13)
text:NSLocalizedString(@"pharmacyTitle",nil)];
[bodyView addSubview:labelCustom];
buttonCustom = [self createDynamicCustomButtons:CGRectMake(120, 103, 65, 65)
image:[UIImage imageFromPath:TKBUNDLE(@"Images.bundle/Images/HomeScreen/photo.png")]
tag:2];
[bodyView addSubview:buttonCustom];
labelCustom = [self createDynamicCustomLabels:CGRectMake(116, 185,80, 13)
text:NSLocalizedString(@"photo Title",nil)];
[bodyView addSubview:labelCustom];
buttonCustom = [self createDynamicCustomButtons:CGRectMake(227, 103, 65, 65)
image:[UIImage imageFromPath:TKBUNDLE(@"Images.bundle/Images/HomeScreen/store_locator.png")]
tag:3];
[bodyView addSubview:buttonCustom];
labelCustom = [self createDynamicCustomLabels:CGRectMake(225, 185, 80, 13)
text:NSLocalizedString(@"StoreTitle",nil)];
[bodyView addSubview:labelCustom];
buttonCustom = [self createDynamicCustomButtons:CGRectMake(12, 208, 65, 65)
image:[UIImage imageFromPath:TKBUNDLE(@"Images.bundle/Images/HomeScreen/coupons.png")]
tag:12];
[bodyView addSubview:buttonCustom];
labelCustom = [self createDynamicCustomLabels:CGRectMake(23, 290, 60, 13)
text:NSLocalizedString(@"couponsTitle",nil)];
[bodyView addSubview:labelCustom];
buttonCustom = [self createDynamicCustomButtons:CGRectMake(120, 208, 65, 65)
image:[UIImage imageFromPath:TKBUNDLE(@"Images.bundle/Images/HomeScreen/refill_by_scan.png")]
tag:6];
[bodyView addSubview:buttonCustom];
labelCustom = [self createDynamicCustomLabels:CGRectMake(116, 290, 89, 13)
text:NSLocalizedString(@"Refill Title",nil)];
[bodyView addSubview:labelCustom];
//buttonCustom = [self createDynamicCustomButtons:CGRectMake(224, 220, 65, 65)
// image:[UIImage imageFromPath:TKBUNDLE(@"Images.bundle/Images/HomeScreen/65x65_weekly_ad.png")]
buttonCustom = [self createDynamicCustomButtons:CGRectMake(227, 208, 65, 62)
image:[UIImage imageFromPath:TKBUNDLE(@"Images.bundle/Images/HomeScreen/multi_scan.png")]
tag:7];
[bodyView addSubview:buttonCustom];
labelCustom = [self createDynamicCustomLabels:CGRectMake(225, 290, 86, 13)
text:NSLocalizedString(@"scanner",nil)];
[bodyView addSubview:labelCustom];
buttonCustom = [self createDynamicCustomButtons: CGRectMake(12, 313, 65, 65)
image:[UIImage imageFromPath:TKBUNDLE(@"Images.bundle/Images/HomeScreen/shopping_list.png")]
tag:9];
[bodyView addSubview:buttonCustom];
labelCustom = [self createDynamicCustomLabels:CGRectMake(15,395, 75, 13)
text:NSLocalizedString(@"ShoppinglistTitle",nil)];
[bodyView addSubview:labelCustom];
buttonCustom = [self createDynamicCustomButtons:CGRectMake(120, 313, 65, 65)
image:[UIImage imageFromPath:TKBUNDLE(@"Images.bundle/Images/HomeScreen/weekly_ad.png")]
tag:8];
[bodyView addSubview:buttonCustom];
labelCustom = [self createDynamicCustomLabels: CGRectMake(120,395, 80, 13)
text:NSLocalizedString(@"Weeklyads title",nil)];
[bodyView addSubview:labelCustom];
buttonCustom = [self createDynamicCustomButtons:CGRectMake(227, 313, 65, 65)
image:[UIImage imageFromPath:TKBUNDLE(@"Images.bundle/Images/HomeScreen/gift_finder.png")]
tag:nil];
[bodyView addSubview:buttonCustom];
labelCustom = [self createDynamicCustomLabels:CGRectMake(237, 395, 60, 13)
text:NSLocalizedString(@"giftFinder",nil)];
[bodyView addSubview:labelCustom];
buttonCustom = [self createDynamicCustomButtons:CGRectMake(333, 103, 65, 65)
image:[UIImage imageFromPath:TKBUNDLE(@"Images.bundle/Images/HomeScreen/shop.png")]
tag:4];
[bodyView addSubview:buttonCustom];
labelCustom = [self createDynamicCustomLabels:CGRectMake(344, 185, 60, 13)
text:NSLocalizedString(@"shop",nil)];
[bodyView addSubview:labelCustom];
buttonCustom = [self createDynamicCustomButtons:CGRectMake(440, 103, 65, 65)
image:[UIImage imageFromPath:TKBUNDLE(@"Images.bundle/Images/HomeScreen/find_a_clinic.png")]
tag:11];
[bodyView addSubview:buttonCustom];
labelCustom = [self createDynamicCustomLabels:CGRectMake(439, 185,80, 13)
text:NSLocalizedString(@"clinicTitle",nil)];
[bodyView addSubview:labelCustom];
buttonCustom = [self createDynamicCustomButtons:CGRectMake(547, 103, 65, 65)
image:[UIImage imageFromPath:TKBUNDLE(@"Images.bundle/Images/HomeScreen/settings.png")]
tag:10];
[bodyView addSubview:buttonCustom];
labelCustom = [self createDynamicCustomLabels:CGRectMake(558, 185, 60, 14)
text:NSLocalizedString(@"settingsTitle",nil)];
[bodyView addSubview:labelCustom];
}
//Begin - To create a icon's custom button ***Sujya***
-(UIButtonCustom *)createDynamicCustomButtons:(CGRect)frame image:(UIImage *)buttonImage tag:(int)tagValue
{
UIButtonCustom *customIconButton = [UIButtonCustom buttonWithType:UIButtonTypeCustom];
[customIconButton retain];
//customIconButton.buttonType =UIButtonTypeCustom;
[customIconButton setImage:buttonImage
forState:UIControlStateNormal];
[customIconButton addTarget:self
action:@selector(btnIconClicked:)
forControlEvents:UIControlEventTouchUpInside];
[customIconButton setTag:tagValue];
frame.size.width=buttonImage.size.width;
frame.size.height=buttonImage.size.height;
[customIconButton setFrame:frame];
return customIconButton;
}
i am able to scroll the view with out tapping on the button but on touching the button and i try to scroll but un able to scroll the view
can any one please tell me how to scroll on touching the buttton
A: If i have understood correctly, you want to scroll the scrollView by tapping a UIButton.
UIScrollView has a method
scrollRectToVisible:animated: to scroll programmatically your scrollView.
You can try this:
-(IBAction)switchToPG2{
CGRect frame = self.scrollView.frame;
frame.origin.x = frame.size.width * 1;//or the index of the page that you want
self.pageControl.currentPage=1;
frame.origin.y = 0;
[self.scrollView scrollRectToVisible:frame animated:YES];
}
Hope this helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527617",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Communication between processes using WCF and F# I would like to make a simple one to one communication between two long time running F# processes using F#. They will exchange information regularly every ca. 5 seconds. Until now, I have reached this point:
#r "System.ServiceModel"
#r "System.Runtime.Serialization"
//#r @"d:\DLL\Protobuf\protobuf-net.dll"
#time "on"
open System.ServiceModel
[<ServiceContract>]
type IService =
[<OperationContract>]
// [<ProtoBuf.ServiceModel.ProtoBehavior>]
abstract Test: float [] [] [] -> string
type Service () =
interface IService with
member o.Test data = sprintf "Hello, %A" data
let server = System.Threading.Thread (fun () ->
let svh = new ServiceHost (typeof<Service>)
svh.AddServiceEndpoint (typeof<IService>, NetNamedPipeBinding(), "net.pipe://localhost/123") |> ignore
svh.Open () )
server.IsBackground <- true
server.Start()
let scf: IService = ChannelFactory.CreateChannel (NetNamedPipeBinding(), EndpointAddress "net.pipe://localhost/123")
let rnd = System.Random ()
let arr =
Array.init 100 (fun i ->
Array.init 10 (fun j ->
Array.init 10 (fun k ->
rnd.NextDouble()
)))
printfn "%s" (scf.Test arr)
I get a plenty of different exceptions mainly due to different WCF security limits.
My questions are
*
*What do I need to do at minimum to make it work?
*Did I write the code correctly to make the communication as fast as possible?
*I have tried to include ProtoBuf serializer (see ProtoBehavior in the code) to make the serialization even faster. Did I implemented it correctly? How do I know that WCF actually uses it or not?
A: You need to increase MaxReceivedMessageSize property on the binding from it's default value of 65536 on both the client and server to accommodate the volume of data you are transferring.
You can use a Message Inspector to check if WCF is actually using the ProtoBuf serializer (which it isn't). The ProtoBehavior appears to only be applied to values with a DataContract/ProtoContract attribute specified. So in the modified example below I have created a Vector record type, also marked with the F# 3 CLIMutable attribute, to wrap the arrays:
#r "System.ServiceModel"
#r "System.Runtime.Serialization"
#r "protobuf-net.dll"
#time "on"
open System.ServiceModel
open System.Runtime.Serialization
[<DataContract; ProtoBuf.ProtoContract; CLIMutable>]
type Vector<'T> = { [<DataMember; ProtoBuf.ProtoMember(1)>] Values : 'T[] }
[<ServiceContract>]
type IService =
[<OperationContract>]
[<ProtoBuf.ServiceModel.ProtoBehavior>]
abstract Test: Vector<Vector<Vector<float>>> -> string
type Service () =
interface IService with
member o.Test data = sprintf "Hello, %A" data
let server = System.Threading.Thread (fun () ->
let svh = new ServiceHost (typeof<Service>)
let binding = NetNamedPipeBinding()
binding.MaxReceivedMessageSize <- binding.MaxReceivedMessageSize * 4L
svh.AddServiceEndpoint (typeof<IService>, binding, "net.pipe://localhost/123") |> ignore
svh.Open () )
server.IsBackground <- true
server.Start()
let scf: IService =
let binding = NetNamedPipeBinding()
binding.MaxReceivedMessageSize <- binding.MaxReceivedMessageSize * 4L
ChannelFactory.CreateChannel (binding, EndpointAddress "net.pipe://localhost/123")
let rnd = System.Random ()
let arr =
{ Values = Array.init 100 (fun i ->
{ Values =
Array.init 10 (fun j ->
{ Values =Array.init 10 (fun k -> rnd.NextDouble()) }
)}
)}
printfn "%s" (scf.Test arr)
A: I can only answer "3" : use wireshark to inspect the data on the wire, or otherwise time it / measure re bandwidth. Try it with/without protobu-net enabled, and compare. A protobuf message will have a chunk of binary data instead of XML.
Note: if you are using protobuf-net here, enabling MTOM will shave a little bit more (if it is available for your chosen transport).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527619",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: jQuery animation delay not working I am animating a div when a user hovers over and just wanted a bit of a delay on it but it doesn't seem to add the delay in, is there something i'm doing wrong?
$(".carousel-desc").mouseenter(function () {
$(this).delay(1000).animate({ 'height': '180px' }, { queue: false, duration: 600 });
});
$(".carousel-desc").mouseleave(function () {
$(this).delay(1000).animate({ 'height': '40px' }, { queue: false, duration: 600 });
});
Thanks, J.
A: I think the problem is queue: false; Usally your animation get queued, but you let the animate-function animate immediately.
Maybe this will do what you propably need:
$("#element").mouseEnter(function(){
$("#element").clearQueue();
//other stuff
}
for your stuff:
$(".carousel-desc").mouseenter(function () {
$(this).clearQueue();
$(this).delay(1000).animate({ 'height': '180px' }, { duration: 600 });
});
$(".carousel-desc").mouseleave(function () {
$(this).clearQueue();
$(this).delay(1000).animate({ 'height': '40px' }, { duration: 600 });
});
A: .delay() delays an animation queue
since you put queue: false in your animation options, it is executed immediately.
use it like this and it will be fixed
$(".carousel-desc").mouseenter(function () {
$(this).delay(1000).animate({ 'height': '180px' }, { duration: 600 });
});
$(".carousel-desc").mouseleave(function () {
$(this).delay(1000).animate({ 'height': '40px' }, { duration: 600 });
});
working example:
http://jsfiddle.net/hxfGg/
A: I agree with Snicksie, however, for your current case of code, there is a better approach:
$('.carousel-desc').hover(function () {
$(this).delay(1000).animate({
'height': '180px'
}, 600);
}, function () {
$(this).delay(1000).animate({
'height': '40px'
}, 600);
});
[ View output ]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527620",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Redis write to master read from slave We want to use Redis to distribute data to remote servers.
There is one master instance in the HQ and many remote slaves in our subsidiaries connected to the master.
Our applications are running in our subsidiaries. In 99% of the time there are read-only requests made to the slave instance.
But there is also the case of modifying data. Such a request is issued against the master.
Is there a way to ensure that the changes made to the master are replicated to the slave before the next read request?
A: I'm not sure if there is a way you can ensure this 100%, but you probably want to check in your redis.conf file and find this:
slave-serve-stale-data yes
Sounds like you'd want that set to no. The comments in the config file explain more about this directive.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527622",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: URL to Keyword API I'm trying to get keywords from any webpage I provide as a param. Unfortunately meta-tag keyword data is no longer used and DIY text-parsing usually takes to long per request. So I'm looking for one of the following two solutions:
Solution 1: a URL to Keyword API
Does anyone know of an API/service that allows you to send over the URL of a webpage and get keywords or refined categories back?
or Solution 2: a quick text-parsing method
Or is there any a quick (1s/request) easy text-parsing method on either the server-side (php) or client-side javascript that could return me a half-way decent set of keywords about any webpage I give it?
A: this artikel sounds like wordstream is what you're looking for. it has a api for (limited) free usage, too.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527630",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Difficulty using jquery I am trying to learn making ajax calls using jQuery. But I am stuck at a very basic point in using jQuery itself. Follwing is the code I have,
<head>
<script type="text/javascript" src="jquery-1.6.2.js"></script>
<script language="javascript">
$(document).ready(function()
{
alert("Hello World!!!!")
$("#txt1").onkeydown(function(){
alert("Event Fired")
$("#add").load("newjsp.jsp?q="+this.value)
})
})
</script>
</head>
<body>
<form>
Comment: <input type="text" id="txt1"></input>
</form>
<p><p></p></p>
<form id="add">
</form>
</body>
On entering any key in the textbox does not fire the event onkeydown(since there is no alert as "Event Fired"). I do not understand what could be the problem. Please help.
Thanks Rishabh
A: Use keydown instead of onkeydown.
.keydown( function(){...} ) is a shorthand for .bind("keydown", function){ ... }).
See also: http://docs.jquery.com
A: If you want to go right all the way, use keypress instead of onkeydown in a combination with a onetime binding to a keyup event
$(document).ready(function () {
alert("Hello World!!!!");
$("#txt1").keypress(function () {
$("#txt1").one('keyup', function () {
alert("Event Fired");
$("#add").load("newjsp.jsp?q=" + this.value);
})
})
});
Live sample in jsfiddle, (click run to start).
This avoids keys like CTRL and Shift being handled and also avoids automatic repeating of keys.
note: you should also filter out all characters that are not allowed in an URL. ;)
keypress
Fires when an actual character is being inserted in, for instance, a text input. It repeats while the user keeps the key depressed.
jQuery.one Attach a handler to an event for the elements. The handler is executed at most once per element. link
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527633",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Php and strings I'm receiving string variable in php and need to add something to it.
I dump the variable and see:
var_dump($myvar);
string(length) " ... "
After that I write:
$myvar += '~';
And it's inserted into DB (This is wordpress plugin and I'm adding a text into post content).
As a result, I get '0' :( What could it be?
A: If you want to add "~" behind your string you should do this:
REPLACE
$myvar += '~';
BY
$myvar .= '~';
A: PHP uses a dot as the operator to concatenate strings, not a plus sign.
The plus sign adds numerically. This explains why you are getting the result of zero, because both of the strings you are adding are numerically equal to zero.
Both plus and dot can be combined with the equal sign in the way you are doing, so the corrected version of your line of code would look like this:
$myvar .= '~';
Hope that helps.
A: Try this code to add ~ symbol to your variable:
$myvar = $myvar."~"
A: you can just use $myvar .= "~" it will add '~' to the $myvar.
A: instead of '+' used in js , '.' in PHP
$myvar .= '~';
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527636",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: c# custom installer class .net 4.0 not called I have c# custom installer class that originally targeted .net 2.0.
I have re-targeted it to .net 4.0, and now it does not seen to run.
I've proved this by adding Debugger.Break at relevent locations.
Under .net 2.0 the breakpoints are hit. I even tried targeting 3.5 and that worked.
I realise there a similar questions relating to this but the answers seem to suggest "wrong framework" or "use something else" variety.
Thanks!
Edit -
I have an installer class
public partial class ScriptRunner : Installer
{...
public override void Install(System.Collections.IDictionary stateSaver)
{
System.Diagnostics.Debugger.Break();
...
This is tested by running the installer (i.e setup.exe). The break statement should cause a dialog to prompt to run the debugger. Under .net 2.0/3.5 this happens, but no under .net 4.0
A: In .Net 4.0 the call to the debugger has been changed, this has thrown me off aswell at some point.
Changing
System.Diagnostics.Debugger.Break();
Into
System.Diagnostics.Debugger.Launch();
Made it work for us, not sure if that also worked for 2.0 and 3.5 since we switched to 4.0 and stuck with it :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527638",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Flex texItem internal Shadow I searched a lot but without result...
is it possibile to add an internal shadow to a textInput? using skin or css?
I'd like to have the textInput feel like it has some depth not a simple flat rectangle...
A: Add a RectangularDropShadow to the skin, turned 180 degrees.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527643",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: No. of hits on Website using c# Could anyone helps me by giving the answer for my question.
Here is the question...
How can we count the number of hits on our website for the day using c#
Thanks,
Bharath
A: You can create a google analytics account and place the javascript on your site. then google analytics will do it for you
A: Just create a counter and a persistence way to keep the values. This can be a File or Database.
The code below is for learning proposes, you should use an existing service for this as it's much more efficiency and you will not have lock problems if to many hits happen in the same time
create a new Class for example:
public static class PageHitCounter
{
private String fileTemplate = "dailyHits_{0:yyyyMMdd}.txt";
private DateTime now = DateTime.Now;
public static void Add()
{
// we'll create one file per day
// lets append a new user hit to a file
TextWriter tw = new StreamWriter(getFilename(now), true);
// let's write the date and something else, f.ex. the browser info
tw.WriteLine(String.Format("{0:dd-MM-yyyy};{1}",
now,
Request.ServerVariables["HTTP_USER_AGENT"]);
// close the file
tw.Close();
}
public static int Count(DateTime day)
{
int hits = 0;
// let's open the file and count how many lines,
// as we are adding one line per hit
using (var reader = File.OpenText(getFilename(day)))
while (reader.ReadLine() != null)
hits++;
return hits;
}
private string getFilename(Datetime day)
{
return Server.MapPath("~/App_Data/" + String.Format(fileTemplate, day));
}
}
in Code:
Page_Load(...) {
PageHitCounter.Add();
}
when you want to see how many hits, you can use
PageHitCounter.Count( DateTime.Now );
If you have a lot of pages and don't want to do this on each one, and assuming your project is WebForms, you can create a MasterPage and append this Add() to the MasterPage OnLoad event or you can create your own page and implement the code.
As an option to your real problem, you can use Woopra service for live results, I use in some forums and it's quite lovely see all users, you just need to create an account and use their javascript code in all your footer (normally we use a master page and just append in one file)
A: There must be an embedded code in your web pages to count the number of hits. Directly you can't access this info.
A: Is this for your website, or is this a class assignment?
There are plenty of existing tools that will give you a lot of information on the number of hits, types of visitors, various metrics about their behaviour, etc, etc...it's far more practical but not in C#.
If this is a class assignment - you could increment a counter on your website and persist it to the file system or a database.
Here is a CodePlex example you could look at and modify to track hits daily.
http://www.codeproject.com/KB/custom-controls/EasyHit.aspx
A: Read article, this may be helpful to you
http://imar.spaanjaars.com/238/howto-create-a-hit-counter-using-a-database-in-aspnet-1x-with-c-sharp
This developed with with C# and Microsoft Access database.
But for better performance use SQL database
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527650",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Apache Command Line Not Functioning Installed Apache Ver 2.2.3 on my vps with Centos 5.6 but when I try the a2dismod and a2enmod got Command not found error.
What can I do to fix it?
Thank you
*
*This is my first vps and this is also my first experience with linux and centos.
*The server is running fine just need to disable few modules.
A: Perhaps those commands were not in your path? If the programs are in your current working directory, try ./a2dismod.
To see what path our shell is searching, try echo $PATH.
A: On CentOS there are no a2enmod and a2dismod commands. To disable unneeded modules in Apache, you need to carry out steps as described at the lower end of – for instance – this post: http://www.cyberciti.biz/faq/howto-disable-apache-modules-under-linux-unix/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527652",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Send data via http to android web service I have to send data via http to android web service.
How to do this?
A: This may help you;
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
A: Have you search on the Google?. Also Look on this discussion, Post data to the server. It will help you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527653",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Using statistical tables with Rails I'm building an app that needs to store a fair amount of events that the users carry out. (Think LOTS as in millions per month).
I need to report on the these events (total of type x in the last month, etc) and need something resilient and fast.
I've toyed with Redis etc to store aggregates of the data, but this could just mean that I'm building up a massive store of single figure aggregates that aren't rebuildable.
Whilst this isn't a bad solution, I'm looking at storing the raw event data in tables that I can then query on a needs basis, and potentially generate aggregate counters on a periodic basis. This would thus give me the ability to add counters over time, and also carry out ad-hoc inspections on what is going on, something which aggregates don't allow.
Question is, how is best to do this? I obviously don't want to have to create a model for each table (which is what Rails would prefer), so do I just create the tables and interact with raw SQL on a needs basis, or is there some other choice for dealing with this sort of data?
A: I've worked on an app that had that type of data flow and the solution is the following :
-> store everything
-> create aggregates
-> delete everything after a short period (1 week or somehting) to free up resources
So you can simply store events with rails, have some background aggregate creation from another fast script (cron sql), read with rails the aggregates and yet another background script for raw event deletion.
Also .. rails and performance don't quite go hand in hand usually ;)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527655",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I add qt-mobility 1.2 to my sis file? I have QT Quick app for Symbian that use qt mobility 1.2 for Map element representation. So I need to add qt mobility as a dependency to my sis file.
For qt mobility 1.1 it is very simple – just add one string to settings of smart installer. But I dont know GUID of qt mobility 1.2 that I can pass to that config. Do we have same sort of workaround??
A: It's the same but QtMobility 1.2 isn't delivered by the SmartInstaller yet as far as I know.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527656",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.