text
stringlengths 8
267k
| meta
dict |
---|---|
Q: Kill parent process without administrator rights How can I kill the parent process without administrator rights? Process A creates process B, and in process B I need to kill process A.
A: Check this:
Taskkill
Ends one or more tasks or processes. Processes can be killed by
process ID or image name. Syntax
taskkill [/s Computer] [/u Domain\User [/p Password]]] [/fi
FilterName] [/pid ProcessID]|[/im ImageName] [/f][/t]
/t : Specifies to terminate all child processes along with the parent
process, commonly known as a tree kill.
You can start a process in C# like:
using System.Diagnostics;
string args = ""; // write here a space separated parameter list for TASKKILL
Process prc = new Process(new ProcessStartInfo("Taskkill", args));
prc.Start();
A: You want to ProcessB to signal to ProcessA that it wants to it to stop running. ProcessA can then clean up any resources and exit gracefully (as suggested in the comments to your answer). So how does a Process signal something to another Process? That is called Inter-Process Communication (IPC) and there are loads of ways to do on the same machine or across machines including message buses, web-service, named pipes.
A simple option is a system-wide EventWaitHandle - good example here Signalling to a parent process that a child process is fully initialised
A: so you have the source code for both processes. in this case you can use a named system event like a semaphore to gracefully end process A. for example, construct a named semaphore in process A, pass the name to process B as one of the command line parameters when starting process B. Open the existing named semaphore from process B and signal it to let process A know it can end. you could also use taskkill but not ending A gracefully could result in corrupting resources A uses.
A: All is very simple if you know parentProcessName, then solution is:
System.Diagnostics.Process.GetProcessesByName ("ParentProcessName")[0].Kill();
If not, then it will be a bit harder.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610097",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: is this linux serial port configured the same as the windows one I am trying to port a program to linux but i cannot get the serial port working.
this is the windows code
if( (idComDev[i] = CreateFile(ComStr,GENERIC_READ | GENERIC_WRITE,0,0,OPEN_EXISTING,0,0)) != INVALID_HANDLE_VALUE )
{
SetupComm(idComDev[i],1024,1024);
cto.ReadIntervalTimeout = MAXDWORD;
cto.ReadTotalTimeoutMultiplier = 0;
cto.ReadTotalTimeoutConstant = 0;
cto.WriteTotalTimeoutMultiplier = 0;
cto.WriteTotalTimeoutConstant = 0;
SetCommTimeouts(idComDev[i],&cto);
sprintf(ComStr,"COM%hd:19,n,8,1",CommNo[i]);
BuildCommDCB(ComStr,&dcb);
dcb.fBinary = TRUE;
dcb.BaudRate = baud;
dcb.fOutxCtsFlow = FALSE; // CTS output flow control
dcb.fOutxDsrFlow = FALSE; // DSR output flow control
dcb.fDtrControl = DTR_CONTROL_ENABLE; // DTR line on
dcb.fDsrSensitivity = FALSE; // DSR sensitivity
dcb.fTXContinueOnXoff = FALSE; // XOFF continues Tx
dcb.fOutX = FALSE; // XON/XOFF out flow control
dcb.fInX = FALSE; // XON/XOFF in flow control
dcb.fErrorChar = FALSE; // enable error replacement
dcb.fNull = FALSE; // enable null stripping
dcb.fRtsControl = RTS_CONTROL_DISABLE; // RTS flow control
dcb.fAbortOnError = FALSE; // abort reads/writes on error
dcb.wReserved = 0; // Not used; must be set to zero
dcb.ByteSize = 8; // number of bits/byte, 4-8
dcb.StopBits = ONESTOPBIT; // 0,1,2 = 1, 1.5, 2
dcb.Parity = SPACEPARITY; // use parity as address bit
if( CardType == 2 ) SetCommMask(idComDev[i],EV_TXEMPTY);
SetCommState(idComDev[i],&dcb);
dbprintf("Seg %d = COM%hd\r\n",i,CommNo[i]);
}
and this is my linux code
idComDev[i] = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NDELAY);
if (idComDev[i] == -1)
{
perror("open_port: Unable to open /dev/ttyS0 - ");
ret = false;
}
else
{
fcntl(idComDev[i], F_SETFL, 0);
struct termios options;
tcgetattr(idComDev[i], &options); // get current settings
cfsetispeed(&options, B115200); // set baud rate
cfsetospeed(&options, B115200); // set baud rate
options.c_cflag |= (CLOCAL | CREAD);
options.c_cflag &= ~PARENB; // set parity to no
options.c_cflag &= ~CSTOPB;//set one stop bit
options.c_cflag &= ~CSIZE; // Mask the character size bits
options.c_cflag |= CS8; // 8 bit data
options.c_lflag |= (ICANON);
options.c_iflag &= ~(IXON | IXOFF | IXANY); //disable software flow controll
tcsetattr(idComDev[i], TCSANOW, &options);// save the settings
whenever i try to write to the serial port it returns with -1 and gives me no information as to what went wrong. i tried using errorno and that said input/output error which is not helpful.
have i configured my serial port in the same way as it is in the original program ?
can anyone give advice on how to debug this problem as this is not my area of expertise
A: Perhaps one or more of the control lines are not set properly. Please look at tty_ioctl(4) section "Modem Control" for TIOCMSET and associated stuff. Your Windows code looks like it want to set DTR at least.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610103",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: compare java lists in the loop , I make some actions then get and add string to the list1
after loop: list1 contains 2 strings : OK
now, in another loop I get value on each iteration which return me a string and I would like to check that strings in list1 aren't available in the second:
for(inti=0;i<nb;i++){
value= table.getValue(i);
list1.add(value);
}
for(int j=0;j<nb;j++){
String toto = table.getValue(i);
//do other actions
//here verify that list1 doesn't contain toto
//I tried :
assetFalse(table.getValue(i).contains(list1)); //not OK !
}
A: Seems like it should be
assertFalse(list1.contains(table.getValue(i)));
If getValue returns a String, you cannot do a contains operation on it passing a List.
A: //here verify that list1 doesn't contain toto
//I tried :
assetFalse(table.getValue(i).contains(list1)); //not OK !
First the method is called assertFalse.
Second you're checking if toto contains the list ( table.getValue(i) is toto).
Note that your code could also be read as assertFalse(toto.contains(list1)); (with the spelling fixed and using the assignment above).
Instead I guess you'd like to do this instead:
assertFalse(list1.contains(toto));
Also note that in your two loops you iterate over the same collection (table) and the same indices ( 0 to nb-1). Thus list will always contain the values you check for (unless you're removing them somewhere) and thus your assertation will always fail.
Finally, please post compilable code: inti=0; won't compile as well as assetFalse(...) nor String toto = table.getValue(i);, since i isn't known in that loop (it is out of scope).
If you want us to help you, please put more effort into your questions.
Edit
If you want to compare two collections, you could also use a utility library like Apache Commons Collections, which has methods like CollectionUtils.containsAny(collection1, collection2) (this would return true if at least one element is present in both collections) etc.
Google Guava should have similar utilities.
A: Seems that you are trying to check if a list (list1) is contained in a string. That does not make sense. Try it vice versa.
A: If you're just comparing lists of strings a simple contains() method should work.
for(String value: list2){
//here verify that list1 doesn't contain string in list2
if(list1.contains(value)){
//Do something here.
}
}
A: You are referencing "i" in the second loop but it is declared in the first loop.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610109",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: objective c cocoa updating gui from a separate thread I have a thread which is incrementing the value of the variable "int count" . I want to update my UI with the new value of "int count" until I stop the increment by pressing the stop button. I've manage to update the UI but the memory footprint keep on growing. It doesn't show as a memory leak but it is an allocation problem.the heap size is being increased every time there is a call to a UI element from the thread. I can clearly see instruments leaks allocation part that I have some allocations which are only being freed when moving the Window of touching a UI element. I did not manage to solve the problem despite trying everything.
If there is a better way to update UI elements with "int count" new value, feel free to let me know.
Thanks
I posted the link to the cocoa project below if you want to run with instrument or allocation to see the problem or look at the source. It' a small project just a few lines.
Xcode Poject GUI UPDATE LINK
-(void) incrementCountGUI:(id)param{ // increment count and update gui
NSAutoreleasePool *pool=[[NSAutoreleasePool alloc]init];// pool just added
count++;
if (count>=100) {// MAKE SURE COUNT DOESN'T GO ABOVE 100
count=0;
}
[sliderDisplayOutlet setIntValue:count];// display value of count in textfield
[sliderOutlet setIntValue:count];// move slider to value of count
[pool release];
}
+(void) updateSliderThread:(id)param{// this thread will call incrementCountGUI method to continuously upgrade UI in the background
NSAutoreleasePool *myThreadPool=[[NSAutoreleasePool alloc]init];
while (shoudStop==NO) {
[ sharedAppInstance performSelectorOnMainThread:@selector(incrementCountGUI:) // update ui in main thread
withObject:nil
waitUntilDone:NO];
usleep(5000);// sleep microsec;
}
[myThreadPool release];
}
- (IBAction)stopCountAction:(id)sender {// START OR STOP counter thread
if ([stopCountButtonOutlet state]==1) { // button depressed=>START
shoudStop=NO;
[NSThread detachNewThreadSelector:@selector(updateSliderThread:) toTarget:[AppController class] withObject:nil];
[stopCountButtonOutlet setTitle: @" STOP" ];
}
if ([stopCountButtonOutlet state]==0){//button depressed=> STOP thread
shoudStop=YES;
[stopCountButtonOutlet setTitle:@" START INCREMENTING COUNT FROM THREAD "];
}
}
- (IBAction)sliderAction:(id)sender { // you can change the value of the variable count manualy.
count=[sliderOutlet intValue];
[sliderDisplayOutlet setIntValue:count];// display value of count
}
A: 1) First of all, you should never update the UI from a thread other than the main thread !
_Post a notification to the mainThread to ask it to update the UI, or use performSelector:onMainThread: or GCD and get_main_queue(), or whatever solution to make the main thread update the UI.
[EDIT] Sorry I missed the part of your code where you call performSelectorOnMainThread: so that's OK.
2) Moreover, using a thread for what you need is really not necessary. In general you should avoid thread, an prefer other techniques like NSOperationQueues, GCD, or even RunLoop scheduling.
In your case, using a thread an usleep(5000) is just overhead and will arise a lot of problems related to multithreading (read Apple's Concurrency Programming Guide and Threading Programming Guide).
You could do the same thing using a repeating NSTimer, it will be much more easier to code and manage, and will avoid you a lot of trouble.
A: Hmm.. let's try to release behind-the-scene objects created by performSelectorOnMainThread calls, if any.
+(void) updateSliderThread:(id)param
{
NSAutoreleasePool *myThreadPool=[[NSAutoreleasePool alloc]init];
int drainCount = 0;
while (shoudStop==NO)
{
[ sharedAppInstance performSelectorOnMainThread:@selector(incrementCountGUI:)
withObject:nil
waitUntilDone:NO];
usleep(5000);// sleep microsec;
// Release pooled objects about every 5 seconds
if (++drainCount >= 1000)
{
[myThreadPool release];
myThreadPool = [[NSAutoreleasePool alloc]init];
drainCount = 0;
}
}
[myThreadPool release];
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610115",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Layer-backed OpenGLView redraws only if window is resized I have a window with a main view of type NSView and a subview which is a subclass of NSOpenGLView whose name is CustomOpenGLView.
The subclass of NSOpenGLView is obtained through a Custom View in Interface Builder and by setting its class to CustomOpenGLView.
This is made according to the Apple Sample Code Layer Backed OpenGLView.
The app is made to draw something to the OpenGLContext every, let's say, 0.05 seconds.
With Core Animation Layer disabled I am able to see the moving object in the view, which is the consequence of the continuous redrawing of the view. And everything works flawlessly.
I now want to have a semitransparent view on top of CustomOpenGLView to house control buttons like play/stop/ecc..
To do this I have add a subview to CustomOpenGLView and I have enabled Core Animation Layer on CustomOpenGLView. Control buttons are placed in this new subview.
This way the view with control buttons correctly appears on top of CustomOpenGLView but now the view doesn't redraw. It draws only if I resize the window containing all these views.
The result is that I do not see any "animation"...I only see a still image which represents the first frame which gets drawn when the drawing loop starts.
If I resize the window, openGLContext gets redrawn until I stop resizing the window. After that I see once again a still image with the last drawing occurred during the resize.
In addition, when the drawing loop starts, only the first "frame" appears on screen and if I resize the window, let's say, 5 seconds later, I see in the view exactly what it should have been drawn 5 seconds after the starting of drawing loop.
It seems like I need to set [glView setNeedsDisplay:TRUE]. I did that but nothing has changed.
Where is the mistake? Why does adding Core Animation Layer break the redraw? Does it imply something I'm not getting?
A: When you have a normal NSOpenGLView, you can simply draw something via OpenGL and then call -flushBuffer of the NSOpenGLContext to make the rendering appear on screen. If your context is not double buffered, which is not necessary if you render to a window, since all windows are already double buffered by themselves in MacOS X, calling glFlush() is sufficient as well (only for real fullscreen OpenGL rendering, you'll need double buffering to avoid artifacts). OpenGL will then render directly into the pixel storage of your view (which is in fact the backing storage of the window) or in case of double buffering, it will render to the back-buffer and then swap it with the front-buffer; thus the new content is immediately visible on screen (actually not before the next screen refresh but such a refresh takes place at least 50-60 times a second).
Things are a bit different if the NSOpenGLView is layer-backed. When you call -flushBuffer or glFlush(), the rendering does actually take place just as it did before and again, the image is directly rendered to the pixel storage of the view, however, this pixel storage is not the backing storage of the window any longer, it is the "backing layer" of the view. So your OpenGL image is updated, you just don't see it happening since "drawing into a layer" and "displaying a layer on screen" are two completely different things! To make the new layer content visible, you'll have to call setNeedsDisplay:YES on your layer-backed NSOpenGLView.
Why didn't it work for you when you called setNeedsDisplay:YES? First of all, make sure you perform this call on the main thread. You can perform this call on any thread you like, it will for sure mark the view dirty, yet only when performing this call on the main thread, it will also schedule a redraw call for it (without that call it is marked dirty but it won't be redrawn until any other parent/child view of it is redrawn). Another problem could be the drawRect: method. When you mark the view as dirty and it is redrawn, this method is being called and whatever this method "draws" overwrites whatever content is currently within the layer. As long as your view wasn't layer-backed, it didn't matter where you rendered your OpenGL content but for a layer-backed view, this is actually the method where you should perform all your drawings.
Try the following: Create a NSTimer on your main thread that fires every 20 ms and calls a method that calls setNeedsDisplay:YES on your layer-backed NSOpenGLView. Move all your OpenGL render code into the drawRect: method of your layer-backed NSOpenGLView. That should work pretty well. If you need something more reliably than a NSTimer, try a CVDisplayLink (CV = CoreVideo). A CVDisplayLink is like a timer, yet it fires every time the screen has just been redrawn.
Update
Layered NSOpenGLView are somewhat outdated, starting with 10.6 they are not really needed any longer. Internally a NSOpenGLView creates a NSOpenGLLayer when you make it layered, so you can as well use such a layer directly yourself and "building" your own NSOpenGLView:
*
*Create your own subclass of NSOpenGLLayer, let's call it MyOpenGLLayer
*Create your own subclass of NSView, let's call it MyGLView
*Override - (CALayer *)makeBackingLayer to return an autoreleased instance of MyOpenGLLayer
*Set wantsLayer:YES for MyGLView
You now have your own layer backed view and it is layer backed by your NSOpenGLLayer subclass. Since it is layer backed, it is absolutely okay to add sub-views to it (e.g. buttons, textfields, etc.).
For your backing layer, you have basically two options.
Option 1
The correct and officially supported way is to keep your rendering on the main thread. Therefor you must do the following:
*
*Override canDrawInContext:... to return YES/NO, depending on whether you can/want to draw the next frame or not.
*Override drawInContext:... to perform your actual OpenGL rendering.
*Make the layer asynchronous (setAsynchronous:YES)
*Be sure the layer is "updated" whenever its resized (setNeedsDisplayOnBoundsChange:YES), otherwise the OpenGL backing surface is not resized when the layer is resized (and the rendered OpenGL context must be stretched/shrunk each time the layer redraws)
Apple will create a CVDisplayLink for you, that calls canDrawInContext:... on main thread each time it fires and if this method returns YES, it calls drawInContext:.... This is the way how you should do it.
If your rendering is too expensive to happen on main thread, you can do the following trick: Override openGLContextForPixelFormat:... to create a context (Context B) that is shared with another context you created earlier (Context A). Create a framebuffer in Context A (you can do that before or after creating Context B, it won't really matter); attach depth and/or stencil renderbuffers if required (of a bit depth of your choice), however instead of a color renderbuffer, attach a "texture" (Texture X) as color attachments (glFramebufferTexture()). Now all color render output is written to that texture when rendering to that framebuffer. Perform all rendering to this framebuffer using Context A on any thread of your choice! Once the rendering is done, make canDrawInContext:... return YES and in drawInContext:... just draw a simple quad that fills the whole active framebuffer (Apple has already set it for you and also the viewport to fill it completely) and that is textured with the Texture X. This is possible, since shared contexts share also all objects (e.g. like textures, framebuffers, etc.). So your drawInContext:... method will never do more than drawing a single, simple textured quad, that's all. All other (possibly expensive rendering) happens to this texture on a background thread and without ever blocking your main thread.
Option 2
The other option is not officially supported by Apple and may or may not work for you:
*
*Don't override canDrawInContext:..., the default implementation always returns YES and that's what you want.
*Override drawInContext:... to perform your actual OpenGL rendering, all of it.
*Don't make the layer asynchronous.
*Don't set needsDisplayOnBoundsChange.
Whenever you want to redraw this layer, call display directly (NOT setNeedsDisplay! It's true, Apple says you shouldn't call it, but "shouldn't" is not "mustn't") and after calling display, call [CATransaction flush]. This will work, even when called from a background thread! Your drawInContext:... method is called from the same thread that calls display which can be any thread. Calling display directly will make sure your OpenGL render code executes, yet the newly rendered content is still only visible in the backing storage of the layer, to bring it to screen you must force the system to perform layer compositing and [CATransaction flush] will do exactly that. The class CATransaction, which has only class methods (you will never create an instance of it) is implicitly thread-safe and may always be used from any thread at any time (it performs locking on its own whenever and wherever required).
While this method is not recommend, since it may cause redraw issues for other views (since those may also be redrawn on threads other than main thread and not all views support that), it is not forbidden either, it uses no private API and it has been suggested on the Apple mailing list without anyone at Apple opposing it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610117",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: How to be warned when overriding a virtual method with wrong visibility When overriding a virtual method, I noticed that when I make a mistake in the visibility (protected method overridden as a public method), I'm not warned by the compiler.
It is valid C++, but usually it is a mistake.
For example:
#include <iostream>
class Base
{
protected:
virtual void ProtectedMethod(void)
{
std::cout << "Base::ProtectedMethod" << std::endl;
}
};
class Derived : public Base
{
public:
virtual void ProtectedMethod(void)
{
std::cout << "Derived::ProtectedMethod" << std::endl;
}
};
int main(int, char* [])
{
Derived d;
d.ProtectedMethod();
}
I tried compiling with gcc and clang, with -Wall -Wextra, with no luck.
I ran CppCheck on this code, still no luck.
What tool can help me detect this ?
I need to fix the whole sources of a library I'm working on.
A: Inspirel lets you define your own rules: http://www.inspirel.com/vera/
A: I found a solution to my needs using ctags.
CTags can parse C++ and dump information to a file.
Using the following options:
$CTAGS -f $TAGFILE --fields=fkstia --c++-kinds=+p -R $SOURCES
I can get all the needed information in an easily parseable format.
Piping $TAGFILE through a few grep commands, I can verify that a known function name has the expected visibility, and issue a warning with the incriminated file otherwise.
Here is a bash snippet to extract info from the ctags output :
#!/bin/bash
function check_method {
echo "Checking $1 (should be $2 and is not)"
cat $TAGFILE | grep "^$1 " | grep "access" | grep -v "access:$2" | cut -f 2
echo
}
# will warn anytime a method called ProtectedMethod is not protected
check_method ProtectedMethod protected
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610121",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: How to retrive all comments for a specific post? Having a bit of block trying to get comments for a specific post. Working with MVC 3 and VBNET. A post url looks like /Blog/Post/1. I can display the post without problem but need to get the comments for PostId=1 from the Comments table. I tried a Linq inner join statement
Dim results = From P In _rdsqlconn.Posts Where P.PostId = id Join c In _rdsqlconn.Comments On P.PostId Equals c.PostId Select P
Public Class RDSQLConn
Inherits DbContext
Public Sub New()
End Sub
Property Posts As DbSet(Of Post)
Property Categories As DbSet(Of Category)
Property Comments As DbSet(Of Comment)
End Class
But this throws:
`Unable to cast object of type 'System.Data.Entity.Infrastructure.DbQuery`1[RiderDesignMvcBlog.Core.Entities.Post]' to type 'RiderDesignMvcBlog.Core.Entities.Post'.`
However a SQL query such as the one below works just fine. Can i just pass in this sql statement to my EF?
Select * From Posts INNER JOIN Comments on dbo.Posts.PostId = Comments.PostId where dbo.Posts.PostId = 1
A: Dim results = From P In _rdsqlconn.Posts Join c In _rdsqlconn.Comments On P.PostId Equals c.PostId
Where P.PostId = id
Select P
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610123",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Lightswitch Organizational Chart Situation:
*
*I have an application that have Employee information
*Each Employee has a Manager field (that refers to another employee)
*To enhance the experience, I was thinking of placing an organization chart based on the inputted information.
Question:
*
*Is there a way to dynamically generate an organizational chart based on Employee-Manager information in Lightswitch? I know I will recurse on the relationships, however I'm unsure on how to present it.
*If it's not possible in a graphical format, would it be possible to have it represented in a grid?
*Would it be possible through creating a custom control?
A: I have create a custom control to work with hierarchies. You can see some screen shots and source code.
The custom control is based on Karol Zadora msdn post.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610127",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Use PHP to convert JPEGs to transparent PNG I have a lot of JPEG images that I want to convert to PNG images using PHP.
The JPEGs are going to be uploaded by clients so I can't trust them to make sure they are in the right format.
I also want to make their white backgrounds transparent.
Does PHP have any functions I can use to achieve this?
A: $f = imagecreatefromjpeg('path.jpg');
$white = imagecolorallocate($f, 255,255,255);
imagecolortransparent($f, $white);
More details here
A: After a few days of trying different solutions and doing some more research,
this is what I found worked for me.
$image = imagecreatefromjpeg( 'image.jpg' );
imagealphablending($image, true);
$transparentcolour = imagecolorallocate($image, 255,255,255);
imagecolortransparent($image, $transparentcolour)
The imagealphablending($image, true); is important.
Using imagesavealpha($f, true); as mentioned in a previous answer definitely doesn't work and seems to actually prevent you from making the background transparent...
To output the transparent image with the correct headers.
<?php
header( 'Content-Type: image/png' );
imagepng( $image, null, 1 );
?>
A: This worked for me:
$image = imagecreatefromjpeg( "image.jpg" );
imagealphablending($image, true);
imagepng($image, "image.png");
A: I found this solution at Convert jpg image to gif, png & bmp format using PHP
$imageObject = imagecreatefromjpeg($imageFile);
imagegif($imageObject, $imageFile . '.gif');
imagepng($imageObject, $imageFile . '.png');
imagewbmp($imageObject, $imageFile . '.bmp');
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610128",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Simple Collision Detection - Android I want to do really simple collision detection in a pong like game.
The ball is a square and the paddle (bats) is rectangles.
I have two entities coming in where I can get the current X and Y position, and the bitmap height and width. Which is the simplest way to do this?
I have this code:
public void getCollision(Entity enitityOne, Entity enitityTwo){
double eventCoordX = (enitityOne.getCenterX() - (enitityTwo.getBitmapWidth() / 2));
double eventCoordY = (enitityOne.getCenterY() - (enitityTwo.getBitmapHeight() / 2));
double X = Math.abs(enitityTwo.getxPos() - eventCoordX);
double Y = Math.abs(enitityTwo.getyPos() - eventCoordY);
if(X <= (enitityTwo.getBitmapWidth()) && Y <= (enitityTwo.getBitmapHeight())){
enitityOne.collision();
enitityTwo.collision();
}
}
But I'm pretty blind, this only works in the middle of the paddle not on the sides.
The problem is I can't see where the code is wrong.
Anybody?
Anybody have a better idea?
A: If all you want is to find whether or not 2 given rectangles somehow intersect (and therefore collide), here's the simplest check (C code; feel free to use floating-point values):
int RectsIntersect(int AMinX, int AMinY, int AMaxX, int AMaxY,
int BMinX, int BMinY, int BMaxX, int BMaxY)
{
assert(AMinX < AMaxX);
assert(AMinY < AMaxY);
assert(BMinX < BMaxX);
assert(BMinY < BMaxY);
if ((AMaxX < BMinX) || // A is to the left of B
(BMaxX < AMinX) || // B is to the left of A
(AMaxY < BMinY) || // A is above B
(BMaxY < AMinY)) // B is above A
{
return 0; // A and B don't intersect
}
return 1; // A and B intersect
}
The rectangles A and B are defined by the minimum and maximum X and Y coordinates of their corners.
Um... This has been asked before.
A: if you are dealing with rectangles then
/**
* Check if two rectangles collide
* x_1, y_1, width_1, and height_1 define the boundaries of the first rectangle
* x_2, y_2, width_2, and height_2 define the boundaries of the second rectangle
*/
boolean rectangle_collision(float x_1, float y_1, float width_1, float height_1, float x_2, float y_2, float width_2, float height_2)
{
return !(x_1 > x_2+width_2 || x_1+width_1 < x_2 || y_1 > y_2+height_2 || y_1+height_1 < y_2);
}
this is a good example...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610129",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Display on page ready First of all sorry for my poor english. Do not hesitate to tell me if the problem I will try to describe is not clear...
I have a menu like this :
<ul class="menu">
<li>
<a href="#">Label 1</a>
<ul class="sub-menu">
<li>
<a href="#">Label 1</a>
</li>
</ul>
</li>
</ul>
When I click on the ul.menu li, the child content is displayed with an accordion system.
My script is working well.
In the css, .sub-menu is displayed at "block" (in case of javascript is not activated in the browser).
In my script.js file, when the doc is ready, i launch a function which manage the menu.In this function, I start by hidding the ul.sub-menu and then come the mechanisms of the menu .
My problem is, when the page is loading, I can firstly see the ul.sub-menu displayed as block, and very quickly, the "script.js" file does its work and hide those elements.
Each time the menu is displayed after a loading, it gives to the user an unpleasant effect as it looks like if the menu is flashing (everything opened, and then every sub-menu disappear).
How can I do to fix this issue ? Thanks in advance for your help...
NB - Everything is working regarding the functionalities, it's only a visual matter.
A: The best thing to do is to start with
ul.sub-menu{
display:none;
}
in your CSS.
And then to show that once the visitor has activated the link/hover, ec.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610131",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Setting image in Alert dialog which comes from other activity I have an alert dialog, in that i have a button and an image view, on click of button an activity is fired which contains a gallery in which there are pictures, when clicked on a picture i have to show it in that image view. please guide.
A: Use startActivityForResult to start the new Activity from the button and Override the onActivityResult method in your Activity where is placed your alert dialog.And depending on the result which your Activity returns, you can set the chosen image.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610135",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: One to one mapping using primary key I have two simple tables: Item and ItemDetail
Table Item has following columns: id, name
Table ItemDetail has following columns: itemId, color, size
An ItemDetail never exists without an Item. An Item can exist without any ItemDetail. For every Item there is at most one ItemDetail.
How should this situation be correctly mapped in hibernate?
So far I found only the following solution:
<class name="Item" table="Item">
<id name="id" column="id">
<generator class="native"></generator>
</id>
<property name="name" />
<one-to-one name="itemDetail" class="ItemDetail" cascade="save-update"/>
</class>
<class name="ItemDetail">
<id name="itemId">
<generator class="foreign">
<param name="property">item</param>
</generator>
</id>
<one-to-one name="item" class="Item" constrained="true" />
<property name="color" />
<property name="size" />
</class>
This solution works however I think it is not "clean" since in class ItemDetail I need to have both properties itemId and item.
private class Item {
private long id;
private String name;
private ItemDetail detail;
}
private class ItemDetail {
private long itemId;
private Item item;
private int color;
private int size;
}
I think that from OOP perspective it is incorrect if object ItemDetail knows anything about Item. This means that it should not have properties itemId and item. Even if we agreed that it is correct if ItemDetail knows about Item, it is still incorrect that it has two references to Item - one using property itemId and one using property itemDetail. It can then very easily happen that these two properties are not synchronized. That is itemId references to different Item than the property item. To avoid this we would need to update both itemId and item everytime when we decide to set an Item to an ItemDetail.
Is there any other solution which does not have these drawbacks?
Thank you
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610142",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Why does gettext translate an empty string to the .po header text? I've got gettext setup within PHP5. After some struggling with the charactersets and the like, I've managed to translate some basic strings. Now I've ran into a problem. When translating an empty string I expect to get the untranslated (empty) string back (correct me if I'm wrong ;)).
However instead of returning the input string, I get the header of the .PO file as the translation:
Project-Id-Version: PACKAGE VERSION Report-Msgid-Bugs-To: POT-Creation-Date: 2011-09-22 15:03+0200 PO-Revision-Date: 2011-09-22 15:37+0200 Last-Translator: timo Language-Team: English Language: en MIME-Version: 1.0 Content-Type: text/plain; charset=ASCII Content-Transfer-Encoding: 8bit Plural-Forms: nplurals=2; plural=(n != 1);
When I look in the .mo file with a text-editor I see that the header seems to placed at a random place within the file. I would like to show you, but I can't paste the file in. It looks like there is a list of my msgid's, then the header and then a list of my msgstr's
I've used the following command to generate the .mo file:
msgfmt -c -v -o en/LC_MESSAGES/messages.mo messages_en.po
After this command I've restarted my webserver (lighttpd).
What did I do wrong and how can I fix it?
A: After searching around with some different queries I stumbled upon this site:
http://framework.zend.com/issues/browse/ZF-2914
Here I found that the translation of the empty string to meta information is actually in the specifications of gettext:
This also has another advantage, as the empty string in a PO file GNU gettext is usually translated into some system information attached to that particular MO file, and the empty string necessarily becomes the first in both the original and translated tables, making the system information very easy to find.
A: You can try creating another function to call gettext only when the message it is different from blank or empty string (""). Something like this in php:
function _tl($msg)
{
$ret = "";
if($msg != "")
{
$ret = _($msg);
}
return $ret;
}
Then on poedit, on your catalog preferences, on the keywords tab set the using of the new function _tl. This is the manner which poedit will recognize it on your code.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610144",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How to map Int to int8 by default? I have an existing model implementation that needs to work with a new database.
Can i configure Hibernate to map int variables to int8 instead of int4 by default?
A: Created a new Dialect for my specific Database type as proposed in a comment.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610151",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: The opposite of Hungarian Notation? Most programmers know of a thing called 'Hungarian Notation', each variable has a nice prefix to denote its data type, i.e.
bIsExciting = false; // Boolean
strName = "Gonzo"; // String
iNumber = 10; // Integer
While this style of notation has fallen out of favor, I am seeing (at work, internet, etc.) a lot of data type indicators added as a 'suffix' to variable names, i.e.
NameStr = "Gonzo"; // String
NumberInt = 10; // Integer
MyRideBike = new Bike(); // Bicycle
Is there a name for this, when the data type is suffixed to a variable name?
EDIT: To clarify..., is there a distinct name for such a thing? If not, some concise ideas on what to call it would certainly be appreciated.
A: This is not the opposite of Hungarian notation, this is Hungarian notation in a different guise, if we follow Stroustrup's definition of Hungarian notation as "embedding an abbreviated version of a type in a variable name". If you want to call it anything, call it suffix Hungarian. (And please tell your colleagues that it's useless in most cases.)
A: I would call this reverse hungarian notation which would be consistent with the difference between polish notation and reverse polish notation.
Additionally billmcc's post on the following link shows real life usage of the term "reverse hungarian notation"
What was the strangest coding standard rule that you were forced to follow?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610157",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Convert PIL Image to Cairo ImageSurface I'm trying to create a cairo ImageSurface from a PIL image, the code I have so far is:
im = Image.open(filename)
imstr = im.tostring()
a = array.array('B', imstr)
height, width = im.size
stride = cairo.ImageSurface.format_stride_for_width(cairo.FORMAT_RGB24, width)
return cairo.ImageSurface.create_for_data(a, cairo.FORMAT_ARGB24, width, height, stride)
But this is giving me
TypeError: buffer is not long enough.
I don't really understand why this is, perhaps I don't understand image formats well enough.
I'm using cairo 1.10.
A: Cairo's create_for_data() is wants a writeable buffer object (a string can be used as a buffer object, but it's not writable), and it only supports 32 bits per pixel data (RGBA, or RGB followed by one unused byte). PIL, on the other hand, provides a 24bpp RGB read-only buffer object.
I suggest you tell PIL to add an alpha channel, then convert the PIL buffer to a numpy array to get a writable buffer for Cairo.
im = Image.open(filename)
im.putalpha(256) # create alpha channel
arr = numpy.array(im)
height, width, channels = arr.shape
surface = cairo.ImageSurface.create_for_data(arr, cairo.FORMAT_RGB24, width, height)
A: The accepted version doesn't work correctly if:
*
*Your image has colors
*Your image is not opaque
*Your image is in a mode different from RGB(A)
In cairo image colors have their value premultiplied by the value of alpha, and they are stored as a 32 bit word using the native CPU endianness. That means that the PIL image:
r1 g1 b1 a1 r2 g2 b2 a2 ...
is stored in cairo in a little endian CPU as:
b1*a1 g1*a1 r1*a1 a1 b2*a2 g2*a2 r2*a2 a2 ...
and in a big endian CPU as:
a1 r1*a1 b1*a1 g1*a1 a2 r2*a2 g2*a2 b2*a2 ...
Here is a version that works correctly on a little endian machine without the NumPy dependency:
def pil2cairo(im):
"""Transform a PIL Image into a Cairo ImageSurface."""
assert sys.byteorder == 'little', 'We don\'t support big endian'
if im.mode != 'RGBA':
im = im.convert('RGBA')
s = im.tostring('raw', 'BGRA')
a = array.array('B', s)
dest = cairo.ImageSurface(cairo.FORMAT_ARGB32, im.size[0], im.size[1])
ctx = cairo.Context(dest)
non_premult_src_wo_alpha = cairo.ImageSurface.create_for_data(
a, cairo.FORMAT_RGB24, im.size[0], im.size[1])
non_premult_src_alpha = cairo.ImageSurface.create_for_data(
a, cairo.FORMAT_ARGB32, im.size[0], im.size[1])
ctx.set_source_surface(non_premult_src_wo_alpha)
ctx.mask_surface(non_premult_src_alpha)
return dest
Here I do the premultiplication with cairo. I also tried doing the premultiplication with NumPy but the result was slower. This function takes, in my computer (Mac OS X, 2.13GHz Intel Core 2 Duo) ~1s to convert an image of 6000x6000 pixels, and 5ms to convert an image of 500x500 pixels.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610159",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Thread ending using java.util.concurrent API I am working with threads, and decided to use the most modern API (java.util.concurrent package).
Here's what I want to do (pseudocode):
//List of threads
private ScheduledExecutorService checkIns = Executors.newScheduledThreadPool(10);
//Runnable class
private class TestThread implements Runnable{
private int index = 0;
private long startTime = 0;
private long timeToExecute = 3000000;
public TestThread(int index){
this.index = index;
}
public void run(){
if(startTime == 0)
startTime = System.currentTimeMillis();
else if(startTime > (startTime+timeToExecute))
//End Thread
System.out.println("Execute thread with index->"+index);
}
}
//Cycle to create 3 threads
for(int i=0;i< 3; i++)
checkIns.scheduleWithFixedDelay(new TestThread(i+1),1, 3, TimeUnit.SECONDS);
I want to run a task on a certain date and repeat it until a certain amount of time. After the time has elapsed, the task ends. My only question is how to end with the thread?
A: Well, you can throw an exception from the task when it should no longer execute, but that's fairly brutal Alternatives:
*
*Schedule the task once, making the task aware of the scheduler, so it can reschedule itself when it's finished its current iteration - but just return immediately if it's after its final time.
*Use something like Quartz Scheduler which is more designed for this sort of thing.
Of course the first version can be encapsulated into a somewhat more pleasant form - you could create a "SchedulingRunnable" which knows when it's meant to run a subtask (provided to it) and how long for.
A: A thread terminated when its run method exists. Seems like you just need to do the following:
public void run(){
if(startTime == 0)
startTime = System.currentTimeMillis();
while (System.currentTimeMillis() < (startTime+timeToExecute)){
// do work here
}
//End Thread
System.out.println("Execute thread with index->"+index);
}
A: If you want to do a continuous task: in the run function make a while loop that every now and then checks if it has run long enough. When the task has completed (the run() function exits), the Thread is free to be used for other tasks. Use the scheduler to shedule the task to repeated daily.
If you don't want a continuous task you have several options. The easily one I would say is to decide when a partial task is done if you want to schedule a new onetime task.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610160",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ASP.NET SQL Server insert error So I've these two statements:
string insertUserData = "INSERT INTO W711_User_Data(Network_ID, F_Name, M_Name, L_NAME, Badge, Telephone, Org_Code, Org_Name, Req_Head_Network_ID)Values(@networkID1, @firstName1, @middleName1, @lastName1, @badgeNumber1, @telephone1, @orgCode1, @orgName1, @myUserName1)";
string insertReservationData = "INSERT INTO W711_Reservation_Data(ID, Network_ID, EventTitle, StartDate, EndDate, Justification) Values(null, @networkID2, @eventTitle1, @startDate1, @endDate1, @justification1)";
The network id in second string is foreign key relation with network id in first table.
The problem is: When I run the application in VS2010, it gives the error:
Can't insert explicit value for identity columnin table 'W711_Reservation_Data' when IDENTITY_INSERT is set to OFF.
Then I read to do this somewhere:
SET IDENTITY_INSERT W711_Reservation_Data ON
But it also fails and gives the same error again!
Please help
Thanks
p.s. sql server
A: Why are you trying to insert null as the value for the ID column anyway? Assuming that this is the IDENTITY column that is the source of the complaint then it seems more likely you need to just leave it out of the column list and don't pass any explicit value in. i.e.
INSERT INTO W711_Reservation_Data
(Network_ID, EventTitle, StartDate, EndDate, Justification)
Values
(@networkID2, @eventTitle1, @startDate1, @endDate1, @justification1)
A: if your id is an identity (aka auto generated from the database), just do not list the ID field in any place in the INSERT Statement, not as column name and not in the values list:
to get the ID generated by SQL Server you call SCOPE_IDENTITY in this way:
INSERT INTO W711_Reservation_Data(Network_ID, EventTitle, StartDate, EndDate, Justification) Values(@networkID2, @eventTitle1, @startDate1, @endDate1, @justification1)";
RETURN SCOPE_IDENTITY()
Edit: this is the second of your two statements, I have removed the ID and the NULL...
A: There might be two possibility.
1]
if Network_ID in first table is primary key auto generated then
insert data in first table.
then get latest network id from that table and
pass that network id with second query.
2].
If ID column in second table is primary key then
Do not pass null in second query.
either make auto generated or pass uniquer value in query.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610165",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Simple functions giving me a crash on Objective-C I'm coding a simple calculator and I want to make an unique function for all 4 arithmetic buttons. I got here:
-(IBAction)simbolo1:(UIButton*)sender{
if (isNumeric(campo1.text)) {
NSString *str=campo1.text;
campo2.text=str;
int S=1;
NSString *cmp1 = [NSString stringWithFormat:@"%d", S];
sinal.text=cmp1;
campo1.text=@"";
} else {
campo1.text=@"Only numeric values";
}
}
But, for some reason, I cant get this to work. Everytime I click in the button, I get a crash.
So, I check where really was the error and I deleted the whole code:
-(void)simbolo1:(UIButton*)sender{
campo1.text=@"Only numeric values";
}
Those lines of code appear to gave me the same error as before
I'm getting a 'green :marker' on this file:
#import <UIKit/UIKit.h>
int main(int argc, char *argv[]){
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
int retVal = UIApplicationMain(argc, argv, nil, nil); <--------- This line right here
[pool release];
return retVal;
}
EDIT---------------
On the debud console im getting this:
2011-09-30 09:17:14.319 Teste iPhone[28432:fb03] Applications are expected to have a root view controller at the end of application launch
2011-09-30 09:17:21.714 Teste iPhone[28432:fb03] -[Teste_iPhoneAppDelegate simbolo1]: unrecognized selector sent to instance 0x6b7c2d0
2011-09-30 09:17:21.715 Teste iPhone[28432:fb03] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Teste_iPhoneAppDelegate simbolo1]: unrecognized selector sent to instance 0x6b7c2d0'
*** First throw call stack:
(0x166d062 0x17fed0a 0x166ecfd 0x15d3f10 0x15d3cf2 0x166eed9 0x16eb2 0x16e4a 0xbc3e6 0xbc8af 0xbbb6e 0x3c2a0 0x3c4c6 0x22c74 0x16399 0x1557fa9 0x16411d5 0x15a6042 0x15a492a 0x15a3dd4 0x15a3ceb 0x1556879 0x155693e 0x1438b 0x272d 0x26a5)
terminate called throwing an exception(gdb)
A: There is not enough information to help you. You need to look in the debugger console and show us the error and the stack.
However, I'm going to take a wild guess and say that you didn't connect the campo1 IBOutlet to its UIView in Interface Builder, and that it's nil. To fix, edit the view in Interface Builder (or in Xcode 4, just click on it), and drag the little circle next to the campo1 outlet (in the Connections tab) onto the UIView component that you want it to correspond to.
If that's not it, the error isn't here, but is probably caused by something else in your program.
[EDIT after seeing console]: Your connections look misconfigured. Why would it try to send the simbolo1 selector to Teste_iPhoneAppDelegate? It should send it to your ViewController. Did you play around with the connections (specifically, the delegate one) in Interface Builder -- or the class?
A: to set text in UITextField use
[campo1 setText:@"Only numeric values"];
and also don't forget to link IBOutlet UITextField* campo1; to proper UITextField in XCode IB
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610173",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is it legal to create a recursive background handler in iphone?(processing when app enters the background) If I register an app for background app in did enter background and make a background handler with approximately 10 mins to finish the task, after the time is over the handler will call finishing block and in this block again create the background handler you will get again 10 mins and so on, in this way application will remain in background. I mean is it OK to do that....? or will apple object to this?
A: From the documentation:
Applications running background tasks have a finite amount of time in
which to run them. (You can find out how much time is available using
the backgroundTimeRemaining property.) If you do not call
endBackgroundTask: for each task before time expires, the system kills
the application.
So, no, you can't indefinitely run in the background.
A: Yeah thats correct, you cannot run infinitely in this way. But i have found one more trick, when applicatuon enters background, start playing an audio with 0 volume :-) Your app will never get killed.
A: There is a VoIP app, Media5, which can receive in background incoming calls using UDP sockets.
Developers said they used a "trick" to mantain the app active forever and I'd exclude the silent audio playing option. So the question is: what's that trick?
Also Bria can receive with UDP in background.
A: From Comment 20 at Issue 515: Background app support for iPhones with multitasking support:
I'm pretty sure that without playing continuously an audio file or
logging GPS position you cannot keep alive UDP listening sockets in
iOS 4.3+ (both in the main thread or in a secondary one). If you play
an audio play with AVAudioPlayer (after initializing an AudioSession
before) in a nsrunloop every 5 seconds, the main thread is kept active
and moreover it's NOT necessary to declare the audio background
support in info.plist.
I think this is the "trick" used by Media5 and Bria. I tried also
creating a infinite TCP stream to the loopback interface declaring it
as VoIP, just to see if also UDP socket is kept alive. The answer is
no, only TCP sockets works while in background (and with screen
locked), UDP is closed in the meanwhile and cannot listen for incoming
calls anymore.
So the key point is that the main thread must be kept active... using
a simple nstimer o infinite runloop alone is useless, since the
watchdog kills the process after few seconds in background (except if
you work in debug mode with GDB interface attached, it runs forever).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610182",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ContentProvider Problems with Phone.DISPLAY_NAME See code to get all contacts on phone:
public ContactInfo[] getContactList(String selection, String[] selectionargs) {
String[] projection = new String[] {
Contacts._ID,
Contacts.DISPLAY_NAME,
};
String sortOrder = Phone.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
Cursor cursor = context.getContentResolver().query(Contacts.CONTENT_URI,
projection, selection, selectionargs, sortOrder);
ContactInfo[] contactInfoList = new ContactInfo[cursor.getCount()];
ContactInfo contactInfo;
int i=0;
while(cursor.moveToNext()) {
contactInfo = new ContactInfo(cursor.getString(cursor.getColumnIndex(Contacts.DISPLAY_NAME)), "");
String[] projectionPhone = new String[] {
Phone.CONTACT_ID,
Phone.DISPLAY_NAME,
Phone.NUMBER,
Phone.TYPE,
};
Cursor phoneCursor = context.getContentResolver().query(Phone.CONTENT_URI,
projectionPhone, Phone.DISPLAY_NAME + "='" + contactInfo.getName() + "'", null, null);
PhoneInfo[] phoneInfoList = new PhoneInfo[phoneCursor.getCount()];
int j = 0;
while(phoneCursor.moveToNext()) {
int type = ContactInfo.TYPE_OTHER;
if (phoneCursor.getInt(phoneCursor.getColumnIndex(Phone.TYPE)) == Phone.TYPE_HOME)
type = ContactInfo.TYPE_HOME;
else if (phoneCursor.getInt(phoneCursor.getColumnIndex(Phone.TYPE)) == Phone.TYPE_MOBILE
|| phoneCursor.getInt(phoneCursor.getColumnIndex(Phone.TYPE)) == Phone.TYPE_WORK_MOBILE)
type = ContactInfo.TYPE_MOBILE;
else if (phoneCursor.getInt(phoneCursor.getColumnIndex(Phone.TYPE)) == Phone.TYPE_FAX_HOME
|| phoneCursor.getInt(phoneCursor.getColumnIndex(Phone.TYPE)) == Phone.TYPE_FAX_WORK)
type = ContactInfo.TYPE_FAX;
else if (phoneCursor.getInt(phoneCursor.getColumnIndex(Phone.TYPE)) == Phone.TYPE_WORK)
type = ContactInfo.TYPE_OFFICE;
phoneInfoList[j++] = contactInfo.new PhoneInfo(
FWUtil.SeparatesCharacters(phoneCursor.getString(phoneCursor.getColumnIndex(Phone.NUMBER))),
type);
}
phoneCursor.close();
String[] projectionEMail = new String[] {
Email.CONTACT_ID,
Email.DATA,
Email.TYPE
};
Cursor emailCursor = context.getContentResolver().query(Email.CONTENT_URI,
projectionEMail, Email.CONTACT_ID + "='" + contactInfo.getName() + "'", null, null);
EmailInfo[] emailInfoList = new EmailInfo[emailCursor.getCount()];
j = 0;
while(emailCursor.moveToNext()) {
int type = ContactInfo.TYPE_OTHER;
if (emailCursor.getInt(emailCursor.getColumnIndex(Email.TYPE)) == Email.TYPE_HOME)
type = ContactInfo.TYPE_HOME;
else if (emailCursor.getInt(emailCursor.getColumnIndex(Email.TYPE)) == Email.TYPE_MOBILE)
type = ContactInfo.TYPE_MOBILE;
else if (emailCursor.getInt(emailCursor.getColumnIndex(Email.TYPE)) == Email.TYPE_WORK)
type = ContactInfo.TYPE_OFFICE;
emailInfoList[j++] = contactInfo.new EmailInfo(
emailCursor.getString(emailCursor.getColumnIndex(Email.DATA)),
type);
}
emailCursor.close();
contactInfo = new ContactInfo(cursor.getString(cursor.getColumnIndex(Contacts._ID)),cursor.getString(cursor.getColumnIndex(Contacts.DISPLAY_NAME)),
phoneInfoList, emailInfoList, new AddressInfo[0], "");
contactInfoList[i++] = contactInfo;
}
cursor.close();
return contactInfoList;
//return new ContactInfo[0];
}`
This code get all contacts, but when contact has ' on name, like: 'Jonh. Systems show an exception, I don't know how to replace this charactere, because Android set query and projection before get the data no auto replace ' by "!!!!
09-30 08:44:19.732: ERROR/DatabaseUtils(9292): android.database.sqlite.SQLiteException: near "Jonh": syntax error: , while compiling: SELECT contact_id, display_name, data1, data2 FROM view_data_restricted data WHERE (1 AND mimetype = 'vnd.android.cursor.item/phone_v2') AND (display_name=''Jonh')
09-30 08:44:19.732: ERROR/DatabaseUtils(9292): at android.database.sqlite.SQLiteCompiledSql.native_compile(Native Method)
09-30 08:44:19.732: ERROR/DatabaseUtils(9292): at android.database.sqlite.SQLiteCompiledSql.compile(SQLiteCompiledSql.java:91)
09-30 08:44:19.732: ERROR/DatabaseUtils(9292): at android.database.sqlite.SQLiteCompiledSql.<init>(SQLiteCompiledSql.java:64)
09-30 08:44:19.732: ERROR/DatabaseUtils(9292): at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:80)
09-30 08:44:19.732: ERROR/DatabaseUtils(9292): at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:46)
09-30 08:44:19.732: ERROR/DatabaseUtils(9292): at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:42)
09-30 08:44:19.732: ERROR/DatabaseUtils(9292): at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1345)
09-30 08:44:19.732: ERROR/DatabaseUtils(9292): at android.database.sqlite.SQLiteQueryBuilder.query(SQLiteQueryBuilder.java:330)
09-30 08:44:19.732: ERROR/DatabaseUtils(9292): at com.android.providers.contacts.ContactsProvider2.query(ContactsProvider2.java:7924)
09-30 08:44:19.732: ERROR/DatabaseUtils(9292): at com.android.providers.contacts.ContactsProvider2.query(ContactsProvider2.java:7909)
09-30 08:44:19.732: ERROR/DatabaseUtils(9292): at android.content.ContentProvider$Transport.bulkQuery(ContentProvider.java:150)
09-30 08:44:19.732: ERROR/DatabaseUtils(9292): at android.content.ContentProviderNative.onTransact(ContentProviderNative.java:111)
09-30 08:44:19.732: ERROR/DatabaseUtils(9292): at android.os.Binder.execTransact(Binder.java:288)
09-30 08:44:19.732: ERROR/DatabaseUtils(9292): at dalvik.system.NativeStart.run(Native Method)
Thanks for help!
A: The ' in the name is breaking your query-string. Use a PreparedStatement instead.
This seams to be a classic SQL-Injection case. If you like, create a user named
';DROP TABLE [your_table];
And see what happens ;)
The query()-method works like a PreparedStatement. Instead of using something like this:
Email.CONTACT_ID + "='" + contactInfo.getName() + "'"
you should use the parameters which are offered by the method. An example might be found here.
A: Use '?' in your name selection.
context.getContentResolver().query(URI, projection, Email.CONTACT_ID + "=?", new String[] { contactInfo.getName()}, null);
Have a try
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610183",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Are there better alternatives to db triggers? I have two databases. I want to keep one table in sync. Let's call it the user table.
When one row in a table changes using a trigger I need to update the second database and the other way around.
*
*Is this safe?
*Is there a better way to do this?
It's not a direct PHP/PostgreSQL question, but I am using them so a specific answer might help.
A: This works just fine going in one direction and in fact is the way the slony replication engine works. Going in both directions not so much. What you can do in slony is have two tables, one going in each direction, and a view on each end that the two tables into one cohesive view to the user.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610185",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: IE8 fixed position top & bottom resize bug Based on my CSS, all Browsers including IE7 show my bottom bar correct and fixed, all the time.
.bottom-fixed {
position: fixed;
bottom: 0;
margin-left: -235px;
min-width: 1160px;
max-width: 130em;
width: 100%;
}
However there is something strange in IE8. If you resize the browser window height with help of your right corner at the bottom (the way you can change a windows width and height at the same time), all is fine.
But if you resize the window height grapping the top or bottom of your browser window, the bar/div stuck at the position like it would when position was absolute instead of position: fixed.
Any idea how to fix that?
(Using Doctype for HTML5)
A: I couldn't fix that with the parent float solution from this thread Umer mentioned.
So I fixed it with a simple Javascript script which applies position: fixed all the time when the window gets resized.
HTML
<!--[if IE 8 ]>
<script type="text/javascript">
$(window).resize(function () {
ApplyPositionFixed();
});
</script>
<![endif]-->
Javascript
function ApplyPositionFixed() {
// Check if element exists
if ($("#bottom-bar-content").length) {
$(".bottom-fixed").attr('style', 'position: fixed;');
console.log("Window resized");
}
else {
console.info("No element changes on Window resize");
}
}
However. I'm ready for better solutions.
A: There is another solution: setting height explicitly on the parent element. For example height: 1% or height: 100%.
A: Had the same issue, but the fix in my case was that the parent had position: relative. Once I removed that, this issue went away.
A: for fixed position in IE 8 - ,
DOCTYPE is very very important.
one of:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
or
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
or
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
or
<!DOCTYPE HTML>
And its very very important that
those be in first line.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610188",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Hyperlink vs Anchor When to use HyperLink and when to use Anchor?
When using HyperLink how to handle clicks?
com.google.gwt.user.client.ui.Hyperlink.addClickHandler(ClickHandler) is deprecated
com.google.gwt.user.client.ui.Hyperlink.addClickListener(ClickListener) is deprecated as well.
Doc suggests to use Anchor#addClickHandler, but how to use Anchor#addClickHandler when using HyperLink
Does it mean that if I need to handle click I should always use Anchor and never use HyperLink?
A: Hyperlink (or InlineHyperlink) is basically no more than a kind of Anchor with a ClickHandler that calls History.newItem and preventDefault() the event (so that the link is not actually followed).
Actually, Hyperlink won't do that if it thinks (and yes, it's only a guess) you right-clicked or middle-clicked (or ctrl-clicked) on the link (depending on the browser), to open the link in a new window or tab.
If you need any other behavior, then don't use Hyperlink and use Anchor instead. And if you want to add some behavior to an Hyperlink, then use an Anchor and mimic what the Hyperlink does. And you can reuse the HyperlinkImpl to have the right-click/ctrl-click handling (see links below).
But actually, if you need something that looks like a link and do something on click, but does not have a "target URL" (i.e. it shouldn't be right-clicked/ctrl-clicked to open in a new window/tab, or it wouldn't mean anything to do so), then do not use either an ANchor or Hyperlink, use a Label of whatever instead, and make it look like a link (but well, maybe you should use a Button and have it look like a button then; Google used to have link-alike buttons –such as the "refresh" link/button in GMail– and changed them to look like buttons when they really aren't links).
See also https://groups.google.com/d/msg/google-web-toolkit/P7vwRztO6bA/wTshqYs6NM0J and https://groups.google.com/d/msg/google-web-toolkit/CzOvgVsOfTo/IBNaG631-2QJ
A: Great question, because it is so simple, and yet opens up what might be a whole new area for a lot of GWT programmers. I've up-voted the question just because it can be a great lead-in for people exploring what GWT can do.
Anchor is a widget for storing and displaying a hyperlink -- essentially the <a> tag. Really not much more exciting than that. If you want your page to link to some external site, use anchor.
Links are also used for internal navigation. Let's say I have a GWT app that requires the user to login, so on my first panel I put a login button. When the user clicks it, I would display a new panel with widgets to collect the user's information, code to validate it, and then if validated successfully, reconstruct that first panel the user was on.
Buttons are nice, but this is a browser, and I want my user's experience to be more like a web page, not a desktop app, so I want to use links instead of buttons. Hyperlink does that. The documentation for hyperlink describes it well:
A widget that serves as an "internal" hyperlink. That is, it is a link
to another state of the running application. When clicked, it will
create a new history frame using History.newItem(java.lang.String),
but without reloading the page.
Being a true hyperlink, it is also possible for the user to
"right-click, open link in new window", which will cause the
application to be loaded in a new window at the state specified by the
hyperlink.
That second sentence should help clear it up. The hyperlink is not changing the page in a URL sense (the way anchor does), though the URL will reflect the state of the program by displaying the "token" associated with the hyperlink appended to the base URL after a slash. You define the token. It would be something descriptive like "login" or "help" or "about". But this isn't a new page. There is no additional HTML file you've had to construct to display a help page, for example. It is the state of the current GWT app that is changing. Even if you "open in a new window" you are just running the same app in a particular state.
It looks like a link, but it is really a widget that manipulates the history frame, which in turn allows you to move the state of your GWT application. You don't write a click handler for the hyperlink widget, but a value change handler for the history stack. When you see that the "help" token has been put on the history stack, your handler will execute GWT code to attach to the RootPanel a FlowPanel with embedded HTML text with your help information. This is perceived by the user as a "new page", which is what he expects when he clicks on a hyperlink. The URL will be something.html/help. Now pretend he returns to this URL via the back button, not your hyperlink. No problem. You don't care about the hyperlink click. You only care that, somehow, the history stack changes. Your value change handler fires again, and does the same thing as before to display the help panel. The user still enjoys the experience of navigating through web pages, even though you and I know that there is only one web page and that you are attaching and detaching panels to the RootPanel (or whatever scheme you are using to display your GWT panels).
And this leads to a bonus topic.
This bonus is a bit more complicated, but ironically, it could help better understand hyperlinks. I say more complicated, but really, it helps solidify this notion that a GWT application is made up of a series of states, and that the web page on the screen is just the user's perception of those state changes. And that is Activities and Places. Activities and Places abstracts away this history frame manipulation, handling it in the background once you've set up a mapper with a GWT-provided class designed for this purpose, allowing you to break down your app into a series of activities, and as the user interacts through these activities he is put into different places, and each place has a view. Moreover, the user can move from place to place using browser controls like the address bar, bookmarks, history, and the backward/forward buttons, giving the user a real web-like experience. If you really want to get a grip on the conceptual difference between hyperlinks and anchors, you should try to learn this GWT topic. It can really make you change the way you see your apps, and for the better.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610189",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "23"
} |
Q: JSON - Access field named '*' asterisk I am trying to access a JSON field that has the key '*':
{
"parse": {
"text": {
"*": "text i want to access"
}
}
}
Neither myObject.parse.text.* nor myObject.parse.text[0] works.
I have searched for an hour but haven't found any hint that an asterisk has special meaning. If I just traverse the complete tree and make String comparison with if (key == "*") I can retrieve the text, but I would like to access this field directly. How can I do that?
A: Try use the index operator on parse.text:
var value = object.parse.text["*"];
A: try to use
var text = myObject.parse.text['*']
A: You could do:
var json = {"parse":
{"text":
{"*":"text i want to access"}
}
}
alert(json.parse.text['*']);
A: json.parse.text["*"]
Yucky name for an object member.
Asterisks have no special meaning; it's a string like any other.
myObject.parse.text.* doesn't work because * isn't a legal JS identifier. Dot notation requires legal identifiers for each segment.
myObject.parse.text[0] doesn't work because [n] accesses the element keyed by n or an array element at index n. There is no array in the JSON, and there is nothing with a 0 key.
There is an element at the key '*', so json.parse.text['*'] works.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610191",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Refactoring in Android Programming Please, if someone could write the meaning of refactoring in android, how it is done and what is its use in android programming. I am using Eclipse.
Thanks
A: Refactoring means making small changes to improve the structure of a program without affecting its operation. So, for example, renaming a method or moving a method from a subclass to a superclass would be examples of small refactorings. Eclipse has a "Refactoring" context menu which automates these and a number of other simple refactorings.
This really has nothing to do with Android, though; it's just a general programming term. There's nothing about refactoring in Android programming that differs from any other system.
A: I just used the refactoring option in Eclipse to rename my package and automatically rename folders and package references, and found it quite useful! I didn't really know what refactoring meant in this case, until I decided to try it out while playing around with different menu options.
I have had many troubles in the past when I manually tried to change a package name or copy one package to a new one but with a different name, so the refactoring option comes in handy if you want to do it all in one fell swoop.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610193",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Set absolute height (offsetHeight) of HTML containers that use CSS padding, margin and border by Javascript I want to do something like setting offsetHeight (offsetHeight is a read only property) - fit 3 div ("d1", "d2", "d3") into one container ("c"):
<!DOCTYPE HTML>
<html>
<body>
<style type="text/css">
.c {
background-color:#FF0000;
overflow:hidden;
}
.d {
left:10px;
border:9px solid black;
padding:13px;
margin:7px;
background-color:#FFFF00;
}
</style>
<div class="c" id="c">
<div id="d1" class="d">text text text</div>
<div id="d2" class="d">text text text</div>
<div id="d3" class="d">text text text</div>
</div>
<script type='text/javascript'>
var h=600;
var hd = Math.floor(h/3);
var c = document.getElementById("c");
var d1 = document.getElementById("d1");
var d2 = document.getElementById("d2");
var d3 = document.getElementById("d3");
c.style.height=h +"px";
d1.style.height=hd +"px";
var hd2 = (2 * hd - d1.offsetHeight) +"px";
d1.style.height=hd2;
d2.style.height=hd2;
d3.style.height=hd2;
</script>
</body>
</html>
but - first: the boxes doesn’t fit perfect :-( and secondly the style is bad. Do you have a idea how to fit the 3 div ("d1", "d2", "d3") into one container ("c")?
=> also I dont know how to read the css properties "padding" and "margin"
alert(d1.style.paddingTop);
doesn't work (maybe because it is defined by css-class and not direct)
Thank you :-)
Best regards Thomas
A: Which browser your using and what DOCTYPE you have determines the default box model for block elements. Usually, the default is content-box, which means that the padding, border, and margin all add to the height/width, so you'll need to factor that into your calculations if you have the box model as content-box.
Another options is, you can change the box model to border-box using the box-sizing CSS property. This means that the padding and border are included in the height and width, and only the margin adds to them. In my opinion, this box model is usually a more convenient one for doing what I want, so I usually end up switching.
Reference:
*
*https://developer.mozilla.org/En/CSS/Box-sizing
*https://developer.mozilla.org/en/CSS/box_model
A: After some testing I figure out this solution:
(works with: Opera, Firefox and Google Chrome)
(box-sizing: doesn't work on Firefox when used JavaScript?!)
<!DOCTYPE HTML>
<html>
<body>
<style type="text/css">
.c {
background-color:#FF0000;
overflow:hidden;
margin:0px;
padding:0px;
}
.d {
left:10px;
border:13px solid black;
padding:7px;
margin-bottom:13px;
margin-top:4px;
background-color:#FFFF00;
}
</style>
<div class="c" id="c">
<div id="d1" class="d">text text text</div>
<div id="d2" class="d">text text text</div>
<div id="d3" class="d">text text text</div>
</div>
<script type='text/javascript'>
///////////////////////////////////////////
// see: http://stackoverflow.com/questions/1601928/incrementing-the-css-padding-top-property-in-javascript
function getStyle(elem, name) {
if (elem.style[name]) {
return elem.style[name];
}
else if (elem.currentStyle) {
return elem.currentStyle[name];
}
else if (document.defaultView && document.defaultView.getComputedStyle) {
name = name.replace(/([A-Z])/g, "-$1");
name = name.toLowerCase();
s = document.defaultView.getComputedStyle(elem, "");
return s && s.getPropertyValue(name);
}
else {
return null;
}
}
///////////////////////////////////////////
var c = document.getElementById("c");
var d1 = document.getElementById("d1");
var d2 = document.getElementById("d2");
var d3 = document.getElementById("d3");
var paddingY = parseInt(getStyle(d1, 'paddingTop'),10) + parseInt(getStyle(d1, 'paddingBottom'), 10);
var marginTop = parseInt(getStyle(d1, 'marginTop'),10);
var marginBottom = parseInt(getStyle(d1, 'marginBottom'),10);
var marginMax = Math.max(marginTop, marginBottom);
var borderY = parseInt(getStyle(d1, 'borderTopWidth'),10) + parseInt(getStyle(d1, 'borderBottomWidth'), 10);
var h=600;
var count=3;
var hd = Math.floor((h-marginMax*(count-1) - marginTop - marginBottom - (paddingY + borderY) *count) / count) ;
c.style.height=h +"px";
d1.style.height=hd +"px";
d2.style.height=hd +"px";
d3.style.height=hd +"px";
</script>
</body>
</html>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610201",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Eclipse Glassfish 3.1 CREDENTIAL ERROR I get the error "credential error" in eclipse indigo 3.7 with glassfish 3.1 when I try to start the server on Win xp. Glassfish starts normally from command line. When I start GS from eclipse I get:
[#|2011-09-29T17:30:58.386+0200|SEVERE|glassfish3.1.1|javax.enterprise.system.tools.admin.org.glassfish.server|_ThreadID=17;_ThreadName=Thread-2;|The log message is null.
java.rmi.NotBoundException: 127.0.0.1
at sun.rmi.registry.RegistryImpl.unbind(RegistryImpl.java:140)
at org.glassfish.admin.mbeanserver.RMIConnectorStarter.stopAndUnexport(RMIConnectorStarter.java:314)
at org.glassfish.admin.mbeanserver.JMXStartupService$JMXConnectorsStarterThread.shutdown(JMXStartupService.java:191)
at org.glassfish.admin.mbeanserver.JMXStartupService.shutdown(JMXStartupService.java:146)
at org.glassfish.admin.mbeanserver.JMXStartupService.access$000(JMXStartupService.java:87)
at org.glassfish.admin.mbeanserver.JMXStartupService$ShutdownListener.event(JMXStartupService.java:115)
at org.glassfish.kernel.event.EventsImpl.send(EventsImpl.java:128)
at com.sun.enterprise.v3.server.AppServerStartup.stop(AppServerStartup.java:435)
at com.sun.enterprise.glassfish.bootstrap.GlassFishImpl.stop(GlassFishImpl.java:88)
at com.sun.enterprise.glassfish.bootstrap.GlassFishDecorator.stop(GlassFishDecorator.java:68)
at com.sun.enterprise.v3.admin.StopServer.doExecute(StopServer.java:70)
at com.sun.enterprise.v3.admin.StopDomainCommand.execute(StopDomainCommand.java:95)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$1.execute(CommandRunnerImpl.java:355)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$2.run(CommandRunnerImpl.java:383)
I assume that the problem is in RMI, the way the glassfish adapter in eclipse is trying to start GS. There is no port occupying 8686 which is the port throw which RMI is trying to get to GS. Is there a workaround. Help
A: I had the same problem just before. Now I started the domain like this:
%glassfish_installdir%\glassfish\bin\asadmin.bat start-domain domain1
(There should also be an startmenu entry)
It finally works.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610206",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to debug tsql stored procedure? How do I debug a tsql Stored procedure. I have tried the following link.
http://msdn.microsoft.com/en-us/library/ms241871(v=vs.80).aspx
But I am unable to hit the break point. Is there a better way to debug. My environment is
Sql Express 2008, Visual Studio 2010
A: I have found the debugger in SQL Managment studio unreliable as it's so dependant on having the correct permissions on the db server which are not always available.
One alternate method I use is to convert the stored proc into a long query. I start by moving any parameteres to variable declarations and set their values. For examples the following
ALTER PROCEDURE [dbo].[USP_ConvertFinancials] (@EffectiveDate datetime, @UpdatedBy nvarchar(100))
AS
BEGIN
DECLARE @PreviousBusinessDay datetime
would become
DECLARE @Value int,
, @EffectiveDate datetime = '01-Jan-2011
, @UpdatedBy nvarchar(100) = 'System'
This allows me to run the queries within the stored procedure starting from the top. As I move down through the queries, I can check the values of variables by simply selecting them and rerunning the query from the top:
SELECT @Value
I can also comment out the INSERT portion of INSERT-SELECT statements to see what is being inserted into tables and table variables.
The bug in the stored proc usually becomes quite evident using this method. Once I get the query running correctly I can simply copy the code to my proc and recompile.
Good luck!
A: You can try out Sql Profiler, it does not allows a classical debugging like "break at this point" but gives you an information in great detail about what is going on on each step of a query/SP execution.
Unfortunately Microsoft does not provide it with Express Edition version of Sql Server.
BUT :) There is a good (relatively because it does not provide a lot of filtering criterias which exists in Microsoft's one) and free alternative - SQL Server 2005/2008 Express Profiler.
A: Debug a stored procedure.
*
*check the logic whether it makes sense or not.
*use break point to help find issues.
*try to do the modular design as per complex process.
*divide the task into multiple simple ones.
*use a master stored procedure to take control on the top, and use several child stored procedures to do the job step by step.
*As per the optimization, use execution plan, SS Profiler and DTA tools.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610207",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Display multidimensional array elements in smarty
Possible Duplicate:
Display array elements in smarty
I have merged two mysql results :
while($rs_1 = mysql_fetch_array($r1)) {
$arr1[] = $rs_1;
}
while($rs_2 = mysql_fetch_array($r2)) {
$arr2[] = $rs_2;
}
$resN = array_merge($arr1,$arr2);
var_dump($resN) shows the following result :
array(5) {
[0]=> array(4) {
[0]=> string(6) "Petric"
["bz_pro_first_name"]=> string(6) "Petric"
[1]=> string(8) "Naughton"
["bz_pro_last_name"]=> string(8) "Naughton"
}
[1]=> array(4) {
[0]=> string(6) "Nitish"
["bz_pro_first_name"]=> string(6) "Nitish"
[1]=> string(12) "Dolakasharia"
["bz_pro_last_name"]=> string(12) "Dolakasharia"
}
[2]=> array(4) {
[0]=> string(6) "Martin"
["bz_pro_first_name"]=> string(6) "Martin"
[1]=> string(3) "Rom"
["bz_pro_last_name"]=> string(3) "Rom"
}
[3]=> array(4) {
[0]=> string(5) "Steve"
["bz_pro_first_name"]=> string(5) "Steve"
[1]=> string(5) "Wough"
["bz_pro_last_name"]=> string(5) "Wough"
}
[4]=> array(4) {
[0]=> string(3) "Liz"
["bz_pro_first_name"]=> string(3) "Liz"
[1]=> string(6) "Hurley"
["bz_pro_last_name"]=> string(6) "Hurley"
}
}
I am supposed to display them in smarty so :
assign_values('rand_pro',$resN);
Now I tried to display in smarty like this :
{foreach name=outer item=pro from=$rand_pro}
{foreach key=key item=item from=$pro}
{$key}: {$item}<br />
{/foreach}
{/foreach}
It displays the results but serially. I need to extract the values in some positions . So how can I extract the values eg first name, last name etc ?
A: {$item.bz_pro_last_name}
{$key.bz_pro_first_name}
Not sure if I got your question but try the above inside your loop.
A: You can write foreach loop like this.
{foreach from=$rand_pro item=pro key=pro_key}
{$key}: {$pro.bz_pro_first_name} {$pro.bz_pro_last_name}<br />
{/foreach}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610210",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: InfoPath form closes and redirects to deleted SharePoint library? When a user clicks submit for the first time, the form closes and they are redirected to an old library that I deleted. But if they were to go back and edit their form then submit again, it will redirect to the correct library. Why does it redirect to the old library, and is there a way to fix this?
A: did you ever checked URL for the InfoPath form (if you are using externally the link for submission form). If so please do ckeck parameters in the URL with name "Source="
(OR) once you open the submission form, copy the url from the browser and paste it in any notepad, do check the passed parameter(s). some parameters are as below:
XsnLocation=
SaveLocation=
Source=
DefaultItemOpen=
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610211",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: What can you do in FQL that you cannot with the Graph API I'm trying to figure out what are the cases where FQL has features which the Graph API doesn't.
I tried to find the answer in the docs, but as many others have pointed out, they aren't the clearest or the most complete. To make things more difficult, a lot of the blogs commenting on the Developer platform are now dated too.
So, what can FQL do that the Graph API can't?
A: FQL has a WHERE clause, which graph API doesn't have any equivalent of. I'm talking of something more sophisticated than just getting object connections (like user's friends). Examples: get user's friends who are also app users and online in chat, get all events which start tomorrow and not created by myself, etc, etc.
Besides that FQL is more like an extension to the graph API rather than something independent and is used to make queries on graph objects.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610221",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Handling Ambiguous Column Names Im in a position where I cannot alter the table structure of my database and I have Ambiguous Column Names in [table1] and [table2]. I do not need to use any fields from [table2] but its existence is necessary to relate to another table. Is there a way that I handle this?
A: Every time you refer to one of the ambiguous column names you should specify the table name or alias.
SELECT ...
FROM [table1]
JOIN [table2]
ON [table1].ambiguous_column = [table2].ambiguous_column
AND ...
A: use table aliases
SELECT A.*
FROM TABLE_A A
JOIN TABLE_B B ON A.ID = B.ID
ORDER BY A.FIELD
A: use the SQL statement AS to create uniquel names
SELECT
A.feld1 AS F1,
A.feld2 AS F2,
B.feld1 AS F3
FROM table1 AS A
JOIN table2 AS B ON A.id = B.id
ORDER BY A.field1
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610227",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to get AppID for fan page? All my old fan pages appear in Apps on FB dev site. How to force a newly created fan page to appear there to get AppID and App Secret?
Thanks
A: Page isn't an application. If you create new application, you'll get page and new appid with appsecret.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610232",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Classic ASP xsl date conversion I have the following code that reads a rss feed into my page, but I would like to have the pubDate convert into a more human readable date if alt all possible.
<?xml version="1.0" encoding="iso-8859-1"?><!-- DWXMLSource="mm_news.xml" -->
<!DOCTYPE xsl:stylesheet]>
<xsl:output method="html" encoding="iso-8859-1"/>
<xsl:template match="/">
<p class="newsList-date"><xsl:value-of select="pubDate"/></p>........
This gives me:
Fri, 9 Sept 2011 15:21:36 GMT
but Would Like to read something like
Friday 9 Sept 2011
Even be happy if I could simply trim off the end to just have 'Fri, 9 Sept 2011'
Also if easier can I add an extra section within the xml so i can simply enter the date like I want it so I can read it, something like below? (The xml is hand written not dynamically created)
<?xml version="1.0" encoding="US-ASCII" ?>
<?xml-stylesheet title="XSL_formatting" type="text/xsl" href="direct.xsl"?>
<rss version="2.0">
<channel>....
<item>....
<title>.....
<description>....
<thedate>.....
Many Thanks
A: Well, the quick & dirty way would be to substitute select="pubDate" for an expression like this:
select="substring(pubDate,1,16)"
That one's dependent on the month being four letters however, and only gives you your 'fallback' result of 'Fri, 9 Sept 2011'.
If necessary, you can be a bit cleverer and remove the requirement of the month being four letters (which seems unlikely for May), by using this expression:
select="substring(pubDate,1,string-length(substring-before(pubDate,':'))-3)"
Rather than taking a fixed length of 16, it bases it on where the first : is (in the time), and subtracts 3 from that.
If you REALLY want, there's a one-line expression that can give you what you want, but it's a bit convoluted:
select="concat(normalize-space(substring('Monday Tuesday WednesdayThursday Friday Saturday Sunday ',string-length(substring-before('MonTueWedThuFriSatSun',substring(pubDate,1,3))) * 3 + 1,9)),substring(pubDate,5,string-length(substring-before(pubDate,':'))-7))"
This uses a 'lookup', to find where the day of the week exists in one string, and uses that to pick the full name from another, finally using 'normalize-space' to trim any extra spaces. Then it just concatenates it with the date part.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610233",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Apache Httpd in front of Tomcat for faster SSL processing? Does placing Apache httpd in front of Tomcat facilitate faster SSL processing? Does the overall throughput go up or down when using both servers?
A: Installing Apache to an other machine will increase the latency (the request has to go through one more machine) and the throughput (you have more cpu) too. Apache JServ Protocol (AJP) (AJP on Wikipedia) is useful to link the Apache to the Tomcat and to reduce the increased latency:
The AJP13 protocol is packet-oriented. A binary format was presumably
chosen over the more readable plain text for reasons of performance.
The web server communicates with the servlet container over TCP
connections. To cut down on the expensive process of socket creation,
the web server will attempt to maintain persistent TCP connections to
the servlet container, and to reuse a connection for multiple
request/response cycles.
(If you install them on the same machine... to be honest, I've never do that but I wouldn't think that there is a big difference in their SSL performance. Anyway, if it's important you should measure it. Don't miss the FAQ in the Tomcat Wiki.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610236",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: j2me audio player I created a audio player using following code.
try {
InputStream is = getClass().getResourceAsStream("bell.wav");
player = Manager.createPlayer(is, "audio/X-wav");
player.realize();
player.prefetch();
player.start();
}
catch (IOException ex) {
ex.printStackTrace();
}
catch (MediaException ex) {
ex.printStackTrace();
}
This code works on the simulator without any problem. But it is not working in the phone.
MediaException is thrown. I think phone does not support for this player.
Have there any solutions for this ?
A: It might help to check what mime types are supported by the device by checking
Manager.getSupportedContentTypes(String protocol);
and
Manager.getSupportedProtocols(String content_type);
You can also try using an URL instead of InputStream
Manager.createPlayer(String url);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610240",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: IE: How to display absolute positioned divs under a relative positioned div currently I'm creating a layout, which requires a div having background graphics and the top and the bottom. My mark-up which I created works fine in FF and looks like this:
#wrapper {
width: 520px;
padding: 2px;
position: relative;
float: left;
z-index: 4000;
}
#upper_bg {
background:url(images/header_top.png);
position:absolute;
height:200px;
width:520px;
z-index: 1000;
margin: -2px;
}
#row_wrapper {
position:relative;
float: left;
z-index: 3000;
}
#lower_bg {
background:url(images/header_bottom.png);
position:absolute;
bottom:0px;
height:200px;
width:520px;
z-index: 1000;
margin: -2px;
}
<div id="wrapper">
<div id="upper_bg">
<!-- ie fix for displaying empty divs -->
</div>
<div id="row_wrapper">
... content!
</div>
<div id="lower_bg">
<!-- -->
</div>
</div>
In IE (7,8 & 9) however the upper and lower_bg divs are invisible. Anybody knows how to fix this?
A: solved the problem. Indeed, the shown html in my question didn't reproduce the result. After a bit fiddling, I found out that IE was in quirks mode. I created the html via xslt and forgott to add the xsl:output tag and set it to html. After doing so, IE was fine down to version 7 with the layout.
A: Add a clear...
<div id="lower_bg">
blabla floating divs
<div style="clear:both"></div>
</div>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610242",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Transforming XML so that all its elements and attributes effectively become "minOccurs 1" I would like to transform a complex XML element so that its structure becomes "regular" - all subelements and attributes present in this element anywhere will be present in 100% of its nodes.
It's probably easier to show what I mean...
Sample input:
<product>
<size name="S"/>
<size>
<stock>10</stock>
</size>
</product>
Desired output:
<product>
<size name="S">
<stock/>
</size>
<size name="">
<stock>10</stock>
</size>
</product>
What happened:
The first size element was supplied with an empty subelement stock (because the second size element had one).
Attribute /size@name with an empty value was added to the second size subelement (because the first size element had one).
Preconditions:
*
*Processed XML is unlikely to be big (no problem with using LINQ, caching all of it in memory etc.)
*I don't know its XML schema in advance.
A: The code below should match your expectations.
Using this test.xml file as input
<product xmlns="http://www.example.com/schemas/v0.1">
<size name="S"/>
<size>
<stock>
<a.el a.att="a.value"/>
</stock>
</size>
<size>
<stock>
10
<b.el b.att="b.value"/>
</stock>
</size>
<size size.att="size.value" name="e">
<stock>
12
<b.el b.att2="b.value2"/>
</stock>
</size>
</product>
This generates the following valid and normalized output
<product xmlns="http://www.example.com/schemas/v0.1">
<size name="S" size.att="">
<stock>
<a.el a.att=""></a.el>
<b.el b.att="" b.att2=""></b.el>
</stock>
</size>
<size name="" size.att="">
<stock>
<a.el a.att="a.value" />
<b.el b.att="" b.att2=""></b.el>
</stock>
</size>
<size name="" size.att="">
<stock>
10
<b.el b.att="b.value" b.att2="" /><a.el a.att=""></a.el></stock>
</size>
<size size.att="size.value" name="e">
<stock>
12
<b.el b.att2="b.value2" b.att="" /><a.el a.att=""></a.el></stock>
</size>
</product>
using System;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
XDocument xDoc = XDocument.Load("test.xml");
XNamespace ns = xDoc.Root.Name.Namespace;
var mgr = new XmlNamespaceManager(new NameTable());
mgr.AddNamespace("ns", ns.ToString());
var elements = xDoc.XPathSelectElements("/ns:product/ns:size", mgr);
Descriptor desc = Descriptor.InferFrom(elements);
desc.Normalize(elements);
Console.Write(xDoc.ToString());
}
}
public class Descriptor
{
private readonly IList<XName> _attributeNames = new List<XName>();
private readonly IDictionary<XName, Descriptor> _elementDescriptors = new Dictionary<XName, Descriptor>();
public XName Name { get; private set; }
public IEnumerable<XName> AttributeNames { get { return _attributeNames; } }
public IEnumerable<KeyValuePair<XName, Descriptor>> ElementDescriptors { get { return _elementDescriptors; } }
private void UpdateNameFrom(XElement element)
{
if (Name == null)
{
Name = element.Name;
return;
}
if (element.Name == Name)
return;
throw new InvalidOperationException();
}
private void Add(XAttribute att)
{
XName name = att.Name;
if (_attributeNames.Contains(name))
return;
_attributeNames.Add(name);
}
public static Descriptor InferFrom(IEnumerable<XElement> elements)
{
var desc = new Descriptor();
foreach (var element in elements)
InferFromInternal(element, desc);
return desc;
}
private static void InferFromInternal(XElement element, Descriptor desc)
{
desc.UpdateNameFrom(element);
foreach (var att in element.Attributes())
desc.Add(att);
foreach (var subElement in element.Elements())
desc.Add(subElement);
}
private void Add(XElement subElement)
{
Descriptor desc;
if (_elementDescriptors.ContainsKey(subElement.Name))
desc = _elementDescriptors[subElement.Name];
else
{
desc = new Descriptor();
_elementDescriptors.Add(subElement.Name, desc);
}
InferFromInternal(subElement, desc);
}
public void Normalize(IEnumerable<XElement> elements)
{
foreach (var element in elements)
NormalizeInternal(element);
}
private void NormalizeInternal(XElement element)
{
if (element.Name != Name)
throw new InvalidOperationException();
foreach (var attribute in AttributeNames)
{
var att = element.Attribute(attribute);
if (att != null)
continue;
element.Add(new XAttribute(attribute, string.Empty));
}
foreach (var attribute in _elementDescriptors)
{
XElement el = element.Element(attribute.Key);
if (el == null)
{
el = new XElement(attribute.Key, string.Empty);
element.Add(el);
}
attribute.Value.NormalizeInternal(el);
}
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610245",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Display contacts in Blackberry Application I had retrieved the contacts from the phone book and displayed the contacts in pop up of Blackberry Simulator. It runs well in simulator, but not running in Blackberry Device. I stuck on this. Please help me.
Thank you.
A: There is a difference between simulator environment and actual device environment: permissions
On simulator you can access any device resources/data without setting relevant permissions. But on actual devices you need the relevant permissions set, before accessing device resources.
Use ApplicationPermissionsManager and ApplicationPermissions classes to invoke "Permissions request" screen on your app startup.
You need at least ApplicationPermissions.PERMISSION_ORGANIZER_DATA permission allowed for your application.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610247",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: IllegalStateException: get field slot from row 0 col 3 My app always crash at the beginning the error is in the log
My Code:
private void onCreateDBAndDBTabled() {
myDB = this.openOrCreateDatabase(MY_DB_NAME, MODE_PRIVATE, null);
//myDB.execSQL("DROP TABLE " + MY_DB_TABLE);
myDB.execSQL("CREATE TABLE IF NOT EXISTS " + MY_DB_TABLE
+ " (_id integer primary key autoincrement, name varchar(100), rate integer(1), eattime varchar(100),image BLOB)"
+";");
ArrayList<Pizza> list = new ArrayList<Pizza>();
Cursor cursor = this.myDB.query(MY_DB_TABLE, new String[] { "name", "rate","eattime" },null,null,null,null,null,null);
if (cursor.moveToFirst()) {
do {
Log.e("XXX", "Courser Enter: " + cursor.getString(0));
Pizza pizza = new Pizza();
pizza.title= cursor.getString(0);
pizza.rate = cursor.getInt(1);
pizza.date = cursor.getString(2);
ByteArrayInputStream inputStream = new ByteArrayInputStream(cursor.getBlob(3));
pizza.picture = BitmapFactory.decodeStream(inputStream);
list.add(pizza);
}
while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
Log.e("XXX", "Count:" + list.size());
//Log.e("XXX", "Item[0] -->" + list.toArray()[0].toString());
CustomAdapter aa = new CustomAdapter(this, R.layout.customlistitem,list);
Log.e("XXX", String.valueOf(aa.getCount()));
lv.setAdapter(aa);
aa.notifyDataSetChanged();
}
AddPizza:
private void addData() {
myDB = this.openOrCreateDatabase(MY_DB_NAME, MODE_PRIVATE, null);
//myDB.execSQL("DROP TABLE " + MY_DB_TABLE);
myDB.execSQL("CREATE TABLE IF NOT EXISTS " + MY_DB_TABLE
+ " (_id integer primary key autoincrement, name varchar(100), rate integer(1), eattime varchar(100),image BLOB)"
+";");
if(!name.getText().equals("") && rating.getRating()!=0.0)
{
Log.e("XXX", "Enter_Insert");
Calendar cal = Calendar.getInstance();
DateFormat formatter = new SimpleDateFormat();
ByteArrayOutputStream out = new ByteArrayOutputStream();
Bitmap bt = ((BitmapDrawable)iv.getDrawable()).getBitmap();
bt.compress(Bitmap.CompressFormat.PNG, 100, out);
ContentValues cv = new ContentValues();
cv.put("image", out.toByteArray());
cv.put("name", name.getText().toString());
cv.put("eattime", formatter.format(cal.getTime()));
cv.put("rate", rating.getRating());
myDB.insert(MY_DB_TABLE, null, cv);
//myDB.execSQL("INSERT INTO "+ MY_DB_TABLE + "(name,rate,eattime,image) VALUES +" + + ", " ++ " , datetime('now', 'localtime'), " );
}
}
LOG:
09-30 12:16:26.755: ERROR/AndroidRuntime(1149): Caused by: java.lang.IllegalStateException: get field slot from row 0 col 3 failed
09-30 12:16:26.755: ERROR/AndroidRuntime(1149): at android.database.CursorWindow.getBlob_native(Native Method)
09-30 12:16:26.755: ERROR/AndroidRuntime(1149): at android.database.CursorWindow.getBlob(CursorWindow.java:242)
09-30 12:16:26.755: ERROR/AndroidRuntime(1149): at android.database.AbstractWindowedCursor.getBlob(AbstractWindowedCursor.java:35)
09-30 12:16:26.755: ERROR/AndroidRuntime(1149): at com.korn.pizzacounter.Main.onCreateDBAndDBTabled(Main.java:70)
09-30 12:16:26.755: ERROR/AndroidRuntime(1149): at com.korn.pizzacounter.Main.onCreate(Main.java:40)
09-30 12:16:26.755: ERROR/AndroidRuntime(1149): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
09-30 12:16:26.755: ERROR/AndroidRuntime(1149): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2459)
A: The fourth column is missing in the DB query statement. You only declare "name", "rate", "eattime", but not "image".
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610252",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: touches ended/After dragging is completed, i need to check, if the dragged image frame touches any of my 100 images frame i have 100 UIViews in UIViewController class . i am dragging a separate imageView over my 100 UIviews.
when touches ended/dragging completed, i need to check, if the dragged image frame touches any of my 100 UIViews frame.
is there any way to check it. I have given tags to my each 100 UiViews.
Is there any easy way to get it the UIView Details.(than 100 switch conditions).
eg:
CGPoint touchEndpoint = [touch locationInView:self.view];
CGPoint imageEndpoint = [touch locationInView:imageview];
if(CGRectContainsPoint([imageview frame], touchEndpoint))
{
A: Add your UIViews to an NSMutableArray (myViews in the example) then you can do...
for(UIView *aView in myViews) {
if(CGRectContainsPoint([myView frame], touchEndPoint)) {
//DO STUFF
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610253",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: PHP MySQL utf 8 encoding My trying to make an Ajax call to a PHP function that pulls out data from my database. I've run into a problem though.
My query looks like this
$query = "SELECT * FROM mytable WHERE field LIKE '%$string%'"
I then check on the number of rows returned by the query, but when i type in æ ø å then i my query returns 0 rows, although I know there are entries in the database that have æ ø å.. why is this
A: Set the connection to use UTF-8:
<?php
// MySQLi:
$connection = new MySQLi( /* ... credentials ...*/);
$connection->set_charset("utf8");
// MySQL:
$connection = mysql_connect(/* ... credentials ... */);
mysql_set_charset("utf8", $connection);
?>
A: in my case, I had to add this line:
mysqli_set_charset($con,"utf8mb4");
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610254",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Storing the state of checkbox in listview while using custom BaseAdapter in android? i have a listview which is having image, text and checkbox i have inflated this using BaseAdapter. i want to send only those images which are selected but how to store the state of checkbox ?
may be i am wrong as i am using baseadapter. you can suggest any other way to do that.
A: please look below my Baseadapter
class ImageInfoAdapter extends BaseAdapter{
@Override
public int getCount() {
if(viewcount == 0){
return 0;
}
return viewcount;
}
@Override
public Object getItem(int position) {
return isSentAlList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View view, ViewGroup parent) {
final ViewHolder viewHolder;
View rowView=view;
if(rowView==null){
LayoutInflater layoutinflate = LayoutInflater.from(ListPictures.this);
rowView=layoutinflate.inflate(R.layout.listviewayout, parent, false);
viewHolder = new ViewHolder();
viewHolder.textViewisSentFlag = (TextView)rowView.findViewById(R.id.textViewisSentFlag);
viewHolder.imageViewToSent = (ImageView)rowView.findViewById(R.id.imageViewToSent);
viewHolder.checkBoxToSend = (CheckBox)rowView.findViewById(R.id.checkBoxToSend);
rowView.setTag(viewHolder);
}
else{
viewHolder = (ViewHolder) rowView.getTag();
}
viewHolder.ref = position;
Log.i("InfoLog","viewHolder.ref = position; "+viewHolder.ref);
viewHolder.textViewisSentFlag.setText(isSentAlList.get(position));
Bitmap blob = BitmapFactory.decodeByteArray(imageAlList.get(position), 0, imageAlList.get(position).length);
viewHolder.imageViewToSent.setImageBitmap(blob);
viewHolder.checkBoxToSend.setClickable(true);
if(checked.containsKey(""+viewHolder.ref)) ///if this id is present as key in hashmap
{
Log.i("InfoLog","checked.containsKey "+viewHolder.ref);
if(checked.get(""+viewHolder.ref).equals("true")) //also check whether it is true or false to check/uncheck checkbox
{
Log.i("InfoLog","checked.get(position) "+viewHolder.ref);
viewHolder.checkBoxToSend.setChecked(true);
}
else
viewHolder.checkBoxToSend.setChecked(false);
}
else
viewHolder.checkBoxToSend.setChecked(false);
viewHolder.checkBoxToSend.setOnCheckedChangeListener(new OncheckchangeListner(viewHolder));
return rowView;
}//End of method getView
}//End of class ImageInfo
class ViewHolder{
private TextView textViewisSentFlag = null;
private ImageView imageViewToSent = null;
private CheckBox checkBoxToSend = null;
int ref;
}//End of class ViewHolder
and here is my oncheckchangedlistener
class OncheckchangeListner implements OnCheckedChangeListener{
ViewHolder viewHolder = null;
public OncheckchangeListner(ViewHolder viHolder)
{
viewHolder = viHolder;
}
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if(viewHolder.checkBoxToSend.equals(buttonView))
{
if(!isChecked)
{
Log.i("InfoLog","checked.get before "+checked.get(""+viewHolder.ref));
checked.put(""+viewHolder.ref,"false");
Log.i("InfoLog","checked.get after "+checked.get(""+viewHolder.ref));
}
else
checked.put(""+viewHolder.ref,"true");
}
else
Log.i("InfoLog","i m in checkchange ");
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610267",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Not able to upload image to the server in android I have used some code from the internet for uploading image
public class ActUpload extends Activity {
InputStream is;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(),
R.drawable.blue);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte [] ba = bao.toByteArray();
String ba1=Base64.encodeBytes(ba);
ArrayList<NameValuePair> nameValuePairs = new
ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("image",ba1));
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new
HttpPost("http://127.0.0.1:80/php/base.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
}
}
and even took some php code copied some php code which i am running in local sever using wamp server. There is no response in the local server.
and this is my php code.
<?php
$base=$_REQUEST['image'];
echo $base;
// base64 encoded utf-8 string
$binary=base64_decode($base);
// binary, utf-8 bytes
header('Content-Type: bitmap; charset=utf-8');
// print($binary);
//$theFile = base64_decode($image_data);
$file = fopen('test.jpg', 'wb');
fwrite($file, $binary);
fclose($file);
echo '<img src=test.jpg>';
?>
Can any one help me in this. thanks in advance.
A: A nice tutorial for uploading image to server-
http://coderzheaven.com/2011/04/android-upload-an-image-to-a-server/
Edit:
You just need to change this according to your local server:
HttpPost httppost = new HttpPost("http://<local ip address>/android/upload_image.php");
// For example,in my code,i used:
// HttpPost httppost = new HttpPost("http://192.168.100.47/android/upload_image.php");
A: Did you manage to solve the problem? I did get it to work when i changed $base=$_REQUEST['image']; => $base=$_POST['image']; and commented out the following line header('Content-Type: bitmap; charset=utf-8'); Btw, did try to convert the code to use HttpURLConnection api?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610270",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Show all pictures from database in a GridView I have stored stored some links from pictures with a text to it in my database, with this:
int drawableID = context.getResources().getIdentifier("devil", "drawable", getPackageName());
iv.setImageResource(drawableID);
String info = String.valueOf(drawableID);
mDbHelper.open();
mDbHelper.createSmiley("You received a satanic message", info);
mDbHelper.close();
Now I have defined a gridview in my layout like this:
<GridView
android:layout_height="175dp"
android:layout_width="fill_parent"
android:gravity="bottom|right"
android:numColumns="5"
>
</GridView>
Now I want to import my pictures from my database that they are shown in my GridView and that I can select one of them. But I don't get how this works, how I can realize that? This is my method to import all Database entries:
public Cursor getAllSmileys() {
return this.mDb.query(DATABASE_TABLE, new String[] { ROW_ID,
SOURCE, INFO }, null, null, null, null, null);
}
So my Question is how I can import all those pictures into my gridview to show them? Also I'd like that the user can select one of them.
A: Check this Inserting image in Database and get it back.
For Storing image in Database , store it as BLOB and retrieve it back and show it..
In the above example i show how to insert the image in DB and display it it in Image View..
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610276",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Android SharedPreferences Limit I am searching for the maximum Android SharedPreferences key, value pairs but cannot find any good answer. Secondly, I want to ask that if I have a key what is its String value limit. How many character can put into it. If I need a choice for a value change frequently, should I use SQLite or SharedPreferences.
Please refer me some good resources.
Yours,
A: All shared prefs are stored in /data/data/[package name]/shared_prefs/[app name].xml, so i think there's no limit based on aechitecture.
I don't know practical limit but i think it's enough for you..
Check Shared Preference for your reference.
should I use SQLite or SharedPreferences.
It is far better to use SQLite if you need to store values that will changes periodically.
Also you can store more amount of data..
A: Following Android Developer reference it seems like key, value and node name have each a max value defined.
If you have to change many related key pairs, I'd recommend creating a simple SQLite database, but if you are using only a few pairs maybe SharedPreferences is not a bad and quick solution.
A: SharedPreferences are for quickly storing values like single strings, settings, flags, etc. The SQLite Database can do the same but is a little more heavy duty, think storing tables of information like customer data with multiple properties and being able to search (the Query in SQL).
So the answer is, "it depends" on what that "something" is you want to store? If it's a user setting then the SharedPreferences is quick and easy. If it's a set of records then the SQLite Database may make more sense.
A: As for the key size limit: I believe it is just the max size of a String. Also it is answered here: Shared Preferences - max length of a single value
The max key/value pairs limit: usingShared preferences these values are stored in .xml files as stated in the answer above, and you can have multiple .xml sharePreference files. The size limit I suppose is limited by the size of your app or the storage space available on the device using your app.
If your preference values change frequently, I would consider using local variables to keep track of current preference set, maybe a global singleton class. And save changes to disk before app is destroyed/closed. If you don't like this idea then try using SharedPreferences, but be sure to use the SharedPreferences.Editor.apply() instead of SharedPreferences.Editor.commit() to save preferences (apply saves to disk asynchronously, commit saves synchronously).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610279",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: JSON:How to handle JSON response like this? Here is the Response
I wonder how can I handle a JSON Response like this?
This a JSONArray, but didn't have a name
Here is the response:
[[84,"sinat","[email protected]"],[88,"msn","[email protected]"],[89,"163t","[email protected]"],[90,"mail","[email protected]"],[93,"mail","[email protected]"]]
A: Data are not JSONObject but JSONArray !
String json_value = '[[84,"sinat","[email protected]"],[88,"msn","[email protected]"],[89,"163t","[email protected]"],[90,"mail","[email protected]"],[93,"mail","[email protected]"]]';
JSONArray json_array = new JSONArray(json_value);
and walk through it like
for(int i = 0; i < json_array.length(); i++){
Log.d("Current index: "+i,"Current value: "+json_array.getJSONArray(i).toString());
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610282",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Expose Member Data Through Read-only Iterator I have a class 'MyClass' which contains some data stored in std::maps. The standard maps contain pointers to objects, e.g.
private:
std::map<int,Object*> m_data;
I want to expose the data to the outside world but I do not want other classes/functions to be able to modify either (i) the map m_data or (ii) the objects pointed to by the values in m_data. I would like some hypothetical function, say getDataBegin() which returns an iterator over the data which has the properties above. For example I want the following pseudo-code examples to fail:
iterator_type itr = myclass.getDataBegin();
erase(itr); // not allowed because we cannot modify m_data;
itr.second = NULL; // not allowed to change content of m_data (falls under first rule)
itr.second->methodWithSideEffect(); // not allowed because changes content of object pointed to.
In short you could say I am after read-only access to some member data. Is this at all possible in a nice way, and if so then how could I go about it?
A: Try exposing a boost transform_iterator wrapped around the map's const_iterator. The transform function should be something like
[](const pair<int, object*>& x)
{
return make_pair(x.first, const_cast<const object*>(x.second));
}
A: return a const_iterator, const_iterator allows read only access.
std::map<int,Object*>::const_iterator const getDataBegin();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610283",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Fetching a file from a PHP file in Google App Engine I need to know if there is anyway that I can use file_get_html or any equivalent function in php on GAE? I know it has something called URLFetch() but I am not able to understand how I will call that from a php file.
Any help?
A: You cannot run PHP on Google App Engine. You can create a servlet which will read from any given URL and manipulate the data in any way you would need to, in Java (since you tagged this question with the Java tag).
From the AppEngine URL Fetch Java API Overview:
URL url = new URL("http://www.example.com/atom.xml");
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
while ((line = reader.readLine()) != null) {
// ...
}
reader.close();
If you meant that you are running PHP in another application and you wish to call your AppEngine servlet from said PHP application, then you can map the servlet which performs this URL fetch to a URL within your AppEngine application, then hit that URL from your PHP application. This, however, seems like a bad design, as you're making two network calls when you could have just used done it within the PHP application in the first place.
A: Here's a quick and dirty wrapper function I created for URL Fetch using PHP via Quercus on Google App Engine:
function fetch_url($url){
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;
$java_url = new URL($url);
$java_bufferreader = new BufferedReader(new InputStreamReader($java_url->openStream()));
while (($line = $java_bufferreader->readLine()) != null) {
$content .= $line;
}
return $content;
}
// Sample usage:
echo fetch_url('http://google.com');
Hope this helps someone who is as lost as I was.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610294",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Moving a Drupal 6.x site to MediaTemple and getting the WSOD I'm trying to move a Drupal site over to a MediaTemple (DV) account and keep getting the WSOD. If I move the site over, using the same procedures, to a MediaTemple (GS) account everything works just fine.
I've tried pouring through the WSOD docs to pinpoint the problem, but clearly, IMO, this has to be something unique to the settings on a DV account vs a GS account and the problem doesn't lie with Drupal itself.
Any ideas?
A: Try to narrow down the problem some more. If you've done everything in the White Screen of Death (Completely Blank Page) handbook page, can you provide more detail about what you found? Specifically, try enabling error reporting by adding the following at the top of your index.php file:
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
That should get any errors being generated to display on the page and should help pinpoint the issue.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610296",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can I specify site after I have built the deployment package with Microsoft Web Deploy? Currently I do the following:
*
*Create package using
msbuild something.csproj /P:Configuration:Some /T:Package
*After that I go to the Package folder under obj\Some\Package and run the following
something.csproj.deploy.cmd /y /M:https://mydeployservice /u:user /p:password --allowUntrusted /A:Basic
Everything works fine, but I wonder how do I specify the site which I want the application installed to? Here I only define the service/server, and the name of the site is from the deploy command. Is it possible to use a parameter for the site name?
A: If you're using Web Deploy, it should be possible to use a parameter for the site name when you package the source, then specify a new site name when you deploy. Here are some articles that show how to use parameters:
*
*Customizing a Deployment Package
*Web Deploy Parameterization in Action
*Web Deploy: Replace Rule vs. Parameterization
*Packaging and Deploying Web Applications for the Visual Studio Development Web Server
*Team Build + Web Deployment + Web Deploy + VS 2010 = Goodness
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610301",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Simple library in Android : Boolean in "1" or "0" Simple library is great and i already parsed many
different XML from soap servers since last 3 days, but i encountered
boolean attributes with "0" or "1" :
<list mybool1="0" mybool2="1" attr1="attr" attr2="attr">
<page mybool3="1">
...
</page>
<page mybool3="0">
...
</page>
...
</list>
I tried to create this class :
public class Boolean01Converter implements Converter<Boolean>
{
@Override
public Boolean read(InputNode node) throws Exception {
return new Boolean(node.getValue().equals("1"));
}
@Override
public void write(OutputNode node, Boolean value) throws Exception {
node.setValue(value.booleanValue()?"1":"0");
}
}
and implemented it on my object definition :
@Root(name="list")
public class ListFcts
{
@Attribute
@Convert(Boolean01Converter.class)
private Boolean mybool1;
@Attribute
@Convert(Boolean01Converter.class)
private Boolean mybool2;
@Attribute
private int ...
@ElementList(name="page", inline=true)
private List<Page> pages;
public Boolean getMybool1() {
return mybool1;
}
}
But i still get false for every boolean.
[edit]
In fact, when i do this :
@Override
public Boolean read(InputNode node) throws Exception {
return true;
}
i still get false for :
Serializer serial = new Persister();
ListFcts listFct = serial.read(ListFcts.class, soapResult);
if(listFct.getMybool1())
{
//this never happens
}else{
//this is always the case
}
so my Converter has no impact...
Also : how can I attach the converter to the Persister instead of
declaring it on @Attributes hundred times ?
Many thanks in advance !!
[edit2]
i give up with Converter, this is my own solution :
@Root(name="list")
public class ListFcts
{
@Attribute
private int mybool1;
@Attribute
private int mybool2;
public int getMybool1() {
return mybool1;
}
public Boolean isMybool1() {
return (mybool1==1)?true:false;
}
...
}
A: Your code is using node.getValue() which returns the value (read: contents) of each XML node (the "..." bit in your examples).
What you need is to reading the attribute values, something like node.getAttributeValue("mybool1").equals("1")
A: i gave up with Converter, I heard about Transform but didn't find how to use it so this is my own basic solution :
@Root(name="list")
public class ListFcts
{
@Attribute
private int mybool1;
@Attribute
private int mybool2;
public int getMybool1() {
return mybool1;
}
public Boolean isMybool1() {
return (mybool1==1)?true:false;
}
...
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610304",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Saving 500/404 errors in Ruby on Rails to a database? Is there a way to save the 500/404 etc errors to your database so you can check them to see if there are any bugs on the site?
I thought you could send an JS AJAX request from the 500.html page. e.g.
/errors/create/?message=error_message&ip=123&browser=ie9
But I'm not sure how to get that information when running in production mode?
Any help greatly appreciated,
Alex
A: This is what I have in my application controller:
def rescue_action_in_public(exception)
#This is called every time a non-local error is thrown.
#Copy the error to the db for later analysis.
Error.create :exception_name => exception.exception.to_s, :backtrace_info => exception.backtrace.to_s
#Then handle the error as usual:
super
end
As you can see I have an Error model I created and this saves a new one to the DB whenever it happens. One thing to remember is that backtraces are much to big for string columns so you will need something bigger like a text type. This works in my Rails 3.0.5 app.
A: Logging errors to the db is inadvisable since these errors can often be caused by database issues. It's safer to append your errors to a file (on a separate disk) if your site is high traffic, if the file system is unresponsive, then your db won't work anyway. Even safer would be to use an asynchronous message queue hosted on another server. In both cases, you can create reports by periodically parsing your log output.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610316",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How could I send JSON object and get in return js code in rails 3.1? I have a list of html input items in my html page each representing different model. On click of the submit button, I would like to send all the details as a json object to the controller. From the controller, I would like to return the js code to the browser.
As far as the examples I have seen, they are either sending the data as json and receive json from the server else send the data using form_for and receive the js code from the server. But I would like to send json and receive back js code. How i can do this in rails 3.1 using jQuery?
A: I believe this Railscast by Ryan Bates provides detailed instructions for doing exactly what you are describing.
Railscast Episode #136 - JQuery
That was the railscast I used when I was first learning to post data using jquery in a JSON format and return javascript. It was really helpful.
Though the Rails version is not 3.1, you should be able to adapt the ideas quickly.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610317",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Difference between extern int a; extern int a=42; While I was reading the answers of Use of 'extern' keyword while defining the variable
One of the user answered these way
extern int a; // not a definition
extern int a = 42; // definition
I was expecting both are not definitions but declarations. I was thinking Both statements says that the variable is defined outside the function and we have to use extern keyword to use it. is this a mistake by him or is it really a definition ?
I know that
extern int a; // variable is already defined but its outside the function
extern int a=42 ; //I guess a variable is assigned a value but not a definition
but these statement
extern int a = 42; // user said its a definition and now i got confused
Please clear me with these.
A: Whenever initialisation is attempted, the statement becomes a definition, no matter that extern is used. The extern keyword is redundant in such a case because, by default, symbols not marked static already have external linkage.
It doesn't make sense to declare an external variable and set its initial value in the current compilation unit, that's a contradiction.
A: extern int a; is a declaration. It does not allocate space for storing a.
extern int a = 42; is a definition. It allocates space to store the int value a and assigns it the value 42.
A: here the variables are declared inside the main() function where its definition was defined outside in the global declaration section
extern int a; //This is a declaration
extern int a=42; //This is a definition
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610321",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Is it possible to spoof a value for a hardware profile in IO/Kit on OS X? As an exercise in OS X IO/Kit manipulation, I am looking to return a different UUID, Serial, Boot ROM version, perhaps even number of cores and processor type (just any value) to the System Profiler as well as any other program that asks.
From my understanding, this information about the system is stored in the IO/Kit registry which is stored in memory after being compiled at boot time.
How would one go about either over-writing these values in the I/O Kit registry in memory, or intercepting the IO/Kit library calls and returning different values than what is in memory? Would doing it via interception require a custom kernel extension, or some kind of library modification?
Is there anyway to reliably do this at all? Just curious.
Thank you!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610323",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: C++ Delete Operator I'm relatively new to C++ and I have an issue which I really do not understand. My code creates a linked list. It is actually longer than this, but I chopped it down for the purpose of this question.
When I run the code, it adds three nodes and then when it goes to delete the node with the URI b, it calls the delete operator and ends up deleting the node, but then it seems to go back to delete operator (when I step through it) and it kills my whole list.
#include <iostream>
#include <string>
#include <cstdlib>
#include <cstdio>
using namespace std;
class CLinkedList
{
protected:
class ip_uri_store
{
public:
string uri, ip;
ip_uri_store* next;
ip_uri_store(const string& URI, const string& IP) {uri = URI, ip = IP, next = NULL;}
};
typedef ip_uri_store* nodeAddress;
nodeAddress head;
void AddNode(const string&, const string&, nodeAddress);
void DeleteNode(const string&, nodeAddress, nodeAddress);
public:
CLinkedList() {head = NULL;}
void AddNode(const string& URI, const string& IP) {AddNode(URI, IP, head);}
void DeleteNode(const string& URI) {DeleteNode(URI, head, head);}
};
void CLinkedList::AddNode(const string& URI, const string& IP, nodeAddress node)
{
nodeAddress temp = new ip_uri_store(URI, IP);
temp->uri = URI;
temp->ip = IP;
temp->next = head;
head = temp;
}
void CLinkedList::DeleteNode(const string& URI, nodeAddress node, nodeAddress behindNode)
{
if(node)
{
if(!node->uri.compare(URI))
node == head ? head = head->next : behindNode->next = node->next;
else
DeleteNode(URI, node->next, node);
delete node;
}
}
int main(int argc, char* argv[])
{
CLinkedList lList;
lList.AddNode("a", "1");
lList.AddNode("b", "2");
lList.AddNode("c", "3");
lList.DeleteNode("b");
return 0;
}
A: You are calling delete node; even if the comparison fails (i.e. node->uri != URI).
if(!node->uri.compare(URI))
{
node == head ? head = head->next : behindNode->next = node->next;
delete node;
}
else
DeleteNode(URI, node->next, node);
Also, the condition seems to be inverted.
A: First, you should use std::list and avoid reinventing the world.
Anyway, if you are stuck to this implementation for some reason :
*
*temp->uri = URI; and temp->ip = IP; in the AddNode method are useless because the members are already initialized in the constructor of ip_uri_store class.
*the deletion of the head of the list occurs because the 'delete node' should only be done in the case node->uri.compare(URI) in the DeleteNode method.
Again, you should seriously consider using standard classes...
A: You are calling delete on all the nodes. It needs to be moved inside the conditional so you only delete the nodes that match the URI
if(!node->uri.compare(URI)) {
node == head ? head = head->next : behindNode->next = node->next;
delete node;
} else {
DeleteNode(URI, node->next, node);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610325",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: RunTimeException in running timerTask in android In my android service I am running a simple timer but android throws exception...
My code as follows
public class MyService extends Service{
private Timer timer = new Timer();
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
func1();
}
}, 0, UPDATE_INTERVAL);
}
}
void func1(){
Log.i(TAG,"Just printing");
}
But my code throws exception like this
09-30 11:56:54.297: ERROR/AndroidRuntime(414): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
09-30 11:56:54.297: ERROR/AndroidRuntime(414): at android.os.Handler.<init>(Handler.java:121)
09-30 11:56:54.297: ERROR/AndroidRuntime(414): at android.location.LocationManager$ListenerTransport$1.<init>(LocationManager.java:173)
09-30 11:56:54.297: ERROR/AndroidRuntime(414): at android.location.LocationManager$ListenerTransport.<init>(LocationManager.java:173)
09-30 11:56:54.297: ERROR/AndroidRuntime(414): at android.location.LocationManager._requestLocationUpdates(LocationManager.java:579)
09-30 11:56:54.297: ERROR/AndroidRuntime(414): at android.location.LocationManager.requestLocationUpdates(LocationManager.java:446)
09-30 11:56:54.297: ERROR/AndroidRuntime(414): at com.example.mobiletracker.MTrackerService.func1(MTrackerService.java:167)
09-30 11:56:54.297: ERROR/AndroidRuntime(414): at com.example.mobiletracker.MTrackerService$4.run(MTrackerService.java:118)
09-30 11:56:54.297: ERROR/AndroidRuntime(414): at java.util.Timer$TimerImpl.run(Timer.java:284)
Can anybody please provide me any solution ?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610326",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Connecting DB using `HTML5` is possible? Is it possible to connect to a DATABASE which is in WEBSERVER through HTML5 only without using ASP.NET, JSP etc.
A: Html5 is a browser display language. It has no inherent methods or capabilities to connect to server side technology. You will always need a server side technology to connect to a database, even when using AJAX through a service. When you think about it, isn't this how you should want it? Would you really WANT to have a client connect directly to your database for any reason? You'd be exposing authentication information and allowing direct public access to your data store. Not terribly sensible.
A: The short answer is "No".
The slightly longer answer is "Maybe, it depends". e.g. If your database is CouchDB, then it is possible to host HTML documents directly on it (as an attachment to a regular CouchDB document). These can include JavaScript which can hold your application logic.
A: There is a specification called Web Sql Html 5, which is a variant of SQL. Unfortunately, this specification is stopped. You can see more details on these links.
Web SQL Database
HTML 5 Web SQL Database
Introducing Web SQL Database
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610328",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-4"
} |
Q: Assigning a jQuery progressbar value from SQL using jQuery/C# Asynchronously I have a SQL server that does a back-end function that updates a field on a table with progress-percentage. I would like to efficiently update the value of the progressbar dynamically.
The webpage is a C# .aspx page and the progressbar is created using jQuery-UI.
What is the best method for doing so?
Thanks
A: In order you update the progress bar in real time you have to make asynchronous calls to the server to check the data. This is done using AJAX. There are many ways to do it using AJAX (ex. JS code, AJAXControlToolkit, etc). You'll have to decide which is the best option for you.
AJAX Wiki: http://en.wikipedia.org/wiki/Ajax_(programming)
ASP.NET AJAX Tutorials: http://www.aspnettutorials.com/tutorials/ajax/
AJAXControlToolkit: http://www.asp.net/ajaxlibrary/AjaxControlToolkitSampleSite/
AJAX w/ jQuery: http://net.tutsplus.com/tutorials/javascript-ajax/5-ways-to-make-ajax-calls-with-jquery/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610332",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: find with exec : how to perform multistep conditional action on each file I have bunch of php files in directory structure say /mylibs
I want to run a simple php -l $file on each php file which checks for syntax errors
find /mylibs -type f -iname "*.php" -exec php -l {} &>/dev/null \;
thats step one, the &>/dev/null eats verbose output from php (found syntax errors or not)
The php -l returns 0 if no error is found depending upon which, I want to copy them to some other dir say /mybin. To check if this works as expected I tried
find /mylibs -type f -iname "*.php" -ok php -l {} &>/dev/null ; echo $? \;
but this simply prints 1 on the terminal and does not ask for confirmation (-ok acts same as -exec after interactive confirmation)
What am I doing wrong here ? is it not possible to do this?
A: You can use a while loop:
find /mylibs -type f -iname "*.php" | while IFS= read -r path
do
php -l "$path" &>/dev/null
if [ $? -eq 0 ]
then
cp "$path" /mybin
fi
done
A: does this work for u?
find ....|xargs awk '{r=system("php -l "$0" &>/dev/null"); if(!r) system("cp "$0" /path/to/targetDir")}'
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610333",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Magento: can't set the default value of custom order attribute using installation script I've added custom attribute to orders using mysql4-install-1.0.0.php in my module:
$installer = $this;
$installer->startSetup();
$installer->addAttribute('order', 'custom_status', array(
'type' => 'varchar',
'label' => 'My Status',
'note' => '',
'default' => "my_default_value",
'visible' => false,
'required' => false,
'user_defined' => false,
'searchable' => false,
'filterable' => false,
'comparable' => false,
'unique' => false
));
It works - when I look at sales_flat_order table, I see new varchar field *custom_status* in the table. But the default value is NULL instead of "my_default_value" as expected there. Any ideas, why?
PS. Installation script is really executed, I reset all to initial state each time.
UPD. config.xml
<resources>
<mymodule_setup>
<setup>
<module>Company_Mymodule</module>
<class>Mage_Sales_Model_Mysql4_Setup</class>
</setup>
<connection>
<use>core_setup</use>
</connection>
</mymodule_setup>
***
A: Magento Sales module has pseudo emulation of old EAV functionality. It takes only type property from your array to create a column in the database. Also it uses "grid" property for determining is it required to make the same column in grid representation table.
BTW, previous sales module that was based on EAV, was not using default, label, required and other properties as well. If you want to set a default value for this attribute you need create an observer for order before save event and set this data in it if field is empty.
A: Make sure you have it like this in your config.xml:
<resources>
<customattr_setup>
<setup>
<module>Yourcompany_ModuleName</module>
<class>Mage_Sales_Model_Mysql4_Setup</class>
</setup>
<connection>
<use>core_setup</use>
</connection>
</customattr_setup>
</resources>
The <class>Mage_Sales_Model_Mysql4_Setup</class> is extremely important!
Then in the install script mysql4-install-0.1.0.php:
<?php
$installer = $this;
$installer->startSetup();
$installer->addAttribute(
'order',
'customattr',
array(
'type' => 'float', // or whatever you want here...
'grid' => false
)
);
$installer->endSetup();
?>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610334",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to deal with huge queries to the Facebook Graph? I'd like to get every status update for every friend. Given I have say 500 friends, each with 200 statuses, this could be 100,000 statuses. How would you approach this from the query point of view?
What query would you write? Would Facebook allow this much data to come through in a single go? If not is there a best practice paging or offsetting solution?
A: From their policy:
If you exceed, or plan to exceed, any of the following thresholds please contact us as you may be subject to additional terms: (>5M MAU) or (>100M API calls per day) or (>50M impressions per day).
http://developers.facebook.com/policy/
It means that 100k is not so big deal. However, it depends. You may have to consider,
*
*Do you REALLY need every status?
*Can't they be downloaded later?
*Do you need these posts/stories from every friend?
A:
Would Facebook allow this much data to come through in a single go?
No. Facebook will throw exception of too much data. Also there is automated system in place which will block time-consuming requests as well as it will block your app if it is making too much queries too frequently on a single table - API Throttling Warnings.
If not is there a best practice paging or offsetting solution?
You can do paging in FQL and when querying connections in graph. It is best practice.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610337",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: NUnit & testing log4net dynamic log file location I'm writing an application where the user can change (at runtime) the directory where the log4net log is stored. The directory string is stored in the app.config.
When I want to test if the log file is created in the right directory with NUnit, the logfile (and the corresponding directory) is not created.
When looking online for this problem I read that NUnit stops the logging from working because it uses log4net itself. The provided sample tells you to create a additional .config (Test.config) which also contains the log4net sections and to load the configuration inside the testing class, which I did.
There is still no log file created when using the unit test.
When starting the application, the log file is created as it should.
Method to set the log directory:
public void MyMethod()
{
string logDirectory = app.Settings["LogDirectory"].Value;
//assure that the file name can be appended to the path
if (!logDirectory.EndsWith(@"\"))
{
logDirectory += @"\";
}
//find the rolling file appender and set its file name
XmlConfigurator.Configure();
Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository();
foreach (IAppender appender in hierarchy.Root.Appenders)
{
if (appender is RollingFileAppender)
{
RollingFileAppender fileAppender = (RollingFileAppender)appender;
string logFileLocation = string.Format("{0}Estimation_Protocol_{1}.txt",
logDirectory, EstimatorHelper.SoftwareVersionAndDateTime());
fileAppender.File = logFileLocation;
fileAppender.ActivateOptions();
break;
}
}
log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
log.Debug("Logging directory & file name set.");
}
The test class:
class EstimatorTests
{
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public EstimatorTests()
{
FileInfo fileInfo = new FileInfo(@"%property{LogName}");
log4net.Config.XmlConfigurator.Configure(fileInfo);
}
[Test]
public void TestLoadInputPaths()
{
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
AppSettingsSection app = config.AppSettings;
string time = DateTime.Now.Ticks.ToString();
app.Settings["ProcessingProtocolDirectory"].Value = "C:\\thisFolderDoesntExist" + time;
Form mainForm = new Form();
Form.MyMethod();
Assert.IsTrue(Directory.Exists("C:\\thisFolderDoesntExist" + time));
//this assert fails!
}
}
The log4net config:
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>
<log4net>
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file type="log4net.Util.PatternString" value="%property{LogName}" />
<appendToFile value="true"/>
<rollingStyle value="Size"/>
<maxSizeRollBackups value="5"/>
<maximumFileSize value="10MB"/>
<staticLogFileName value="true"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %level %logger - %message%newline%exception%newline"/>
</layout>
</appender>
<root>
<level value="DEBUG"/>
<appender-ref ref="RollingFileAppender"/>
</root>
</log4net>
A: I did not test it but I think you need to remove the call to XmlConfigurator.Configure(); in MyMethod because this will overwrite the configuration you do in the test class.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610341",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What is the name of this jQuery form validation plugin? (Screenshot included) I am looking for a good jquery plugin for form validation. I have found many related plugins but not of them matches the one I'm after. Below is a screenshot of what I'm looking for. Can anyone provide me with a link or the name of the plugin?
I've looked through the following links but they do not look like the one I am looking for:
*
*http://docs.jquery.com/Plugins/validation
*http://jquery.malsup.com/form/
*http://www.position-absolute.com/articles/jquery-form-validator-because-form-validation-is-a-mess/
*http://www.webresourcesdepot.com/powerful-jquery-form-validation-plugin-validity/
*http://demos.usejquery.com/ketchup-plugin/
*http://www.matiasmancini.com.ar/jquery-plugin-ajax-form-validation-html5.html
*http://frontendbook.com/jquery-form-validation-plugin
A: It may not even be an off-the-shelf jquery plugin.
That design could certainly be created with the jQuery Validation plugin. You will just have to manually manage your error containers. Some good info here:
Jquery Validation plug-in custom error placement
A: its html5 validation popups . If you specify novalidate="novalidate" in form , it will not show
A: Maybe you could tried this one:
http://git.aaronlumsden.com/progression/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610343",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How I know when a class is a Helper or a Service? i'm using DDD architecture in my project and I need to create a class to generate a GUID to use in another class.
This class that generate my GUID is a Infrastructure Service or a Infrastructure Helper?
How I know when a class is a Helper or a Service?
A: Service able to serve some clients, and often this is a SOA specific entity.
Helper provides a set of methods which commonly are pure functions.
From my point of view if a class which provides the GUID generation functionality stores or uses this GUID for further needs - it is a Service class, otherwise I would say it is a Helper because simply work by principle do and forget / generate and forget.
Often if you can make method a static method - this is a helper method, it does not depends on any class state and does not affect it as well.
A: Glad you found an answer but you might want to rethink the question itself. What is 'Helper'? There is no such pattern or stereotype in DDD or anywhere else. Take a look at this answer. [Something]Helper is usually a sign of SRP violation or just a bad naming. For example if your language/framework does not provide Guid generation (which is highly unlikely) you can create your own GuidGenerator class. The name should reflect responsibility.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610349",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: How to simulate virtuality for method template I have a class hierarchy where I want to introduce a method template that would behave like if it was virtual. For example a simple hierarchy:
class A {
virtual ~A() {}
template<typename T>
void method(T &t) {}
};
class B : public A {
template<typename T>
void method(T &t) {}
};
Then I create object B:
A *a = new B();
I know I can get the type stored in a by typeid(a). How can I call the correct B::method dynamically when I know the type? I could probably have a condition like:
if(typeid(*a)==typeid(B))
static_cast<B*>(a)->method(params);
But I would like to avoid having conditions like that. I was thinking about creating a std::map with typeid as a key, but what would I put as a value?
A: You can use the "Curiously Recurring Template Pattern"
http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern
Using this pattern, the base class takes the derived class type as a template parameter, meaning that the base class can cast itself to the derived type in order to call functions in the derived class. It's a sort of compile time implementation of virtual functions, with the added benefit of not having to do a virtual function call.
template<typename DERIVED_TYPE>
class A {
public:
virtual ~A() {}
template<typename T>
void method(T &t) { static_cast<DERIVED_TYPE &>(*this).methodImpl<T>(t); }
};
class B : public A<B>
{
friend class A<B>;
public:
virtual ~B() {}
private:
template<typename T>
void methodImpl(T &t) {}
};
It can then be used like this...
int one = 1;
A<B> *a = new B();
a->method(one);
A: Is there any common code you could extract and make virtual?
class A {
virtual ~A() {}
template<typename T>
void method(T &t)
{
...
DoSomeWork();
...
}
virtual void DoSomeWork() {}
};
class B : public A {
virtual void DoSomeWork() {}
};
A: As you may know, you cannot have templates for virtual functions, since the entirety of the virtual functions is part of the class type and must be known in advance. That rules out any simple "arbitrary overriding".
If it's an option, you could make the template parameter part of the class:
template <typename T> class A
{
protected:
virtual void method(T &);
};
template <typename T> class B : public A<T>
{
virtual void method(T &); // overrides
};
A more involved approach might use some dispatcher object:
struct BaseDispatcher
{
virtual ~BaseDispatcher() { }
template <typename T> void call(T & t) { dynamic_cast<void*>(this)->method(t); }
};
struct ConcreteDispatcher : BaseDispatcher
{
template <typename T> void method(T &);
};
class A
{
public:
explicit A(BaseDispatcher * p = 0) : p_disp(p == 0 ? new BaseDispatcher : p) { }
virtual ~A() { delete p_disp; };
private:
BaseDispatcher * p_disp;
template <typename T> void method(T & t) { p_disp->call(t); }
};
class B : public A
{
public:
B() : A(new ConcreteDispatcher) { }
// ...
};
A: Oops. Initially answered at the wrong question - ah well, at another question
After some thinking I recognized this as the classic multi-method requirement, i.e. a method that dispatches based on the runtime type of more than one parameter. Usual virtual functions are single dispatch in comparison (and they dispatch on the type of this only).
Refer to the following:
*
*Andrei Alexandrescu has written (the seminal bits for C++?) on implementing multi-methods using generics in 'Modern C++ design'
*
*Chapter 11: "Multimethods" - it implements basic multi-methods, making them logarithmic (using ordered typelists) and then going all the way to constant-time multi-methods. Quite powerful stuff !
*A codeproject article that seems to have just such an implementation:
*
*no use of type casts of any kind (dynamic, static, reinterpret, const or C-style)
*no use of RTTI;
*no use of preprocessor;
*strong type safety;
*separate compilation;
*constant time of multimethod execution;
*no dynamic memory allocation (via new or malloc) during multimethod call;
*no use of nonstandard libraries;
*only standard C++ features is used.
*C++ Open Method Compiler, Peter Pirkelbauer, Yuriy Solodkyy, and Bjarne Stroustrup
*The Loki Library has A MultipleDispatcher
*
*Wikipedia has quite a nice simple write-up with examples on Multiple Dispatch in C++.
Here is the 'simple' approach from the wikipedia article for reference (the less simple approach scales better for larger number of derived types):
// Example using run time type comparison via dynamic_cast
struct Thing {
virtual void collideWith(Thing& other) = 0;
}
struct Asteroid : Thing {
void collideWith(Thing& other) {
// dynamic_cast to a pointer type returns NULL if the cast fails
// (dynamic_cast to a reference type would throw an exception on failure)
if (Asteroid* asteroid = dynamic_cast<Asteroid*>(&other)) {
// handle Asteroid-Asteroid collision
} else if (Spaceship* spaceship = dynamic_cast<Spaceship*>(&other)) {
// handle Asteroid-Spaceship collision
} else {
// default collision handling here
}
}
}
struct Spaceship : Thing {
void collideWith(Thing& other) {
if (Asteroid* asteroid = dynamic_cast<Asteroid*>(&other)) {
// handle Spaceship-Asteroid collision
} else if (Spaceship* spaceship = dynamic_cast<Spaceship*>(&other)) {
// handle Spaceship-Spaceship collision
} else {
// default collision handling here
}
}
}
A: I think the only solution is the http://en.wikipedia.org/wiki/Visitor_pattern
See this topic:
How to achieve "virtual template function" in C++
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610350",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Font in Android Library At the follow link
Android Dev Guide
is write:
Library projects cannot include raw assets
The tools do not support the use of raw asset files (saved in the assets/ directory) in a library project. Any asset resources used by an application must be stored in the assets/ directory of the application project itself. However, resource files saved in the res/ directory are supported.
So if I want to create a custom view component that use a custom font how can I access the resource? Can't I redistribute my component with my favorite font !!!!
Best regards
A: Ok I have found a workaround for the problem. You need to copy the file to an external directory then load a typeface from file with Typeface.createFromFile and then delete the temporary file. I know is not a clean mode of work but is working grate.
1 - You need to put your font on "/res/raw/font.ttf"
2 - Inser in your code the following method
3 - put in your code Typeface mFont = FileStreamTypeface(R.raw.font);
4 - All is done
Typeface FileStreamTypeface(int resource)
{
Typeface tf = null;
InputStream is = getResources().openRawResource(resource);
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/gmg_underground_tmp";
File f = new File(path);
if (!f.exists())
{
if (!f.mkdirs())
return null;
}
String outPath = path + "/tmp.raw";
try
{
byte[] buffer = new byte[is.available()];
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(outPath));
int l = 0;
while((l = is.read(buffer)) > 0)
{
bos.write(buffer, 0, l);
}
bos.close();
tf = Typeface.createFromFile(outPath);
File f2 = new File(outPath);
f2.delete();
}
catch (IOException e)
{
return null;
}
return tf;
}
if someone have an alternative I'm pleased to read it.
Do you have to remember that this workaround is only for Android Libraries
Best regards
A: Here's a method for loading fonts from resources that actually works ;-)
Credit to mr32bit for the first version.
private Typeface getFontFromRes(int resource)
{
Typeface tf = null;
InputStream is = null;
try {
is = getResources().openRawResource(resource);
}
catch(NotFoundException e) {
Log.e(TAG, "Could not find font in resources!");
}
String outPath = getCacheDir() + "/tmp" + System.currentTimeMillis() ".raw";
try
{
byte[] buffer = new byte[is.available()];
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(outPath));
int l = 0;
while((l = is.read(buffer)) > 0)
bos.write(buffer, 0, l);
bos.close();
tf = Typeface.createFromFile(outPath);
// clean up
new File(outPath).delete();
}
catch (IOException e)
{
Log.e(TAG, "Error reading in font!");
return null;
}
Log.d(TAG, "Successfully loaded font.");
return tf;
}
A: Intellij Idea (and android studio as it's based on intellij) has a feature that let you include the asset files of the library module to application module, I don't know about other environment.
Go to project structure in file menu, then facets, choose application module, in compiler tab check "include assets from dependencies to the into APK" checkbox.
As intellij is far better than Eclipse, I think migrating is reasonable.
EDIT:
Asset and manifest merging are fully supported in android studio.
A: If you extend a TextView and want to use many of this views you should have only one instance of the Typeface in this view. Copy the *.ttf file into res/raw/ and use the following code:
public class MyTextView extends TextView {
public static final String FONT = "font.ttf";
private static Typeface mFont;
private static Typeface getTypefaceFromFile(Context context) {
if(mFont == null) {
File font = new File(context.getFilesDir(), FONT);
if (!font.exists()) {
copyFontToInternalStorage(context, font);
}
mFont = Typeface.createFromFile(font);
}
return mFont;
}
private static void copyFontToInternalStorage(Context context, File font) {
try {
InputStream is = context.getResources().openRawResource(R.raw.font);
byte[] buffer = new byte[4096];
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(font));
int readByte;
while ((readByte = is.read(buffer)) > 0) {
bos.write(buffer, 0, readByte);
}
bos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
setTypeface(getTypefaceFromFile(context));
}
}
mFont is a static variable, so the reference will not be destroyed and can be reused in other MyTextViews.
This code is nearly the same as the other answers but I guess mor efficient and consumes less memory if you are using it in a ListView or something.
A:
So if I want to create a custom view component that use a custom font how can I access the resource?
Your code would access it the same way that it does not. You will simply have to tell reusers of your custom view to include the font file in their assets.
Can't I redistribute my component with my favorite font !!!!
Sure you can. Put the font in a ZIP file along with the rest of your library project, along with instructions for where to place it in a project. Be sure to use a font that you have rights to redistribute this way, though.
A: Even though You put Your fonts in assets/fonts folder, somehow this library works and its very easy to use: https://github.com/neopixl/PixlUI . I've successfully tested it on Android 2.3.
as well as 4.4
A: Just use the response of @bk138 with this little change it works to me
add this in the manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
and add this before creating the Buffered
File f2 = new File(outPath);
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(outPath));
A: The code below modifies the solution from @bk138 and includes @Jason Robinson recommendations for not deleting the file and checking for a previously cached file first. Also, it names the temp file after the font instead of the time created.
public static Typeface getFontFromRes(Context context, int resId, boolean deleteAfterwards){
String tag = "StorageUtils.getFontFromRes";
String resEntryName = context.getResources().getResourceEntryName(resId);
String outPath = context.getCacheDir() + "/tmp_" + resEntryName + ".raw";
//First see if the file already exists in the cachDir
FileInputStream fis = null;
try {
fis = new FileInputStream(new File(outPath));
} catch (FileNotFoundException e) {
Log.d(tag,"fileNotFoundException outPath:"+outPath+e.getMessage());
}
if(fis != null){
try {
Log.d(tag,"found cached fontName:"+resEntryName);
fis.close();
} catch (IOException e) {
Log.d(tag,"IOException outPath:"+outPath+e.getMessage());
}
//File is already cached so return it now
return Typeface.createFromFile(outPath);
}
InputStream is = null;
try {
is = context.getResources().openRawResource(resId);
}catch(NotFoundException e) {
Log.e(tag, "Could not find font in resources! " + outPath);
}
try{
byte[] buffer = new byte[is.available()];
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(outPath));
int l = 0;
while((l = is.read(buffer)) > 0)
bos.write(buffer, 0, l);
bos.close();
}catch (IOException e){
Log.e(tag, "Error reading in font!");
return null;
}
Typeface tf = Typeface.createFromFile(outPath);
if(deleteAfterwards){
// clean up if desired
new File(outPath).delete();
}
Log.d(tag, "Successfully loaded font.");
return tf;
}
A: Here's my modified version/improvement on @Mr32Bit's answer. On the first call, I copy the font to the app private dir /custom_fonts. Future reads check if exists and if so reads existing copy (saves time on coping file each time).
note: This assumes only a single custom font.
/**
* Helper method to load (and cache font in app private folder) typeface from raw dir this is needed because /assets from library projects are not merged in Eclipse
* @param c
* @param resource ID of the font.ttf in /raw
* @return
*/
public static Typeface loadTypefaceFromRaw(Context c, int resource)
{
Typeface tf = null;
InputStream is = c.getResources().openRawResource(resource);
String path = c.getFilesDir() + "/custom_fonts";
File f = new File(path);
if (!f.exists())
{
if (!f.mkdirs())
return null;
}
String outPath = path + "/myfont.ttf";
File fontFile = new File(outPath);
if (fontFile.exists()) {
tf = Typeface.createFromFile(fontFile);
}else{
try
{
byte[] buffer = new byte[is.available()];
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(outPath));
int l = 0;
while((l = is.read(buffer)) > 0)
{
bos.write(buffer, 0, l);
}
bos.close();
tf = Typeface.createFromFile(outPath);
}
catch (IOException e)
{
return null;
}
}
return tf;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610355",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: How to convert NSString value @"3.45" into float? How to convert NSString value @"3.45" into float. 3.45
float fCost = [[NSDecimalNumber decimalNumberWithString:@"3.45"]floatValue] ;
A: float number = [string floatValue];
A: NSString *val = @"3.45";
float fCost = [val floatValue];
A: NSString's: - (float)floatValue;
For example:
NSString *str = @"3.45";
float f = [str floatValue];
A: Reading your comment to Marek's answer it looks like your string actually = @"$3.45"
To convert that to a float use:
NSNumberFormatter * formatter = [[[NSNumberFormatter alloc] init] autorelease];
formatter.numberStyle = NSNumberFormatterCurrencyStyle;
formatter.currencyCode = @"USD";
float value = [[formatter numberFromString: @"$3.45"] floatValue];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610359",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "29"
} |
Q: How do I handle multiple web.config transforms for different instances when dealing with multiple publish targets? I have an Asp.NET MVC site that I manage multiple instances of. Each instance uses it's own database but the code base is all the same. To facilitate this I have several build configurations with matching web.config transforms, so that when I publish it doesn't use my development database but instead uses the specific database for that site instance.
The problem with this came today when I went to publish an update to one of the sites. I forgot to change the build configuration, so my publish to site A was using a web.config transform that was meant for site B, and mayhem and confusion ensued.
Is there any way to to specify that a specific publish target will ONLY be used with a specific build configuration?
Or is there a better way to handle this situation than juggling build configurations?
A: One way to deal with this sort of thing, and I'm not certain it's the best, but it is a way, is to set certain configuration values in a higher level web.config or machine.config file that always resides on the machine in question.
Then just make sure that your project files don't override those configuration values.
Here are some considerations if you do this.
*
*If you want to source control these values, it can be more difficult
this way (this could be a pro or a con depending on your
environment).
*If other virtual sites are on the same machine and use the same
configuration values, this could affect them all, and if multiple
sites do use that same configuration value, changing it at the
source will change them all (again, could be a pro or a con
depending).
*If something is wrong with the value, it can be harder to
determine where the problem is or what is causing it.
*Getting to machine.config may be difficult in your organization
or with your hosting provider depending on your access/security
privileges, and it's not always possible to put a web.config at a
higher level than your application.
Obviously the good thing here is that you can have a different value configured on each machine and as long as these values are not also set in your web.config (which would probably result in an error), you won't have to worry about compiling different versions.
I believe that Visual Studio 2010 has a way for setting different config files for different build types, but that sounds pretty much like what you are already doing, so forgetting to build the right way can still end up with similar results.
You could attempt to set up continuous integration with something like TFS Build if that is available to you, in which case what gets built for prod could be set up to always work a certain way and always pull from the correct build type.
Hope something here helps.
A: With kwateeSDCM you can not just deploy apps and web applications but you can also manage instance-by-instance parameters or file overrides. I've only used it with tomcat wars but it's not tied to a language or a platform so I suppose it should be straightforward to configure it to work with ASP.NET as well.
A: Maybe you could go a solution where you don't rely on the 'Publish' dialog of the web application that requires you to make the right setting every time, but instead use a automated command-line like solution (batch file, your own msbuild target, or a build server like CStroliaDavis suggested [cruisecontrol, tfs, teamcity]).
You can just call the 'package' target from command line which creates a package:
msbuild MyWebProject.csproj /t:Package /P:Configuration=Release;DeployIisAppPath="Default Web Site/Main/MyWebProject";PackageLocation="F:\MyWebProjectDeploy.zip"
This also creates a *.cmd file so you can deploy it like this:
F:\MyWebProjectDeploy.deploy.cmd /Y -allowUntrusted /M:http://webserver/MSDeployAgentService /U:Administrator /P:"Secret"
You can add a custom *.msbuild file to your solution that performs these actions, or maybe it's easiest to just add a command to Tools -> External tools.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610360",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How do I access files on a c$ resource from C# I'm using an example like this:
System.IO.File.Copy("\\host\c$\folder\file.end", "c:\file.end", true);
But I'm only getting a DirectoryNotFoundException with the description
Could not find a part of the path '\host\c$\folder\file.end'
What do I have to do to access files on a DRIVE$ resource? I have administrative privileges on the machine.
A: Try using a verbatim string for the path
System.IO.File.Copy(@"\\host\c$\folder\file.end", @"c:\file.end", true);
or escape the slashes
System.IO.File.Copy("\\\\host\\c$\\folder\\file.end", "c:\\file.end", true);
A: Try:
System.IO.File.Copy(@"\\host\c$\folder\file.end", @"c:\file.end", true);
Because as you can see from exception path is not well formatted. You need to escape \ symbol.
A: Try
System.IO.File.Copy(@"\\host\c$\folder\file.end", @"c:\file.end", true);
Force a string literal.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610362",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to Share on CRM2011 with XRM services? I'm new to CRM 2011. How to Share (create share record contact between team) on CRM2011 with XRM services? I can't find on SDK and I don't know to where shared record on MSCRM db.
A: You're looking for the GrantAccessRequest class. Here's the SDK article.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610366",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can't set value of hidden input to comma seperated list in ASP VB.net Hi I've run into a really annoying problem, I'm trying to set the value of a hidden input to a comma seperated list taken from a database but in pure CSV format it won't set the value.
The input tag and ul tag looks like this (I am aware of asp:hiddenfield and it's value property but I'm not using it as I still have this issue):
<ul id="keywords" runat="server">
</ul>
<input type="hidden" id="keywordsBox" runat="server" />
The code I'm using to populate it is:
'connection strings and all that stuff is set up and using a SqlDataReader to sort through results
while result.Read()
keywordsBox.Attribute.Add("value", result.Item("keywords"))
keywords.innerHTML = "<li>" & Replace(result.Item("keywords"),",","</li><li>") & "</li>"
End while
This will populate the li tags but will not populate the value for the input, I've tried using the replace function on the list for the value but it only works if I remove the commas or put other characters infront of them. I've also tried replacing it with the HTML code for a comma but just prints the HTML code out.
Has anybody else ran into this at all? How'd you fix it?
A: Try the below code, this will solve your problem:
dim hValue as string =""
while result.Read()
hValue += result.Item("keywords")
keywords.innerHTML = "<li>" & Replace(result.Item("keywords"),",","</li><li>") & "</li>"
End while
keywordsBox.Attribute.Add("value", hValue )
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610372",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to sort an NSArray of float values? I have an NSArray like this:
how to sort NSarray float with value like this:122.00,45.00,21.01,5.90
A: try this it work for me
NSArray *array=[[NSArray alloc] initWithObjects:[NSNumber numberWithFloat:12.01],[NSNumber numberWithFloat:13.01],[NSNumber numberWithFloat:10.01],[NSNumber numberWithFloat:2.01],[NSNumber numberWithFloat:1.5],nil];
NSArray *sorted = [array sortedArrayUsingSelector:@selector(compare:)];
A: @Ron's answer is perfect, but I want to add sorting by using an comparator block. For this trivial case it might be overkill, but it is very handy when it comes to sorting of objects in respect to several properties
NSArray *myArray =[NSArray arrayWithObjects: [NSNumber numberWithFloat:45.0],[NSNumber numberWithFloat:122.0], [NSNumber numberWithFloat:21.01], [NSNumber numberWithFloat:5.9], nil];
NSArray *sortedArray = [myArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
if ([obj1 floatValue] > [obj2 floatValue])
return NSOrderedDescending;
else if ([obj1 floatValue] < [obj2 floatValue])
return NSOrderedAscending;
return NSOrderedSame;
}];
A: Here... use NSSortDescriptor
First Convert the float values into NSNumber
NSSortDescriptor *sortDescriptor;
sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"floatValue"
ascending:YES] autorelease];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray *sortedArray;
sortedArray = [drinkDetails sortedArrayUsingDescriptors:sortDescriptors];
Hope it helps :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610379",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Does DotNetNuke 6 support Ajax Control Toolkit? Does anybody have successfully working module in DNN 6 with the Ajax Control Toolkit?
My modules stopped working when we migrated from DNN 5.x to to 6.x.
Modules compile without errors but I am getting client side script error:
'AjaxControlToolkit requires ASP.NET Ajax 4.0 scripts. Ensure the correct version of the scripts are referenced. If you are using an ASP.NET ScriptManager, switch to the ToolkitScriptManager in AjaxControlToolkit.dll'
Seems like this is conflict with Telerik's controls, according to information that I have found. But I didn't find any info how to fix it.
A: You should be able to use older versions of the ASP.NET AJAX Control Toolkit, but once they start requiring the ToolkitScriptManager, you're out of luck with DNN (though you'll be out of luck with any version of DNN, since there's not a way to override the type of ScriptManager it uses.
Starting with DNN 6, they use Telerik's RadScriptManager. Previously, you could modify the core code to switch out for the ToolkitScriptManager, but now switching out might cause other issues.
A: It could work together, but you'll need do some modifications to the core of DNN.
Here the list of things to do:
*
*Check that you're using latest version of .Net 4.0 binaries of AjaxControlToolkit (I was able to let it work for DNN 6.0.1 with Telerik 2011.01.519 and ACT September 2011 v4.1.50927)
*Check that in your web.config you have assembly binding redirects for System.Web.Extensions and System.Web.Extensions.Design to the version 4.0
*Take DNN source package, find Library\Framework\AJAX.cs, locate method AddScriptManager, instantiation of RadScriptManager in it, for the version 6.0.1 look into line 54. Add one more property initializer:
EnableScriptCombine = false. Compile it (in Release configuration, of course), take DotNetNuke.dll and drop into your DNN installation.
You should be done.
Credits goes to Telerik support, despite it's stated there that it should work out of the box starting from 2010.1.625. Not sure, did I get them wrong, or they just reintroduced this bug.
P.S. DNN support promises to release version 6.1.0 in November with updated Telerik controls, which should fix this issue, at least on their opinion.
A: Just checked with nuke 6.1 and the last version of jaxcontroltoolkit - still the same error.
It looks like it's not supported anymore. Sad:(
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610380",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Rails 3, Devise, Multiple Roles Sharing Same Views I'm writing a trading system and I have 3 models/roles: Buyers, Sellers and Administrators. I have generated the devise views for each of the models but I would like to use the same sign in, forgotten password pages etc. for them, rather than maintaining 3 sets of views, is there a way of doing this?
The buyer and seller have similar fields (forename, surname, email address, telephone etc.), is it possible to use STI with devise and is it fairly straightforward? At the moment I have 3 separate models with no inheritance.
A: You can simply have a single User model with a :role attribute and also implement a simple ACL via CanCan or decl_auth (gems). This way they will all sign in etc. via the same session. Devise and CanCan is quite a popular approach and well documented online and in their respective Github wiki's.
For administrators, you can modify your validations to skip on the extra attributes and leave them as blank in the DB.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610387",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Cannot create an object through actionscript I created MovieClip, "Exported it for ActionScript" with the same name. It's okay when I create an object visually, by dragging it to the stage but when using var smth:* = new myClass() an error occurs. There is an error because I have some code in the MovieClip I exported, and it involves the Stage. It happens so that stage is not instantiated at the moment of running code? I mean, I'm creating the object on the second frame so it's seems kinda impossible. When (in the MovieClip) I write trace(stage); output is null. As I said, there is no problem when creating object visually. Ladies and gentlemen, what the...?!
A: import flash.events.Event;
In the constructor of the class add an eventListener for the stage to be added.
this.addEventListener(Event.ADDED_TO_STAGE, myFunction);
then just create an eventListener with the name init and with an event as parameter.
function myFunction(e : Event) : void
{
this.removeEventListener(Event.ADDED_TO_STAGE, myFunction);
// execute code here
}
The removeEventListener is required, don't forget to remove it! A bug in flash will trigger the event added to stage twice, so if you don't want to execute the code twice, you have to remove it.
A: If I follow what you're saying, you don't have a reference to the stage right-away inside your MovieClip subclass? This happens if the MovieClip is not attached to the stage or another DisplayObjectContainer that is already attached to it (somewhere up the Display-list chain).
One way to verify if the stage is available AND to execute your code WHEN IT IS available, is a little code snippet often found in FlashDevelop projects:
public function Main():void {
stage ? init() : addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void {
removeEventListener(Event.ADDED_TO_STAGE, init);
// entry point
}
So if the stage IS found, it immediatly triggers the init() method (without arguments), otherwise it will wait for when it is added to the stage (or some other DisplayObjectContainer that is already attached), which will pass in the Event parameter when it makes use of init(e:Event) as a callback method.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610388",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: .NET 3.5 application running a .NET 4.0 API We have a few applications that are under the .net 3.5 framework. We have a code API (library for reusable access to central database information) that is distributed. We have moved that piece of the site to that .net 4.0 framework.
My question is; how can we make the api available to the applications that are not in a position to migrate to the .net 4.0 framework yet? The new functionality that needed by everyone is under the 4.0 framework.
Should I just create two APIs?
To the comments left on the question; if you don't have anything constructive, please don't post.
I'm not sure what the confusion about a custom API is not clear.
We are very familier with writing applications, and are in the process of migrating to the 4.0 framework. It can be costly for a company (and it's clients) to have to re-write/update an application every time a new framework comes out.
A: Just recompile in .NET 4 - best solution.
A: As long as you haven't explicitly targeted the 3.5 framework in your configuration files, and you haven't used any features which broke in .NET 4.0, you should be good to go as is.
A: I am afraid you'll have to recompile the older applications with the .NET 4 framework for them to work with your new API.
Or you can re-compile your API (If possible) targeting the 3.5 framework.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610389",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Deriving a random long value from random integers I have a method int randInt(int min, int max) that generates a random integer between min and max inclusive. It interfaces with an external system that has a good source of entropy.
The external system only generates 32-bit integers, while I need to get a 64-bit long.
Is it possible to compose several random integers to create a long without introducing any new bias?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610390",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to setup SSL on a local django server to test a facebook app? I've configured my local machine's HOSTS configuration to access the local server ( @ 127.0.0.1 ) whenever I hit http://www.mydomain.com on the browser.
And I was using this to interact with facebook's graph api to build my app. But now facebook requires us to have an HTTPS url or rather an SSL secured url to interact with their api.
So the question is -> How do I setup SSL on a local django server ?
A: Short answer is you'll need to setup a proper webserver on your development machine. Use whichever one (Apache, nginx, cherokee etc) you're most familiar with.
Longer answer is that the django development server (manage.py runserver) isn't designed to do SSL etc and the effort to make it do so is likely greater than you'd want to spend.
See discussions of this passim on the django-users list: http://groups.google.com/group/django-users/browse_thread/thread/9164126f70cebcbc/f4050f6c82fe1423?lnk=gst&q=ssl+development+server#f4050f6c82fe1423
A: Not to necro a thread, but I found this tool to be extremely easy to use.
It's a premade django application with very simple install instructions.
You can add a certified key once it is installed simply by running:
python manage.py runsslserver --certificate /path/to/certificate.crt --key /path/to/key.key
I hope this helps any passer-by who might see this.
A: Workaround to run https on django.
This can be done with stunnel that lets the Facebook server and stunnel on your machine communicate in SSL and stunnel turns around to communicate with Python in HTTP. First install stunnel. For instance in Mac OS X:
brew install stunnel
Then you need to create a settings file for stunnel to execute. You can create a text file anywhere. For instance, you can create dev_https and input:
pid=
cert=/usr/local/etc/stunnel/stunnel.pem
foreground=yes
debug=7
[https]
accept=8001
connect=8002
TIMEOUTclose=1
stunnel creates a fake certificate. By default on Mac, it’s at /usr/local/etc/stunnel/stunnel.pem. It’ll bring up a warning on your browser saying that your webpage can be fake but Facebook operations still work right. Since stunnel has to listen on one port and Python’s development server cannot run on the same server, you must use different ports for accept (incoming) and connect (internal). Once you have your dev_https file or whatever you called it, run
sudo stunnel dev_https
to start the tunnelling. Then start your Python server.
HTTPS=1 python manage.py runserver 0.0.0.0:8002
Environment variable HTTPS must be set to 1 for it to return secure responses and since we previously set the internal port to 8002, we listen on 8002 from all incoming IPs. Then, your IP:8001 can accept HTTPS connections without changing your webserver and you can continue running another instance of HTTP Python server on a different port.
ref:
https://medium.com/xster-tech/django-development-server-with-https-103b2ceef893
A: I understand this has already been answered, but for a clearer solution:
Step 1: Install library
pip install django-sslserver
Step 2: Add to installed apps in settings.py
INSTALLED_APPS = [
'sslserver',
'...'
]
Step 3: Run the code using runsslserver instead of runserver. Certificate & key are optional.
python manage.py runsslserver --certificate /path/to/certificate.crt --key /path/to/key.key
A: This doesn't solve the automatic testing issue via
./manage.py test
but to run a server with HTTPS you can use RunServerPlus: http://pythonhosted.org/django-extensions/runserver_plus.html
Just install django-extensions and pyOpenSSL:
pip install django-extensions pyOpenSSL
and then run:
python manage.py runserver_plus --cert cert
A: With django-extensions you can run the following command:
python manage.py runserver_plus --cert certname
It will generate a (self-signed) certificate automatically if it doesn't exist. Almost too simple.
You just need to install the following dependencies:
pip install django-extensions
pip install Werkzeug
pip install pyOpenSSL
Now, as Ryan Pergent pointed out in the comments, you lastly only need to add 'django_extensions', to your INSTALLED_APPS and should be good to go.
I used a tunnel before, which worked, but this is much easier and comes with many other commands.
A: I've been able to setup ssl on django's test server by using stunnel. Here is some info on how to set it up
Just a note, I wasn't able to get it working using the package provided by debian in apt-get and I had to install from source. In case you have to do the same, please check out the excellent instructions debian forums on how to build debian packages.
There are plenty of instructions online and also on stunnel FAQ on how to create your pem certificate, but ultimately dpkg-buildpackage on Debian built it for me.
I would imagine that things could actually be more straight forward on Windows.
I then was able to make pydev in eclipse start the test server (and also attach to it) by adding a HTTPS=1 environment variable under "Debug Configurations" -> "Environment" -> Variables
A: I got the same problem when wanna test Sign up using Facebook. After use django SSL Server from https://github.com/teddziuba/django-sslserver. This problem is solved. You may need it too.
A: This discussion page is really old, earlier Django does not supported SSL, it needs to be done through stunnel or Werkzeug.
Django now supports SSL configuration with django-sslserver:
https://djangopackages.org/packages/p/django-sslserver/
Add in install app and pass certs in command line.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610394",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "29"
} |
Q: Sorting ArrayList data within table I have a TreeTable and would like to perform the sort by number and alphabetically when clicking on header.
Example:
*
*On a first click, I have to check that the column content is sorted by number
*If I click on another column that contains String data, I have to check that column content is sorted alphabetically.
Are there known functions that could I use?
I've used Collections for sorting number , but how do I can make the sort alphabetically ?
Collections.sor(myList) is OK for sorting by number but I would sort data alphabetically.
thanks
A: This can easily be done via Collections.sort(...). Create a copy of your list, sort it and check if they are equal.
Example:
List <String> copy = new ArrayList <String>(original);
Collections.sort(copy);
assertEquals(copy, original);
This can be done, if the elements in the list are comparable (i.e. are of type T implements Comparable <T>). Strings are comparable, and their default comparator sorts them alphabetically (though upper-case are always comes before lower-case)
You may also provide a Comparator for a more flexible sorting.
Here is a more complicated example.
List <String> unholyBible = new ArrayList <String>();
unholyBible.add("armageddon");
unholyBible.add("abyss");
unholyBible.add("Abaddon");
unholyBible.add("Antichrist");
Collections.sort(unholyBible);
System.out.println(unholyBible);
This will print us [Abaddon, Antichrist, abyss, armageddon]. This is because default comparation is case-sensitive. Lets fix it:
List <String> unholyBible = new ArrayList <String>();
unholyBible.add("armageddon");
unholyBible.add("abyss");
unholyBible.add("Abaddon");
unholyBible.add("Antichrist");
Collections.sort(unholyBible, new Comparator <String>() {
public int compare(String o1, String o2){
return o1.compareToIgnoreCase(o2);
}
});
System.out.println(unholyBible);
This one prints [Abaddon, abyss, Antichrist, armageddon].
Now you may worship Satan in strict alphabetical order.
See also
*
*Comparator API
*Collections.sort(List, Comparator)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610400",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: ffmpeg unsupported video codec I tried to convert a .flv into an mpeg with this code:
ffmpeg -i my.flv -target ntsc-dvd -aspect 4:3 my.mpg
And I get a lot of these here:
[flv @ 0x5597b8]Unsupported video codec (7)
and then:
Stream mapping:
Stream #0.0 -> #0.0
Stream #0.1 -> #0.1
Unsupported codec (id=0) for input stream #0.0
But when I ask ffmpeg for formats flv is supported.
What is wrong?
Thanks!
A: Flash video is the file (container) format not the video codec. In your example, the container contains two streams and it is stating that it doesn't support the video codec that stream 0.0 uses. Do you know what video codec it is?
See the wikipedia article on Flash video and the wikipedia article on container formats for more details.
A: rename your my.flv to be my.mp4 and try that.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610401",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Making the jqueryUI theme picker widget work with localhost versions of css files The jQueryUI theme picker widget is awesome and I would really like to use it for a project in ASP.NET. But the theme picker loads the files from the jQuery website which isn't necessary because I have a copy of it. I did look into the code that is created by the theme switcher widget from here http://jqueryui.com/themeroller/themeswitchertool/ and the urls are hardcoded. Well I don't mind changing the url's :) just wondered why all those styles and font sizes have been specified in the query string and how can I get it to work with my local files?
A: It's dead simple. After looking into the theme switcher gadget i was able to understand that html markup for the themes too are hard coded. Here is a snippet of how your new to be added theme should look if you wanted to add custom themes.
<ul>
<li>
<a link="relative link to css">
<img src="source of image to show in drop down"/>
<span>Theme name</span>
</a>
<li>
</ul>
you just have to create a image of for how the theme looks in image editor, drop the link to css that's it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610405",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: On div hover with some class, find the last class and add class to a link element with the same last class. How in jQuery? How to add a class to an element(link) when hovering a div with the last class? Here is what I mean:
I have this code:
<a href="http://google.com" class="menu nice menu-2">Google</a>
<a href="http://yahoo.com" class="menu nice menu-10">Yahoo</a>
<a href="http://facebook.com" class="menu nice menu-20">Facebook</a>
.
.
.
<div class="pretty fixed menu-20">Some text here</div>
IMPORTANT! I do not know the name of div class. I only know that it will be always the last one! So when I have classes like pretty, fixed and menu-20, I need menu-20.
Now, I have to find the last class of the div and somehow find the same class in link element and add class to that link element e.g. "awesome" so it look like:
<a href="http://google.com" class="menu nice menu-2">Google</a>
<a href="http://yahoo.com" class="menu nice menu-10">Yahoo</a>
<a href="http://facebook.com" class="menu nice menu-20 awesome">Facebook</a>
.
How to do this?
Thanks in advance.
A: Classes are just another attribute, which means you can extract them using attr() and manipulate them as strings:
$('div').hover(function() { // mouseover
var arrClasses = $(this).attr("class").split(" ");
var strLastClass = arrClasses[arrClasses.length-1];
$('a.'+strLastClass).addClass("awesome");
}, function() { // mouseout
$('a').removeClass("awesome"); // easier to just remove it everywhere
});
A: Try this
$('div').hover(function(){
var myClass =$(this).attr('class').split(' ')[$(this).attr('class').split(' ').length - 1];
$('a.'+myClass ).addClass("awesome");
})
A: You could do;
function getNameOfLastClass(el){
var classNames=$(el).attr('class');
var classes = classNames.split(' ');
var lastClass = classes.pop();
return lastClass;
}
$('div').hover(function(){
var last = getNameOfLastClass(this);
console.log(last);
$('a').each(function(){
var lastA = getNameOfLastClass(this);
if (lastA === last){
$(this).addClass('awesome');
}
});
}
function(){
$('a').removeClass('awesome');
});
fiddle here http://jsfiddle.net/JqMfZ/1/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610406",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: .htacess Redirect & Secure Browsing on my Facebook Page I use the following Code on my Facebook page to check if user is FAN or NOT FAN. After this the users get different contents. It works fine but if I use Secure Browsing in Facebook I always see just: "You don't like this page yet."
<?php
require_once 'facebook-php-sdk/src/facebook.php';
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => 'X',
'secret' => 'X',
'cookie' => true,
));
$signed_request = $facebook->getSignedRequest();
$like_status = $signed_request["page"]["liked"];
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>zukundo</title>
<link rel="stylesheet" href="css/blueprint/screen.css" type="text/css" media="screen, projection">
</head>
<body>
<?php
if ($like_status) {
echo "You like this page.";
} else {
echo "You like this page not yet.";
}
?>
</body>
</html>
I found the problem: It's because of this in my .htaccess
Do you know if there is a way to solve this problem without to remove the following code, because it's good for SEO?
RewriteCond %{HTTP_HOST} ^page\.de
RewriteRule (.*) http://www.page.de/$1 [R=301,L]
A: You are losing the signed_request when doing the redirect, so $like_status will always be false. You need to change your htaccess. Maybe this answer will help you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610408",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: How to include .resource files into an assembly? I have a couple of compiled resource files (myProg.en_US.resource, myProg.de_DE.resource and so on) which are currently loaded during runtime using ResourceManager.CreateFileBasedResourceManager().
I want to modify that and embed the resources into the assembly. How can this be done? MSDN only speaks of .resx-files.
A: Click the file in solution explorer, then find it's properties. there is an item called build action. You can choose the option "embedded resource"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610419",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: post decrement in c
Possible Duplicate:
Undefined Behavior and Sequence Points
pre fix and post fix increment in C
Please explain how this program goes on to print i=2
#include<stdio.h>
void main()
{
int i=1;
i=i+2*i--;
printf("%d",i);
}
By the logic it should evaluate the value 3 because -- 1+2*1=3
But this first evaluates i-- and the updates the value of i. Why is this happening? :S
A: Modifying a variable in an expression and then assigning that result to the same variable is undefined behavior, so any behavior you're seeing is technically correct (including rebooting the computer, or destroying the universe). From the C standard, §6.5.2:
Between the previous and next sequence point an object shall have its
stored value modified at most once by the evaluation of an
expression.
To fix it, move the post-decrement out of the expression, like this:
int main() {
int i=1;
i=i+2*i;
i--;
printf("%d",i);
return 0;
}
A: i=i+2*i--;
This code invokes Undefined Behavior. You are modifying i and reading it within a single sequence point. Please read about Sequence Points.
How can I understand complex expressions like the ones in this section, and avoid writing undefined ones? What's a ``sequence point''?
A: i = i + 2 * i--;
i = 1 + 2 * 1; (as it is post decrement so the i value is still 1)
i = 1 + 2; (multiplication has higher priority, post decrement still not made)
i = 3 ;
on the next statement
printf("%d",i); the post decrement is done here on i and i value is 3 so 3 -1 = 2
The output is 2
pre-decrement or preincrement are made on the same statements whereas post increments and post decrements are made on the next statement . I remember i read it somewhere
This is i Have explained to make you clear on pre and post operations
but mostly belive
ITS UNDEFINED BEHAVIOR when you try to do increment and decrements operations on the same variable which is to be assigned a value
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610429",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-4"
} |
Q: how display html body part content from web url protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.details);
Bundle bundle = this.getIntent().getExtras();
WebView detailsLink=(WebView)findViewById(R.id.web_view);
detailsLink.getSettings().setJavaScriptEnabled(true);
detailsLink.loadUrl(bundle.getString("keyLink"));
}
This displays the whole html page in android webview field, but I have to display body part in my web view. I tried query for this but it is not working.
String detailsLink1="<html><body><iframe src='keyLink' width='100%' height='100' scrolling='no'> </iframe></body></html>";
detailsLink.loadData(detailsLink1, "text/html", "utf-8");
This is not working.
A: Do it this way:
URL url = new URL("your url");
InputStream is = url.openStream();
byte[] b = new Byte[size of data you want to read];
String s = new String(b);
and now store or display this string where ever you want.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610431",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: My app was rejected becasue In App Purchase does not have binary I submitted an App with an In App Purchase. The app is free and In App Purchase unleashes some of the features already programmed by setting a flag in user defaults.
However, my app was just rejected because they said they need a binary update for In App Purchase. There is no binary for it, it is just a flag.
How can I resolve this.
Thanks
A: App store guys responded to my comments promptly and everything is fine now. My app is in the app store now.
Thanks for all the help I got from this site.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610433",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: UIText Field with backgroung image i have a UITextfield with background image(TextBox.png) in IBoutlet...every thing working fine but the problem is cursor blinking inside,cursor is not visible up to two characters,can any one help me to solve this
so i tried to solve this in the way that
i have added a image View with TextBox.png image and placed text field on the top of image view
but textfield going behind the image view (Place holder is not visible)...
can i add textfield as subView to imageView in IBOutlet,i know how to add programatically
Can any one help me to solve this problem
A: You can have a UIImageView containing the background UIImage and the UITextView as siblings, then in Interface Builder move the text view to overlap the image view (or add them both to the same parent view if doing it programmatically). You also have to make sure the text view is not opaque and give it a 0% opacity background (There is a predefined clearColor you can use).
It's a pretty cheap trick, but it's the only way to really give yourself full control over the appearance.
A: I wrote a UITextField subclass with custom background and padding in this answer: Indent the text in a UITextField There are no cursor issues.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610434",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: what php modules my website uses? I have to move fairly complex PHP website (which was not developed by me) to another server, but I'm quite sure it uses some non-default PHP modules. Is it possible to find out what those modules are without drilling through thousands of lines of code? I can get the whole list of PHP modules on current server ("php -m"), but I only need those used by my website.
Centos 5.3
PHP 5.3.8
A: An absolutely un-programmatic approach would be to deploy the website, open it, look what errors show up and install the according module until you can work with the page :)
A: Well, you have to see if the functions/classes/etc... are being called.
You can try to disable them, and then test some pages.
A: run an phpinfo(); from withing a file and you will see what run with your PHP
<?php
phpinfo();
?>
A: Im not to hot on linux yet, but phpinfo will give you all the info you should need, all the installed enabled and disabled modules.
<?php // Save this in any file.php and browse to it.
php_info();
?>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610438",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to achieve the lowest usage of server resources for this PHP/MySQL issue? I'm creating a system where users get paid to click advertisements and I need to keep track of the amount of advertisements a user has clicked for the last 7 days. To do this I figured 2 ways:
*
*For each advertisement clicked, there will be inserted an entry into the database table 'ads_clicked'. Each day the entries that are older than 7 days will be cleared (cronjob script).
*For each advertisement clicked, there will be inserted an entry into the database table 'ads_clicked'. However this time each log will only remain in the database table for 1 day. Each end of the day the ads clicked will be calculated for each user and saved in a field 'ck_1' ( in the table 'users' ) which holds the ads clicked yesterday. There'll also be ck_2 (= ads clicked 2 days ago), ck_3, etc., which will be moved each day ( ck_7 = ck_6, ck_6 = ck_5, etc. ).
Both ways are possible but the 2nd way requires UPDATE queries in the cronjob script that's ran daily and the 1st way does not. However using the 2nd way it will be easier to display the ads clicked over the last 7 days for each user as it's just stored inside fields (ck_1, ck_2,etc.) which are part of the user entry in the database, while using the 2nd way I'd need to calculate it ( counting the rows in 'ads_clicked' table for each day ) every time I want to display the ads clicked over the last 7 days.
Do notice that the website may get huge traffic and thus lots of entries made to the 'ads_clicked' table, so I need to be sure which way is most efficient.
Thanks in advance.
A: If you want to go with option 2 I would suggest you create a separate table for the user clicks, that way you won't lock access to the users table when you're doing heavy processing with the cron job.
Another thing: don't insert clicks right away. You can do this (if it's possible to you) by saving those clicks in a memory cache such as memcached and every ten minutes or so fetch those clicks (maybe even do some processing to minimize inserts) and insert that batch of clicks to the 'ads_clicked' table, only making one load spike instead of several continuous ones.
A: The only real way to know how each option is going to preform with your data on your hardware is to try it both ways and measure the results. (And if you do that, post an update here.)
I created a similar system a while back and went with something like option 1. It's the simplest and most straightforward way to do it. If you eventually determine that MySQL inserts just can't possibly cope with the level of data you're trying to insert, it should be pretty easy to replace this with a cache or a message queue or some other fancy new thing.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610439",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to include plugins to Eclipse install using a script? If you try to use Eclipse for too many purposes you'll end-up with what I call Eclipzilla.
In order to overcome this you may want to have several Eclipse installation and use the one that has the proper plugins installed.
Now the question is how can I add these plugins to an Eclipse install from inside a script, instead of the manual process?
A: The p2 director application enables you to install additional software to (or remove from) an Eclipse installation on the command line.
You can export a description of the software items (or a subset of them) in an Eclipse installation with File > Export... > Install > Install Software Items to File (available since Eclipse 3.7). The so exported XML document contains the ids of the corresponding installable units and the repositories that provide them, which you will both need as parameters for the p2 director application.
Note that there is also the counterpart File > Import > Install > Install Software Items from File, which can be used to recreate an Eclipse installation from an exported description of software items. Maybe this already fits your use case: to be able to recreate a particular Eclipse installation in a single step.
A: You can export and import repository lists in Eclipse Preferences under Install/Update>Available Software Sites.
You could use this to get part of what you want. Create export files by hand or script that contain the sites you want for a particular configuration. Then for a new installation, import one of those files. Next, in Install New Software, select --All Available Sites-- and see your tailored list and standard Eclipse sites below. Pick the ones you want.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610443",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: CherryPy Returning Status 301 on nsIXMLHttpRequest (but works fine for firefox HTTP request) I am developing a web API in using CherryPy. The intent is that it is accessed by JavaScript through nslXMLHttpRequest. When I access the API through Firefox (as though it were an ordinary-variety URL), the following appears in my logs:
!!!SUCCESS!!!
[my IP] - - [30/Sep/2011:08:30:19] "GET /myAPI/ HTTP/1.1" 200 11 "" "Mozilla/5.0 (Windows NT 6.1; rv:6.0.2) Gecko/20100101 Firefox/6.0.2"
That "!!!SUCCESS!!!" is printed at the start of the code that runs on the myAPI page. But when I access it through JavaScript, the following appears in my logs:
[my IP] - - [30/Sep/2011:08:32:19] "GET /myAPI?arg1=value1&arg2=value2 HTTP/1.1" 301 221 "[requesting page]" "Mozilla/5.0 (Windows NT 6.1; rv:6.0.2) Gecko/20100101 Firefox/6.0.2"
(those arguments are optional)
Notice that in the second case, !!!SUCCESS!!! was never printed (my code was never executed) and the status code was 301 - "moved permanently". Any idea what would cause CherryPy to do this?
A: Probably because /myAPI and /myAPI/ are not the same URI, so it's redirecting you from one to the other. You can fine-tune this behavior with http://docs.cherrypy.org/dev/refman/lib/cptools.html#cherrypy.lib.cptools.trailing_slash
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610444",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Reading an entire file into a hash in Perl I have some problems reading a file into a hash in Perl.
Chr1_supercontig_000000000 1 500
PILOT21_588_1_3_14602_59349_1
Chr1_supercontig_000000001 5 100
PILOT21_588_1_21_7318_90709_1
PILOT21_588_1_43_18803_144592_1
PILOT21_588_1_67_13829_193943_1
PILOT21_588_1_42_19678_132419_1
PILOT21_588_1_67_4757_125247_1
...
So I have this file above. My desired output is a hash with the "Chr1"-lines as key, and the "PILOT"-lines as values.
Chr1_supercontig_000000000 => PILOT21_588_1_3_14602_59349_1
Chr1_supercontig_000000001 => PILOT21_588_1_21_7318_90709_1, PILOT21_588_1_43_18803_144592_1,...
As far as I know, multiple values can be assigned to a key only by reference, is that correct?
I got stuck at this point and need help.
A: You are right, the hash values need to be references that point to arrays which contain the PILOT lines.
Here's a way to do it:
my %hash;
open FILE, "filename.txt" or die $!;
my $key;
while (my $line = <FILE>) {
chomp($line);
if ($line !~ /^\s/) {
($key) = $line =~ /^\S+/g;
$hash{$key} = [];
} else {
$line =~ s/^\s+//;
push @{ $hash{$key} }, $line;
}
}
close FILE;
A: You can read the file line-by-line keeping track of the current hash key:
open my $fh, '<', 'file' or die $!;
my (%hash, $current_key);
while (<$fh>) {
chomp;
$current_key = $1, next if /^(\S+)/;
s/^\s+//; # remove leading space
push @{ $hash{$current_key} }, $_;
}
A: How about:
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dump qw(dump);
my %hash;
my $key;
while(<DATA>) {
chomp;
if (/^(Chr1_supercontig_\d+)/) {
$key = $1;
$hash{$key} = ();
} else {
push @{$hash{$key}}, $_;
}
}
dump%hash;
__DATA__
Chr1_supercontig_000000000 1 500
PILOT21_588_1_3_14602_59349_1
Chr1_supercontig_000000001 5 100
PILOT21_588_1_21_7318_90709_1
PILOT21_588_1_43_18803_144592_1
PILOT21_588_1_67_13829_193943_1
PILOT21_588_1_42_19678_132419_1
PILOT21_588_1_67_4757_125247_1
output:
(
"Chr1_supercontig_000000001",
[
" PILOT21_588_1_21_7318_90709_1",
" PILOT21_588_1_43_18803_144592_1",
" PILOT21_588_1_67_13829_193943_1",
" PILOT21_588_1_42_19678_132419_1",
" PILOT21_588_1_67_4757_125247_1",
],
"Chr1_supercontig_000000000",
[" PILOT21_588_1_3_14602_59349_1"],
)
A: Many good answers already, so I'll add one that does not rely on regexes, but rather on that the key-lines contain three space/tab delimited entries, and the values only one.
It will automatically strip leading whitespace and newlines, and so is somewhat convenient.
use strict;
use warnings;
my %hash;
my $key;
while (<DATA>) {
my @row = split;
if (@row > 1) {
$key = shift @row;
} else {
push @{$hash{$key}}, shift @row;
}
}
use Data::Dumper;
print Dumper \%hash;
__DATA__
Chr1_supercontig_000000000 1 500
PILOT21_588_1_3_14602_59349_1
Chr1_supercontig_000000001 5 100
PILOT21_588_1_21_7318_90709_1
PILOT21_588_1_43_18803_144592_1
PILOT21_588_1_67_13829_193943_1
PILOT21_588_1_42_19678_132419_1
PILOT21_588_1_67_4757_125247_1
A: Here is another fairly short, clear version:
while (<>) {
if(/^Chr\S+/) {
$c=$&;
} else {
/\S+/;
push @{ $p{$c} }, $&;
}
}
And to print the results:
foreach my $pc ( sort keys %p ) {
print "$pc => ".join(", ", @{$p{$pc}})."\n";
}
This is a shorter print-results (but the first one seems more readable to me):
map { print "$_ => ".join(", ", @{$p{$_}})."\n" } sort keys %p;
One-liner from command line:
perl <1 -e 'while(<>){ if(/^Chr\S+/){ $c=$&; }else{ /\S+/; push(@{$p{$c}},$&);} } map { print "$_ => ".join(", ", @{$p{$_}})."\n" } sort keys %p;'
A: Try this ,
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
my ( $fh,$cur );
my $hash = ();
open $fh,'<' , 'file' or die "Can not open file\n";
while (<$fh> ) {
chomp;
if ( /^(Chr.+? ).+/ ) {
$cur = $1;
$hash->{$cur} = '';
}
else {
$hash->{$cur} = $hash->{$cur} .$_ . ',';
}
}
print Dumper $hash;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610445",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Issue Tracker for Building applications We currently have an existing issue tracker, which the service management team utilise for logging user reported issues.
What I would like to do is create a server based (probably web-ui) system that can query the issue tracker for bugs assigned to the dev team and if the Impacted file is ready to be build then the Build can be triggered from the Issue tracker such that checkout from the SVN repository,uploading the code on the build server and finally building it happens in an automated manner.How to start about it?
A: A similar approach works like that:
*
*Install a central build server (Hudson, Jenkins, Bamboo, ...).
*Configure a build job there that has a trigger to start the build when a commit is done by a developer.
*The build is then done, and as a result, all tickets that are named in the commit message are listed for the build.
*When a build is then taken to a test environment, you may look at the build result to see which tickets are resolved by the build.
We have that installed in numerous development environments, e.g. with the following software used:
*
*Trac with Subversion
*JIRA, Subversion, Hudson
*Polarion, build management in Polarion, Subversion
*...
You need a configuration management as one of the components to work.
A: look into SVN hook scripts. you're probably better off trying to do builds from a hook script than trying to do them from an integrated issue tracker.
you can write a post-commit hook script to:
look up the comment for the revision just committed.
parse the comment for a keyword (something like "build" or "fixed").
then based on the detection of this keword this script can then kick off an svn-update on your build machine, then your build script. psexec seems like a good (although insecure) way to run the svn update and build script from the SVN server on the build machine. this is how i have been thinking of implementing automatic builds for my own team, i just havnt gotten time to write the scripts yet though.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610446",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What is the importance of setting `IList` capacity? What is the importance of setting a lists capacity at creation?
For example, say I know for sure that my list will only contain n items throughout its lifetime.
A: Whenever a list needs to exceed its current capacity, reallocations of memory and moving around of stuff must happen, which takes time and effort.
If you know ahead of time exactly how large the list will be, you can avoid this.
A: You'll make a little speed because the list won't have to be grown. Growing a list is O(n) where n is the current number of elements, and the standard List<> grows by doubling its current size. Everything considered, adding an element to the end of a list is still on average an O(1) operation (this because in the end to insert n elements you'll have on average n inserts to the end (each one an O(1) operation) and n copy operations between old buffer and newer buffer (each one an O(1) operation), so each add is on overage O(1))
A: This will improve performance slightly, as the necessary memory will be allocated when you create the List, and the CLR won't have to increase the List size when you add more elements.
Note that even if you specify a List size, it will be increased anyway if you add more elements than expected.
A: Inside of a List<T>, there is a statically sized collection that holds your items. Once you reach the capacity of that collection, the List<T> re-sizing it which is a performance hit (may or may not be significant to you).
By setting the initial capacity, you are avoiding having to perform those re-sizing operations.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610449",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Unable to iterate over ManyToMany - how do I calculate the sum? My models look like this:
class Article(models.Model):
name = models.CharField(max_length=50)
description = models.TextField()
price = models.FloatField()
def __unicode__(self):
return "%s - %s" % (self.name, self.price)
class Order(models.Model):
client = models.ForeignKey(User)
articles = models.ManyToManyField(Article)
total = models.FloatField(editable=False, blank=True, default=0)
def __unicode__(self):
return "%s - %s" % (self.client.username, self.total)
def save(self):
for a in self.articles:
self.total += a.price
super(Order, self).save()
And I try to calculate the total price in save(). If I try to save an order via the admin, I get
'Order' instance needs to have a primary key value before a many-to-many relationship can be used
If I call
super(Order, self).save()
before calculating the sum, I get
'ManyRelatedManager' object is not iterable
.
I don't know to do... I thought about calculating total in the view, but I would like to store it in my database.
How to I iterate over all the articles in the Order-Model?
Thanks in advance :)
A: I'd replace your total field with a property:
class Order():
....
@property
def total(self):
return self.articles.aggregate(Sum('price'))['price__sum']
the reason is: when you add items to collection your object is not saved again, so it wouldn't update your counter. With this property you'll be sure to always have correct data.
A: If you really need to do this, you could save the instance first if it has no PK:
def save(self, *args, **kwargs):
if self.pk is None:
super(Order, self).save(*args, **kwargs)
for a in self.articles.all():
self.total += a.price
super(Order, self).save(*args, **kwargs)
A: Use aggregation. Replace
for a in self.articles:
self.total += a.price
with
from django.db.models import Sum
#..............
self.total = self.articles.aggregate(Sum('price'))['price__sum']
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7610457",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.