text
stringlengths
8
267k
meta
dict
Q: I want to store void pointers to functions along with the type of them I am trying to make a vector hold void pointers to functions, which will later be called secuentially. So, lets say that I have got three functions. int a(), void b();, bool c(); My vector is vector<void *> vec; And my function that stores pointers to functions. void registerFunction(void *func) { vec.push_back(func); } Now my problem is when trying to call all the functions stored, since they are all void pointers, I just cannot call the functions without knowing their type. So my question is... is there any way to store types of symbols so I can relate them to their respective pointers and then typecast when calling a void pointer to a function? Note: Functions won’t be always be of type, for example, void (*)(), I will want to add methods also, hence ie. void (someclass::)(). Is it asking for too much? Should it work? A: You cannot convert a function pointer to void*. It is not allowed. If all of the functions are callable with zero arguments and you don't care about the return type, you can use std::vector<std::function<void()>> (function can also be found in Boost and TR1 if your C++ Standard Library does not support it). Though, if I recall correctly, return-type conversion is not allowed in the C++11 std::function implementation, in which case you may need something like the following: template <typename T> struct ignore_result_impl { ignore_result_impl(T fp) : fp_(fp) { } void operator()() { fp_(); } T fp_; }; template <typename T> ignore_result_impl<T> ignore_result(T fp) { return ignore_result_impl<T>(fp); } int g() { return 42; } std::function<void()> f(ignore_result(g)); (In the Boost implementation I know you can use function<void()> directly, but I'm pretty sure that is no longer allowed in C++11. I could be wrong and I'd appreciate clarification in the comments, if someone does know.) A: As long as all the functions follow the same type signature, you can cast the void pointers back to that type. A better solution is to typedef the function type: typedef int(*fun_ptr)(); vector<fun_ptr> vec; Then you will not need the cast. A: void* can't safely be used as a generic pointer-to-function type (though you might be able to get away with it). But any function-to-pointer value can be converted to another pointer-to-function type and back again without loss of information. So you can use, for example, void (*)() (pointer to function returning void and taking no arguments) as a generic pointer-to-function type. As for storing the type, I'm not sure that's possible. If there are only a limited number of possibilities, you can use an enumeration type and a switch statement. But you'll probably be better off using a design based on inheritance.
{ "language": "en", "url": "https://stackoverflow.com/questions/7521863", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Does Lift prevent HTTP response splitting? When I manually add a header to a response in Lift with S.setHeader, do I have to check for newlines manually or is that done by the framework? This is needed to prevent http response splitting. A: You should test it. Tamper Data for Firefox allows you to modify http requests and view the response. Setup a call to S.setHeader that accepts a get variable header. Open tamper data within Firefox and it will log all requests. Visit a url like this: http://localhost/?header=1%0atest:+CRFL. If tamper data shows a response header with a new server element of test: CRLF then your platform is vulnerable to HTTP response splitting.
{ "language": "en", "url": "https://stackoverflow.com/questions/7521868", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: SAP adapter: disasembler problem "Unexpected end of stream while looking for:..." Use WCF-SAP binding in WCF-Custom adapter, ReceiveIDOCFormat is set to 'String', in the pipeline component, we wrap and call a flat file disassembler to disassemble the SAP request to XML and process it later. We also have a log compnent which will log the SAP raw message prior to disassembler (the string version) to database (streaming way using CForwardOnlyStream) Here is the problem, during the UAT testing with SAP, we find occasionally the flat file disassembler is complaining 'Unexpected end of stream while looking for:....', when we inspect the SAP message sent over the wire, we find the SAP request only contains the header (EDI_DC40), with emty content after that. What makes me worry is , when we go into SAP, resubmit the failed message using transaction WE19, disassembler has no problem parsing it. I am totally lost, can someone please sugguest how to troubleshoot this? Thanks a million!! A: I think probably I found the problem now, SAP guys added a field, what I used to do (which I think is right but it may be the flaw) is, I didn't regenerate the schema, instead, I just manually added the field in Visual Studio and set the field length based on IDOC description. I regenerated the IDOC using the WCF wizard, it seems it is not as same as added a field in visual studio, I just deployed this schema and hope it will address the problem, I'll post my findings later if it worked
{ "language": "en", "url": "https://stackoverflow.com/questions/7521874", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: when is C++ std::foreach useful Possible Duplicate: Should I use std::for_each? I've come from a predominantly C# background, and have used a fairly large number of languages aside from that with foreach loop capabilities. It seems to me that the need of a function object to provide the functionality to the foreach loop is very... long-winded? within C++. Other languages just use it as another for loop (but more efficient for the coder as opposed to less efficient). It is pretty rare that there is a feature in C++ that isn't made as it is for a good reason, so can someone provide me with a specific, real-world example where a for-each loop in C++ would be a better decision than another looping structure (like for, while)?
{ "language": "en", "url": "https://stackoverflow.com/questions/7521878", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: `.button()` space behaviour This is my code (http://jsfiddle.net/UXdLQ/3/): $('input').button(); One bizarre behaviour is when I hit the space bar, the background color changes to white, which is not consistent with the fact that typing letters does not change the background. How can I disable this behaviour? A: Quick & Dirty: (as there isn't an option for this) $('input').bind("keydown", function(event) { if ( event.keyCode == $.ui.keyCode.SPACE ) { event.stopImmediatePropagation(); } }); $('input').button();
{ "language": "en", "url": "https://stackoverflow.com/questions/7521885", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Printing named tuples In Python 2.7.1 I can create a named tuple: from collections import namedtuple Test = namedtuple('Test', ['this', 'that']) I can populate it: my_test = Test(this=1, that=2) And I can print it like this: print(my_test) Test(this=1, that=2) but why can't I print it like this? print("my_test = %r" % my_test) TypeError: not all arguments converted during string formatting Edit: I should have known to look at Printing tuple with string formatting in Python A: You can do this: >>> print("my_test = %r" % str(my_test)) my_test = 'Test(this=1, that=2)' A: It's unpacking it as 2 arguments. Compare with: print("dummy1 = %s, dummy2 = %s" % ("one","two")) In your case, try putting it in a tuple. print("my_test = %r" % (my_test,)) A: Since my_test is a tuple, it will look for a % format for each item in the tuple. To get around this wrap it in another tuple where the only element is my_test: print("my_test = %r" % (my_test,)) Don't forget the comma. A: The earlier answers are valid but here's an option if you don't care to print the name. It's a one-liner devised to pretty print only the contents of a named tuple of arbitrary length. Given a named tuple assigned to "named_tuple" the below yields a comma-delineated string of key=value pairs: ', '.join(['{0}={1}'.format(k, getattr(named_tuple, k)) for k in named_tuple._fields]) A: As now documented at 4.7.2. printf-style String Formatting, the % string formatting or interpolation operator is problematic: The [printf-style string formatting operations] exhibit a variety of quirks that lead to a number of common errors (such as failing to display tuples and dictionaries correctly). Using the newer formatted string literals or the str.format() interface helps avoid these errors So for example you can now do: from collections import namedtuple Test = namedtuple('Test', ['this', 'that']) my_test = Test(this=1, that=2) print("my_test = {0!r}".format(my_test))
{ "language": "en", "url": "https://stackoverflow.com/questions/7521887", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Why is there a thin vertical line in my table cell in IE9 only? Here is my test code: <!DOCTYPE html> <html> <head> <style type="text/css"> table { border-collapse: collapse; } td { background-color: gray; } td.first { -webkit-border-bottom-left-radius: 10px; -moz-border-radius-bottomleft: 10px; border-bottom-left-radius: 10px; width: 100px; } td.second { -webkit-border-bottom-right-radius: 10px; -moz-border-radius-bottomright: 10px; border-bottom-right-radius: 10px; width: 100px; } </style> </head> <body> <table> <tbody> <tr> <td>Column 1</td> <td>Column 2</td> <td>Column 3</td> <td>Column 4</td> </tr> <tr> <td class="first"></td> <td class="second" colspan="3">Column 2</td> </tr> </tbody> </table> </body> This only occurs in IE9. If I add some padding, remove the border radius in td.second, or add a cell and change the colspan, it disappears (for this sample anyway). I have another project where doing the same isn't feasible or just doesn't work. What is causing this to happen and is there some magical CSS I can use that can fix it for IE9 and not break and other browser? A: Played around with it a bit and I have to confirm thirtydot's conclusion that it's a display bug. If you take out the colspan or change the second row to: <tr> <td class="first">X</td> <td colspan="2">Column 2</td> <td class="second">&nbsp;</td> </tr> Then no more line. Probably having to something to do with the corner radius not rendering correctly, since it's a new feature for IE.
{ "language": "en", "url": "https://stackoverflow.com/questions/7521890", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: java - Array brackets after variable name Possible Duplicate: Difference between int[] array and int array[] I saw this example in a java tutorial: private int puzzle[]; This is different to the 'normal' declaration type I'm familiar with: private int[] puzzle; eclipse accepts both. Is there a difference between these 2 notations?
{ "language": "en", "url": "https://stackoverflow.com/questions/7521891", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Notifying other page database item has changed, best practice for MVVM WP7.5? First of all, I'm using MVVM for this and I would like to continue using it and ofc using the best practices as well. I have a Mainpage which will display a list of items. On another page you can add such items. The items will be saved in a database which came with the Mango update. When a item is added I want to navigate back to the mainpage and I want the list to be updated automatically. Is this possible and what's the best way? I'm thinking of following scenario's: * *Use the Refresh query string when you navigate. Check in the back end of your main if there is a refresh. Then send a message 2 the ViewModel that he needs to update his list. I have tried this and this works. But this doesn't really sound the right way for MVVM. *Can't this be done with the NotifyPropertyChanged event that you can raise on your Database Model ? Or doesn't it work over different pages? *Reload the whole ViewModel for the main page somehow. Any other idea's? A: Use MVVM-Lights Messenger. The MainViewMode can subscribe to a Refresh event and the ViewModel where the items are added can publish a Refresh event. This is a good example of how messenger can be used.
{ "language": "en", "url": "https://stackoverflow.com/questions/7521892", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to combine these tables? In sql server 2005, how do I get the result set in table3 below? table3 is created by combining table1 and table2 like this: table1.empid table1.ticket table2.identid And update against table1 joined to table2 doesn't work because empid isn't unique. If need to increment to the next table2.indentid if the ID is already being used by that employee. Also, table3 below isn't created yet. It's a generated set from table1 and table2. I'm using table3 as an example of what the generated set should look like. table1 empid ticketid indentid 1 7 20 1 9 4 2 9 21 table2 indentid empid 90 1 91 1 92 2 table3 empid ticketid table1_indentid table2_identid 1 7 20 90 1 9 4 91 2 9 21 92 A: The only connection between table1 and table2 is empid. The lines 1 and 2 of your table3 example have the same empid, so they should have the same table2_identid as well. Your example is not proper, or not possible to get with a query on the existing data. But maybe this is what you want: If you join the tables like so SELECT empid, ticketid, t1.indentid as table1_indentid, t2.identid as table2_identid FROM table1 AS t1 INNER JOIN table2 AS t2 ON t1.empid = t2.empid you will get table3 empid ticketid table1_indentid table2_identid 1 7 20 90 1 7 20 91 1 9 4 90 1 9 4 91 2 9 21 92 A: This is what you need: select t1.empid, t1.ticketid, t1.indentid as table1_indentid, t2.indentid as table2_identid from table1 t1 inner join table2 t2 on t1.empid = t2.empid You should however consider reviewing your data structure.
{ "language": "en", "url": "https://stackoverflow.com/questions/7521894", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Android: Always getting GET on the server eventhough POST was sent I am trying to send data using POST method from my android apps. However in the server it is always recognized as GET. I am using Rails apps as the web service. Here is the snippet of my Android code:   URI uri = new URI(hostName); HttpPost httpRequest = new HttpPost(uri);  httpRequest.addHeader("Accept", "application/json");  httpRequest.addHeader("Content-Type", "application/json");  List<NameValuePair> pairs = new ArrayList<NameValuePair>();  pairs.add(new BasicNameValuePair("key1", "value1"));  httpRequest.setEntity(new UrlEncodedFormEntity(pairs)); HttpClient httpClient = new DefaultHttpClient(); HttpResponse httpResponse = httpClient.execute(httpRequest); Have I done anything wrong? Thanks for your help. A: You're android code looks fine, make sure your log doesn't show a 301 redirect code for POST despite showing a 200 code for GET. Strangely, this can be the case depending on your host configuration. e.g. You might see something like this : 123.156.189.123 - - [21/Oct/2011:09:03:34 -0700] "POST /server_script.php HTTP/1.1" 301 532 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.202 Safari/535.1" 123.156.189.123 - - [21/Oct/2011:09:03:34 -0700] "GET /server_script.php HTTP/1.1" 200 250 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.202 Safari/535.1" Here the GET was not redirected (code 200), but the POST was (code 301). If this is happening then you need to override your redirect settings using a .htaccess or other configuration options. A: Were you being redirected? I suspect that if you try to POST to domain A that redirects you to domain B, your request will be turned in to a GET request. I had the same problem until I decided to use the server's IP address in the POST request directly, instead of using a alphabet name that redirects to the IP.
{ "language": "en", "url": "https://stackoverflow.com/questions/7521895", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Inconsistent Behaviour Between 2 Players of Game I've been making a game for an English presentation (I know right?) and I've been having a few weird problems recently. At this stage, there are two squares for the players that can fire bullets. When the bullets hit the side of the screen or the middle border, they should disappear and possibly be reused later. The problem is, first of all, when either player shoots up or down, the bullets disappear into the top/bottom/middle of the screen like they're supposed to. If player 2 shoots a few to the side, as soon as one hits, they seem to all disappear (only player 2's bullets) and I have to wait a few seconds before it starts shooting again. The main problem though, is that even when I use the exact same code modified for player 1 instead of player 2, when player 1's first shot to hit the side of the screen gets there, it segfaults the program. The REALLY odd thing is that at one point, this happened, and without changing anything, I ran it again and it all worked perfectly fine. It might have to do with the order of bullets between player 1 and 2, or even where I shoot first. I've tried recreating it, but no results yet. Just a note before you try to compile the code, I used a wrapper I made to make the window with ease. I noted down what goes on behind the scenes with /// comments though, so adding that info into whatever method you use to make your windows will work just as well. Problem areas are listed near the bottom: ///Works best on 1280x1024 resolution ///1 vs 1 splitscreen game that involves flying around and shooting things ///angles start at 0 facing upwards and increase clockwise #include <window.h> //incomplete wrapper, but works perfectly for quick, easy window creation #define _USE_MATH_DEFINES //for M_PI #include <cmath> //for M_PI #include <iostream> //used for debugging using std::cout; //output struct Actions //actions a player can take { bool up; //if player is moving in these 4 directions, they will be true bool left; bool down; bool right; bool shoot; //if player is shooting, this will be true }; struct Player //a player { Player() {}; void fire(); //fire a bullet void checkActions (HWND); //check what actions player is taking double x; //position (centre of square) double y; double angle; //angle (might add diagonals so...) int pnum; //player number (0 or 1) COLORREF colour; //player's colour Actions action; //player's actions }; struct Bullet //a bullet { double x; //position (centre of square) double y; Player owner; //owner of bullet int index; //bullet's index in array double angle; //bullet's angle }; Player *p = new Player[2]; //2 players Bullet **bullet; //2d array of bullets int bcount[2] = {0}; //number of bullets for each player int btime [2] = {0}; //timer for bullets const double PLSIZE = 10; //player size = 20x20 square (10 from centre outwards) const double BSIZE = 2; //bullet size = 4x4 square const double SPEED = 1; //player's moving speed is 1 const int BDELAY = 100; //delay between bullets is 100ms LRESULT CALLBACK WndProc (HWND, UINT, WPARAM, LPARAM); //window procedure void OnPaint (HDC, HWND); //painting function void moveBullets (HWND); //calculates bullet positions void deleteBullet (int, int); //"deletes" a bullet int main() //main function { //hide(console()); //hides console window (currently showing for debugging) bullet = new Bullet*[2]; //create bullet array of 1000/player (I'll size down the 1000 later) bullet[0] = new Bullet[1000]; bullet[1] = new Bullet[1000]; p[0].x = 630; //player 1's position p[0].y = 250; p[0].colour = RGB(255,0,0); //player 1 is red p[0].pnum = 0; //player 1's number is 0 p[0].angle = 0; //face upwards p[0].action = {0}; //player 1 is doing nothing p[1].x = 630; //player 2's position p[1].y = 750; p[1].colour = RGB(0,0,255); //player 2 is blue p[1].pnum = 1; //player 2's number is 1 p[1].angle = 0; //face upwards p[1].action = {0}; //player 2 is doing nothing Window window; //create window object (part of wrapper, sets default values for class and window) ///background = (HBRUSH)COLOR_WINDOW ///class name = "Default Wrapper Class" ///hInstance = GetModuleHandle (NULL) ///all others are standard default or 0 window.createClass(WndProc); //create class using earlier-mentioned window procedure window.setStyle(WS_OVERLAPPEDWINDOW | WS_MAXIMIZE); //set window style to overlapped and maximized window.setTitle (L"Word Blaster"); //set window title to "Word Blaster" (it's an English project, shush) ///x/y/width/height = CW_USEDEFAULT ///class name = other class name ///hInstance = GetModuleHandle (NULL) ///all others are standard default or 0 HWND hwnd = window.createWindow(); //create window MSG msg; //message loop while(GetMessage(&msg,0,0,0) > 0) { TranslateMessage(&msg); DispatchMessage(&msg); } return msg.wParam; } LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) //window proc { HDC hdc; //hdc for painting PAINTSTRUCT ps; //paintstruct for painting bool ret = false; //return value (you'll see later) switch(msg) { case WM_CREATE: //currently not in use break; case WM_KEYDOWN: //check for pressed keys switch (wParam) //keycode { case 0x57: //'w' p[0].action.up = true; //player 1 wants to move up (couldn't just change position here or no diagonal movement) break; case 0x41: //'a', left p[0].action.left = true; break; case 0x53: //'s', down p[0].action.down = true; break; case 0x44: //'d', right p[0].action.right = true; break; case 0x20: // space, shoot p[0].action.shoot = true; break; case VK_UP: //up arrow, player 2 up p[1].action.up = true; break; case VK_LEFT: //left arrow p[1].action.left = true; break; case VK_DOWN: //down arrow p[1].action.down = true; break; case VK_RIGHT: //right arrow p[1].action.right = true; break; case VK_RETURN: //either enter key, p2 shoot p[1].action.shoot = true; break; } break; case WM_KEYUP: //check for unpressed keys switch (wParam) { case 0x57: //'w', player 1 should stop moving up p[0].action.up = false; break; case 0x41: //all same order as above p[0].action.left = false; break; case 0x53: p[0].action.down = false; break; case 0x44: p[0].action.right = false; break; case 0x20: // space p[0].action.shoot = false; break; case VK_UP: p[1].action.up = false; break; case VK_LEFT: p[1].action.left = false; break; case VK_DOWN: p[1].action.down = false; break; case VK_RIGHT: p[1].action.right = false; break; case VK_RETURN: p[1].action.shoot = false; break; } break; case WM_PAINT: //draw on screen hdc = BeginPaint (hwnd, &ps); //prepare window for drawing OnPaint (hdc,hwnd); //draw EndPaint (hwnd, &ps); //finish drawing break; case WM_CLOSE: //if ready to close show(console()); //show console window in case it doesn't close end(); //close console window (PostMessage (GetConsoleWindow(),WM_CLOSE,0,0)) DestroyWindow(hwnd); //close main window break; case WM_DESTROY: //window is closing PostQuitMessage(0); //post WM_QUIT to end (probably won't get here since console closes earlier) break; case WM_ERASEBKGND: //if background is going to be erased, don't let it (causes flicker) ret = true; //hold that thought for a bit break; } p[0].checkActions(hwnd); //check player 1's actions p[1].checkActions(hwnd); //check player 2's actions moveBullets (hwnd); //move any bullets InvalidateRect (hwnd,NULL,true); //update window Sleep (1); //delay a bit if (!ret) return DefWindowProc(hwnd, msg, wParam, lParam); //if WM_ERASEBKGND wasn't called, take default action } void Player::fire() //fire a bullet { bullet [pnum][bcount[pnum]].x = x; //bullet starts in player's centre bullet [pnum][bcount[pnum]].y = y; bullet [pnum][bcount[pnum]].owner = *this; //owner of bullet is the object calling this function bullet [pnum][bcount[pnum]].index = bcount[pnum]; //index of bullet is the number of bullets for player bullet [pnum][bcount[pnum]].angle = angle; //angle of bullet is player's angle while ( (bullet[pnum][bcount[pnum]].x - BSIZE < x + PLSIZE && bullet[pnum][bcount[pnum]].x - BSIZE > x - PLSIZE //left side of bullet inside player OR || bullet[pnum][bcount[pnum]].x + BSIZE < x + PLSIZE && bullet[pnum][bcount[pnum]].x + BSIZE > x - PLSIZE) //right side in player --- AND --- && (bullet[pnum][bcount[pnum]].y - BSIZE < y + PLSIZE && bullet[pnum][bcount[pnum]].y - BSIZE > y - PLSIZE //top in player OR || bullet[pnum][bcount[pnum]].y + BSIZE < y + PLSIZE && bullet[pnum][bcount[pnum]].y + BSIZE > y - PLSIZE) //bottom in player ) { bullet[pnum][bcount[pnum]].x += sin (bullet[pnum][bcount[pnum]].angle * M_PI / 180); //start moving bullet until it's out bullet[pnum][bcount[pnum]].y -= cos (bullet[pnum][bcount[pnum]].angle * M_PI / 180); } btime [pnum] = GetTickCount(); //set up bullet delay for that player ++bcount[pnum]; //increase number of bullets for that player } void Player::checkActions (HWND hwnd) //check player's actions { RECT r; GetClientRect (hwnd, &r); //get canvas space if (action.up) //if moving up { y -= SPEED; //change y position angle = 0; //change angle if (pnum == 0) //if player 1 { if (y - PLSIZE < 1) y = PLSIZE + 1; //check top of screen boundary } else //if player 2 { if (y - PLSIZE < r.bottom / 2 + 5) y = r.bottom / 2 + 5 + PLSIZE; //check middle boundary } } if (action.left) //if moving left { x -= SPEED; //change x position angle = 270; //change angle if (x - PLSIZE < 1) x = PLSIZE + 1; //check left of screen boundary } if (action.down) //down is opposite of up { y += SPEED; angle = 180; if (pnum == 0) { if (y + PLSIZE > r.bottom / 2 - 5) y = r.bottom / 2 - 5 - PLSIZE; } else { if (y + PLSIZE > r.bottom) y = r.bottom - PLSIZE; } } if (action.right) //right is opposite of left { x += SPEED; angle = 90; if (x + PLSIZE > r.right) x = r.right - PLSIZE; } if (action.shoot && GetTickCount() - btime [pnum] > BDELAY) fire(); //if player wants to shoot and enough time has passed, fire bullet } void OnPaint (HDC hdc, HWND hwnd) //draw stuff { RECT r; GetClientRect (hwnd, &r); //get canvas area HDC buffer = CreateCompatibleDC (hdc); //create buffer DC HBITMAP bitmap = CreateCompatibleBitmap (hdc,r.right,r.bottom); //create buffer bitmap HBITMAP oldBM = (HBITMAP)SelectObject (buffer, bitmap); //create another bitmap HBRUSH player1brush = CreateSolidBrush(p[0].colour); //player 1's brush HBRUSH player2brush = CreateSolidBrush(p[1].colour); //player 2's brush HBRUSH blackBrush = CreateSolidBrush (RGB(0,0,0)); //black brush HPEN /*player1*/pen = CreatePen (PS_NULL,1,RGB(255,0,0)); //don't need pen BitBlt(buffer,0,0,r.right,r.bottom,NULL,0,0,WHITENESS); //erase bitmap background SelectObject(buffer,pen); //select pen (since I need one to do anything) SelectObject (buffer, blackBrush); //select black brush Rectangle (buffer, 0, r.bottom / 2 - 5, r.right, r.bottom / 2 + 5); //draw middle line // MoveTo () //these comments are because I was about to change the graphics to ships SelectObject (buffer,player1brush); //select player 1's brush Rectangle (buffer,p[0].x-PLSIZE,p[0].y-PLSIZE,p[0].x+PLSIZE,p[0].y+PLSIZE); //draw player 1 SelectObject (buffer,player2brush); //do the same for p2 Rectangle (buffer,p[1].x-PLSIZE,p[1].y-PLSIZE,p[1].x+PLSIZE,p[1].y+PLSIZE); if (bcount[0] > 0) //if p1 has a bullet { SelectObject (buffer, blackBrush); //select black brush for (int i = 0; i < bcount[0]; ++i) //draw bullet(s) { Ellipse (buffer, bullet [0][i].x - BSIZE, bullet [0][i].y - BSIZE, bullet [0][i].x + BSIZE, bullet [0][i].y + BSIZE); } } if (bcount[1] > 0) //same goes for p2 { SelectObject (buffer, blackBrush); for (int i = 0; i < bcount[1]; ++i) { Ellipse (buffer, bullet [1][i].x - BSIZE, bullet [1][i].y - BSIZE, bullet [1][i].x + BSIZE, bullet [1][i].y + BSIZE); } } BitBlt(hdc, 0,0, r.right , r.bottom, buffer, 0,0, SRCCOPY); //copy buffer bitmap to window DeleteObject (player1brush); //delete stuff DeleteObject (player2brush); DeleteObject (pen); SelectObject (buffer, oldBM); DeleteObject (bitmap); DeleteDC(buffer); } void moveBullets (HWND hwnd) //move the bullets ***PROBLEM AREA*** { RECT r; GetClientRect (hwnd, &r); //get canvas area if (bcount[0] > 0) //if p1 has bullet(s) { for (int i = 0; i < bcount[0]; ++i) //go through p1's bullets { ///DOESN'T WORK bullet [0][i].x += sin (bullet [0][i].angle * M_PI / 180); //move the bullet horizontally if (bullet [0][i].x - BSIZE < 1 || bullet [0][i].x + BSIZE > r.right) //if out of bounds { deleteBullet (0, bullet [0][i].index); //delete the bullet --i; //if bullet [2] was deleted, bullet [2] will now be the old bullet [3] so recheck this one next time } ///WORKS PERFECTLY bullet [0][i].y -= cos (bullet [0][i].angle * M_PI / 180); //do same for y, including middle border if (bullet [0][i].y - BSIZE < 1 || bullet [0][i].y + BSIZE > r.bottom / 2 - 5) { deleteBullet (0, bullet [0][i].index); --i; } } } if (bcount[1] > 0) //exact same thing (I checked a LOT) for p2 { for (int i = 0; i < bcount[1]; ++i) { ///WORKS PERFECTLY (at least in the p1 sense, there is a slight problem) bullet [1][i].x += sin (bullet [1][i].angle * M_PI / 180); if (bullet [1][i].x - BSIZE < 1 || bullet [1][i].x + BSIZE > r.right) { deleteBullet (1, bullet [1][i].index); --i; } ///WORKS PERFECTLY bullet [1][i].y -= cos (bullet [1][i].angle * M_PI / 180); if (bullet [1][i].y - BSIZE < r.bottom / 2 + 5 || bullet [1][i].y + BSIZE > r.bottom) { deleteBullet (1, bullet [1][i].index); --i; } } } } void deleteBullet (int player, int index) //delete bullet ***PROBLEM AREA*** { if (index != bcount [player] - 1) //if it isn't the last bullet { for (int j = index; j < bcount[player] - 1; ++j) //go from here to the end of the current bullets - 1 { bullet [player][j] = bullet [player][j+1]; //copy the next bullet into this spot --bullet [player][j].index; //change the index of the bullet since it was moved back one } } --bcount [player]; //lessen the bullet count, this is all that's needed if it's the last bullet } Any help with said problems or with something else you notice would be greatly appreciated. EDIT: one side thing I forgot to ask was if there was a better way to continuously do things like move bullets for example than to put all that outside of the switch in the window procedure and the DefWindowProc after it. A: It looks like deleteBullet may get called twice on the same i inside the loop for (i=0...) in moveBullets. I think this could happen if the bullet is moving diagonally. I'm not sure it's the cause of the trouble, though. First English question I've seen on stackoverflow!
{ "language": "en", "url": "https://stackoverflow.com/questions/7521907", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to connect to another DB with an already existing EF (4.1) DbContext? I'm pretty new to EF and use to old school SqlConnection.... Question: I have an existing mvc3/EF database context object that already hits a local sql server 2008 instance. I want to add a new connection string in the web config and have the existing DBContext connect to a remote database to run a stored proc. How can I do this? A: If by existing context you mean the same context instance than it is not possible: one context instance = one connection string. If you need to connect to two databases you need two context instances and pass connection string to them. Even in such case it can have many restrictions depending on your EF usage. Using the same context type for databases with different schema (different tables) doesn't always work as expected. When using completely different databases the best way is to have two different context types and instance of each of them. But if you only want to execute stored procedure the simplest way is simply use ADO.NET SqlCommand and SqlConnection directly. A: One of the ObjectContext constructors takes a connection string as a parameter. That should help.
{ "language": "en", "url": "https://stackoverflow.com/questions/7521910", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Deploying using enterprise certificate has UI discrepancy Deploying an iOS application using an Enterprise certificate has UI elements missing, and/or attribute differences compared to deploying with a regular development certificate. Would anyone happen to know why this occurs? I have confirmed some images are not being copied and bundled with the build. A: * *For any missing images, check the case of your image names. *Do a full rebuild of your app (ie Build->Clean). *Do a fuller rebuild - delete the "build" and simulator folders *Make sure all of your NIBs and images are included in your enterprise target *Try an Ad Hoc build XCode itself can be a bit flaky. I've noticed some things fixed in 4.1 that are broken in 4.0.2, although the latest beta versions introduce their own bugs. That aside, blowing away the build folder forces the compiler to start over - ie, it forces the compiler to be consistent in ways that the IDE isn't written to handle. Just because a file is included in the Project Navigator doesn't mean that it will be included in your project. Select the file and look in the "Target Membership" section of the File Inspector tab within the Utilities view (the right-side pane of XCode). Some attributes don't work in IB. IB can be buggy. Plus there's some differences between the simulator and a device; testing a debug and ad hoc build on a device might help you uncover the issue. I've sometimes had to blow away a distribution build and start over from scratch due to some weird behavior, like you're describing. An Ad Hoc build is a slightly different type of distribution, so creating a new distribution might somehow bypass whatever weird attribute got set for your Enterprise configuration. A: If you build to Archive or do Ad Hoc to Archive, make sure that you set the Skip Install property to YES for Release builds, if you're using static linked libraries. Without this, any place you're using static linked libraries (i.e. #defines) could potentially be ignored. This documentation explains that part of the process: http://developer.apple.com/library/mac/#documentation/ToolsLanguages/Conceptual/Xcode4UserGuide/DistApps/DistApps.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7521911", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Workaround for logging objects to console in Chrome If you execute this code: var foo = {bar: 'baz'}; window.console.log(foo); foo.bar = 'bla'; The console shows this after expanding the object: (when logging objects and arrays, it's not the run-time value that's recorded) This bug was documented over a year ago: http://code.google.com/p/chromium/issues/detail?id=50316 Is there a workaround for logging objects in Chrome? A: I just use JSON.stringify when i need it. Don't know if it will do it for you, but it is easy and effective for debugging purposes. This is no good for objects with function references in it tho, so if you need that i would consider using either a deep copy of the object (you can use jQuery's excellent extend method) or roll you own logging function that will loop recursively over the object and print it out. A: You could use a dedicated logging library such as my own log4javascript.
{ "language": "en", "url": "https://stackoverflow.com/questions/7521916", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Sending name array in PHP Mail I'm using PHP's Mail function to send emails to individuals. I wanted an easy way to customize the greeting name in the email, so i created a form where there is a comma separated list of emails and a comma separated list of names, and they get posted and mailed via PHP. However, every time I send it, the name spits out the entire array of names, and not the ONE value I specify. I've been working on this for an hour now and cannot for the life of me see where the problem is.. its such simple code! Here is the code let me know if you see any glaring errors. $to_emails = $_POST['to_emails']; $to_names = $_POST['to_names']; $from_email = $_POST['from_email']; $message = $_POST['message']; $subject = $_POST['subject']; $explode_emails = str_replace(" ", "", explode(",",$to_emails)); $explode_names = explode(",",$to_names); $email_array = array(); $i=0; foreach($explode_names as $e) { $name = $e; $to = $explode_emails[$i]; $subject = $subject; $message = $name.",\r\n".$message; $headers = 'From: '.$from_email . "\r\n" . 'Reply-To: '.$from_email . "\r\n" . 'X-Mailer: PHP/' . phpversion(); mail($to, $subject, $message, $headers); echo "<font color='#FF0000'>".$i." Emailed: ".$name." : ".$to."</font><br />"; $i++; } <form method="post"> To Emails (comma separated) <input type="text" name="to_emails" value=""> <br /><br /> To Names (comma separated) <input type="text" name="to_names" value=""> <br /><br /> From <input type="text" name="from_email" value="trgentes@gmail.com"> <br /><br /> Subject <input type="text" name="subject" value=""> <br /><br /> Message <textarea name="message" rows="5" id="message"></textarea> <br /><br /> <input type="submit" /> </form> A: Here's what I came up with. I'm not sure if this exactly answers what you want, but it would send email to all the people specified: $to_emails = $_POST['to_emails']; $to_names = $_POST['to_names']; $from_email = $_POST['from_email']; $message = $_POST['message']; $subject = $_POST['subject']; $explode_emails = array_map('trim', explode(",", $to_emails)); $explode_names = array_map('trim', explode(",",$to_names)); $recipients = array_combine($explode_emails, $explode_names); $i=0; foreach($recipients as $email => $name) { $headers = 'From: ' . $from_email; $headers .= "\r\nReply-To: " . $from_email; $headers .= "\r\nX-Mailer: PHP/" . phpversion(); $finalMessage = $name . ",\r\n" . $message; mail($email, $subject, $finalMessage, $headers); echo "<font color='#FF0000'>" . $i . " Emailed: " . $name . " : " . $email . "</font><br />"; $i++; } Here's a quick rundown of the changes I made: * *str_replace() wasn't really needed. trim() is a more efficient function to trim leading or trailing whitespace. *I merged the email addresses and their corresponding names into an associative array called $recipients. This is easier to keep track of than referencing them by a numeric key, and actually associates the data to each other. This also makes looping over them easier to read. *I simplified how headers are created. It's easier to add the carriage return \r\n at the start of the string, making it easier to read, and less likely to forget one, or leave an extra return on the end. While the above code will work, I'll also take this opportunity to also warn you of a vulnerability present in your current code: Email Header Injection. If an attacker submits content to your form containing the "\r\n" character, they can inject their own headers. Meaning, they could end up sending this email to more people than you want it to go to, or they may inject their own custom body message. This example should be a good example for you on how to prevent this kind of attack, as its code example highly resembles yours. You should NEVER trust input sent via $_POST. You should validate the submitted data is in the correct format you expect and does not contain any malicious characters.
{ "language": "en", "url": "https://stackoverflow.com/questions/7521918", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to open an HTML JavaScript page in a wx.Python or other python gui window? Is there any way to open a browser based editor (such as CKEdit, tinymce, or any other HTML + JavaScript editor) in a Python window (perhaps wx.Python) rather than in a browser? Thank you in advance. A: I suggest you try using Webkit python bindings. You can load an arbitrary Webview and put it anywhere as a GTK widget: http://code.google.com/p/pywebkitgtk/ I'm not sure about WX. One complexity you will find is how to get the values from JS into Python. Here's an article describing a trick to call the sandboxed JS from Python: http://www.aclevername.com/articles/python-webgui/ Good luck!
{ "language": "en", "url": "https://stackoverflow.com/questions/7521925", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: creating a class that pops up an advertisement image I have a tab bar controller and some nav controllers containing view controllers. In those view controllers I want to be able to have a timed banner that will animate up from the bottom of the view. I started making a subclass of UIViewController with the images, but when I add it to my viewControlers it renders anything beneath it not clickable. What is the best way of achieving this ad pop up and have it be reusable in all my viewControllers? A: Make sure the main view of this ad popup is not of zero width or height - banners from many ad networks will actually be displayed if you add them to such a view, but won't be clickable. Also make sure the ad view is in front (bringSubviewToFront:) and, if you have a tab bar, try adding it to the main app's window, rather then to the current view. Tab bar can play tricks with Action Sheets (basically some buttons will be unclickable) which are solved by adding the Action Sheet to the main window. This may help with your popup ad views, too.
{ "language": "en", "url": "https://stackoverflow.com/questions/7521938", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Attach function (not event) to dynamically created object To attach a date picker to an input element, I'm using a date-picker plugin like so: $('.foo').simpleDatePicker(); How would I attach this function to dynamically created $('.foo')s, so that if I append another $('.foo') element to the page, the simpleDatePicker function is already attached? I would prefer to do it on document.ready instead of every time it is appended. Neither 'live()' nor 'bind()' seemed appropriate. A: you can use .live for this using a late-binding technique. $(".foo:not(.live)").live('click',function(){ $(this).addClass('live').datepicker().click(); return false; }); A: You can overload the jQuery append method and build a rule into the overloaded method that applies the .simpleDatePicker() to all .foo elements. It's not really a solution i will recommend however, since the overhead of every append call seems a much greater cost to me than the gain. But if you are really looking for and need the convenience, then that is probably the only solution.
{ "language": "en", "url": "https://stackoverflow.com/questions/7521940", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to export data from Chrome developer tool? Network analysis by Chrome when page loads I would like to export this data to Microsoft Excel so that I will have a list of similar data when loaded at different times. Loading a page one time doesn't really tell me much especially if I want to compare pages. A: from Chrome 76, you have Import/Export buttons. A: I came across the same problem, and found that easier way is to undock the developer tool's video to a separate window! (Using the right hand top corner toolbar button of developer tools window) and in the new window , simply say select all and copy and paste to excel!! A: In Chrome, in the Developer Tools, under Network, in the Name column, right-click and select "Save as HAR with content". Then open a new tab, go to https://toolbox.googleapps.com/apps/har_analyzer/ and open the saved HAR file. A: Note that &Lt;Copy all as HAR&Gt; does not contain response body. You can get response body via &Lt;Save as HAR with Content&Gt;, but it breaks if you have any more than a trivial amount of logs (I tried once with only 8k requests and it doesn't work.) To solve this, you can script an output yourself using _request.contentData(). When there's too many logs, even _request.contentData() and &Lt;Copy response&Gt; would fail, hopefully they would fix this problem. Until then, inspecting any more than a trivial amount of network logs cannot be properly done with Chrome Network Inspector and its best to use another tool. A: You can use fiddler web debugger to import the HAR and then it is very easy from their on... Ctrl+A (select all) then Ctrl+c (copy summary) then paste in excel and have fun A: I don't see an export or save as option. I filtered out all the unwanted requests using -.css -.js -.woff then right clicked on one of the requests then Copy > Copy all as HAR Then pasted the content into a text editor and saved it. A: I was trying to copy the size data measured from Chrome Network and stumbled on this post. I just found an easier way to "export" the data out to excel which is to copy the table and paste to excel. The trick is click Control + A (select all) and once the entire table will be highlighted, paste it to Microsoft Excel. The only issue is if there are too many fields, not all rows are copied and you might have to copy and paste several times. UPDATED: I found that copying the data only works when I turn off the filter options (the funnel-looking button above the table). – bendur A: Right-click and export as HAR, then view it using Jan Odvarko's HAR Viewer This helps in visualising the already captured HAR logs. A: if you right click on any of the rows you can export the item or the entire data set as HAR which appears to be a JSON format. It shouldn't be terribly difficult to script up something to transform that to a csv if you really need it in excel, but if you're already scripting you might as well just use the script to ask your questions of the data. If anyone knows how to drive the "load page, export data" part of the process from the command line I'd be quite interested in hearing how A: I had same issue for which I came here. With some trials, I figured out for copying multiple pages of chrome data as in the question I zoomed out till I got all the data in one page, that is, without scroll, with very small font size. Now copy and paste that in excel which copies all the records and in normal font. This is good for few pages of data I think. A: In more modern versions of Chrome you can just drag a .har file into the network tab of Chrome Dev Tools to load it. A: To get this in excel or csv format- right click the folder and select "copy response"- paste to excel and use text to columns. A: You can try use Haiphen, which is a chrome extension that allows you to analyze network traffic and what API calls a web application is making.
{ "language": "en", "url": "https://stackoverflow.com/questions/7521942", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "174" }
Q: How can I implement an opacity gradient across multiple selectable images in a grid/carousel? long time listener, first time caller. I have a matrix of icons that can be navigated horizontally in a carousel, and vertically as categories (which are rows of icons) that are detached/appended as the app cycles through the categories with up/down arrows. I want to make the lowest row of icons fade in opacity (I have a black background) from the native colors of the icons into blackness as you go from top to bottom, to indicate that there are subsequent rows beneath. The only way I have been able to determine how to do this is using background: -webkit-gradient, as indicated here: CSS3 Transparency + Gradient I apply this to a DIV which I overlay above my lowest row. Unfortunately, I lose clickability of the items behind the overlaid div. I have to use the overlay, however, because the property is a background property. Is there any other way I can implement a gradient opacity on a row of clickable icons that fades to black without sacrificing the clickability? I don't want an overlay that only covers the lower 25%/whatever either... I need an all-or-nothing solution to this. So far it's looking like "nothing" is my only option. Thank you very much in advance. A: Hmmm... two solutions come to mind. First, you could use the overlay, and track mouse events on that element. Then, with some math, you could probably figure out what the underlying element is use jQuery to trigger the click of that element (ie. $("#icon14").click(); ). The second option would be to draw out a companion transparent div with each icon you make in your matrix. Place it in exactly the same spot as the icon itself, but give it a css z-index that brings it above the overlay. This transparent div can now handle all the mouse events for you, and still live above the overlay. If you go down this road, I'd look into using the .data() function that lets you quickly tack on variables to any jQuery object. You can set this companion div to be a property of the normal icons in the matrix, with something like $("#icon14").data('clickDiv', $("#icon14_click")); (though you'd probably want to assign these in a loop or something =) Good luck!
{ "language": "en", "url": "https://stackoverflow.com/questions/7521948", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Bind to an ItemsControl's Templated Parent from inside the ItemsControl.ItemTemplate What is the proper way to bind to the Parent of an ItemsControl from within the ItemsControl.ItemTemplate? Non working attempt: <ControlTemplate TargetType="{x:Type local:ParentUserControl}"> <ItemsControl ItemsSource="{Binding MyCollectionViewSource.View, RelativeSource={RelativeSource TemplatedParent}}" IsTabStop="False" Focusable="False"> <ItemsControl.ItemTemplate> <DataTemplate> <local:ChildUserControl BoundProp1="{Binding Prop1}" BoundObjProp2="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type local:ParentUserControl}}}"/> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> </ControlTemplate> A: The binding looks fine to me, but you do not specify a Binding.Path, are you sure that you want to bind directly to the control and not a property? A: I had similar requirement and the following worked for me: <ItemsControl ItemsSource="{Binding Items}"> <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <WrapGrid Orientation="Horizontal" ItemWidth="{Binding ItemWidth}" ItemHeight="{Binding ItemHeight}"/> </ItemsPanelTemplate> </ItemsControl.ItemsPanel> <ItemsControl.ItemTemplate> <DataTemplate > <views:MyUserControl Width="{Binding DataContext.ItemWidth, ElementName=PageRoot}" Height="{Binding DataContext.ItemHeight, ElementName=PageRoot}"/> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> P.S. my app is in XAML for WinRT A: I have not found a solution to this problem. In the end I had to use work arounds which violated my desired separation of concerns, but functioned as expected. I believe this comes down to an issue in the wpf framework, hopefully 4.5 will fix it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7521949", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: excel data filter I have a csv file open in excel. I want to create two line graphs by choosing two rows. The problem is that these rows are in one row. How is this possible? One row contains many values from which a set of values needs to be plotted against set of values in the same row. The power of the two sets are identical. These two sets of values are fetched by filtering the row according to the values of other columns. I can create the plot of one set since I can apply the filter once. How can I add the second set of values onto the existing plot by doing an independent filter on the same column? I don't want to split the file into two different files. I am not that familiar with excel 2007. A: If your data is labeled, you probably want to use a pivot chart. Click the link for an overview
{ "language": "en", "url": "https://stackoverflow.com/questions/7521950", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Help with jquery-ui-autocomplete select menu height I am working with jQuery and the ui-autocomplete in a Rails project. Right now when the autocomplete renders, it will open a drop down and display suggestions, but the drop down menu goes below the footer. I saw this: http://www.filamentgroup.com/lab/jquery_ui_selectmenu_an_aria_accessible_plugin_for_styling_a_html_select/ and think that the 'pop-up with maxHeight set' would be perfect, but I can't find where to put the maxHeight option and if it takes just a number to show or what. I believe that I need to make the change to jquery-ui.js, also. Any pointers, help or links would help greatly! Thanks! P.S. Since my rep is low I can't post a picture with this but I can gladly email it or send it in another fashion to show anyone A: You can style the .ui-autocomplete class to do this, which will force a max height. .ui-autocomplete { max-height: 300px; overflow-y: auto; /* prevent horizontal scrollbar */ overflow-x: hidden; /* add padding to account for vertical scrollbar */ padding-right: 20px; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7521952", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to Sort a PHP Simple XML Tree by Date I'm navgating through an XML Tree like this: $notesXML = simplexml_load_string(XMLSTRING); foreach($notesXML as $thenote){ $noteAttr = $thenote->attributes(); echo $noteAttr['modified']; } As you can see there is an attribute called "modified" as a part of the XML tree, what I want to do for now is just print out the XML tree in ascending or descending order based on the modified date. BTW the date string is formatted like this: "Tuesday 6th of September 2011 03:49:14 PM" Thanks for any help A: You could build an array of the elements that you want to sort, then use one of the array sorting functions to re-order them. The snippet below uses array_multisort() to sort them by descending date order. DateTime::createFromFormat() is used to get the Unix timestamp from the date strings. $notes = array(); $dates = array(); foreach ($notesXML as $note) { $notes[] = $note; $dates[] = DateTime::createFromFormat('l jS \of F Y H:i:s A', $note['modified'])->getTimestamp(); } array_multisort($dates, SORT_DESC, $notes); // Loop over $notes however you like
{ "language": "en", "url": "https://stackoverflow.com/questions/7521955", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Setting up Associations with DataMapper & Sinatra Ok, so this is driving me crazy. I have read the Associations article and example and been trying to work this out for the las three days and I'm tired of this making me feel dumb, so... How does one set up associations with DataMapper? (I am using DM with Sinatra with SQLite3. Everything word fine for single tables with multiple values etc. It's when I start to try to associate them that I start getting errors.) Let's say I have an Orchard full of Apple Trees. Each Tree has many Apples. Each Apple has many Seeds. Therefore each tree has many Seeds through its Apples require 'sinatra' require 'datamapper' DataMapper::setup(:default, "sqlite3://#{Dir.pwd}/orchard.db") # Trees in the orchard. class Tree include DataMapper::Resource property :id, Serial has n, :apples has n, :seeds, :through => :apples end # Apples on a Tree. class Apple include DataMapper::Resource property :id, Serial belongs_to :tree belongs_to :seed end # Seeds in an Apple class Seed include DataMapper::Resource property :id, Serial has n, :apple has n, :tree, :through => apple end DataMapper.finalize.auto_upgrade! Is that correct? I keep getting various errors when I try to run this. Mostly along the lines of invalid association or cannot create column NULL with value NULL etc. What am I not understanding about this relationship? Further, Once I have a working model how do I go about getting information from it? If there are 3 trees: Tree.all.count => 3 If there are 2 apples: Apple.all =>[#<Apple @id=1>, #<Apple @id=2>] Ok cool. But how many Apples does Tree #2 have? How many Seeds does Tree #4 have? How many Apples in total? How many Seeds in total? Any help would be greatly appreciated. A: Your model seems a bit confused: Let's say I have an Orchard full of Apple Trees. Each Tree has many Apples. Each Apple has many Seeds. Therefore each tree has many Seeds through its Apples. So a tree has many apples, an apple belongs to a tree and has many seeds, and a seed belongs to an apple (and ultimately a single tree). We can almost (but not quite) take that language as it is and use it to create the associations. After a little translation to get the syntax right we get this: # Trees in the orchard. class Tree include DataMapper::Resource property :id, Serial has n, :apples # "a tree has many apples" has n, :seeds, :through => :apples end # Apples on a Tree. class Apple include DataMapper::Resource property :id, Serial belongs_to :tree # "an apple belongs to a tree..." has n, :seeds # "...and has many seeds" end # Seeds in an Apple class Seed include DataMapper::Resource property :id, Serial belongs_to :apple # "and a seed belongs to an apple" end In your code you have seeds having multiple apples and trees, which doesn't really make any sense. As for querying: But how many Apples does Tree #2 have? Assuming you mean the Tree with id == 2: tree_2 = Tree.get(2) apples_of_tree_2 = tree_2.apples # this gives an array of apples count_of_apples_of_tree_2 = tree_2.apples.count How many Seeds does Tree #4 have? The association we added to the Tree model has n, :seeds, :through => :apples means we have a seeds method available in Tree objects. Tree.get(4).seeds.count How many Apples in total? How many Seeds in total? Simply: Apple.count # note singular not plural (it's a class method on Apple) Seed.count Try loading this new model into irb (you might need to delete your orchard.db file when you change the model), and then playing around with some of the queries and creation methods, hopefully that'll give you a better idea of what's going on. Creating associations (See the section "Adding To Associations" on the Associations page.) To add an existing Apple to a Tree: a_tree.apples << an_apple Note that a Tree isn't associated with a single Apple but a collection (it has n Apples), so the method created is apples (i.e. it's pluralized), and there's no method apple which is why you're seeing the no method error. You can also create a new Apple associated with a Tree directly: a_tree.apples.new #created but not saved to database a_tree.apples.create #created and saved to database You can also create the association the other way round, from the Apple side: an_other_apple = Apple.new an_other_apple.tree = a_tree but you need to be careful doing it this way, as the new apple won't show up in the a_trees collection of Apples (a_tree.apples won't include an_other_apple). In order for it to appear you need to save the apple, and then call reload on the Tree: an_other_apple.save a_tree.reload You need to watch out with this, as you can end up with an Apple that appears to be in two Trees at the same time if you're not careful. A: I think it's a pluralization issue - don't you hate that? # Seeds in an Apple class Seed include DataMapper::Resource property :id, Serial has n, :apples # here has n, :tree, :through => :apples # and here end A: Without much knowledge of Datamapper and after skipping through the datamapper documentation, what about these answers? How many apples does tree 2 have: Tree.get(2).apples.count How many seed does tree 4 have: Tree.get(4).apples.inject(0) {|count, apple| count + apple.seeds.count}
{ "language": "en", "url": "https://stackoverflow.com/questions/7521958", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Disable textboxes on check changed I have a checkbox that disables 2 textboxes when checked. When it is unchecked it enables the checkboxes. Here is the JavaScript: function enableField() { prePracticeCodeTextBox = document.getElementById('prePracticeCodeTextBox'); preContactTextBox = document.getElementById('preContactTextBox'); checkTheBox = document.getElementById('CheckBox1'); if (checkTheBox.checked == true) { prePracticeCodeTextBox.disabled = false; preContactTextBox.disabled = false; } else { prePracticeCodeTextBox.disabled = true; preContactTextBox.disabled = true; } } Here is the HTML: <dl> <dt><label for="CheckBox1">PreAnalytical?</label></dt> <dd> <asp:CheckBox ID="CheckBox1" runat="server" CausesValidation="false" Visible="true" OnCheckChanged="enableField()"/></dd> </dl> <dl> <dt><label for="prePracticeCodeTextBox">Practice Code:</label></dt> <dd><asp:TextBox ID="prePracticeCodeTextBox" runat="server" Enabled="False" /></dd> </dl> <dl> <dt><label for="preContactTextBox">Contact:</label></dt> <dd><asp:TextBox ID="preContactTextBox" runat="server" Enabled="False" /></dd> </dl> The JavaScript function is not being called at all. What am I doing wrong? A: Try to use onclick instead. Use the following code to register it on your code behind : CheckBox1.Attributes.Add("onclick", "enableField();"); BTW, you won't be able to reach the elements as you do on asp.net web forms application with default settings. You need to get the ClientIDs of the elements which will be rendered : function enableField() { prePracticeCodeTextBox = document.getElementById('<%=prePracticeCodeTextBox.ClientID%>'); preContactTextBox = document.getElementById('<%=preContactTextBox.ClientID%>'); checkTheBox = document.getElementById('<%=CheckBox1.ClientID%>'); if (checkTheBox.checked == true) { prePracticeCodeTextBox.disabled = false; preContactTextBox.disabled = false; } else { prePracticeCodeTextBox.disabled = true; preContactTextBox.disabled = true; } } If you are developing on .net 4, read the below article : http://www.tugberkugurlu.com/archive/we-lovenet-4-clean-web-control-ids-with-clientidmode-property-to-static-and-predictable A: Change OnCheckChanged="enableField() to onclick="enableField();". You are using server controls. OnCheckChanged is an event for the asp.net CheckBox control. A: function enableField() { prePracticeCodeTextBox =.getElementById('<%=prePracticeCodeTextBox.ClientID%>'); preContactTextBox = document.getElementById('<%=preContactTextBox.ClientID%>'); checkTheBox = document.getElementById('<%=CheckBox1.ClientID%>'); if (checkTheBox.checked == true) { prePracticeCodeTextBox.disabled = false; preContactTextBox.disabled = false; } else { prePracticeCodeTextBox.disabled = true; preContactTextBox.disabled = true; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7521959", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What does this string represent as a Javascript object? Given the following data being fed into a javascript engine (like rhino): { hello=66.66, whygod=sun.org.mozilla.javascript.internal.NativeArray@7ba28183, sku=[2490748], world=sun.org.mozilla.javascript.internal.NativeArray@69e4fede, price=[] } 1) What kind of objects do the sku=[2490748] and price=[] represent in javascript? I would have thought that they were arrays but it doesn't seem like that because when I run the following logic as part of the javascript engine that processes this data, price does not get removed: function doStuff(row) { var price = row.get( 'price' ); if ( price == null || price == '' || price.length == 0) { row.remove( 'price' ); } return row; } 2) So then what is it, any ideas? A: If this is a function block delineated by the outside braces as in this: function init() { hello=66.66 whygod=sun.org.mozilla.javascript.internal.NativeArray@7ba28183, sku=[2490748], world=sun.org.mozilla.javascript.internal.NativeArray@69e4fede, price=[] } then: sku=[2490748] is assigning an array of length 2490748 to the variable sku. To know for sure, we'd have to see a little more context around the code you presented. You can see some diagnostics on the sku case in this jsFiddle: http://jsfiddle.net/KFgwF/. If sku isn't defined in a local scope, then it's implicitly being declared as a global variable (because no var in front of it. price=[] is assigning an empty array to price. Edit based on your comment: If you are expecting this to be a data structure that gets passed to a function: { hello=66.66 whygod=sun.org.mozilla.javascript.internal.NativeArray@7ba28183, sku=[2490748], world=sun.org.mozilla.javascript.internal.NativeArray@69e4fede, price=[] } Then, that is simply not legal javascript. For that to be a legal data structure declaration, it would have to look like this: { hello: 66.66, whygod: "sun.org.mozilla.javascript.internal.NativeArray@7ba28183", sku: [2490748], world: "sun.org.mozilla.javascript.internal.NativeArray@69e4fede", price: [] } A: On the java side before being fed into rhino javascript engine, I found out that price=[] was a mapping of the key called price to an ArrayList object with only one empty string object. Afterwards, spitting out the key/value pairs of the price object on the javascript side showed me that it wasn't really any type of standard javascript object at all! I spit out both price which should have had an empty string and sku. Now at least the sku should have had the value 2490748 somewhere in its key/value map dump but it didn't! Sigh ... no idea how to work this thing. Other than the empty:false property nothing seems useable. But I thought it merited a mention: sku= empty: false indexOf: function indexOf() {/* int indexOf(java.lang.Object) */} notifyAll: function notifyAll() {/* void notifyAll() */} removeAll: function removeAll() {/* boolean removeAll(java.util.Collection) */} trimToSize: function trimToSize() {/* void trimToSize() */} containsAll: function containsAll() {/* boolean containsAll(java.util.Collection) */} contains: function contains() {/* boolean contains(java.lang.Object) */} equals: function equals() {/* boolean equals(java.lang.Object) */} notify: function notify() {/* void notify() */} subList: function subList() {/* java.util.List subList(int,int) */} class: class java.util.ArrayList set: function set() {/* java.lang.Object set(int,java.lang.Object) */} isEmpty: function isEmpty() {/* boolean isEmpty() */} add: function add() {/* void add(int,java.lang.Object) boolean add(java.lang.Object) */} ensureCapacity: function ensureCapacity() {/* void ensureCapacity(int) */} size: function size() {/* int size() */} iterator: function iterator() {/* java.util.Iterator iterator() */} clear: function clear() {/* void clear() */} wait: function wait() {/* void wait() void wait(long) void wait(long,int) */} listIterator: function listIterator() {/* java.util.ListIterator listIterator(int) java.util.ListIterator listIterator() */} retainAll: function retainAll() {/* boolean retainAll(java.util.Collection) */} toString: function toString() {/* java.lang.String toString() */} hashCode: function hashCode() {/* int hashCode() */} toArray: function toArray() {/* java.lang.Object[] toArray(java.lang.Object[]) java.lang.Object[] toArray() */} lastIndexOf: function lastIndexOf() {/* int lastIndexOf(java.lang.Object) */} addAll: function addAll() {/* boolean addAll(java.util.Collection) boolean addAll(int,java.util.Collection) */} clone: function clone() {/* java.lang.Object clone() */} get: function get() {/* java.lang.Object get(int) */} getClass: function getClass() {/* java.lang.Class getClass() */} remove: function remove() {/* java.lang.Object remove(int) boolean remove(java.lang.Object) */}
{ "language": "en", "url": "https://stackoverflow.com/questions/7521962", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Phonegap app performance vs native app performance we are looking at getting a barcode scanning application built. We are considering using PhoneGap but our only worry is speed. All the application will do is just scan a barcode and check a server to see if it's valid or not. The application uses the camera very intensely to scan the barcode via an image. My main question is, will scanning via phonegap be just as fast as a native app? Speed is really important as the user will have to scan multiple barcodes very quickly. A: The phone's built-in software is what does the scanning and camera action. PhoneGap will only trigger the event and help transfer the data but the phone does all the work. A: As others noted the html5-based UI may feel sluggish. Maybe it's not an issue; you just have to try it and see. For scanning a barcode and uploading to a server the Phonegap overhead might not be signficant. A: I have developed a smartphone app where barcode scanning is an alternative to the primary function of scanning an image which is recognized by picture matching technology. I use PhoneGap. I have not compared this to native app performance. I am able to say that for my basic UI (it is a web app for the smartphone), my web pages are rendered fast enough not to be an issue. This performance has been observed on a 600MHz smartphone CPU (LG Optimus One running Android 2.2.1). The picture matching as well as barcode scanning is done on a server backend, not on the smartphone itself. The issue becomes one of networking speed from smartphone over WiFi or service provider network, over the Internet and onto the server - then there is the response from server back to smartphone. The processing speed of picture matching or barcode scanning has to be less than a second (ideally half a second) so that by the time networking delay is added, it is still a 1-2 second response time for the user. The image files that I am transferring from smartphone to server is targeted to be around 40KB. At a typical 54Mbps WiFi network or the going rate of around 40Mbps in HSPA+ service provider networks, I find the performance of my app to be suitable. Even with a fair signal WiFi speed of 15Mbps, end-user response is acceptable between 1-2 seconds. The pace of smartphone development (dual core processors) and service provider networks (4G HSPA+) will only take the industry higher. It is a tremendous opportunity for apps development moving forward. Side Topic: I am using Zbar code on the server for barcode scanning and I am hunting for better alternatives. The challenge with ISBN barcode scanning from smartphones having non-zoom, non-macro lens is that the typical barcode size is too small for "simple" barcode scanning algorithms to work properly. I'd like to hear about alternatives and people's experience with barcode scanning. I would be looking for code that I can deploy in my server backend, as opposed to running smartphone resident barcode scanning. A: Phonegap uses the same native APIs, it just abstracts them so that you can write your application in html and javascript. The time to take a picture or any other native process is less important than the time the user perceives. This is the portion of the native execution time that you need to expose to the user + Abstraction API time + UI responsiveness. There is always an overhead from an abstraction but I think that's negligible in an app like this (in phones newer than BB OS5). The current issues originate from the hardware rendering the HTML and the browser software installed on the device. A lot of BlackBerry phones don't use webkit (OS5 and below) and the the browsers they do use can seem very sluggish while rendering webapps. BB OS versions less than 5 don't have a production worthy way of communicating between the native and javascript layers, the hack that's often seen is to set and poll for changes in cookies. Android has always had a good design for JavaScript to native interaction afaik. BlackBerry phones and many lower end Android phones don't have GPU's, or some Android phones that do have GPU's don't compile webkit for the GPU! Without this your UI app may have that sluggish feel, pages/buttons take that bit longer to respond which is very noticeable when you're trying to whiz through menus. This has improved a lot since phonegap was released. UI lag should continue to decrease to a point where even new low end phones are production ready for webapps. But from my experiences we've not yet reached that point in 2011.
{ "language": "en", "url": "https://stackoverflow.com/questions/7521963", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Returning an array from a Java method I am trying to return two numbers from this method. I thought this was correct. Where am I going wrong? public int[] getDimension() { int shapeWidth = 0; int shapeHeight = 0; // ..... int[] result = new int[] {shapeWidth, shapeHeight}; return result; } And then at a calling site, is this correct? public int getWidth() { return getDimension()[0]; } I am asking because I believe there's a bug but I don't see it. A: That's fine. Short but complete program to demonstrate it working: public class Test { public static void main(String args[]) { int width = getDimension()[0]; System.out.println(width); } public static int[] getDimension() { int shapeWidth = 5; int shapeHeight = 10; int[] result = new int[] {shapeWidth, shapeHeight}; return result; } } You can make the result declaration line slightly simpler, by the way: int[] result = {shapeWidth, shapeHeight}; A: Rather than using an array, I would recommend using a class class Dimensions { private int width; private int height; public Dimensions(int width, int height) { this.width = width; this.height = height; } // add either setters and getters // or better yet, functionality methods instead } This will give you compile time referential integrity, which is much better than inferring based on "we know index 0 is width and index 1 is height". If you still want to use an array, Jon's answer is spot on. A: Your code looks fine, but try not to use an array if you only need a pair. Since Java doesn't have tuples/pairs you have to implement them, but it's pretty easy. Refer to this question for a possible implementation. public class Test { public static void main(String args[]) { int width = getDimension().getLeft(); System.out.println(width); } public static Pair<Integer, Integer> getDimension() { int shapeWidth = 5; int shapeHeight = 10; return new Pair<Integer, Integer>(shapeWidth, shapeHeight); } } This is better than a Dimension class, because you can use it everywhere in your code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7521965", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is the benefit of using java.util.properties while connecting to database? I was reading Oreilly Java Programming With Oracle JDBC edition and I notice that there was one example using java.util.properties object like below; public class Connector { Connection con = null; private Properties info = new Properties(); public void connect(){ info.put("user", "sys as sysdba"); info.put("password", "testpass"); String driverName = "oracle.jdbc.driver.OracleDriver"; try { Class.forName(driverName); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } String serverName = "localhost"; String port = "1521"; String sid = "XE"; String url = "jdbc:oracle:thin:@" + serverName + ":" + port + ":" + sid; try { con = DriverManager.getConnection(url, info); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void closeConnection(){ try { con.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } I have checked API that I understand main benefit of properties is reading local sources. Google OCI driver examples using java.util.properties more than thin driver examples. My question is; *Should I use properties for thin driver? *if yes what will be benefit? *Why I can not cast full details as properties that I have to use String object for connection? Thank you A: The properties could be loaded from some jdbc.properties file on classpath which allows you for external configuration. Its sole content could look like: user=sys as sysdba password=testpass So, instead of info.put("user", "sys as sysdba"); info.put("password", "testpass"); you could do info.load(getClass().getResourceAsStream("/jdbc.properties")); (note that the filename is free to your choice, it'll work as long as it's in the runtime classpath) This way you don't need to edit, recompile, rebuild, fuss the class whenever you want to change the connection details. You just have to edit a simple textbased file. This is particularly helpful in distributed applications which needs to be managed by someone without any Java knowledge (e.g. serveradmins). See also: * *Java Properties tutorial A: "To log on as SYSDBA with the JDBC Thin driver you must configure the server to use the password file. " http://docs.oracle.com/cd/B28359_01/java.111/b31224/dbmgmnt.htm I'm trying to use a thin driver to connect to Oracle as sysdba but the connections are failing. I tried steps there but my attempts after those changes also fail. Anyone interested in this, may also be interested in the internal_logon property since it is mentioned in relation to logging on for specific roles like sysdba but again, I had no success using that either.
{ "language": "en", "url": "https://stackoverflow.com/questions/7521968", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C++ Skipping the rest of the current `for` iteration and beginning a new one. Consider this C++ code for(int i=0; i<=N; ++i) { if(/* Some condition 1 */) {/*Blah Blah*/} if(/* Some condition 2 */){/*Yadda Yadda*/} } Is there any keyword/command so that if condition 1 evaluates to true and execution of /*Blah Blah*/ I can skip the rest of the current iteration and begin a new iteration by incrementing i. The closest thing I know to this kind of statement skipping is break but that terminates the loop entirely. I guess one could do this by using some flags and if statements, but a simple keyword would be very helpful. A: This case seems better suited for if..else.. than a continue, although continue would work fine. for(int i=0; i<=N; ++i) { if(/* Some condition 1 */) {/*Blah Blah*/} else if(/* Some condition 2 */) {/*Yadda Yadda*/} } A: Use the keyword continue and it will 'continue' to the next iteration of the loop. A: Using the Continue statement, stops the current loop and continues to the next, rather than breaking altogether Continue
{ "language": "en", "url": "https://stackoverflow.com/questions/7521969", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: Rhino Mocks: How to tell if object is mocked or real? Given an object o, how can I tell if it's a mocked or a real object? The only way I can see doing this looks a bit hacky: public bool IsMockedObject(object o) { try { o.GetMockRepository(); return true; } catch(InvalidOperationException) { return false; } } Please tell me there's a better way! A: You can check if the object implements IMockedObject: bool isMocked = o is Rhino.Mocks.Interfaces.IMockedObject; This of course would require referencing the RhinoMocks assembly, which I would try to avoid for your production code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7521974", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Excel macro to prepare query string based on rows I have one excel Sheet having below records id Empname state 1 steve NJ 2 karl NYC I have to write one macro to prepare sql update stement like below and insert into new sheet within the same workbook. UPDATE emp SET state='NJ' WHERE id=1 UPDATE emp SET state='NYC' WHERE id=2 Any suggestions or ideas please. Regards, Raju A: You could do this with formulas; there's no need to write a macro (if I read your requirements correctly). If your data is in Sheet1!A2:C3, then on Sheet2 you could start in cell A1 with the formula: ="UPDATE emp SET state = '" & Sheet1!C2 & "' WHERE id = " & Sheet1!A2 And then extend the formula down the column to repeat the pattern. After that you can simply copy the cells and paste the query into wherever you're going to use it. A: Use below sub and you should be all set Sub generateUpdate() Dim myRow As Integer: myRow = 2 'Starting Row of data in source table Dim temp As Integer: temp = 1 Do Until Sheet1.Cells(myRow, 1) = "" 'Loop until you find a blank 'Do Until myRow = 5 '5 is Row number till while you wish to loop Sheet2.Cells(temp, 1) = "UPDATE emp SET state='" & Sheet1.Cells(myRow, 3) & "' where id = " & Sheet1.Cells(myRow, 1) myRow = myRow + 1 temp = temp + 1 Loop End Sub
{ "language": "en", "url": "https://stackoverflow.com/questions/7521975", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Packaging symlinks via rpmbuild? Is it possible to make rpmbuild to preserve symlinks on packaging? The current behavior is to create copies of files, which I would like to avoid. A: I know this Q is old, but here's how I do it. In the %install section, simply touch the file that will be the symlink. touch %{buildroot}[path to your file] In the %files section, you specify it as a %ghost file: %ghost [path to symlink file] By doing this, it'll be listed as part of the package's files and will also be automatically removed when the package is uninstalled. Finally, create the symlink in the %post section: ln -sf [file to link to] [symlink] A: Sure it supports symlinks. But you actually have to package symlink and not copy the contents to the buildroot. Example spec packaging a symlink to /bin directory called /newbin Name: test Version: 1.0 Release: 1%{?dist} Summary: nothing License: GPLv2 Source0: nothing %description %install rm -rf %{buildroot} mkdir %{buildroot} ln -sf /bin %{buildroot}/newbin %files /newbin You'll also need nothing file in your SOURCES directory to succesfully build rpm out of this. Tested with rpm 4.9.1.2 A: I don't think so. I've used the post-install script set up symlinks in my packages.
{ "language": "en", "url": "https://stackoverflow.com/questions/7521980", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: Play Vimeo Videos in Windows 7 phone I am trying to get Vimeo videos to play in a windows 7 phone app. I used the answer here: How can I find download links for vimeo videos? to get a Vimeo URL that looks like this: http://vimeo.com/moogaloop/play/clip:29415171/f44f7a1dc39fb9b6ebede558e459274e/1310792258 The problem is when I use a non-mobile web browser the video will redirect you to the MP4 version of the file which plays correctly but if played on my Win7 phone (any browser) it doesn’t work. Instead I get a “We are having trouble displaying this page” and a “Error: HTTP 500 Server Internal error”. Does anyone know how to work around this to get the video to play? Maybe another approach entirely? I saw this similar question here vimeo video as .mp4 format in android for the Android but its 2 months old and no one has even commented or answered. I know it’s possible to play Vimeo videos in W7 Phone because there are apps for it. Any help would be appreciated. As always thanks in advance. A: For starters, ensure the version of Windows Phone being tested in Windows Phone 7 Mango. As that version has IE 9 with HTML5 video support. I then believe you need a paid Vimeo account to create mobile videos. A: It seems that Vimeo has now added mobile support for Win 7 phones on its site. So if you go to a Vimeo video http://vimeo.com/m// a page will open that will allow you to play and successfully watch the video. This is not the best solution, as I would rather have a direct link to the video, but for now it's a working solution. If in the future I figure out a way to directly link to the video files I will post it here (or if someone else has done this I would love to know how you did it)
{ "language": "en", "url": "https://stackoverflow.com/questions/7521981", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Trying to display live data from Telnet connection I've searched for a couple days I haven't found a solution for my problem. I need to have a script connect to a telnet server send data to log in then display the output in a web page as the server sends is until the user leaves the page. My experience is basic programing in PHP and Perl, but I'm willing to try others. My initial thought is to write daemon script that connects to the server then repeats the data to the web clients via it's own server. Then when a user loads the web page a client connects to the daemon script. Then telnet server only allows 1 connection from a specific user at a time that's why I'm thinking of the "Repeater" Server. I'd like to have the data scroll up as it comes in. The data rate varies from several lines a second to minutes between lines depending on what's going on. Can any one point me in the right direction? A: There are several web-ssh-clients, one is with python on the server side and ajax in the browser. Maybe you can take this as an example. See http://antony.lesuisse.org/software/ajaxterm/
{ "language": "en", "url": "https://stackoverflow.com/questions/7521983", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using JSON with XQuery page So I am using a jQuery plugin (jsonp) to make a cross-domain call to an api and getting JSON data back. I need to somehow get this data into my XQuery page. I'm using Marklogic server to store all my XML data and I know it has some XDMP functions to handle JSON data, it is getting the JSON from javascript to XQuery that is giving me a pain. Any ideas on how to go about this? A: I'm not 100% sure what is giving you problems but will try to offer up a solution that will hopefully get you on your way. There is an open source project on GitHub called MLJSON (https://github.com/marklogic/mljson/wiki). It can take a JSON string, parse it and return an XML document that MarkLogic can easily make use of. If understanding the internal structure of the XML isn't appealing (even though it is fairly straightforward, it is undocumented), the project also includes a path parser to extract bits out of the parsed JSON document. Here's a quick sample XQuery page that will take some JSON sent to the server as a POST or GET parameter, parse it and pull out a value: xquery version "1.0-ml"; import module namespace json="http://marklogic.com/json" at "lib/json.xqy"; import module namespace path="http://marklogic.com/mljson/path-parser" at "lib/path-parser.xqy"; let $jsonString := xdmp:get-request-field("json") let $jsonXML := json:parse($jsonString) let $firstName := path:select($jsonXML, "author.firstName", "json") return concat("First name: ", $firstName) If the above script is passed a JSON document like: { "author": { "firstName": "Noam", "lastName": "Chomsky" } } It will return the string: "First name: Noam". MLJSON has a number of other features that I won't go over here, but will mention that it has functions to construct JSON objects, arrays, etc and serialize them out as a JSON string. Hope that helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7521984", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Tomcat: Wrong Image I have a pretty bad example of a heisenbug: Every now and then tomcat delivers a wrong image. Instead of an asteriks it delifers some image a user uploaded. In the rendered HTML file the img-src points to the correct url. Does anybody have pointer where to start looking? A: Yes - could be a race condition. If those images are shared state in a servlet, perhaps access isn't synchronized properly. A: The problem is almost guaranteed to be there is not enough information in the img-src attribute to obtain the image by itself. Making hte code work without that constraint is going to be so much of a headache you will have an easier time putting everything needed to construct the image in its img-src.
{ "language": "en", "url": "https://stackoverflow.com/questions/7521987", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CSS Menu Dropdowns are all appearing under the same (left most) parent item I have tried moving the position:relative; setting around, but to my understanding it is where it is supposed to be... Please correct me, because my understanding is clearly wrong! <ul id="menu"> <li><a href="/products/">All Products</a> <ul> <li><a href="/products/stock/">Stock Lanyards</a></li> <li><a href="/products/screen-printed/">Screen Printed Lanyards</a></li> <li><a href="/products/full-color/">Full Color Lanyards</a></li> <li><a href="/products/custom-cord/">Custom Cord Lanyards</a></li> <li><a href="/products/specialty/">Specialty Lanyards</a></li> </ul> </li> <li><a href="/reorders/">Reorders</a></li> <li><a href="/resources/">Resources</a> <ul> <li><a href="/products/faq/">FAQ</a></li> <li><a href="/products/art-requirements/">Art Requirements</a></li> <li><a href="/products/production-times/">Production Times</a></li> <li><a href="/products/about-us/">About Us</a></li> <li><a href="/products/contact-us/">Contact Us</a></li> <li><a href="/products/request-a-sample/">Request A Sample</a></li> </ul> </li> <li><a href="/blog/">Blog</a></li> </ul> css.... ul#menu { margin:0px; padding-top:20px; position:absolute; right:0px; font-weight:bold; font-size:14px; } ul#menu li { display:inline; padding-left:8px; } ul#menu a{ color:#8ba693; text-decoration:none; padding:5px; } ul#menu a:hover, a:active{ /* text-shadow: 0 0 0.9em #ccc; text-decoration:underline; */ background-color:#000; } /* -- DROPDOWN MENU STYLES -- */ #menu ul { margin: 0; padding: 0; list-style: none; } #menu ul li { display: block; position: relative; left:0; top:100%; } #menu li ul { display: none; position: absolute; z-index:1000; margin:5px 0 0 0px; top:100%; left:0; } #menu ul li a { display: block; text-decoration: none; padding: 7px 15px 6px 10px; margin: 0px 0 0 0; white-space: nowrap; border-top: 1px solid #8ba693; border-left: 1px solid #8ba693; border-right: 1px solid #8ba693; } #menu ul li a:hover { background: #000; } #menu li:hover > ul { display: block; } #menu li:hover li { float: none; font-size: 11px; } #menu li:hover a { background: #fff; } #menu li:hover li a:hover { background: #8ba693; color: #fff; } A: ul#menu li { display: inline; padding-left: 8px; position: relative; } http://jsfiddle.net/HFp6K/2/ position:relative needs to be in position:absolute's parent.
{ "language": "en", "url": "https://stackoverflow.com/questions/7521988", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jquery $(function () is not working on Web UI I am a new bee in jquery and trying to find out what's going wrong with my code : <script type="text/javascript"> $(function () { $("#BtnSubmit").click(function () { alert(" I am here"); $("#BtnSubmit").attr("disabled", "disabled").addClass("ui-state-disabled"); $("#BtnCancel").attr('disabled', 'disabled').addClass("ui-state-disabled"); }); }); </script> Not even showing the aler msg. Though the same code is working in another page as: <script type="text/javascript"> $(document).ready(function() { $("#BtnSubmit").click(function () { alert(" I am here"); $("#BtnSubmit").attr("disabled", "disabled").addClass("ui-state-disabled"); $("#BtnCancel").attr('disabled', 'disabled').addClass("ui-state-disabled"); }); }); </script> What's going wrong here? Can anybody help? A: Is your content generated dynamically? If so, try using .live rather than .click: <script type="text/javascript"> $(document).ready(function() { // $("#BtnSubmit").click(function () { $("#BtnSubmit").live('click', function () { alert(" I am here"); $("#BtnSubmit").attr("disabled", "disabled").addClass("ui-state-disabled"); $("#BtnCancel").attr('disabled', 'disabled').addClass("ui-state-disabled"); }); }); </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/7521990", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: problem with PHP looping through members I am having a problem with my updation script, basically if I keep the line as mysql_fetch_row then it only seems to want to insert every other member into the database, but if I change it to mysql_fetch_array then it inserts each member twice, but still not all the users from the database. I have just shown the start of the script below as I am pretty sure this must be where the error is. Any help with this would be fantastic. Cheers. $result = mysql_query("SELECT member_id FROM members ORDER BY member_id"); while ($member = mysql_fetch_array($result)){ foreach ($member as &$member_id){ $results_query = mysql_query("SELECT driver1 as driver1, driver2 as driver2, driver3 as driver3, driver4 as driver4, team as team, engine as engine, total_points as total FROM members WHERE member_id = '$member_id'") or die ("Failed to update" . mysql_error()); $userteam = mysql_fetch_assoc($results_query); //this is the bottom of the script after calculations have take place and the insert into the database// $results_query = mysql_query("INSERT INTO member_results (member_id, track_id, driver1, driver2, driver3, driver4, team, engine, driver1_points, driver2_points, driver3_points, driver4_points, team_points, engine_points, qualifying_points, race_points, total_points) VALUES ('$member_id', '$track', '$userteam[driver1]', '$userteam[driver2]', '$userteam[driver3]', '$userteam[driver4]', '$userteam[team]', '$userteam[engine]', '$userpoints[driver1]', '$userpoints[driver2]', '$userpoints[driver3]', '$userpoints[driver4]', '$userpoints[team]', '$userpoints[engine]', '$userpoints[qualifying]', '$userpoints[race]', '$userpoints[total]')") or die ("Failed to update" . mysql_error()); $userteam["total"] += $userpoints["total"]; $results_query = mysql_query("UPDATE members SET total_points = '$userteam[total]' WHERE member_id = '$member_id'") or die ("Failed to update" . mysql_error()); } } A: You shouldn't need a foreach loop when using mysql_fetch_array. The reason your query is being entered twice is because mysql_fetch_array fetches both an associative array and a numerical array for the row data, so it's looking at both of them and inserting the data twice, one for each array. $member doesn't require a foreach for this reason. $member is just one row being pulled, not the entire data set. An associative array returns the column names as array keys. while ($member = mysql_fetch_array($result)){ $results_query = mysql_query("SELECT driv1 as drivone, driv2 as drivtwo, driv3 as drivthree, driv4 as drivfour, team as teamone, eng as engone, total_points as total FROM members WHERE member_id = '$member['member_id']'") // If member_id is the column name for the ID or die ("Failed to update" . mysql_error()); A: mysql_fetch_array returns multiple arrays(associative array, a numeric array, or both) thats why its inserting twicein your foreach, and could be the reason why your script is breaking. try var_dumping $member to see what syntax you can use to refine your foreach see documentation here: http://php.net/manual/en/function.mysql-fetch-array.php A: Use mysql_fetch_assoc($result) or mysql_fetch_array($result, MYSQL_ASSOC); by default mysql_fetch_array return: * *the NUM indexation ( array( 0 => ..., 1 => ...)), *but also merge-in the assoc indexation ( array( 'fieldname' => ... , 'colname' => ...)) So your code should look like: ** Note that've removed the foreach. $result = mysql_query("SELECT member_id FROM members ORDER BY member_id"); while ($member = mysql_fetch_assoc($result)){ $member_id = $member['member_id']; //foreach ($member as &$member_id){ $results_query = mysql_query("SELECT driver1 as driver1, driver2 as driver2, driver3 as driver3, driver4 as driver4, team as team, engine as engine, total_points as total FROM members WHERE member_id = '$member_id'") or die ("Failed to update" . mysql_error()); $userteam = mysql_fetch_assoc($results_query); //...
{ "language": "en", "url": "https://stackoverflow.com/questions/7521993", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Node.js: Available/Creating Web Proxies I'm trying to create a web proxy alot like Proxify without th options that allows users to surf third-party websites instead of an iframe for maximum usability (Circumventing Iframe issues.). How would I be able to achieve this? Also, I've googled around and found some Node.js Web Proxies that don't seem to work anymore as they are out of date. Examples: * *Node Web Proxy Example 1 *Node Web Proxy Example 2 Are their any recent Node.js web proxies available? A: Just use node-http-proxy Their documentation is solid and they have an examples folder. A lot of people use this in production. Nodejitsu itself uses it in production. A: Take a look at Hoxy. I haven't used it myself, but I am working on a similar problem (I want to circumvent the iframe same domain policy), so from the quick glimpse that I took of the project it seems to do what you want.
{ "language": "en", "url": "https://stackoverflow.com/questions/7522001", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Game Timers Slowing Down Overall Performance I'm working on an iPhone App where I rely heavily on timers and animations, but I've realized my game is really slowing down and lagging on certain aspects of the game. I'm not quite sure how to improve this without removing any animations or anything. Essentially what I'm using is the accelerometer to update my character's position (Left/Right). I also use several timers to read from different URLs, update images and the one that lags the most is one that loops an image to move from left to right. Basically I'm using about 6 or 7 timers and the Accelerometer, is there a way I can improve the performance of my game without having to remove any of my animations or changing the interval of the timers? Thanks in advance! A: Try use Allocation RUN-> RUN WITH PERFORMANCE TOOLS->Allocation to see which part is overload in the application A: Instead of using NSTimer to animate, you might want to look at using the animationImages property in UIImageView (which lets you show multiple frames of animation, possibly looping) or beginAnimations within UIView (which lets you move an object along a path, among other things). A good place to start is with this question on recommend reading for iPhone animation, although for reference the documentation in XCode and Apple's programming guides are good sources by themselves. What others have suggested - in terms of using a game loop - make sense, too, but depending on the complexity of your game, sometimes just letting the iOS SDK take care of your animations for you can be good enough.
{ "language": "en", "url": "https://stackoverflow.com/questions/7522003", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I implement a choose folder option in Uploadify? Uploadify works great, and I love it. However, I just can't figure out how to make a dropdown list to select what upload folder to choose. I want my user to be able to select a folder to upload the file to. Anyone know a good way to do this? Preferably simple. A: It's pretty simple. <script type="text/javascript"> $(document).ready(function() { $('#file_upload').uploadify({ 'uploader' : '/uploadify/uploadify.swf', 'script' : '/uploadify/uploadify.php', 'cancelImg' : '/uploadify/cancel.png', 'folder' : $("#folder").val(), 'auto' : true }); }); $("#folder").change(function() { $('#file_upload').uploadifySettings('folder',$("#folder").val()); }); </script> and make a html select with folder values. <select id="folder"> <option value="/uploads">Uploads</option> <option value="/videos">Videos</option> <option value="/music">Music</option> </select> A: slight mistake .... <script type="text/javascript"> $(document).ready(function() { $('#file_upload').uploadify({ 'uploader' : '/uploadify/uploadify.swf', 'script' : '/uploadify/uploadify.php', 'cancelImg' : '/uploadify/cancel.png', 'folder' : $("#folder").val(), 'auto' : true }); }); // should not be here - goes above </script> $("#folder").change(function() { $('#file_upload').uploadifySettings('folder',$("#folder").val()); }); </script> my code (ignore locations of script / also I set folder to first option of #folder which happens to be dubstep on my dropdown) js head section <script type="text/javascript"> $(document).ready(function() { $('#file_upload').uploadify({ 'uploader' : 'upload/uploadify.swf', 'script' : 'upload/uploadify.php', 'cancelImg' : 'upload/cancel.png', 'folder' : 'upload/dropbox/dubmin', 'fileExt' : '*.mp3', 'fileDesc' : '.mp3 files only', 'multi' : true, 'queueSizeLimit' : 4, 'queueID' : 'queue', 'sizeLimit' : 52428800, 'wmode' : 'transparent' }); $("#folder").change(function () { var path = "upload/dropbox/" + $(this).val(); $('#file_upload').uploadifySettings('folder', path); }); /* begin test to see if js switching to correct folder (remove or comment out section when done) */ $('#test').click(function(){ var folderz = $('#file_upload').uploadifySettings('folder'); alert("folder is set to: "+folderz); }); /* begin test to see if js switching to correct folder */ }); </script> html code <select id="folder" name="folder"> <option value="dubtem">Dubstep</option> <option value="liqmin">Liquid</option> <option value="drknro">Neuro</option> <option value="other">Other</option> </select> <button type="button" id="test">Which Folder?</button> </p> <input id="file_upload" name="file_upload" type="file" /> <div id="queue"></div> <a href="javascript:$('#file_upload').uploadifyUpload();"><img src="submit.png" id="submit_img"></a> comment out or erase test section from either html or js when done with it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7522005", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Slider refuses to center photos, forces left justified This is a really great slider but it has just one annoying fault. If I have different widths of images, the ones that are too small for the default width, are left justified. I've tried every which way to do it with the html/css but it's somewhere in the js I think. I even loaded the js after the images load and it still put it left justified even though they were centered for that split second before the js loaded. What seems to happen is, the js takes the smaller width image and makes it the full default width and adds whitespace to the right of it, essentially making it a full width image. I am just curious if this is customizable so that the photo is centered and whitespace is added on either side. Any thoughts are appreciated, thanks for taking a look. (function ($) { var params = new Array; var order = new Array; var images = new Array; var links = new Array; var linksTarget = new Array; var titles = new Array; var interval = new Array; var imagePos = new Array; var appInterval = new Array; var squarePos = new Array; var reverse = new Array; $.fn.coinslider = $.fn.CoinSlider = function (options) { init = function (el) { order[el.id] = new Array(); images[el.id] = new Array(); links[el.id] = new Array(); linksTarget[el.id] = new Array(); titles[el.id] = new Array(); imagePos[el.id] = 0; squarePos[el.id] = 0; reverse[el.id] = 1; params[el.id] = $.extend({}, $.fn.coinslider.defaults, options); $.each($('#' + el.id + ' img'), function (i, item) { images[el.id][i] = $(item).attr('src'); links[el.id][i] = $(item).parent().is('a') ? $(item).parent().attr('href') : ''; linksTarget[el.id][i] = $(item).parent().is('a') ? $(item).parent().attr('target') : ''; titles[el.id][i] = $(item).next().is('span') ? $(item).next().html() : ''; $(item).hide(); $(item).next().hide(); }); $(el).css({ 'background-image': 'url(' + images[el.id][0] + ')', 'width': params[el.id].width, 'height': params[el.id].height, 'position': 'relative', 'background-position': 'top left' }).wrap("<div class='coin-slider' id='coin-slider-" + el.id + "' />"); $('#' + el.id).append("<div class='cs-title' id='cs-title-" + el.id + "' style='position: absolute; bottom:0; left: 0; z-index: 1000;'></div>"); $.setFields(el); if (params[el.id].navigation) $.setNavigation(el); $.transition(el, 0); $.transitionCall(el); } $.setFields = function (el) { tWidth = sWidth = parseInt(params[el.id].width / params[el.id].spw); tHeight = sHeight = parseInt(params[el.id].height / params[el.id].sph); counter = sLeft = sTop = 0; tgapx = gapx = params[el.id].width - params[el.id].spw * sWidth; tgapy = gapy = params[el.id].height - params[el.id].sph * sHeight; for (i = 1; i <= params[el.id].sph; i++) { gapx = tgapx; if (gapy > 0) { gapy--; sHeight = tHeight + 1; } else { sHeight = tHeight; } for (j = 1; j <= params[el.id].spw; j++) { if (gapx > 0) { gapx--; sWidth = tWidth + 1; } else { sWidth = tWidth; } order[el.id][counter] = i + '' + j; counter++; if (params[el.id].links) $('#' + el.id).append("<a href='" + links[el.id][0] + "' class='cs-" + el.id + "' id='cs-" + el.id + i + j + "' style='width:" + sWidth + "px; height:" + sHeight + "px; float: left; position: absolute;'></a>"); else $('#' + el.id).append("<div class='cs-" + el.id + "' id='cs-" + el.id + i + j + "' style='width:" + sWidth + "px; height:" + sHeight + "px; float: left; position: absolute;'></div>"); $("#cs-" + el.id + i + j).css({ 'background-position': -sLeft + 'px ' + (-sTop + 'px'), 'left': sLeft, 'top': sTop }); sLeft += sWidth; } sTop += sHeight; sLeft = 0; } $('.cs-' + el.id).mouseover(function () { $('#cs-navigation-' + el.id).show(); }); $('.cs-' + el.id).mouseout(function () { $('#cs-navigation-' + el.id).hide(); }); $('#cs-title-' + el.id).mouseover(function () { $('#cs-navigation-' + el.id).show(); }); $('#cs-title-' + el.id).mouseout(function () { $('#cs-navigation-' + el.id).hide(); }); if (params[el.id].hoverPause) { $('.cs-' + el.id).mouseover(function () { params[el.id].pause = true; }); $('.cs-' + el.id).mouseout(function () { params[el.id].pause = false; }); $('#cs-title-' + el.id).mouseover(function () { params[el.id].pause = true; }); $('#cs-title-' + el.id).mouseout(function () { params[el.id].pause = false; }); } }; $.transitionCall = function (el) { clearInterval(interval[el.id]); delay = params[el.id].delay + params[el.id].spw * params[el.id].sph * params[el.id].sDelay; interval[el.id] = setInterval(function () { $.transition(el) }, delay); } $.transition = function (el, direction) { if (params[el.id].pause == true) return; $.effect(el); squarePos[el.id] = 0; appInterval[el.id] = setInterval(function () { $.appereance(el, order[el.id][squarePos[el.id]]) }, params[el.id].sDelay); $(el).css({ 'background-image': 'url(' + images[el.id][imagePos[el.id]] + ')' }); if (typeof (direction) == "undefined") imagePos[el.id]++; else if (direction == 'prev') imagePos[el.id]--; else imagePos[el.id] = direction; if (imagePos[el.id] == images[el.id].length) { imagePos[el.id] = 0; } if (imagePos[el.id] == -1) { imagePos[el.id] = images[el.id].length - 1; } $('.cs-button-' + el.id).removeClass('cs-active'); $('#cs-button-' + el.id + "-" + (imagePos[el.id] + 1)).addClass('cs-active'); if (titles[el.id][imagePos[el.id]]) { $('#cs-title-' + el.id).css({ 'opacity': 0 }).animate({ 'opacity': params[el.id].opacity }, params[el.id].titleSpeed); $('#cs-title-' + el.id).html(titles[el.id][imagePos[el.id]]); } else { $('#cs-title-' + el.id).css('opacity', 0); } }; $.appereance = function (el, sid) { $('.cs-' + el.id).attr('href', links[el.id][imagePos[el.id]]).attr('target', linksTarget[el.id][imagePos[el.id]]); if (squarePos[el.id] == params[el.id].spw * params[el.id].sph) { clearInterval(appInterval[el.id]); return; } $('#cs-' + el.id + sid).css({ opacity: 0, 'background-image': 'url(' + images[el.id][imagePos[el.id]] + ')', 'background-repeat': 'no-repeat', 'background-color': '#fff', }); $('#cs-' + el.id + sid).animate({ opacity: 1 }, 300); squarePos[el.id]++; }; $.setNavigation = function (el) { $(el).append("<div id='cs-navigation-" + el.id + "'></div>"); $('#cs-navigation-' + el.id).hide(); $('#cs-navigation-' + el.id).append("<a href='#' id='cs-prev-" + el.id + "' class='cs-prev'></a>"); $('#cs-navigation-' + el.id).append("<a href='#' id='cs-next-" + el.id + "' class='cs-next'></a>"); $('#cs-prev-' + el.id).css({ 'position': 'absolute', 'top': 0, 'left': 0, 'z-index': 1001, 'line-height': '30px', 'opacity': params[el.id].opacity }).click(function (e) { e.preventDefault(); $.transition(el, 'prev'); $.transitionCall(el); }).mouseover(function () { $('#cs-navigation-' + el.id).show() }); $('#cs-next-' + el.id).css({ 'position': 'absolute', 'top': 0, 'right': 0, 'z-index': 1001, 'line-height': '30px', 'opacity': params[el.id].opacity }).click(function (e) { e.preventDefault(); $.transition(el); $.transitionCall(el); }).mouseover(function () { $('#cs-navigation-' + el.id).show() }); $("<div id='cs-buttons-" + el.id + "' class='cs-buttons'></div>").appendTo($('#coin-slider-' + el.id)); for (k = 1; k < images[el.id].length + 1; k++) { $('#cs-buttons-' + el.id).append("<a href='#' class='cs-button-" + el.id + "' id='cs-button-" + el.id + "-" + k + "'>" + k + "</a>"); } $.each($('.cs-button-' + el.id), function (i, item) { $(item).click(function (e) { $('.cs-button-' + el.id).removeClass('cs-active'); $(this).addClass('cs-active'); e.preventDefault(); $.transition(el, i); $.transitionCall(el); }) }); $('#cs-navigation-' + el.id + ' a').mouseout(function () { $('#cs-navigation-' + el.id).hide(); params[el.id].pause = false; }); $("#cs-buttons-" + el.id) /*.css({'right':'50%','margin-left':-images[el.id].length*15/2-5,'position':'relative'})*/ ; } $.effect = function (el) { effA = ['random', 'swirl', 'rain', 'straight']; if (params[el.id].effect == '') eff = effA[Math.floor(Math.random() * (effA.length))]; else eff = params[el.id].effect; order[el.id] = new Array(); if (eff == 'random') { counter = 0; for (i = 1; i <= params[el.id].sph; i++) { for (j = 1; j <= params[el.id].spw; j++) { order[el.id][counter] = i + '' + j; counter++; } } $.random(order[el.id]); } if (eff == 'rain') { $.rain(el); } if (eff == 'swirl') $.swirl(el); if (eff == 'straight') $.straight(el); reverse[el.id] *= -1; if (reverse[el.id] > 0) { order[el.id].reverse(); } } $.random = function (arr) { var i = arr.length; if (i == 0) return false; while (--i) { var j = Math.floor(Math.random() * (i + 1)); var tempi = arr[i]; var tempj = arr[j]; arr[i] = tempj; arr[j] = tempi; } } $.swirl = function (el) { var n = params[el.id].sph; var m = params[el.id].spw; var x = 1; var y = 1; var going = 0; var num = 0; var c = 0; var dowhile = true; while (dowhile) { num = (going == 0 || going == 2) ? m : n; for (i = 1; i <= num; i++) { order[el.id][c] = x + '' + y; c++; if (i != num) { switch (going) { case 0: y++; break; case 1: x++; break; case 2: y--; break; case 3: x--; break; } } } going = (going + 1) % 4; switch (going) { case 0: m--; y++; break; case 1: n--; x++; break; case 2: m--; y--; break; case 3: n--; x--; break; } check = $.max(n, m) - $.min(n, m); if (m <= check && n <= check) dowhile = false; } } $.rain = function (el) { var n = params[el.id].sph; var m = params[el.id].spw; var c = 0; var to = to2 = from = 1; var dowhile = true; while (dowhile) { for (i = from; i <= to; i++) { order[el.id][c] = i + '' + parseInt(to2 - i + 1); c++; } to2++; if (to < n && to2 < m && n < m) { to++; } if (to < n && n >= m) { to++; } if (to2 > m) { from++; } if (from > to) dowhile = false; } } $.straight = function (el) { counter = 0; for (i = 1; i <= params[el.id].sph; i++) { for (j = 1; j <= params[el.id].spw; j++) { order[el.id][counter] = i + '' + j; counter++; } } } $.min = function (n, m) { if (n > m) return m; else return n; } $.max = function (n, m) { if (n < m) return m; else return n; } this.each(function () { init(this); }); }; $.fn.coinslider.defaults = { width: 828, height: 200, spw: 1, sph: 1, delay: 4000, sDelay: 30, opacity: 0.7, titleSpeed: 500, effect: '', navigation: true, links: false, hoverPause: true }; })(jQuery); A: It seems to be taking the image source url and putting it into the background of the slider. I would first try changing 'background-position': 'top left' to: 'background-position': 'center center' ... actually, the entire script seems geared towards tiling the images. I'd imagine that's the technique it uses to generate some of its cool effects. This line is where it's centering the current image within the tile defined by sph and spw. 'background-position': -sLeft + 'px ' + (-sTop + 'px'), and if you use spw=1 and sph=1 you can center it by changing that to a fixed 'center center'. I don't really care for this script in terms of general purpose, but it seems to have worked well for the person who wrote it. A: this is my hacky solution <script> $(window).load(function() { $('#coin-slider').coinslider({ opacity: 0.6, effect: "rain", hoverPause: true, dely: 3000 }); // center coin slider setTimeout(function(){ centerCS(); },500); }); // center coin slider image function centerCS(){ var w=$(".container").width(); // container of coin slider var csw=$("#coin-slider").width(); var lpad=(w-csw)/2; $("#coin-slider").css("margin-left",lpad+"px"); } </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/7522008", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Django and MongoDB in E-commerce? sorry for this silly questions, * *can someone share experience about combining Django in e-commerce when used with NoSql, if it's not MongoDB, so what about CouchDB or other Non-Document nosql? *which webserver to use when using e-commerce, cherrypy seems to have SSL? so Tornado is obsolete when using e-commerce + django? A: I can't speak for the Django part since I've never used Python for web dev but this blog post from Kyle Banker is the best I've read so far describing the pros and cons of using MongoDB in e-commerce. The hype around NoSQL (Mongo, Couch, ...) and e-commerce has mainly to do with ontologies, which are a very difficult thing to model into a fixed schema. For instance, fans, washing machines and HDDs all have the RPM attribute, while a monitor does not. Since it's impossible to model every classification and attribute for every product RDBMS usually rely on the very flexible EAV data model which is a pain in the ass to query / maintain in the long run. Also, check out MongoDB and Ecommerce: A Perfect Combination. A: You definitely gain flexibility by using MongoDB from the reasons that Alix has touched on, also it is very quick and sharding capabilities are built in, which means that scaling should be a bit easier. However you will need ACID for certain aspects of what I believe you refer to e-commerce (a web version of a physical store, where you have products listed online, inventory control, sales records, etc) mainly around the issue of payment. Long story short, if you break your "e-commerce" into 2 parts, being: " products listing" and "products purchasing" you can apply MongoDB to the first part and some ACID compliant (PostgreSQL, MySQL etc) to the 2nd part. You'd need some sort of UUID for this of course. Also, I'm not sure if this added complexity would be beneficial. If you choose to sell a restricted category of products, you can perhaps have smart SQL solution that'd still give you reasonable flexibility. You could have for example all products in the same basic table, this table would have let's sat 20 columns for products' "features". Does a pair of jeans need all 20 columns? No, so use let's say 5. Does a car need all 20 columns? Maybe... You could then have each product be associated with another table which would name the columns for you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7522013", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: User authentication using MySQL and GRANT or custom software solution? I'm a long time programmer but have done very little database design. So I'm seeking some feedback on a solution I'm developing. Description I will have several (10 to 20) customers storing sensitive data on my remote server. A customer is an organization that has users. Access is done via piece of java software running on the server accessing a MySQL server. A separate client java program accesses the server and does the interchange. Data privacy is very important, so I am planning on a separate DB (schema) for each customer. Within each database there are three user levels: input, query, and admin. A user fits into one of those levels and gets various permissions on the DB. I'm planning to do everything with stored procedures, so really they are getting access to a set of stored procedures on a specific DB. The biggest challenge is that the customer's Admin users have to be able to add (or remove) additional users that only have access to the customer's database. Users should be unique to the DB, but not to the MySQL instance. Each customer should be about to have a user named 'bob' for example. Question So I have two ways currently of approaching this. The one I currently prefer is to have each user be a real MySQL user that can have privileges GRANTed. This makes sure they can only execute what their role specifies right at the MySQL level. The problem is name collision since MySQL usernames are global to all DBs. I solved that by having a "root" table that maps a User's customerID (unique to each customer, not each user) to a DB, then a table in that DB maps the user's name to a userID, which is then the actual MySQL user. The java server software would connect to the DB using the mapped userID and user's password, and go about business. It's a good bit of effort and hoop jumping to do this, but I like it from a security standpoint. The other way is just to have a couple of base users in the DB for the java software to connect and then write our own auth by storing usernames and passwords in each customer's DB. It would be up to the software to make sure only the right DBs are modified, only the right functions are called, etc since nothing in MySQL would be able to prevent it. The base users would have to have all permissions for all user types, so a software glitch or compromise in the java software could lead to bad things for the DB. Makes the DB easier but the software somewhat more complex. Feedback So do any DB veterans have some feedback on this? Has anyone solved an issue like this in a better way? Trying to get some ideas before we commit to something. Thanks, Matt A: The other way is just to have a couple of base users in the DB for the java software to connect and then ... Use LDAP to store users, schema associations, privileges, roles, authorizations, etc., etc. It is always up to the software -- via authorization rules -- to make sure only the right DBs are modified, only the right functions are called, etc The base users would have to appropriate permissions for specific user types, so a software glitch or compromise in the java software could lead to bad things for the DB. That's always true. So use testing to prevent this mysterious "glitch". The database is not magically "more secure" or magically "less subject to software glitches". DB security is just as trustworthy as application security. Both are just as trustworthy as the administrative procedures and human factors. Use application-level authorization. Use LDAP. Don't impute magical powers to RDBMS authorization schemes. They're not "better" or "more trustworthy". Application authorization checks -- in most languages and frameworks -- are single line-of-code decorators (or if statements) that explicitly define what group of users has access to the functionality. It's not difficult. It's not subject to "glitches".
{ "language": "en", "url": "https://stackoverflow.com/questions/7522015", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to delete stuff printed to console by System.out.println()? In a Java application I'm using some calls to System.out.println(). Now I want to find a way to programmatically delete this stuff. I couldn't find any solution with google, so are there any hints? A: I am using blueJ for java programming. There is a way to clear the screen of it's terminal window. Try this:- System.out.print ('\f'); this will clear whatever is printed before this line. But this does not work in command prompt. A: You could print the backspace character \b as many times as the characters which were printed before. System.out.print("hello"); Thread.sleep(1000); // Just to give the user a chance to see "hello". System.out.print("\b\b\b\b\b"); System.out.print("world"); Note: this doesn't work flawlessly in Eclipse console in older releases before Mars (4.5). This works however perfectly fine in command console. See also How to get backspace \b to work in Eclipse's console? A: System.out is a PrintStream, and in itself does not provide any way to modify what gets output. Depending on what is backing that object, you may or may not be able to modify it. For example, if you are redirecting System.out to a log file, you may be able to modify that file after the fact. If it's going straight to a console, the text will disappear once it reaches the top of the console's buffer, but there's no way to mess with it programmatically. I'm not sure exactly what you're hoping to accomplish, but you may want to consider creating a proxy PrintStream to filter messages as they get output, instead of trying to remove them after the fact. A: To clear the Output screen, you can simulate a real person pressing CTRL + L (which clears the output). You can achieve this by using the Robot() class, here is how you can do this: try { Robot robbie = new Robot(); robbie.keyPress(17); // Holds CTRL key. robbie.keyPress(76); // Holds L key. robbie.keyRelease(17); // Releases CTRL key. robbie.keyRelease(76); // Releases L key. } catch (AWTException ex) { Logger.getLogger(LoginPage.class.getName()).log(Level.SEVERE, null, ex); } A: There are two different ways to clear the terminal in BlueJ. You can get BlueJ to automatically clear the terminal before every interactive method call. To do this, activate the 'Clear screen at method call' option in the 'Options' menu of the terminal. You can also clear the terminal programmatically from within your program. Printing a formfeed character (Unicode 000C) clears the BlueJ terminal, for example: System.out.print('\u000C'); A: Just to add to BalusC's anwswer... Invoking System.out.print("\b \b") repeatedly with a delay gives an exact same behavior as when we hit backspaces in {Windows 7 command console / Java 1.6} A: I've found that in Eclipse Mars, if you can safely assume that the line you replace it with will be at least as long as the line you are erasing, simply printing '\r' (a carriage return) will allow your cursor to move back to the beginning of the line to overwrite any characters you see. I suppose if the new line is shorter, you can just make up the different with spaces. This method is pretty handy in eclipse for live-updating progress percentages, such as in this code snippet I ripped out of one of my programs. It's part of a program to download media files from a website. URL url=new URL(link); HttpURLConnection connection=(HttpURLConnection)url.openConnection(); connection.connect(); if(connection.getResponseCode()!=HttpURLConnection.HTTP_OK) { throw new RuntimeException("Response "+connection.getResponseCode()+": "+connection.getResponseMessage()+" on url "+link); } long fileLength=connection.getContentLengthLong(); File newFile=new File(ROOT_DIR,link.substring(link.lastIndexOf('/'))); try(InputStream input=connection.getInputStream(); OutputStream output=new FileOutputStream(newFile);) { byte[] buffer=new byte[4096]; int count=input.read(buffer); long totalRead=count; System.out.println("Writing "+url+" to "+newFile+" ("+fileLength+" bytes)"); System.out.printf("%.2f%%",((double)totalRead/(double)fileLength)*100.0); while(count!=-1) { output.write(buffer,0,count); count=input.read(buffer); totalRead+=count; System.out.printf("\r%.2f%%",((double)totalRead/(double)fileLength)*100.0); } System.out.println("\nFinished index "+INDEX); } A: Clearing screen in Java is not supported, but you can try some hacks to achieve this. a) Use OS-depends command, like this for Windows: Runtime.getRuntime().exec("cls"); b) Put bunch of new lines (this makes ilusion that screen is clear) c) If you ever want to turn off System.out, you can try this: System.setOut(new PrintStream(new OutputStream() { @Override public void write(int b) throws IOException {} })); A: You could use cursor up to delete a line, and erase text, or simply overwrite with the old text with new text. int count = 1; System.out.print(String.format("\033[%dA",count)); // Move up System.out.print("\033[2K"); // Erase line content or clear screen System.out.print(String.format("\033[2J")); This is standard, but according to wikipedia the Windows console don't follow it. Have a look: http://www.termsys.demon.co.uk/vtansi.htm A: The easiest ways to do this would be: System.out.println("\f"); System.out.println("\u000c"); A: For intellij console the 0x08 character worked for me! System.out.print((char) 8); A: I found a solution for the wiping the console in an Eclipse IDE. It uses the Robot class. Please see code below and caption for explanation: import java.awt.AWTException; import java.awt.Robot; import java.awt.event.KeyEvent; public void wipeConsole() throws AWTException{ Robot robbie = new Robot(); //shows the Console View robbie.keyPress(KeyEvent.VK_ALT); robbie.keyPress(KeyEvent.VK_SHIFT); robbie.keyPress(KeyEvent.VK_Q); robbie.keyRelease(KeyEvent.VK_ALT); robbie.keyPress(KeyEvent.VK_SHIFT); robbie.keyPress(KeyEvent.VK_Q); robbie.keyPress(KeyEvent.VK_C); robbie.keyRelease(KeyEvent.VK_C); //clears the console robbie.keyPress(KeyEvent.VK_SHIFT); robbie.keyPress(KeyEvent.VK_F10); robbie.keyRelease(KeyEvent.VK_SHIFT); robbie.keyRelease(KeyEvent.VK_F10); robbie.keyPress(KeyEvent.VK_R); robbie.keyRelease(KeyEvent.VK_R); } Assuming you haven't changed the default hot key settings in Eclipse and import those java classes, this should work. A: BalusC answer didn't work for me (bash console on Ubuntu). Some stuff remained at the end of the line. So I rolled over again with spaces. Thread.sleep() is used in the below snippet so you can see what's happening. String foo = "the quick brown fox jumped over the fence"; System.out.printf(foo); try {Thread.sleep(1000);} catch (InterruptedException e) {} System.out.printf("%s", mul("\b", foo.length())); try {Thread.sleep(1000);} catch (InterruptedException e) {} System.out.printf("%s", mul(" ", foo.length())); try {Thread.sleep(1000);} catch (InterruptedException e) {} System.out.printf("%s", mul("\b", foo.length())); where mul is a simple method defined as: private static String mul(String s, int n) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < n ; i++) builder.append(s); return builder.toString(); } (Guava's Strings class also provides a similar repeat method) A: I have successfully used the following: @Before public void dontPrintExceptions() { // get rid of the stack trace prints for expected exceptions System.setErr(new PrintStream(new NullStream())); } NullStream lives in the import com.sun.tools.internal.xjc.util package so might not be available on all Java implementations, but it's just an OutputStream, should be simple enough to write your own. A: this solution is applicable if you want to remove some System.out.println() output. It restricts that output to print on console and print other outputs. PrintStream ps = System.out; System.setOut(new PrintStream(new OutputStream() { @Override public void write(int b) throws IOException {} })); System.out.println("It will not print"); //To again enable it. System.setOut(ps); System.out.println("It will print");
{ "language": "en", "url": "https://stackoverflow.com/questions/7522022", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "78" }
Q: How do I add a custom CHECK constraint on a MySQL table? I am having trouble with this table CREATE TABLE `Participants` ( `meetid` int(11) NOT NULL, `pid` varchar(15) NOT NULL, `status` char(1) DEFAULT NULL, PRIMARY KEY (`meetid`,`pid`), CONSTRAINT `participants_ibfk_1` FOREIGN KEY (`meetid`) REFERENCES `Meetings` (`meetid`) ON DELETE CASCADE CONSTRAINT `participants_ibfk_2` CHECK (status IN ('a','d','u')) CONSTRAINT `participants_ibfk_3` CHECK (pid IN (SELECT name FROM Rooms) OR pid IN (SELECT userid FROM People)) ); I want to have a foreign key constraint, and that works. Then, I also want to add a constraint to the attribute status so it can only take the values 'a', 'd' and 'u'. It is not possible for me to set the field as Enum or set. Can anyone tell me why this code does not work in MySQL? A: CHECK constraints are not supported by MySQL. You can define them, but they do nothing (as of MySQL 5.7). From the manual: The CHECK clause is parsed but ignored by all storage engines. The workaround is to create triggers, but they aren't the easiest thing to work with. If you want an open-source RDBMS that supports CHECK constraints, try PostgreSQL. It's actually a very good database. A: I don't understand why nobody here has mentioned that VIEW WITH CHECK OPTION can be a good alternative to the CHECK CONSTRAINT in MySQL: CREATE VIEW name_of_view AS SELECT * FROM your_table WHERE <condition> WITH [LOCAL | CASCADED] CHECK OPTION; There is a doc on the MySQL site: The View WITH CHECK OPTION Clause DROP TABLE `Participants`; CREATE TABLE `Participants` ( `meetid` int(11) NOT NULL, `pid` varchar(15) NOT NULL, `status` char(1) DEFAULT NULL check (status IN ('a','d','u')), PRIMARY KEY (`meetid`,`pid`) ); -- should work INSERT INTO `Participants` VALUES (1,1,'a'); -- should fail but doesn't because table check is not implemented in MySQL INSERT INTO `Participants` VALUES (2,1,'x'); DROP VIEW vParticipants; CREATE VIEW vParticipants AS SELECT * FROM Participants WHERE status IN ('a','d','u') WITH CHECK OPTION; -- should work INSERT INTO vParticipants VALUES (3,1,'a'); -- will fail because view uses a WITH CHECK OPTION INSERT INTO vParticipants VALUES (4,1,'x'); P.S.: Keep in mind that your view should be updatable! See MySQL Updatable Views (thanks Romeo Sierra for clarification in comments). A: Beside triggers, for simple constraints like the one you have: CONSTRAINT `participants_ibfk_2` CHECK status IN ('a','d','u') you could use a Foreign Key from status to a Reference table (ParticipantStatus with 3 rows: 'a','d','u' ): CONSTRAINT ParticipantStatus_Participant_fk FOREIGN KEY (status) REFERENCES ParticipantStatus(status) A: Starting with version 8.0.16, MySQL has added support for CHECK constraints: ALTER TABLE topic ADD CONSTRAINT post_content_check CHECK ( CASE WHEN DTYPE = 'Post' THEN CASE WHEN content IS NOT NULL THEN 1 ELSE 0 END ELSE 1 END = 1 ); ALTER TABLE topic ADD CONSTRAINT announcement_validUntil_check CHECK ( CASE WHEN DTYPE = 'Announcement' THEN CASE WHEN validUntil IS NOT NULL THEN 1 ELSE 0 END ELSE 1 END = 1 ); Previously, this was only available using BEFORE INSERT and BEFORE UPDATE triggers: CREATE TRIGGER post_content_check BEFORE INSERT ON topic FOR EACH ROW BEGIN IF NEW.DTYPE = 'Post' THEN IF NEW.content IS NULL THEN signal sqlstate '45000' set message_text = 'Post content cannot be NULL'; END IF; END IF; END; CREATE TRIGGER post_content_update_check BEFORE UPDATE ON topic FOR EACH ROW BEGIN IF NEW.DTYPE = 'Post' THEN IF NEW.content IS NULL THEN signal sqlstate '45000' set message_text = 'Post content cannot be NULL'; END IF; END IF; END; CREATE TRIGGER announcement_validUntil_check BEFORE INSERT ON topic FOR EACH ROW BEGIN IF NEW.DTYPE = 'Announcement' THEN IF NEW.validUntil IS NULL THEN signal sqlstate '45000' set message_text = 'Announcement validUntil cannot be NULL'; END IF; END IF; END; CREATE TRIGGER announcement_validUntil_update_check BEFORE UPDATE ON topic FOR EACH ROW BEGIN IF NEW.DTYPE = 'Announcement' THEN IF NEW.validUntil IS NULL THEN signal sqlstate '45000' set message_text = 'Announcement validUntil cannot be NULL'; END IF; END IF; END; A: Here is a way of getting the checks you wanted quickly and easily: drop database if exists gtest; create database if not exists gtest; use gtest; create table users ( user_id integer unsigned not null auto_increment primary key, username varchar(32) not null default '', password varchar(64) not null default '', unique key ix_username (username) ) Engine=InnoDB auto_increment 10001; create table owners ( owner_id integer unsigned not null auto_increment primary key, ownername varchar(32) not null default '', unique key ix_ownername (ownername) ) Engine=InnoDB auto_increment 5001; create table users_and_owners ( id integer unsigned not null primary key, name varchar(32) not null default '', unique key ix_name(name) ) Engine=InnoDB; create table p_status ( a_status char(1) not null primary key ) Engine=InnoDB; create table people ( person_id integer unsigned not null auto_increment primary key, pid integer unsigned not null, name varchar(32) not null default '', status char(1) not null, unique key ix_name (name), foreign key people_ibfk_001 (pid) references users_and_owners(id), foreign key people_ibfk_002 (status) references p_status (a_status) ) Engine=InnoDB; create or replace view vw_users_and_owners as select user_id id, username name from users union select owner_id id, ownername name from owners order by id asc ; create trigger newUser after insert on users for each row replace into users_and_owners select * from vw_users_and_owners; create trigger newOwner after insert on owners for each row replace into users_and_owners select * from vw_users_and_owners; insert into users ( username, password ) values ( 'fred Smith', password('fredSmith')), ( 'jack Sparrow', password('jackSparrow')), ( 'Jim Beam', password('JimBeam')), ( 'Ted Turner', password('TedTurner')) ; insert into owners ( ownername ) values ( 'Tom Jones'),( 'Elvis Presley'),('Wally Lewis'),('Ted Turner'); insert into people (pid, name, status) values ( 5001, 'Tom Jones', 1),(10002,'jack Sparrow',1),(5002,'Elvis Presley',1);
{ "language": "en", "url": "https://stackoverflow.com/questions/7522026", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "41" }
Q: Node.js/Express form post req.body not working I'm using express and having trouble getting form data from the bodyParser. No matter what I do it always comes up as an empty object. Here is my express generated app.js code (the only thing I added was the app.post route at the bottom): var express = require('express'); var app = module.exports = express.createServer(); // Configuration app.configure(function(){ app.set('views', __dirname + '/views'); app.set('view engine', 'jade'); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(app.router); app.use(express.static(__dirname + '/public')); }); app.configure('development', function(){ app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); }); app.configure('production', function(){ app.use(express.errorHandler()); }); // Routes app.get('/', function(req, res){ res.sendfile('./public/index.html'); }); app.post('/', function(req, res){ console.log(req.body); res.sendfile('./public/index.html'); }); app.listen(3010); Here is my HTML form: <!doctype html> <html> <body> <form id="myform" action="/" method="post" enctype="application/x-www-form-urlencoded"> <input type="text" id="mytext" /> <input type="submit" id="mysubmit" /> </form> </body> </html> When I submit the form, req.body is an empty object {} Its worth noting that this happens even if I remove the enctype attribute from the form tag ...Is there something I am missing/doing wrong? I am using node v0.4.11 and express v2.4.6 A: <form id="myform" action="/" method="post" enctype="application/x-www-form-urlencoded"> <input type="text" name="I_appear_in_req_body" id="mytext" /> <input type="submit" id="mysubmit" /> </form> The body of a HTTP post is a key/value hash of all the form controls with a name attribute, and the value is the value of the control. You need to give names to all your inputs. A: It also due to content type. please see console.log(req) object. 'content-type': 'application/json; charset=UTF-8’ // valid. 'content-type': 'application/JSON; charset=UTF-8’ // invalid & req.body would empty object {}. To check content type by console.log(req.is('json')) // return true/false I think 'charset=UTF-8' is negligible in above. A: If your form looks like this <form action="/", method="post"> <label for="for_name">Name: </label> <input id="for_name" type="text" name="user_name"/> <button type="submit">Submit</button> </form> And if you are using the following line of code app.use(express.json()); then the req.body will be empty because it only parses req with content-type application/json but the default value of request originating from element is application/x-www-form-urlencoded. Hence the following line of code will solve the issue app.use(express.urlencoded({ extended: true })); My first StackOverflow contribution. Yay!!
{ "language": "en", "url": "https://stackoverflow.com/questions/7522034", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "29" }
Q: How can I send email asynchronously from a MVC 3 application? In my MVC 3 Razor application, an ActionResult Create() method in the Controller handles a user HttpPost. At that point: * *Data is saved to a database. *Emails are sent to interested parties using another project in the solution. *A Confirmation page is served back to the user. Since emailing is the most time-consuming activity, I'm attempting to use SmtpClient.SendAsync(), rather than SmtpClient().Send. Is this scenario possible if inheritance is from AsyncController? Can anyone provide an example? Thanks, Arnold A: You should definitely check out MVC Mailer. Very nice tool to create emails with razor views. It has an option to send mails asynchronously. MVC mailer is also available via nuget.
{ "language": "en", "url": "https://stackoverflow.com/questions/7522035", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Google Custom Search - Refinements I have a Google Custom Search I'm using for a site I'm working on (the search is restricted to this one site). As part of the results you can specify "refinements". These refinements appear as tabs but I want them to appear as links. I do not see anyway to control this nor do I find anything in the docs about how to control this. Anyone have any experience with this? On Google's own examples they appear as links, like so: http://code.google.com/intl/en/apis/customsearch/images/refine_treatment.png However all I can get are tabs, like so: http://2.bp.blogspot.com/_HUb2ygrQR50/TCHcpRiZS8I/AAAAAAAAEPc/m9R1yA2lZaw/s1600/SupportLineRefinement.png How can I control this? A: Actually, I do not think it is possible to do this. I think the tabs are your only option. A: The reason why you see links in the google example, is because it's the old version, similar to the iframe option. You're using the new search element. As far as making them into links, not hard to do using some CSS with !important, to make them look like links.
{ "language": "en", "url": "https://stackoverflow.com/questions/7522037", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Viewing the updated HTML in ie6 I am working with ie6 (unfortunately) and i am having a javascript error. Its wondrous error message gives me a line in the html source, but unfortunately the javascript that does run changes the code for the page(dramatically). So the error that its pointing me to is a closing div tag, not actual code. Is there a way to view the updated code for the page so I can at least know where my code is breaking? I should also point out what im developing in. I am developing a sharepoint 2007 solution for an winxp and ie6 user base. I am working via remote desktop on a sandbox winserver 2008 r2 and can access the site from my terminal. Now, unfortunately in my sandbox server i have ie 8 in which my code works. So im stuck on ideas. If anyone knows how to view the updated source on the page, i would be very grateful. Thanks. Edit. I should also mention i dont have admin access on my terminal. So i cant install visual studio. It would take a couple weeks for an issue ticket for temp admin access to install it, and this is sort of important. A: If you can't install anything and the error console information isn't meaningful, then about all you can do is start modifying your code until you can find which section is causing the error. The kinds of modifications you can do are as follows: * *Comment out a chunk of code in a way that won't cause more errors. If the error goes away, then you know it's in that block of code or something that code calls. Put that block back in and then comment out a piece of it and so on until you narrow down where the problem is. *Start inserting alert("1"), alert("2") prompts into your code with the goal of identifying which alert the error comes before and after until you've eventually tracked down where it is. When you rule out an area, remove the alerts to make it feasible to still run the app. *On a more modern computer (e.g. Vista/Win7) go to Microsoft's site and download both Microsoft Virtual PC and the Windows image for XP with IE6. You can then actually install things into the VM and do real IE6 debugging or at least see what the actual error is. *Find a computer with XP/IE6 on it that you can install real debugging tools on. *Build your own dummy little debug window using a textarea and a couple functions that append text to it. Put that into your browser page and start sprinkling mydebug("Entering function foo") statements throughout your code so you can narrow down which statements occur before and after the error and eventually find the error. This is how I've done some IE6 debugging when it was't worth the trouble of setting up a full-blown debug environment for IE6. This works much better than alerts for some types of problems because it doesn't interrupt the flow of the app or require lots of user intervention and you can scroll back through the history. A: If you are using visual studio you can use it to debug js errors in ie. Go to the Advanced Internet settings in ie and make sure that the two Disable script debugging settings are turned off (so that script debugging is enabled) and that the setting display a notification on every script error is enabled. If you don't have visual studio installed you can download and install microsofts script debugger (it's free just google it) and use that, tho it is not as easy to work with and won't give you as much useful information
{ "language": "en", "url": "https://stackoverflow.com/questions/7522039", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: invalid validators in Symfony - sfForkedApplyPlugin public function configure() { parent::configure(); $email = $this->getWidget('email'); $class = get_class($email); $this->setWidget('email2', new $class( array(), array('maxlength' => $email->getAttribute('maxlength') ) ) ); $this->widgetSchema->moveField( 'email2', sfWidgetFormSchema::AFTER, 'email' ); $this->widgetSchema->setNameFormat('sfApplyApply[%s]'); $this->widgetSchema->setFormFormatterName('list'); $this->setValidator('email', new sfValidatorAnd( array( new sfValidatorEmail( array('required' => true, 'trim' => true) ), new sfValidatorString( array('required' => true, 'max_length' => 80) ), new sfValidatorDoctrineUnique( array( 'model' => 'sfGuardUserProfile', 'column' => 'email'), array('invalid' => 'An account with that email address already exists. If you have forgotten your password, click "cancel", then "Reset My Password."') ) ))); $this->setValidator('email2', new sfValidatorEmail( array( 'required' => true, 'trim' => true ))); $schema = $this->validatorSchema; // Hey Fabien, adding more postvalidators is kinda verbose! $postValidator = $schema->getPostValidator(); $postValidators = array( new sfValidatorSchemaCompare( 'password', sfValidatorSchemaCompare::EQUAL, 'password2', array(), array('invalid' => 'The passwords did not match.') ), new sfValidatorSchemaCompare( 'email', sfValidatorSchemaCompare::EQUAL, 'email2', array(), array('invalid' => 'The email addresses did not match.') ) ); if( $postValidator ) { $postValidators[] = $postValidator; } $this->validatorSchema->setPostValidator( new sfValidatorAnd($postValidators) ); } } why if is in database another user with same email then i have two error - first with this information, and second - The emails did not match. how can i fix it?
{ "language": "en", "url": "https://stackoverflow.com/questions/7522042", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Unique jQuery click issue - stops firing after first click on same element I'm experiencing a fairly unique problem that I have not see any information on... anywhere. It seems that the click event breaks down on an element after the first click (not always on the second, there doesn't seem to be any consistency – other than the first click always fires) – once the click event stops working it requires two clicks (not a double click) for the click event to fire. Here are some specifics: on page load, I am parsing through a JSON string to populate X dynamically generated lists to be used similar to a dropdown menu. In the code, immediately after each “dropdown menu” is generated and displayed on the screen, I apply a .click(function(){... Here is the suspect script the variable “tags” represents an Object that is basically a collection of dropdown menus. $.each(tags, function(k, v){ v.display('div#tags'); var selector = '#' + v.getId(); if(v.isTabled()){ selector += ' tr.Option td'; }else{ selector += ' .Option'; } var narrowedProducts = []; $(selector).click(function(){ $.each($('div.Select'), function(i,e){ var temp = $(this).children('input').attr('value'); narrowedProducts = Row.narrowProducts(temp.split('-'), narrowedProducts); }); if(narrowedProducts.length === 1){ $('input#THEPRODUCT') .attr('name', narrowedProducts[0]) .attr('value', narrowedProducts[0]) }else if(narrowedProducts.length === 0){ $('input#THEPRODUCT') .removeAttr('name') .removeAttr('value') }else{} narrowedProducts = []; return; }); }); and the html for the dropdowns... <div id="tags"> <input type="input" id="THEPRODUCT" /> <div class="Select Select-sizechart" id="sizechart"> <span class="Display">Select a sizechart:</span><input type="hidden" name= "sizechart" /> <table class="Selectable"> <tbody> <tr class="TableHeading"> <th>Size</th> <th>Comparable Size</th> <th>Bust</th> <th>Hip</th> <th>Back Length</th> </tr> <tr class="Option" rel="L" id="68435-68414-68416-68423"> <td>L</td> <td>16-18</td> <td>43"-45"</td> <td>45"-47"</td> <td>43"</td> </tr> <tr class="Option" rel="XL" id="68432-68437-68419-68428"> <td>XL</td> <td>20-22</td> <td>47"-49"</td> <td>49"-51"</td> <td>44"</td> </tr> <tr class="Option" rel="S" id="68433-68420-68425-68431"> <td>S</td> <td>8-10</td> <td>36"-37"</td> <td>38"-39"</td> <td>41"</td> </tr> <tr class="Option" rel="XS" id="68436-68417-68424-68429"> <td>XS</td> <td>4-6</td> <td>34"-35</td> <td>36"-37"</td> <td>40"</td> </tr> <tr class="Option" rel="M" id="68415-68418-68421-68427"> <td>M</td> <td>12-14</td> <td>38.5"-40.5"</td> <td>40.5"-42.5"</td> <td>42"</td> </tr> </tbody> </table> </div> <div class="Select Select-color" id="color"> <span class="Display">Select a color:</span><input type="hidden" name="color" /> <div class="Selectable"> <div class="Option" rel="River" id="68435-68418-68420-68424-68428"> River </div> <div class="Option" rel="Smoke" id="68432-68433-68414-68415-68417"> Smoke </div> <div class="Option" rel="Punch" id="68436-68419-68423-68427-68431"> Punch </div> <div class="Option" rel="Sandstone" id="68437-68416-68421-68425-68429"> Sandstone </div> </div> </div> </div> Does anyone have any clue how to solve this to create a better user experience? I looked into delegate (and live), but unfortunately I'm tied to using version 1.3.2 for reason outside of my control. Any other suggestions? A: I can't tell you why the problem occurs, but if i was you, I'd would look into using a delegated click handler instead of binding the same click function to all these elements. Try to read up on http://api.jquery.com/delegate/ - it might just solve your problem, or at least make your code perform better ;)
{ "language": "en", "url": "https://stackoverflow.com/questions/7522049", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Alternative to jQuery append() When adding text to an element, jQuery's append() function adds quotation marks around text. I want to change that, and instead separate values by comma or whatever I come up with. Is there an alternative to append() that will do that ? To give it some context, I'm using jQuery to dynamically write to a hidden <input> element. Currently after a few additions (using append) the resulting HTML looks like this: <input type="hidden">"first" "second" "third" </input> In an ideal world, the HTML should come out looking like this: <input type="hidden">first, second, third</input> Using jQuery to read, concatenate, and then replace the original <input> text might work, but I don't see a function that will do a wholesale replace of innerHTML (I'm assuing it's called that). Thoughts ? A: in jquery: <div id="test"></div> $('#test').append('a'); $('#test').append('b'); will look like this (in chrome dev tool): <div id="test"> "a" "b" </div> while <div id="test"></div> $('#test').html($('#test').html() + 'a'); $('#test').html($('#test').html() + 'b'); will look like this: <div id="test">ab</div> the dom tree in both cases is the same, only it shows it in chrome dev tool with the quotes (they are not really there, right click -> edit as html and they will disappear) A: The big problem here is that input values are set in the value attribute, not as an inner child: <input type="hidden" id="myInput" name="myInput" value="first"> To do what you seem to want, you'd probably want to change the value of the input with .val(): $('#myInput').val($('#myInput').val() + ', second'); A: Alternatively you could append text to a hidden span: <style> #hidden { display:none; } </style> <span id="hidden"></span> <script> var x; // Where 'x' is the data that you would like to append. $('#hidden').append(x); </script> A: (function($) { $.fn.iappend = function(str) { return this.each(function(){ var $this = $(this); if($this.val().length > 0) { $this.val($this.val() + "," + str); } else { $this.val($this.val() + str); } }); }; })(jQuery); I haven't fully tested it yet.. but it should work.. $("#hidden").iappend("first").iappend("second").iappend("third"); output Hello,World,!
{ "language": "en", "url": "https://stackoverflow.com/questions/7522052", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to access Repeater FooterTemplate TextBox? * *What I am trying to do is to access the value from the TextBox1 to display back on the screen. *I tried to access it from the Page_Load() and the OnItemDataBound and they both failed. *It seem like the code is able to access the control but it return nothing back. protected void Page_Load(object sender, EventArgs e) { Literal Literal1 = (Literal)Repeater1.Controls[Repeater1.Controls.Count - 1].FindControl("Literal1"); Response.Write(Literal1.Text); //this techique is not working for the line below TextBox TextBox1 = (TextBox)Repeater1.Controls[Repeater1.Controls.Count - 1].FindControl("TextBox1"); Response.Write(TextBox1.Text); } public void myRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e) { //this techique is not working if (e.Item.ItemType == ListItemType.Footer) { TextBox TextBox1 = (TextBox)e.Item.FindControl("TextBox1"); Response.Write(TextBox1.Text); } } A: I'm not sure what you mean by "they both failed" but if the Text property of the Textbox is empty i might be because you are rebinding your repeater on each post back. Try wrapping your repeater .DataBind() with a !IsPostBack condition. A: I have to use "Literal" as an alternate solution by passing the html Textbox problem. I do not like this solution but i guess i have to use it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7522056", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Setting a java ProcessBuilder environment with a bash script I've been using ProcessBuilder to successfully invoke a process with various environment variables using env.put("VAR","value"). Now I'd like to source some bash scripts to set a whole bunch of environment variables that are not predetermined within java. Anyone know of an easy way to do this? A: bash supports the environment variable BASH_ENV on startup. Set the variable to your script and its contents will be sourced before execution. See bash(1) for details. A: If your "batch scripts" to be sourced are in properties format, you can always load them using Properties and merge into the env.
{ "language": "en", "url": "https://stackoverflow.com/questions/7522057", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: When not to use MPI This is not a question on specific technical coding aspect of MPI. I am NEW to MPI, and not wanting to make a fool of myself of using the library in a wrong way, thus posting the question here. As far as I understand, MPI is a environment for building parallel application on a distributed memory model. I have a system that's interconnected with Infiniband, for the sole purpose of doing some very time consuming operations. I've already broke out the algorithm to do it in parallel, so I am really only using MPI to transmit data (results of the intermediate steps) between multiple nodes over Infiniband, which I believe one can simply use OpenIB to do. Am I using MPI the right way? Or am I bending the original intention of the system? A: Its fine to use just MPI_Send & MPI_Recv in your algorithm. As your algorithm evolves, you gain more experience, etc. you may find use for the more "advanced" MPI features such as barrier & collective communication such as Gather, Reduce, etc. A: The fewer and simpler the MPI constructs you need to use to get your work done, the better MPI is a match to your problem -- you can say that about most libraries and lanaguages, as a practical matter and argualbly an matter of abstractions. Yes, you could write raw OpenIB calls to do your work too, but what happens when you need to move to an ethernet cluster, or huge shared-memory machine, or whatever the next big interconnect is? MPI is middleware, and as such, one of its big selling points is that you don't have to spend time writing network-level code. A: At the other end of the complexity spectrum, the time not to use MPI is when your problem or solution technique presents enough dynamism that MPI usage (most specifically, its process model) is a hindrance. A system like Charm++ (disclosure: I'm a developer of Charm++) lets you do problem decomposition in terms of finer grained units, and its runtime system manages the distribution of those units to processors to ensure load balance, and keeps track of where they are to direct communication appropriately. Another not-uncommon issue is dynamic data access patterns, where something like Global Arrays or a PGAS language would be much easier to code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7522058", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: LongClickListener on ListView I have a ListView and want to get the long-click events on the ListView itself, not on the individual items in the ListView. I believe it should be as straight forward as just called ListView.setOnLongClickListener(View.OnLongClickListener). However, for me, it seems to do nothing at all. I'm just wondering if anyone else has the same issue with all ListViews or it just me and my implementation of the ListView made this not work. I referred to this answer and tried using ListView.setLongClickable(true) but it still didn't work. A: It might be easier to define a separate TextView in the parent layout, with id attribute to be android:id="@+id/android:empty" which would be displayed if there are no elements in the ListView, saying something like "--List is empty--", and that being long-clickable. You can easily manipulate the Click for the respective TextView. In cases where the ListView ought to be long clickable, you can leave a small gap on the parent view, and set the parent view as Long clickable, rather than the ListView.
{ "language": "en", "url": "https://stackoverflow.com/questions/7522060", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Django: Shopping site similar to eBay I need to build a site similar to ebay. I've found some "e-commerce" packages for Django but those are not related to the "C2C" model from eBay. I've tried these: https://www.django-shop.org/ http://www.satchmoproject.com/ Do you know any app (package, framework) that can deal with it? Thank you very much! A: While this is a frequently asked-for application, it doesn't appear as if anyone has actually implemented it. It doesn't seem like that hard a project. You would need a Profile app to track the user's reputation, a messaging app (easily available), a Products app (users offer products, users bid on products, at a given time the bidding is closed, etc...). A weekend for the basics, I think. Rip the Hell out of Satchmo for your transaction handling, and get a real authorization account through Authorize.NET, not some Google Checkout or Paypal thingy. You'd be on the hook for one big fraud risk, though, which is why auction sites are generally for the Big Kids. A: Here is a near similar solution for you: Collector City Marketplace
{ "language": "en", "url": "https://stackoverflow.com/questions/7522062", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Xcode code documentation Are there any guidelines/standards about how to document the code written in XCode? I mean, is there a way to document the code if you want to make it easily understandable to others? Does XCode provide an instrument that can be used to automatically produce documentation like the API reference docs from your code+comments? At least I'm interested in understanding if there is a standard way of writing comments before interfaces/protocols/methods defined in your code. I've seen using directives like the following one, but I did not understand how they work: #pragma mark - #pragma mark Initialization A: You can merge those two lines in one: #pragma mark - Initialization. Click on the method list (up, right) and you'll see a bold header with a line. It's just a marker to group methods in sections. The Coding Guidelines link posted by Derek above is a must read. If you want to produce Apple-like documentation you have to use this excellent and free third party tool: http://www.gentlebytes.com/appledoc/ Apple doesn't provide you with anything close to that. Pragmas are a ISO C feature to pass hints to the compiler. The only pragma addition in XCode (AFAIK) is mark with - and/or text. This creates a line and/or bold text in the method finder. // Mark a section in your code with a line and a bold text. // You can use the line or the text alone. #pragma mark - random text If you are editing files on languages which don't compile with GCC, you still can use mark on comments (this works for GCC languages too): // MARK: - random text /* MARK: more random text */ But I use #pragma mark because my color theme has pragmas in red and they stand out better than comments. If you want a pragma code snippet binded to a hotkey, use #pragma mark - <#Description#> so you can tab jump to the description text. More about pragmas: * *What is a pragma? *6.56 Pragmas Accepted by GCC *Clang's Controlling Diagnostics via Pragmas *Function attributes are preferred to pragmas because you can't generate pragmas from macros and a pragma might have a different meaning on another compiler. A: Adding to @jano's answer, use below format to describe the functionality of your method. /*! @function getEmployeeDetails @abstract getEmployeeDetails @discussion This function will fetch employee details based on employee id @param strEmpId employee unique id @result an Array of Employee */ -(NSArray*)getEmployeeDetails:(NSString *)strEmpId{ /*Do somethings.*/ }
{ "language": "en", "url": "https://stackoverflow.com/questions/7522076", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Variable not available outside FOR loop I need to get the first and last date of the previous week. I use the code below and it works fine UNTIL I try to read the variable outside of the loop. <?php $current_week = date(W); $previous_week = $current_week - 1; $year = date(o); for($day=1; $day<=7; $day++) { $temp = array ($day => date('Y-m-d', strtotime($year."W".$previous_week.$day)) . ' 00:00:00'); $firstday = $temp[1]; // echo here works fine echo $firstday; } // echo here doesnt work anymore echo $firstday; ?> I really have no idea why this is not working. I've read through the PHP docs and everything tells me it should work.. I'm no wizz at all and I'm really confused now. Can anybody shine some light on this? Thanks in advance! A: You're overwriting the $firstday variabile in following iterations of the loop, so at the end it contains null. If you turn on error reporting you'll see the notices generate from iterations with $i > 1, when accessing $temp[1] You should always turn on error reporting when developing and when learning, and you should (or better must) solve all warning before releasing your code. Here are the warning in your script with error_reporting set to E_ALL: > php /tmp/foo.php 2>&1 | grep Notice PHP Notice: Use of undefined constant W - assumed 'W' in /private/tmp/foo.php on line 3 Notice: Use of undefined constant W - assumed 'W' in /private/tmp/foo.php on line 3 PHP Notice: Use of undefined constant o - assumed 'o' in /private/tmp/foo.php on line 5 Notice: Use of undefined constant o - assumed 'o' in /private/tmp/foo.php on line 5 2011-09-12 00:00:00PHP Notice: Undefined offset: 1 in /private/tmp/foo.php on line 8 Notice: Undefined offset: 1 in /private/tmp/foo.php on line 8 PHP Notice: Undefined offset: 1 in /private/tmp/foo.php on line 8 Notice: Undefined offset: 1 in /private/tmp/foo.php on line 8 PHP Notice: Undefined offset: 1 in /private/tmp/foo.php on line 8 Notice: Undefined offset: 1 in /private/tmp/foo.php on line 8 PHP Notice: Undefined offset: 1 in /private/tmp/foo.php on line 8 Notice: Undefined offset: 1 in /private/tmp/foo.php on line 8 PHP Notice: Undefined offset: 1 in /private/tmp/foo.php on line 8 Notice: Undefined offset: 1 in /private/tmp/foo.php on line 8 PHP Notice: Undefined offset: 1 in /private/tmp/foo.php on line 8 Notice: Undefined offset: 1 in /private/tmp/foo.php on line 8 A: $firstDay is being reused and overwritten: <?php $current_week = date(W); $previous_week = $current_week - 1; $year = date(o); for($day=1; $day<=7; $day++) { $temp = array ($day => date('Y-m-d', strtotime($year."W".$previous_week.$day)) . ' 00:00:00'); $firstday = $temp[1]; // echo here works fine echo "Inloop - ".$firstday."\n"; } // echo here doesnt work anymore echo "After loop - ".$firstday."\n"; ?> Results: Inloop - 2011-09-12 00:00:00 Inloop - Inloop - Inloop - Inloop - Inloop - Inloop - After loop - Hope this helps
{ "language": "en", "url": "https://stackoverflow.com/questions/7522078", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android: Unable to restart an ListActivity First post, so please go easy. I have an app with a handful of tabs, the first is opened on running the app. One of the tabs is 'My Account' (a ListActivity) showing account options. I switch to this and if the user is not logged in, it, in turn, runs a UserLogon activity using the following: Intent logonActivity = new Intent(getBaseContext(), UserLogon.class); startActivityForResult(logonActivity, 0); To catch the result, I use the following code: protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(requestCode == 0){ MainBlock ta = (MainBlock) this.getParent(); TabHost th = ta.getMyTabHost(); th.setCurrentTab(0); finish(); } if (requestCode == 100) { showAccountOptions(); } } In the UserLogon class, I have the usual fare; TextView's and Button's. The intention is that if the user cancels the login, it will revert to the initial tab, or if login is successful, it will show the Account Options. And this is indeed what does happen. All good so far. The problem I'm having is that if I cancel the login and return to the first tab, when I select the Accounts tab again, I'm not presented with the UserLogon activity. I was under the impression that finish() would close the UserLogon activity, and the Accounts activity but it would appear not. So, my question is simply, how do I, in effect, restart the Accounts activity so that the user would be presented with the option to login once more. A: We're good people and all willing to help ;-) I'll give it a shot. Still, I'm not quite sure I get that all right. Basically you have an TabActivity which you setup and where you do something like that: myTabHost.setOnTabChangedListener(new OnTabChangeListener(){ @Override public void onTabChanged(String tabId) { if (tabId.equals("account") && !loggedIn) { Intent logonActivity = new Intent(getBaseContext(), UserLogon.class); startActivityForResult(logonActivity, 0); } }}); You're basically saying that the first Activity start of UserLogon works, but the second one doesn't, right? Did you debugged to that point to check whether you reach the code which starts the activity again? Update based on comment Your UserLogon should always provide a result information, here's a blueprint: public class UserLogon extends Activity { public void onCreate(Bundle bundle) { // ... do something ... // if activity is canceled this will be the "last" result setResult(RESULT_CANCELED); } public void checkLoginOrSomethingLikeThat() { Intent result = new Intent(); // put your results in this intent setResult(RESULT_OK, intent); // close activity since we have the information we need finish(); } } The parent activity which is waiting for the result should do it like that: protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // it's good practice to use a constant for 0 like LOGIN_REQUEST // otherwise you will ask yourself later "What the hell did 0 stand for?" if(requestCode == 0){ if (resultCode == RESULT_OK) { // get needed data from data intent and react on that } else { // no success, react on that } } // ... I don't know what your resultCode 100 is but handle itwith the same pattern }
{ "language": "en", "url": "https://stackoverflow.com/questions/7522079", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Prawnto won't display pdf inline I'm trying to use prawn and prawnto (both installed via gems) in order to generate pdf's for my app. I want the pdf to display in the browser, but it won't, it automatically downloads instead. I have the following prawnto options in my controller: prawnto :inline => true, :filename => "results.pdf", :prawn => {:top_margin => 75} The filename and margin arguments both work, but the document won't display inline. I'm pretty sure this is a prawnto issue and not a prawn issue. The prawn gem seems pretty old. Someone has created a new gem (prawnto_2) to update for rails 3.1, but I'm still using rails 3.0.7. Has anyone else had this issue? How can I get prawnto to show the pdf inline (ideally in a new tab or window)? A: The :inline option uses the Content-Disposition HTTP header, which relies on a browser plugin to interpret the content. This means that the results can vary depending on the browser/OS combination you're using, Linux especially doesn't seem very good at handling this. A: @benoit Linux / Mozilla and Opera both open all pdfs on websites I visit - except on my site using this method. I get "open in application" or "save" as the only choices - it will not render inline.
{ "language": "en", "url": "https://stackoverflow.com/questions/7522080", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Do i need to release NSMutableDictionary in this case? Do I need to release dictCellCollectionIndividual in this case? - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { ... ... ... ... ... ... // Local declaration of dictCellCollectionIndividual NSMutableDictionary *dictCellCollectionIndividual; // Copy the specific dictionary from dictCellCollection to dictCellCollectionIndividual. dict CellCollection is declared elsewhere. dictCellCollectionIndividual = [dictCellCollection objectForKey:[NSString stringWithFormat:@"%@", [arrayCellCollectionOrder objectAtIndex:indexPath.row]]]; ... ... ... ... ... ... // Do I need to release? [dictCellCollectionIndividual release]; return cell; } Doesn't using objectForKey increase the retain count? Don't I have to release it? Thanks in advance. A: No, it simply returns a pointer to the object held within the dictionary; if you plan to keep the object around for any period of time, you need to take ownership of it, so that the object will remain valid if NSDictionary is deallocated in the meantime. In this case, you'll need to make sure to either release or autorelease the object when you're done with it. If you're planning to use it only as a temporary value (say, as an argument to an NSLog call), it's probably unnecessary to retain the object, and therefore unnecessary to release it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7522081", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: com.sun.java.accessibility.util package doesnt exists I am trying to import com.sun.java.accessibility.util.*; but Netbeans IDE says package doesn't exist. I have a folder with .class files which I add to the netbeans library and still doesn't work. I try to look for this package online but I am not able to find it. When typing import com. I get sun as an option, then I get java as an option but I don't get accessibility after. Even if i just do com.sun.java.*; Com will be shown as an error. If i follow netbeans suggestions, it will also be an error with the com. Thanks for the help (I need it to use TopLevelWindowListener, GUIInitializedListener) ANSWER Okay, not sure this is the RIGHT answer but its an answer. I uninstall java, java jdk, netbeans, and then restarted my computer. Download jdk, install, java and netbeans and now it works. Ask me why, I dont know. Thats another Question
{ "language": "en", "url": "https://stackoverflow.com/questions/7522083", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to save a json-object in an array? is there a possibility to convert a json-object to a array or something? i like to have a function, which is retrieving data from a sqldatabase via json: jQuery.getJSON("file.php", function(data) { ... }); this data should be stored in an array, so that i can use it on several positions in the website A: If you just want to wrap the json object in an existing array, then use the push() method of the array in question, passing the object as the parameter. A: If your file.php script returns the appropriate data type for it's response, then the data argument will already contained parsed JSON (e.g. in live javascript variable form). If you don't like the form that the data is in and you want to convert it to an array from something else, you would have to show us what format it's in so we can advise on code to convert it to some other form. If you just want to store the data in a variable so you can use it elsewhere, then you can do that by storing it in a global variable: var fileData; jQuery.getJSON("file.php", function(data) { fileData = data; // call any functions here that might want to process this data as soon as it's ready }); The data is now in a global variable named fileData that you can use anywhere on your page. Keep in mind that a getJSON call is asychronous so it might take a little while to complete and the data won't be available in your variable until the getJSON callback is called. If you were calling this multiple times and wanted to collect each response, you could collect them into an array like this: var fileData = []; // declare empty array jQuery.getJSON("file.php", function(data) { fileData.push(data); // add onto the end of the array // call any functions here that might want to process this data as soon as it's ready });
{ "language": "en", "url": "https://stackoverflow.com/questions/7522087", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: PHP web service, send response before end of script execution I have a web service written in PHP to which an iPhone app connects to. When the app calls the service, a series of notification messages are sent to Apple's APNs server so it can then send Push Notifications to other users of the app. This process can be time consuming in some cases and my app has to wait a long time before getting a response. The response is totally independent of the result of the notification messages being sent to the APNs server. Therefore, I would like the web service to send the response back to the app regardless of whether the messages to APNs have been sent. I tried using pcntl_fork to solve the problem: <?php ... $pid = pcntl_fork(); if($pid == -1) { // Could not fork (send response anyway) echo "response"; } else if($pid) { // Parent process - send response to app echo "response"; } else { // Child process - send messages to APNs then die sendMessageAPNs($token_array); die(); } ?> // end of script Unfortunately, the parent process seems to wait for the child process to end before sending the response even though I do not use pcntl_wait in the parent process. Am I doing something wrong or is this normal behaviour? If this is normal then is there another way I can solve this problem? Thank you! A: I think you can send the response back before doing the "long" process. Take a look at the flush() function of PHP it'll maybe help A: If you're hosting the PHP process in Apache then you really shouldn't use this: see this for the section that says *Process Control should not be enabled within a web server environment and unexpected results may happen if any Process Control functions are used within a web server environment. *. You should probably set up a separate daemon in your preferred language of choice and hand the APNS communication tasks off to that. If you really really really must try using ob_flush().
{ "language": "en", "url": "https://stackoverflow.com/questions/7522090", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ASP.NET, C#, IIS, Start Up I am a total Noob to to .NET. I have all my files, folders, master pages, and code behind pages in my directory... I have been building it on a local development environment that was set up by the person who was here before me. I do not know much about what the specs of the environment are. I just tried transferring all of my files over to the server we will be running off of and I am getting a "500 - Internal server error"... I am thinking I am missing something real basic. What can I do with my Web.config file to get rid of this error and make the page viewable? I know the 500 error is very common and could mean alot of things, but just the most basic problem, what are you thinking? Thanks, Chris A: Your first step should be to check the Event Viewer on the server. You'll get more detailed errors in there, than the generic 500 error returned to the browser. However, some guesses include... * *IIS is not configured to run .NET at all... *IIS is configured to run the wrong version of .NET. (may be set to 2.0 and your app is 4.0, for example.) *Actual errors in your code. (Trying to read from a database without opening a connection, or any one of a million possible errors. At any rate, the event log should have errors thrown either by IIS or by ASP.NET. Start there.
{ "language": "en", "url": "https://stackoverflow.com/questions/7522093", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Change Gridview column width dynamically I am trying to change the size of the items within my GridView. Currently the items are arranged by style (GridView_words_small) in an xml: numColumns: auto_fit stetchMode: 'spacingWidth' ColumnWidth: width of the items being added (resource). Now, through a settings change, the buttonsize can be changed. However, when I setColumnWidth() and invalidate(), no items are displayed (leaving the area blank.) Does anyone know how to properly change gridview column widths dynamically?
{ "language": "en", "url": "https://stackoverflow.com/questions/7522094", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Creating search query in MSACCESS I created three table in MSAccess (PCH Info, Attorney zip-county, Medical-zip code-county). Each table have similar field of zip code, city and county. My Goal is to search for either of the zip code, city and county in the 3 table and return result meeting either one or 2 of the search criteria. I ve already created 3 search field and build my query using UNION on the three table. But my problem is if I search specifically for a data it returns the results with other results which doesnt meet the criteria. See code below SELECT [PCH Info].City, [PCH Info].[Zip Code], [PCH Info].County, "PCH Info" FROM [PCH Info] WHERE (([PCH Info].City) Like Forms!Search.qcity & "*") And (([PCH Info].[Zip Code]) Like Forms!Search.qcode & "*") And (([PCH Info].County) Like Forms!Search.qcounty & "*") OR (([PCH Info].[Network Member]) = Yes) UNION SELECT [Medical-Zip Code-County].City, [Medical-Zip Code-County].[ZIP Code], [Medical-Zip Code-County].County , "Medical-Zip Code-County" FROM [Medical-Zip Code-County] WHERE (([Medical-Zip Code-County].City) Like Forms!Search.qcity & "*") And (([Medical-Zip Code-County].[ZIP Code]) Like Forms!Search.qcode & "*") And (([Medical-Zip Code-County].County) Like Forms!Search.qcounty & "*") UNION SELECT [Attorney-Zip-County].City, [Attorney-Zip-County].[ZIP Code], [Attorney-Zip-County].[Country/Region], "Attorney-Zip-County" FROM [Attorney-Zip-County] WHERE (([Attorney-Zip-County].City) Like Forms!Search.qcity & "*") And (([Attorney-Zip-County].[ZIP Code]) Like Forms!Search.qcode & "*") And (([Attorney-Zip-County].[Country/Region]) Like Forms!Search.qcounty & "*"); My major challenge comes from the first query where PCH Info.Network Member = Yes, if i do a search to meet this criteria, it still give me results which does meet the criteria. What could I be doing wrong or is the UNION query the problem? thank you. A: How about: SELECT City, [ZIP Code], County, Source, [Network Member] FROM ( SELECT p.City, p.[Zip Code], p.County, "PCH Info" As Source, p.[Network Member] FROM [PCH Info] p UNION ALL SELECT m.City, m.[ZIP Code], m.County , "Medical-Zip Code-County" As Source, False As [Network Member] FROM [Medical-Zip Code-County] m UNION ALL SELECT a.City, a.[ZIP Code], a.[Country/Region], "Attorney-Zip-County" As Source, False As [Network Member] FROM [Attorney-Zip-County] a) As r WHERE (r.City Like Forms!Search!qcity & "*" And r.[Zip Code] Like Forms!Search!qcode & "*" And r.County Like Forms!Search!qcounty & "*") OR r.[Network Member] = Yes
{ "language": "en", "url": "https://stackoverflow.com/questions/7522098", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Spring AOP and AspectJ. Need advice/comments on Around Advice I posted this on another forum and wanted to see if I can reach more people. I am working on an application that consists of different Spring web apps. Say we have: * *ComponentA.jar *ComponentB.jar And WAR files: * *Foo.war (contains ComponentA) *Baa.war (contains ComponentA & ComponentB) We are using Logback to log to our debug log. So say that the various classes of the application have the the following logger declaration: private static final Log log = LoggerFactory.getLogger(NAME_OF_WAR_FILE + "." + NAME_OF_CONTAINING_COMPONENT + "." + PACKAGE.CLASS_NAME); So example: package a.b.c; public class SomeClass { private static final Log log = LoggerFactory.getLogger("Foo.war" + "." + "ComponentA" + "." + SomeClass.class); } package x.y.z; public class SomeOtherClass { private static final Log log = LoggerFactory.getLogger("Baa.war" + "." + "ComponentA" + "." + SomeOtherClass .class); } Assume that the name of the war file and component is set by a property and not hard-coded. Is it possible to have an Aspect and Advice that can do something like the following (pseudo since I'm not sure it can be done): @Aspect public class TheAspect{ @Around("execution of a method") public Object aroundSomething(ProceedingJoinPoint pjp){ Log log = get the log instance from the class that this advice is running on if(log.isDebugEnabled()) // log something Object o = pjp.proceed(); if(log.isDebugEnabled()) // log something else return o; } } The point here is to write to the log file using the log of the class instance which contains the method which is being intercepted by the Advice. The application is presented as a single web app composed of Foo.war and Baa.war. Both Foo.war and Baa.war write to the same log file. Example: 2011-09-22 14:35:35.159 MDT,DEBUG,Foo.war.ComponentA.a.b.c.SomeClass,Hello World Debug message 2011-09-22 14:35:35.159 MDT,DEBUG,Baa.war.ComponentA.a.b.c.SomeClass,Hello World Debug message 2011-09-22 14:35:35.159 MDT,DEBUG,Baa.war.ComponentB.x.y.z.SomeOtherClass,Hello World Debug message Thanks in advance. A: You can use thisJoinPoint inside your aroundSomething method. To get the class name: Signature sig = thisJoinPoint.getSignature(); String className = sig.getDeclaringTypeName(); You can also get the class object: Class<?> type = sig.getDeclaringType(); And maybe you can use the package to identify your war file: Package pack type.getPackage();
{ "language": "en", "url": "https://stackoverflow.com/questions/7522102", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Emacs C-c } command and parentheses-match checking I am working in Emacs 23, editing LaTeX via AUCTeX. I noticed in emacs that when I press C-c }, I receive the minibuffer message Scan error: "Unbalanced parentheses", 16026, 16440 Question 1. What exactly is this command doing? Question(s) 2. More generally, how can I determine what I a given macro is doing? Is there, for example, a universal command that request the keyboard shortcut as an input and outputs a description of the command to which that shortcut is bound? Is there a list of all active keyboard shortcuts? Question 3. How can I find my unmatched parentheses? The post here recommends the command M-x check-parens, but it availed me nothing, not even a minibuffer message. A: The answer to 1 and 2 is to do C-h k C-c } and see what the help buffer tells you. This is one of the features that allows us to call Emacs a self-documenting editor. Don't forget that you can follow the links in the help buffer to both the source code where this function is implemented and to other documentation. You may also want to use C-h m to see all the key bindings added by the major and minor modes that are currently enabled and C-h ? to see what other interesting help functions there are. I've never used check-parens specifically, but it does work in my current buffer, which is javascript. I see from its documentation (C-h f check-parens) that it relies on the current syntax table, so perhaps for TeX the syntax table doesn't contain enough information for check-syntax to find the error.
{ "language": "en", "url": "https://stackoverflow.com/questions/7522108", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Implementing Select List Lookup ViewModel Attribute I'm trying to implement a more customisable version of using ViewModel attributes and a Model Enricher to populate viewmodels lists like in this this question and associated blog post. I would like to be able to specify the method on my select list interface from the Attribute. Each Select List service I have returns an IEnumerable that I use to make a select list and presently exposes an All interface as the sample does. I can easily use the All method because all interfaces provide that. However I often wish to able to use other methods like the AllTradingCompanies() AllManafacturingCompanies() methods of my select list class to get filtered lists. It is presently looking like I may have to implement a Custom attribute to map to specific e.g. [AllCompanyList] attributes but that moves me away from the nice generic method that the existing version gives me. I guess I could use it to complement it but then its starting to lose some of the charm. I also am implementing IModelEnrichers which can do custom per view model logic. Any thoughts on a nice way to implement this? A: I implemented the solution using pairs of Attributes to define a requirement for data on a ViewModel and a provider of data a repository or a service within my domain. See my follow up question asking whether this is a good idea.
{ "language": "en", "url": "https://stackoverflow.com/questions/7522109", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Passing an object in every Django page I have an object called Groups that is used in every single page on my website. However, Django only passes in Python objects to html through render_to_response and I can't render to response everytime something happens to the groups object. How do I maintain this object(as in make it respond to adding and deletion) and produce it in every Django template that I have without calling render_to_response? A: write a template context processor: #my_context_processors.py def include_groups(request): #perform your logic to create your list of groups groups = [] return {'groups':groups} then add it in your settings file: #settings.py TEMPLATE_CONTEXT_PROCESSORS = ( "django.core.context_processors.auth", "django.core.context_processors.debug", "django.core.context_processors.i18n", "django.core.context_processors.media", "path.to.my_context_processors.include_groups", ) now a variable groups will be available to you in all your templates A: If you need data added to more than one template contexts you should look into achieving that via your own template context processor. A: You need to create template context processor to pass an object to each request. Here is some example A: #tu_context_processor.py from setting.models import Business def include_business(request): business = Business.objects.all().last() return {'business': business} in your settings file: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'core.tu_context_processor.include_business', ], }, }, ] now a variable business will be available to you in all your templates tested in Django 4
{ "language": "en", "url": "https://stackoverflow.com/questions/7522115", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: php mod_rewrite cannot get second parameter from rewritecond I have a server that I am setting up to rewrite subdomains as get parameters So, subdomain.example.com/blog/test would actually point to: example.com/index.php?website=subdomain&request=blog/test I have setup the domain with an A record with a value of *, and I have setup the server to ALIAS *.example.com to example.com. All of that is working. In my .htaccess I have RewriteCond %{HTTP_HOST} !^www. [NC] RewriteCond %{HTTP_HOST} ^([^/\.]+).example.com(.*)$ [NC] RewriteRule ^(.*)$ index.php?website=%1&request=%2 [L] Here is a var_dump() of $_GET when i go to subdomain.example.com/blog/test array(2) { ["website"]=> string(8) "subdomain" ["request"]=> string(0) "" } the subdomain is coming in perfectly in the website parameter, but the rest of the request is not there in the request parameter. Any Ideas? I really appreciate the help. Thanks in advance. By the way if I use RewriteRule ^(.*)$ index.php?website=%1&request=$1 [L] Then I get index.php in the request parameter. If that tells you something additional. AMENDMENT Per John's suggestion I tried the following RewriteCond %{HTTP_HOST} !^www. [NC] RewriteCond %{HTTP_HOST} ^([^/\.]+).wescms.com(.*) [NC] RewriteRule ^(.*)$ index.php?website=%1&request=%{REQUEST_URI} [NC,L] If you go to subdomain.example.com/blog/test the REQUEST_URI comes back with index.php I did a var_dump() of the $_SERVER variable, and in the REQUEST_URI it shows /blog/test, but its not making it through the RewriteRule. If I use THE_REQUEST in the rewrite rule rather than REQUEST_URI, I get back what I need plus some extra bits but I would appreciate understanding more about why REQUEST_URI is not working as in my last example. Thanks. A: Your second RewriteCond is matching against %{HTTP_HOST}, which only includes the hostname the of the request, not the "path" portion. The requested resource (basically, the part of the URL after the hostname) is available as the %{REQUEST_URI} variable. In your situation, you could use the variable directly in your rule rather than trying to capture that data in a RewriteCond.
{ "language": "en", "url": "https://stackoverflow.com/questions/7522127", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ListPreference keeps repeating rows I am trying to display a list with checkboxes using a preference activity. The list is supplied with 121 entries and by debugging I have confirmed that the complete list is passed into the ListPreference. However the scrollable list ends up with the first 4 entries repeated to the size of the entries i.e. 121. I found code on here which is as follows. Stepping through with the debugger it seems that CustomHolder(View row, int position) is supplied with position as first 0 then 2 and so on to 3 at which point it appears as 0 again. I cant see where and why this is happening so. First a preference.xml <?xml version="1.0" encoding="utf-8"?> <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"> <PreferenceCategory android:title="Your Title"> <com.Applitastic.CustomListPreference android:key="multipref" android:id="@+id/multiselectlist" android:title="Apps to exclude" android:summary="Specify exclusion" android:dialogTitle="Apps to exclude" android:defaultValue="1"/> </PreferenceCategory> </PreferenceScreen> Now an xml for a tablelayout <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:paddingBottom="8dip" android:paddingTop="8dip" android:paddingLeft="10dip" android:paddingRight="10dip"> <TableLayout android:id="@+id/custom_list_view_row_table_layout" android:layout_width="fill_parent" android:layout_height="wrap_content" android:stretchColumns="0"> <TableRow android:id="@+id/custom_list_view_row_table_row" android:gravity="center_vertical" android:layout_width="wrap_content" android:layout_height="wrap_content"> <TextView android:id="@+id/custom_list_view_row_text_view" android:textSize="22sp" android:textColor="#000000" android:gravity="center_vertical" android:layout_width="160dip" android:layout_height="40dip" /> <RadioButton android:checked="false" android:id="@+id/custom_list_view_row_radio_button"/> </TableRow> </TableLayout> Now the ListPreference code. import java.util.ArrayList; import android.content.Context; import android.content.DialogInterface; import android.content.SharedPreferences; import android.graphics.Color; import android.preference.ListPreference; import android.preference.PreferenceManager; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.CompoundButton; import android.widget.RadioButton; import android.widget.TextView; import android.app.AlertDialog.Builder; import android.app.Dialog; public class CustomListPreference extends ListPreference{ CustomListPreferenceAdapter customListPreferenceAdapter = null; Context mContext; private LayoutInflater mInflater; CharSequence[] entries; CharSequence[] entryValues; ArrayList<RadioButton> rButtonList; SharedPreferences prefs; SharedPreferences.Editor editor; public CustomListPreference(Context context, AttributeSet attrs) { super(context, attrs); mContext = context; mInflater = LayoutInflater.from(context); rButtonList = new ArrayList<RadioButton>(); prefs = PreferenceManager.getDefaultSharedPreferences(mContext); editor = prefs.edit(); } @Override protected void onPrepareDialogBuilder(Builder builder) { entries = getEntries(); entryValues = getEntryValues(); if (entries == null || entryValues == null || entries.length != entryValues.length ) { throw new IllegalStateException( "ListPreference requires an entries array and an entryValues array which are both the same length"); } customListPreferenceAdapter = new CustomListPreferenceAdapter(mContext); builder.setAdapter(customListPreferenceAdapter, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }); } private class CustomListPreferenceAdapter extends BaseAdapter { public CustomListPreferenceAdapter(Context context) { } public int getCount() { return entries.length; } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } public View getView(final int position, View convertView, ViewGroup parent) { View row = convertView; CustomHolder holder = null; if(row == null) { row = mInflater.inflate(R.layout.excludeapps, parent, false); holder = new CustomHolder(row, position); row.setTag(holder); // do whatever you need here, for me I wanted the last item to be greyed out and unclickable // if(position != 3) //{ row.setClickable(true); row.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { for(RadioButton rb : rButtonList) { if(rb.getId() != position) rb.setChecked(false); } int index = position; // int value = Integer.valueOf((String) entryValues[index]); //editor.putInt("yourPref", value); Dialog mDialog = getDialog(); mDialog.dismiss(); } }); // } } else { holder = (CustomHolder) convertView.getTag(); } return row; } class CustomHolder { private TextView text = null; private RadioButton rButton = null; CustomHolder(View row, int position) { text = (TextView)row.findViewById(R.id.custom_list_view_row_text_view); text.setText(entries[position]); rButton = (RadioButton)row.findViewById(R.id.custom_list_view_row_radio_button); rButton.setId(position); // again do whatever you need to, for me I wanted this item to be greyed out and unclickable //if(position == 3) //{ // text.setTextColor(Color.LTGRAY); // rButton.setClickable(false); //} // also need to do something to check your preference and set the right button as checked rButtonList.add(rButton); rButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if(isChecked) { for(RadioButton rb : rButtonList) { if(rb != buttonView) rb.setChecked(false); } int index = buttonView.getId(); //int value = Integer.valueOf((String) entryValues[index]); //editor.putInt("yourPref", value); Dialog mDialog = getDialog(); mDialog.dismiss(); } } }); } } } } A: Well, look at getView. Your last action for a recycled view is: // ... } else { holder = (CustomHolder) convertView.getTag(); // Edit: how to update the holder (see explanation further below) holder.updateText(position); } return row; You have to fill and updated that holder with the new data for that position. It your case it just stays the same (so the data which was set in the if section). Edit: How to update the holder? Suppose you would implement this method in CustomHolder, then you could update it the way showed obove: public void updateText(int position) { text.setText(entries[position]); } Notice: the common pattern is not to implement the update itself in the holder. My holder is usually a class with public members like holder.title (and no methods, just a container for references), so I can call holder.title.setTitle(...) from getView directly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7522131", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: EF Code First: Object with One-to-Many and M-T-M of same classes fails to generate M-T-M in db I have the following classes (shortened) Game { public int id {get;set;} public virtual ICollection<Player> Players {get;set;} public virtual Player Owner {get;set;} public virtual ICollection<Character> Characters {get;set;} } Players { public int id {get;set;} public virtual ICollection<Game> Games {get;set;} } Characters { public virtual ICollection<Game> Games {get;set;} } For whatever reason, my database generates a one-to-many link for Game-Players. It does, however, create one for games-characters. I have no idea why this would be, other than perhaps the one-to-many is screwing with it in some way! A: Your Game class has two navigation properties to the Player class. EF doesn't know which one to map to the target Player.Games. Because of that it decides that there are actually three relationships: * *Game.Players <-> not exposed *Game.Owner <-> not exposed *Player.Games <-> not exposed And the fourth relationship is * *Game.Characters <-> Character.Games For the last one EF detects the right ends of the relationship because they are not ambiguous. The easiest way to fix that is to give EF a hint which of the two navigation properties on Game refering to Player actually belongs to Player.Games: public class Game { public int id {get;set;} [InverseProperty("Games")] public virtual ICollection<Player> Players {get;set;} public virtual Player Owner {get;set;} public virtual ICollection<Character> Characters {get;set;} } Now the result are the expected three relationships: * *Game.Players <-> Player.Games *Game.Owner <-> not exposed *Game.Characters <-> Character.Games Instead of using the [InverseProperty] attribute you can also specify this in Fluent API by explicitely mapping a many-to-many relationship between Game.Players and Player.Games. A: The public int id is the default variable name for EF Code first key values. It does recognize this implicitly. This key value is omitted in Characters, and therefore handled differently.
{ "language": "en", "url": "https://stackoverflow.com/questions/7522132", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Strange apostrophe issue in web form > SQL Server We look after a site for a client on which they have a page with a HTML form text area that gets written to a SQL Server ntext field. One of their customers was updatng their profile using this form and mentioned that when they entered the word "don't" into the form and then viewed their profile the word had changed to: d’t I've done some searches for this on Google, and surprisingly there's over 2 million pages on sites where this seems to of happened - but I can't see any information about it. Interestingly, If I write into the form I don't get the same issue and was wondering if it was a result of a 'strange' apostrophe from some pasted text into the form? Anyone else came across this? A: Sounds like the HTML page where the form is located doesn't have a meta charset tag defined, leaving the option of which character set to use up to the browser's preferences/defaults.
{ "language": "en", "url": "https://stackoverflow.com/questions/7522133", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: obtain an Image with Jquery and Php I want to obtain images from the server. The html code : <div id='container'></div> Here is my code in jquery : $.post('php/Image.php', function(data) { $('#container').html(data); }); And the php code : header('Content-Type: image/png'); $img = imagecreatefrompng("image.png"); imagepng($img); On my web page I can see the "binary" of the image and that's not what I expect. Somebody can tell me what I'm doing wrong ? Or if there is a better solution to do that. Thanks in advance for your help. A: You don't need to request the image body itself, but insert an img tag with link to it: $('#container').html('<img src="php/Image.php" />'); A: Assuming that your PHP isn't stripped down (only reads an image and sends it), you can simply request the image from the server by changing the src attribute of your img tag, like so. All you need to add now is an <img> tag to your HTML: $('#container').html('<img src="php/Image.php">');
{ "language": "en", "url": "https://stackoverflow.com/questions/7522134", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: regex for scheme kind of input I am writing a java program which would act upon the input which would be in scheme kind of language. Something like (+ (+ a b)) Say I now want to check the syntax like if there are 2 brackets which have been opened, there have to be 2 other closing brackets. I am not sure how to achieve this with a regex. Can you help me out A: Regular expressions can't pair parentheses to an arbitrary depth. Scheme syntax is not regular. http://en.wikipedia.org/wiki/Regular_language#The_number_of_words_in_a_regular_language Thus, a non-regularity of some language L' can be proved by counting the words in L'. Consider, for example, the Dyck language of strings of balanced parentheses. The number of words of length 2n in the Dyck language is equal to the Catalan number ..., which is not of the form p(n)λn, witnessing the non-regularity of the Dyck language. You're going to have to tokenize it and then walk over tokens counting paren depth and make sure the depth is zero at the end and never goes negative. For a simple language that has parentheses spaces and identifiers made from repetitions of the letter 'a', you might do Patter token = Pattern.compile("[() ]|a+|.", Pattern.DOT_ALL); Matcher m = token.matcher(sourceCode); int parenDepth = 0; while (m.find()) { char ch = m.group().charAt(0); switch (ch) { case '(': ++parenDepth; break; case ')': if (parenDepth == 0) { fail("Too many close parens"); } --parenDepth; break; } } if (parenDepth != 0) { fail(parenDepth + " unclosed lists"); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7522136", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What design pattern is this? It has to do with threads Forgive me if I've missed an obvious answer, but I have looked around for this and I cannot find it. I am trying to build a multi-threaded program that uses mutexes as little as possible. The following is the basic design. I want to know if I'm recreating the wheel and, if I am, what design pattern/algorithm/approach am I unwittingly borrowing from? I have a global object that is basically a message queue for a bunch of threads. Every time a thread is created it gets a function to which it submits messages. Only the thread can access the function. When a message is submitted to the function, the object takes the message and puts it into a queue. This is a FIFO queue that basically works as shared memory for inter-thread communication. The thing is, only the global object can add or delete messages. Every thread regularly checks the queue. Every time it finds a message it can use, it copies the message to itself and then signals the global object that it's read the data. If a thread looks at the message and doesn't need it, then it still signals that it has read the message, but it doesn't copy it. When every thread has looked at the data, the global object deletes the message. That's it. It's basic. It eats up memory. It's just meant to avoid locking variables, etc. A: It is a message bus. Don't write one yourself, there is probably a framework in your language. A: The operating system term you are looking for is Message Passing. http://en.wikipedia.org/wiki/Message_passing
{ "language": "en", "url": "https://stackoverflow.com/questions/7522143", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Can gnuplot split data? I have some data in the following format: 10.0 1 a 2 10.2 2 b 2 10.4 3 a 2 10.6 4 b 2 10.8 4 c 10 11.0 4 c 20 ... where the third column basically indicates belonging to a 'separate' dataset; and so I would like to show, say, those samples belonging to 'a' in red, those belonging to 'b' in blue etc (using gnuplot Version 4.4 patchlevel 2). I managed to somehow get the 'sample' style as a mix between 'impulses' and 'point' styles; and via Choosing line type and color in Gnuplot 4.0, managed to employ individual colors - this is how far I got (basictest.gnuplot): #!/usr/bin/env gnuplot print "Generating data..." # to specify data inline in script: # only system can work, as it is quoted; # but still have to escape newlines! system "cat > ./inline.dat <<EOF\n\ 10.0 1 a 2\n\ 10.2 2 b 2\n\ 10.4 3 a 2\n\ 10.6 4 b 2\n\ 10.8 4 c 10\n\ 11.0 4 c 20\n\ EOF\n" print "done generating." # set ranges set yrange [0:30] set xrange [0:4] # define line styles - can call them up later set style line 1 linetype 1 linewidth 3 pointtype 3 linecolor rgb "red" set style line 2 linetype 1 linewidth 2 pointtype 3 linecolor rgb "green" set style line 3 linetype 1 linewidth 2 pointtype 3 linecolor rgb "blue" # offset the X axis: instead of 1:2, use: ($1-10):2 # to "mix", use "" for last datset - but must also repeat the "using"! # ... and plot: plot 'inline.dat' using ($1-10):2 with impulses linestyle 1,\ "" using ($1-10):2 notitle with points linestyle 1,\ "" using ($1-10):2 notitle with lines linestyle 2,\ 'inline.dat' using ($1-10):4 with impulses linestyle 3,\ "" using ($1-10):4 notitle with points linestyle 3 # below just for saving file #set terminal png #set output 'basictest.png' #replot ... which looks like this: In other words, instead of the above - say for ($1-10):2, I'd like to see the 1st and 3rd sample ('a') in blue, 2nd and 4th sample ('b') in red, and the last two ('c') in green (I left the green line there just to see the effect of the style mixing). I'm aware that this could be achieved by writing a script, that will parse the original data, and generate three tables out of that, as in: 10.0 1 a 2 10.4 3 a 2 --- 10.2 2 b 2 10.6 4 b 2 --- 10.8 4 c 10 11.0 4 c 20 ... which could then be plotted 'separately' - but I was wandering if gnuplot maybe had some internal facility for something like that? Thanks in advance for any answers, Cheers!   PS: Some useful links for me: * *gnuplot / intro / style Introduction to gnuplot --- Plot Style *gnuplot / intro / plotexp (E) Introduction to gnuplot --- Experimental Dat *Gnuplot: An Interactive Plotting Program *Gnuplot tricks: Further new features in gnuplot 4.4   EDIT: just wanted to post a link to a script with which I'm getting close to visualizing the data the way I wanted to: I'm kinda wanting to treat the labels (with the added 'points' as rectagle backgrounds) as nodes in graphviz or in TikZ, and set up those nice connection lines between them - but even this already helps me much :) Note that this is the wxt output - other terminals like png or pdfcairo will have a completely messed up rendering of boxes/labels (and would need to be tuned by hand). A: You could use awk for that. I don't know if I would call that "some internal facility" of gnuplot, but I think it does what you want it to do: With a data file Data.csv: 10.0 1 a 2 10.2 2 b 2 10.4 3 a 2 10.6 4 b 2 10.8 4 c 10 11.0 4 c 20 plot the data with plot "<awk '{if($3 == \"a\") print $1,$2}' Data.csv" u ($1 - 10):2 w lp, \ "<awk '{if($3 == \"b\") print $1,$2}' Data.csv" u ($1 - 10):2 w lp, \ "<awk '{if($3 == \"c\") print $1,$2}' Data.csv" u ($1 - 10):2 w lp Note the \" to escape the script parser ^^. As for plot style issues you can make use of the full spectrum gnuplot has to offer. A: It is possible. Gnuplot has a ternary operator like in C. Gnuplot also will ignore undefined expressions, such as logarithms of negative numbers or dividing by zero. Putting those together, you can plot only those lines that satisfy some particular condition by producing invalid numbers for those that fail to satisfy the condition. Simplifying a bit from the question, the approach looks like this: plot "inline.dat" using (strcol(3) eq 'a' ? $1 : 1/0):2
{ "language": "en", "url": "https://stackoverflow.com/questions/7522147", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PHP Curl - Cookies problem I am trying to grab my amazon associates stats automatically via cUrl. However I am falling down at the first hurdle; logging in. When I use the following code: $url = 'https://affiliate-program.amazon.com/gp/flex/sign-in/select.html'; $post_data = "action=sign-in&email=$username&password=$password"; $fp = fopen('/my/path/to/cookie.txt', 'w'); fclose($fp); $login = curl_init(); curl_setopt($login, CURLOPT_COOKIESESSION, 1); curl_setopt($login, CURLOPT_COOKIEJAR, '/my/path/to/cookie.txt'); curl_setopt($login, CURLOPT_COOKIEFILE, '/my/path/to/cookie.txt'); curl_setopt($login, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)'); curl_setopt($login, CURLOPT_TIMEOUT, 40); curl_setopt($login, CURLOPT_RETURNTRANSFER, 1); curl_setopt($login, CURLOPT_URL, $url); curl_setopt($login, CURLOPT_HEADER, 1); curl_setopt($login, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); curl_setopt($login, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($login, CURLOPT_POST, 1); curl_setopt($login, CURLOPT_POSTFIELDS, $post_data); echo curl_exec($login); curl_close($login); I get the following output: HTTP/1.1 200 OK Date: Thu, 22 Sep 2011 22:08:39 GMT Server: Server x-amz-id-1: 1NNZMSS8X73EE0G7HKW8 x-amz-id-2: HRW1ZoN4KVzDCp/tS5E7l+7fn9XGH2k/T7qxzi+WLOw= Set-cookie: session-id-time=1317279600l; path=/; domain=.amazon.com; expires=Thu Sep 29 07:00:00 2011 GMT Set-cookie: session-id=181-7755537-2127814; path=/; domain=.amazon.com; expires=Thu Sep 29 07:00:00 2011 GMT Vary: Accept-Encoding,User-Agent Cneonction: close Transfer-Encoding: chunked Content-Type: text/html; charset=UTF-8 Please Enable Cookies to Continue To continue shopping at Amazon.com, please enable cookies in your Web browser. Learn more about cookies and how to enable them. Once you have enabled cookies in your browser, please click on the button below to return to the previous page. cookie.txt contains the following: # Netscape HTTP Cookie File # http://curl.haxx.se/rfc/cookie_spec.html # This file was generated by libcurl! Edit at your own risk. .amazon.com TRUE / FALSE 1317279600 session-id-time 1317279600l .amazon.com TRUE / FALSE 1317279600 session-id 181-7755537-2127814 Live HTTP headers: https://affiliate-program.amazon.com/gp/flex/sign-in/select.html POST /gp/flex/sign-in/select.html HTTP/1.1 Host: affiliate-program.amazon.com User-Agent: Mozilla/5.0 (Windows NT 6.0; rv:6.0) Gecko/20100101 Firefox/6.0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8 Accept-Language: en-gb,en;q=0.5 Accept-Encoding: gzip, deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Connection: keep-alive Referer: https://affiliate-program.amazon.com/ Cookie: apn-user-id=P0000000000; session-id-time=1317366000l; session-id=182-9139891-5240049; __utma=125759317.157031897.1316727783.1316727783.1316795373.2; __utmz=125759317.1316727783.1.1.utmccn=(direct)|utmcsr=(direct)|utmcmd=(none); ubid-main=190-8295480-4625243; __utmv=125759317.koicarandsup-20; x-main=qIM@jFtaFnr4KaiFFutR7WZ1QkQHqoq9; at-main=4|eaxYjMp+5TWMiQOn6gROkHUvCfKF3Y9hkvacYbU0+fzL3Pr1ejcGt78Tb6W5zvUYj67hWyx3AuNd3UparIBCnnrL62d5IMyn7zeFKr7GfjnPvjjaGOPArk7n7tr7go+QgBU6OZ0hKse6MJIdApDrSe2cI0Mz9XDvbumEU5twDKgq338hejMR23IXuWrvq1o0hcfN6DS0oabY7mVIddSMig==; __utmb=125759317; __utmc=125759317 Content-Type: application/x-www-form-urlencoded Content-Length: 1276 sessionId=182-9139891- 5240049&path=%2Fgp%2Fassociates%2Flogin%2Flogin.html&query=returl%3D%2Fgp%2Fassociates%2Fjoin%2Flanding%2Fmain.html%26retquery%3D&action=sign-in&mode=1&email=xxx&password=xxx&x=31&y=18&metadata1=xppc1AIU%2Fl8IERp8RJxYooTCV9Vo2Nico9wyEvW9ByghGgc%2FSNU8XqMQnjgshs3DZpFQgLXCAT1qAama%2Bj5WBGxvTRiC45v6Am7hMY99RwJfUIozi5v1ZkwV%2Bcjp9PecvpcPSxLVuwOF4QSf7Q%2BPxNwlxLm5nHXqSNPwmw5Ezg2ENIagMWcrwuDlp50%2B0XKi0e8yyawdc5TjH%2BhGXz12KABRLoH1WuTSwAWleHzGzBUN515WgRMElB583b9h%2FoDINumjmwwsHsjzXjLaEjYaM1w6nw%2F5fqmpABPcN31D7wgDQoOi1xxIyUtZceAa3rwwUxKvpZecStM2T6QtSJhx6YdpLNmHwGSdhkBrsCQVlcLruKNMnUVrb%2FZni3le380YsUeIsVZy113lqayCwla9vwvDTA4mstx2YTKtTU1NOzfblMlYBEL4rhLN1fpeF0EaiAoiatLb1kH%2BCvt6tp78KyPCd0XeEBGqMeDWm2b%2FBSg%2BUqVLBMSeHtJ4VZXxMaWhodZZYU0uxUNwL8hCVruO5KxSbssorByNybuPx%2FmkS87UZMDB62VALgb90MUXLvbVX%2BcmizzBkmwCs3Q6ampHa40NIYQKXTCCnGjVUwavCPv73OrMA8OjVJX3h371m3OHvzpBKRTFG5uiTfZoaaPI%2FYxikE2v99%2FaR3vlwkTZfOhM%2Fba9seIbMpxArTj6ekpmTLbU5LwKn2yVbiAZgsUuFSCNcQMlE%2FJ9nAIuYZ2guks0Zz%2BPhJ07TOXuTscuc%2Fm0wgqqluPq5NShRINoiGLjiKva6ngslLoQWeKovNwYyVCyNfuwsZ7BIo6%2Fo7yaEfIK6Yb%2BZPMommN%2FI7BFrlW7wrWmaG%2FgbtSx1bg9A5DgtKBDI21j3ibebBZVN%2FP2ZrEB6upCDHEKa1pMCkP6nbOhu%2BxcrNYS%2FyS6e0bv3WiWqugclX%2FnYmBWBdNunCFtI8LKU%2FMvhDT820M%3D HTTP/1.1 302 MovedTemporarily Date: Fri, 23 Sep 2011 16:30:35 GMT Server: Server x-amz-id-1: 1JGFY8JCATS8GCJ05WP3 x-amz-id-2: vNYWJ+3yN1Qrya1cxENZdlFuZNF4Yc4uYhCmoR3UFBU= Set-Cookie: at-main=4|3iPYr7E1Pn32BbMI4MHFaMtbn/0v54qEG1Jn9Pk+7Hi2Cws1f+jBSUt9oyBzrpy6BX1XCsZ/qoJlbswA0G2U3L9Yhec4CjSlsLZM+mEPRs/AiNAbvuUDzj9wL1HI2x+e7tBqDLhK+fas6R562qkQBX+9Y7bhE1St11hjislFijGuTcbtr+5mUz1FuweEFaH/xtHacsJ3Yth9iOiska0CbQ==; path=/; domain=.amazon.com; expires=Tue Jan 01 08:00:01 2036 GMT; secure Set-Cookie: ubid-main=190-8295480-4625243; path=/; domain=.amazon.com; expires=Tue Jan 01 08:00:01 2036 GMT Location: https://affiliate-program.amazon.com/gp/associates/join/landing/main.html Vary: Accept-Encoding,User-Agent Content-Encoding: gzip nnCoection: close Transfer-Encoding: chunked Content-Type: text/html; charset=UTF-8 https://affiliate-program.amazon.com/gp/associates/join/landing/main.html GET /gp/associates/join/landing/main.html HTTP/1.1 Host: affiliate-program.amazon.com User-Agent: Mozilla/5.0 (Windows NT 6.0; rv:6.0) Gecko/20100101 Firefox/6.0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8 Accept-Language: en-gb,en;q=0.5 Accept-Encoding: gzip, deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Connection: keep-alive Referer: https://affiliate-program.amazon.com/ Cookie: apn-user-id=P0000000000; session-id-time=1317366000l; session-id=182-9139891-5240049; __utma=125759317.157031897.1316727783.1316727783.1316795373.2; __utmz=125759317.1316727783.1.1.utmccn=(direct)|utmcsr=(direct)|utmcmd=(none); ubid-main=190-8295480-4625243; __utmv=125759317.koicarandsup-20; x-main=qIM@jFtaFnr4KaiFFutR7WZ1QkQHqoq9; at-main=4|3iPYr7E1Pn32BbMI4MHFaMtbn/0v54qEG1Jn9Pk+7Hi2Cws1f+jBSUt9oyBzrpy6BX1XCsZ/qoJlbswA0G2U3L9Yhec4CjSlsLZM+mEPRs/AiNAbvuUDzj9wL1HI2x+e7tBqDLhK+fas6R562qkQBX+9Y7bhE1St11hjislFijGuTcbtr+5mUz1FuweEFaH/xtHacsJ3Yth9iOiska0CbQ==; __utmb=125759317; __utmc=125759317 HTTP/1.1 302 MovedTemporarily Date: Fri, 23 Sep 2011 16:30:36 GMT Server: Server x-amz-id-1: 0DVGSNJ16FJ7BZSXKZEA x-amz-id-2: 3zBVVCqaFC6uLEb69n0ImqYEWcveHC/fr3DWJZ9XwfU= Set-Cookie: ubid-main=190-8295480-4625243; path=/; domain=.amazon.com; expires=Tue Jan 01 08:00:01 2036 GMT Location: https://affiliate-program.amazon.com/gp/associates/network/main.html Vary: Accept-Encoding,User-Agent Content-Encoding: gzip Cneonction: close Transfer-Encoding: chunked Content-Type: text/html; charset=UTF-8 https://affiliate-program.amazon.com/gp/associates/network/main.html GET /gp/associates/network/main.html HTTP/1.1 Host: affiliate-program.amazon.com User-Agent: Mozilla/5.0 (Windows NT 6.0; rv:6.0) Gecko/20100101 Firefox/6.0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8 Accept-Language: en-gb,en;q=0.5 Accept-Encoding: gzip, deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Connection: keep-alive Referer: https://affiliate-program.amazon.com/ Cookie: apn-user-id=P0000000000; session-id-time=1317366000l; session-id=182-9139891-5240049; __utma=125759317.157031897.1316727783.1316727783.1316795373.2; __utmz=125759317.1316727783.1.1.utmccn=(direct)|utmcsr=(direct)|utmcmd=(none); ubid-main=190-8295480-4625243; __utmv=125759317.koicarandsup-20; x-main=qIM@jFtaFnr4KaiFFutR7WZ1QkQHqoq9; at-main=4|3iPYr7E1Pn32BbMI4MHFaMtbn/0v54qEG1Jn9Pk+7Hi2Cws1f+jBSUt9oyBzrpy6BX1XCsZ/qoJlbswA0G2U3L9Yhec4CjSlsLZM+mEPRs/AiNAbvuUDzj9wL1HI2x+e7tBqDLhK+fas6R562qkQBX+9Y7bhE1St11hjislFijGuTcbtr+5mUz1FuweEFaH/xtHacsJ3Yth9iOiska0CbQ==; __utmb=125759317; __utmc=125759317 HTTP/1.1 200 OK Date: Fri, 23 Sep 2011 16:30:36 GMT Server: Server x-amz-id-1: 02WEQDKB29RGKP5T4NWE x-amz-id-2: xFfF8ncVlxX9KZtDLganiEY4CcDu+qXwkV5CBJGrKWY= Set-Cookie: ubid-main=190-8295480-4625243; path=/; domain=.amazon.com; expires=Tue Jan 01 08:00:01 2036 GMT Vary: Accept-Encoding,User-Agent Content-Encoding: gzip Cneonction: close Transfer-Encoding: chunked Content-Type: text/html; charset=UTF-8 V192206992.jpg">https://images-na.ssl-images-amazon.com/images/G/01/associates/network/thumb-slideshow-widget.V192206992.jpg GET /images/G/01/associates/network/thumb-slideshow-widget.V192206992.jpg HTTP/1.1 Host: images-na.ssl-images-amazon.com User-Agent: Mozilla/5.0 (Windows NT 6.0; rv:6.0) Gecko/20100101 Firefox/6.0 Accept: image/png,image/;q=0.8,/*;q=0.5 Accept-Language: en-gb,en;q=0.5 Accept-Encoding: gzip, deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Connection: keep-alive Referer: https://affiliate-program.amazon.com/gp/associates/network/main.html HTTP/1.1 200 OK Server: Server Content-Length: 4119 Last-Modified: Wed, 02 Jun 2010 17:03:17 GMT Content-Type: image/jpeg X-Cache-Lookup: HIT from cdn-images.amazon.com:8080, MISS from cdn-images.amazon.com:10080 Cache-Control: max-age=607570264 Date: Fri, 23 Sep 2011 16:30:37 GMT Connection: keep-alive SL75.jpg">https://images-na.ssl-images-amazon.com/images/I/41WtSRWclnL.SL75.jpg GET /images/I/41WtSRWclnL.SL75.jpg HTTP/1.1 Host: images-na.ssl-images-amazon.com User-Agent: Mozilla/5.0 (Windows NT 6.0; rv:6.0) Gecko/20100101 Firefox/6.0 Accept: image/png,image/;q=0.8,/*;q=0.5 Accept-Language: en-gb,en;q=0.5 Accept-Encoding: gzip, deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Connection: keep-alive Referer: https://affiliate-program.amazon.com/gp/associates/network/main.html HTTP/1.1 200 OK Server: Server Content-Length: 1317 Last-Modified: Thu, 26 May 2011 11:17:40 GMT Content-Type: image/jpeg X-Cache-Lookup: HIT from cdn-images.amazon.com:10080 Cache-Control: public, max-age=628443948 Expires: Sat, 23 Aug 2031 08:16:25 GMT Date: Fri, 23 Sep 2011 16:30:37 GMT Connection: keep-alive SL75.jpg">https://images-na.ssl-images-amazon.com/images/I/417XQ0XwQuL.SL75.jpg GET /images/I/417XQ0XwQuL.SL75.jpg HTTP/1.1 Host: images-na.ssl-images-amazon.com User-Agent: Mozilla/5.0 (Windows NT 6.0; rv:6.0) Gecko/20100101 Firefox/6.0 Accept: image/png,image/;q=0.8,/*;q=0.5 Accept-Language: en-gb,en;q=0.5 Accept-Encoding: gzip, deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Connection: keep-alive Referer: https://affiliate-program.amazon.com/gp/associates/network/main.html HTTP/1.1 200 OK Server: Server Content-Length: 1321 Last-Modified: Thu, 29 Jul 2010 04:26:28 GMT Content-Type: image/jpeg Cache-Control: public, max-age=628496714 Expires: Sat, 23 Aug 2031 22:55:51 GMT Date: Fri, 23 Sep 2011 16:30:37 GMT Connection: keep-alive SL75.jpg">https://images-na.ssl-images-amazon.com/images/I/417tb3B43YL.SL75.jpg GET /images/I/417tb3B43YL.SL75.jpg HTTP/1.1 Host: images-na.ssl-images-amazon.com User-Agent: Mozilla/5.0 (Windows NT 6.0; rv:6.0) Gecko/20100101 Firefox/6.0 Accept: image/png,image/;q=0.8,/*;q=0.5 Accept-Language: en-gb,en;q=0.5 Accept-Encoding: gzip, deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Connection: keep-alive Referer: https://affiliate-program.amazon.com/gp/associates/network/main.html HTTP/1.1 200 OK Server: Server Content-Length: 2462 Last-Modified: Fri, 26 Jun 2009 04:52:12 GMT Content-Type: image/jpeg X-Cache-Lookup: HIT from cdn-images.amazon.com:8080, MISS from cdn-images.amazon.com:10080 Cache-Control: max-age=607635331 Date: Fri, 23 Sep 2011 16:30:37 GMT Connection: keep-alive SL75.jpg">https://images-na.ssl-images-amazon.com/images/I/41sh5uiQ83L.SL75.jpg GET /images/I/41sh5uiQ83L.SL75.jpg HTTP/1.1 Host: images-na.ssl-images-amazon.com User-Agent: Mozilla/5.0 (Windows NT 6.0; rv:6.0) Gecko/20100101 Firefox/6.0 Accept: image/png,image/;q=0.8,/*;q=0.5 Accept-Language: en-gb,en;q=0.5 Accept-Encoding: gzip, deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Connection: keep-alive Referer: https://affiliate-program.amazon.com/gp/associates/network/main.html HTTP/1.1 200 OK Server: Server Content-Length: 1341 Last-Modified: Thu, 15 Sep 2011 20:05:25 GMT Content-Type: image/jpeg X-Cache-Lookup: MISS from cdn-images.amazon.com:10080 Cache-Control: public, max-age=630611997 Expires: Wed, 17 Sep 2031 10:30:34 GMT Date: Fri, 23 Sep 2011 16:30:37 GMT Connection: keep-alive utm.gif?utmwv=1&utmn=61668861&utmcs=UTF-8&utmsr=1280x1024&utmsc=24-bit&utmul=en-gb&utmje=1&utmfl=10.3%20r183&utmdt=Amazon.com%20Associates%20Central%20-%20Home&utmhn=affiliate-program.amazon.com&utmr=0&utmp=/gp/associates/network/main.html">https://affiliate-program.amazon.com/_utm.gif?utmwv=1&utmn=61668861&utmcs=UTF-8&utmsr=1280x1024&utmsc=24-bit&utmul=en-gb&utmje=1&utmfl=10.3%20r183&utmdt=Amazon.com%20Associates%20Central%20-%20Home&utmhn=affiliate-program.amazon.com&utmr=0&utmp=/gp/associates/network/main.html GET /__utm.gif?utmwv=1&utmn=61668861&utmcs=UTF-8&utmsr=1280x1024&utmsc=24-bit&utmul=en- gb&utmje=1&utmfl=10.3%20r183&utmdt=Amazon.com%20Associates%20Central%20-%20Home&utmhn=affiliate-program.amazon.com&utmr=0&utmp=/gp/associates/network/main.html HTTP/1.1 Host: affiliate-program.amazon.com User-Agent: Mozilla/5.0 (Windows NT 6.0; rv:6.0) Gecko/20100101 Firefox/6.0 Accept: image/png,image/;q=0.8,/*;q=0.5 Accept-Language: en-gb,en;q=0.5 Accept-Encoding: gzip, deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Connection: keep-alive Referer: https://affiliate-program.amazon.com/gp/associates/network/main.html Cookie: apn-user-id=P0000000000; session-id-time=1317366000l; session-id=182-9139891-5240049; __utma=125759317.157031897.1316727783.1316727783.1316795373.2; __utmz=125759317.1316727783.1.1.utmccn=(direct)|utmcsr=(direct)|utmcmd=(none); ubid-main=190-8295480-4625243; __utmv=125759317.koicarandsup-20; x-main=qIM@jFtaFnr4KaiFFutR7WZ1QkQHqoq9; at-main=4|3iPYr7E1Pn32BbMI4MHFaMtbn/0v54qEG1Jn9Pk+7Hi2Cws1f+jBSUt9oyBzrpy6BX1XCsZ/qoJlbswA0G2U3L9Yhec4CjSlsLZM+mEPRs/AiNAbvuUDzj9wL1HI2x+e7tBqDLhK+fas6R562qkQBX+9Y7bhE1St11hjislFijGuTcbtr+5mUz1FuweEFaH/xtHacsJ3Yth9iOiska0CbQ==; __utmb=125759317; __utmc=125759317 HTTP/1.1 200 OK Date: Fri, 23 Sep 2011 16:30:37 GMT Server: Server Last-Modified: Fri, 16 Sep 2011 11:22:34 GMT Etag: "23-35b3d280" Accept-Ranges: bytes Content-Length: 35 Cneonction: close Content-Type: image/gif SL75.jpg">https://images-na.ssl-images-amazon.com/images/I/51993R08WLL.SL75.jpg GET /images/I/51993R08WLL.SL75.jpg HTTP/1.1 Host: images-na.ssl-images-amazon.com User-Agent: Mozilla/5.0 (Windows NT 6.0; rv:6.0) Gecko/20100101 Firefox/6.0 Accept: image/png,image/;q=0.8,/*;q=0.5 Accept-Language: en-gb,en;q=0.5 Accept-Encoding: gzip, deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Connection: keep-alive Referer: https://affiliate-program.amazon.com/gp/associates/network/main.html HTTP/1.1 200 OK Server: Server Content-Length: 1325 Last-Modified: Tue, 27 Jul 2010 16:47:41 GMT Content-Type: image/jpeg X-Cache-Lookup: MISS from cdn-images.amazon.com:10080 Cache-Control: public, max-age=628244375 Expires: Thu, 21 Aug 2031 00:50:12 GMT Date: Fri, 23 Sep 2011 16:30:37 GMT Connection: keep-alive SL75.jpg">https://images-na.ssl-images-amazon.com/images/I/41is%2B997KUL.SL75.jpg GET /images/I/41is%2B997KUL.SL75.jpg HTTP/1.1 Host: images-na.ssl-images-amazon.com User-Agent: Mozilla/5.0 (Windows NT 6.0; rv:6.0) Gecko/20100101 Firefox/6.0 Accept: image/png,image/;q=0.8,/*;q=0.5 Accept-Language: en-gb,en;q=0.5 Accept-Encoding: gzip, deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Connection: keep-alive Referer: https://affiliate-program.amazon.com/gp/associates/network/main.html HTTP/1.1 200 OK Server: Server Content-Length: 1662 Last-Modified: Sun, 11 Nov 2007 01:27:41 GMT Content-Type: image/jpeg X-Cache-Lookup: MISS from cdn-images.amazon.com:10080 Cache-Control: public, max-age=628487843 Expires: Sat, 23 Aug 2031 20:28:00 GMT Date: Fri, 23 Sep 2011 16:30:37 GMT Connection: keep-alive SL75.jpg">https://images-na.ssl-images-amazon.com/images/I/518ISDAvx1L.SL75.jpg GET /images/I/518ISDAvx1L.SL75.jpg HTTP/1.1 Host: images-na.ssl-images-amazon.com User-Agent: Mozilla/5.0 (Windows NT 6.0; rv:6.0) Gecko/20100101 Firefox/6.0 Accept: image/png,image/;q=0.8,/*;q=0.5 Accept-Language: en-gb,en;q=0.5 Accept-Encoding: gzip, deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Connection: keep-alive Referer: https://affiliate-program.amazon.com/gp/associates/network/main.html HTTP/1.1 200 OK Server: Server Content-Length: 1111 Last-Modified: Tue, 27 Jul 2010 00:37:08 GMT Content-Type: image/jpeg X-Cache-Lookup: MISS from cdn-images.amazon.com:10080 Cache-Control: public, max-age=628003065 Expires: Mon, 18 Aug 2031 05:48:22 GMT Date: Fri, 23 Sep 2011 16:30:37 GMT Connection: keep-alive SL75.jpg">https://images-na.ssl-images-amazon.com/images/I/4155OOdySdL.SL75.jpg GET /images/I/4155OOdySdL.SL75.jpg HTTP/1.1 Host: images-na.ssl-images-amazon.com User-Agent: Mozilla/5.0 (Windows NT 6.0; rv:6.0) Gecko/20100101 Firefox/6.0 Accept: image/png,image/;q=0.8,/*;q=0.5 Accept-Language: en-gb,en;q=0.5 Accept-Encoding: gzip, deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Connection: keep-alive Referer: https://affiliate-program.amazon.com/gp/associates/network/main.html HTTP/1.1 200 OK Server: Server Content-Length: 1494 Last-Modified: Thu, 20 Aug 2009 15:52:47 GMT Content-Type: image/jpeg X-Cache-Lookup: MISS from cdn-images.amazon.com:10080 Cache-Control: public, max-age=630336792 Expires: Sun, 14 Sep 2031 06:03:49 GMT Date: Fri, 23 Sep 2011 16:30:37 GMT Connection: keep-alive utm.gif?utmwv=1&utmt=var&utmn=1408273993">https://affiliate-program.amazon.com/_utm.gif?utmwv=1&utmt=var&utmn=1408273993 GET /__utm.gif?utmwv=1&utmt=var&utmn=1408273993 HTTP/1.1 Host: affiliate-program.amazon.com User-Agent: Mozilla/5.0 (Windows NT 6.0; rv:6.0) Gecko/20100101 Firefox/6.0 Accept: image/png,image/;q=0.8,/*;q=0.5 Accept-Language: en-gb,en;q=0.5 Accept-Encoding: gzip, deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Connection: keep-alive Referer: https://affiliate-program.amazon.com/gp/associates/network/main.html Cookie: apn-user-id=P0000000000; session-id-time=1317366000l; session-id=182-9139891-5240049; __utma=125759317.157031897.1316727783.1316727783.1316795373.2; __utmz=125759317.1316727783.1.1.utmccn=(direct)|utmcsr=(direct)|utmcmd=(none); ubid-main=190-8295480-4625243; __utmv=125759317.koicarandsup-20; x-main=qIM@jFtaFnr4KaiFFutR7WZ1QkQHqoq9; at-main=4|3iPYr7E1Pn32BbMI4MHFaMtbn/0v54qEG1Jn9Pk+7Hi2Cws1f+jBSUt9oyBzrpy6BX1XCsZ/qoJlbswA0G2U3L9Yhec4CjSlsLZM+mEPRs/AiNAbvuUDzj9wL1HI2x+e7tBqDLhK+fas6R562qkQBX+9Y7bhE1St11hjislFijGuTcbtr+5mUz1FuweEFaH/xtHacsJ3Yth9iOiska0CbQ==; __utmb=125759317; __utmc=125759317 HTTP/1.1 200 OK Date: Fri, 23 Sep 2011 16:30:37 GMT Server: Server Last-Modified: Fri, 16 Sep 2011 11:22:34 GMT Etag: "23-35b3d280" Accept-Ranges: bytes Content-Length: 35 Cneonction: close Content-Type: image/gif Can anyone shed some light on why this is not working? A: EDIT: This code is broken as of June 2016. See this answer for explanation and potential workaround. The same technology mentioned in the previous link was added to associates' login. I wrote this code up and it works well for me, in the last var_dump I see all my account info and things like that. If you don't delete the cookies, you can make subsequent curl requests to protected pages with your login. Hopefully this can help you learn about how to do it. A lot of times on big sites you need to visit the login page to get cookies set, and also they usually have csrf tokens on the forms you need to submit with them. Of course if amazon changes their forms or url's around a bit, this will have to be adapted some, but hopefully they don't do that too often. <?php $email = 'you@yoursite.com'; $password = 'password'; // initial login page which redirects to correct sign in page, sets some cookies $URL = 'https://affiliate-program.amazon.com/gp/associates/join/landing/main.html'; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $URL); curl_setopt($ch, CURLOPT_COOKIEJAR, 'amazoncookie.txt'); curl_setopt($ch, CURLOPT_COOKIEFILE, 'amazoncookie.txt'); curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HEADER, 1); //curl_setopt($ch, CURLOPT_VERBOSE, true); curl_setopt($ch, CURLOPT_STDERR, fopen('php://stdout', 'w')); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); $page = curl_exec($ch); //var_dump($page);exit; // try to find the actual login form if (!preg_match('/<form name="sign_in".*?<\/form>/is', $page, $form)) { die('Failed to find log in form!'); } $form = $form[0]; // find the action of the login form if (!preg_match('/action=(?:\'|")?([^\s\'">]+)/i', $form, $action)) { die('Failed to find login form url'); } $URL2 = $action[1]; // this is our new post url // find all hidden fields which we need to send with our login, this includes security tokens $count = preg_match_all('/<input type="hidden"\s*name="([^"]*)"\s*value="([^"]*)"/i', $form, $hiddenFields); $postFields = array(); // turn the hidden fields into an array for ($i = 0; $i < $count; ++$i) { $postFields[$hiddenFields[1][$i]] = $hiddenFields[2][$i]; } // add our login values $postFields['username'] = $email; $postFields['password'] = $password; $post = ''; // convert to string, this won't work as an array, form will not accept multipart/form-data, only application/x-www-form-urlencoded foreach($postFields as $key => $value) { $post .= $key . '=' . urlencode($value) . '&'; } $post = substr($post, 0, -1); // set additional curl options using our previous options curl_setopt($ch, CURLOPT_URL, $URL2); curl_setopt($ch, CURLOPT_REFERER, $URL); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $post); $page = curl_exec($ch); // make request var_dump($page); // should be logged in A: You need to get amazon to set the cookie first. Try: // 1. Create a cookie file and set basic params $ckfile = tempnam ("/your/path/to/cookie/folder", "cookie.txt"); $target_host = "https://affiliate-program.amazon.com"; $target_request = "/gp/flex/sign-in/select.html"; $post_data = "action=sign-in&email=$username&password=$password"; // 2. Visit homepage to set cookie $ch = curl_init ($target_host); curl_setopt ($ch, CURLOPT_COOKIEJAR, $ckfile); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true); $output = curl_exec ($ch); // 3. Continue $login = curl_init ($target_host.$target_request); curl_setopt($login, CURLOPT_COOKIESESSION, 1); curl_setopt($login, CURLOPT_COOKIEJAR, $ckfile); curl_setopt($login, CURLOPT_COOKIEFILE, $ckfile); curl_setopt($login, CURLOPT_TIMEOUT, 40); curl_setopt($login, CURLOPT_RETURNTRANSFER, 1); curl_setopt($login, CURLOPT_HEADER, 1); curl_setopt($login, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); curl_setopt($login, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($login, CURLOPT_POST, 1); curl_setopt($login, CURLOPT_POSTFIELDS, $post_data); echo curl_exec($login); curl_close($login);
{ "language": "en", "url": "https://stackoverflow.com/questions/7522149", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Dropdown option that include all values, saving to database as FK Let's say I have a table "Products" with 3 products ID: 1, 2 and 3. Then in my asp.net app, I have a dropdown to select the product with these options: * *Product 1 (with value 1) *Product 2 (with value 2) *Product 3 (with value 3) *Any product (with value 0) If "any product" is selected, I return the SQL query that matches any of the 3 products. On the other side, I also have to save each of these searches too. As the "Searches" table has a FK of ProductID the question is: Is it OK to save the searches of "Any product" with a NULL value in ProductID? Because it's a FK and I've been reading FK should not be null. I'm not sure if there is a better way (I don't want to enter a new product called "Any product" to the table Products, it does not make sense to me). Many thanks. A: you could do as you say, BUT, when you say that the productid in the searches table is a foreign key, do you actually have a constraint for the foreign key? because if you do, you won't be able to enter null (or any other value for that matter) that doesn't exist in the product table. you could create a dummy product with Id -1 for example, and when you select the products from the table, you just have to ignore the one with Id -1. A: Definitely, it is not a good idea to set to null your ProductID field. Setting a foreign key to null habitually indicate that the referenced field had been deleted or updated. Knowing what exactly is the purpose of your Searches table would help to find a solution to your problem. But my guess is that you should treat this scenario in your code, not in the database.
{ "language": "en", "url": "https://stackoverflow.com/questions/7522150", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I collect client-side information on errors in my PHP application? I'm putting together an enterprise application using PHP and Yii. I want an easy way for the users to report a problem or bug if one occurs however I'm having a difficult time deciding the best way to capture/record the state of the system to help duplicate the problem. I was looking for an extension or library that integrates everything but that might not exist. Otherwise I need to look for a way to serialize the DOM for later evaluation or some other method like that. So the user can click the "Report Bug" button which captures the state of the site and brings up a pop-up box with a "what happened?" text box the user can fill in. What are my options to do this? A: Take a look at Airbrake (formerly known as Hoptoad) and its php notifier. By default they don't save full DOM code, but I think you can extend the notifier to do that. To allow users to trigger reports you can use ajax plus a custom exception. They have free plans and the setup is pretty easy to do. A: To get the HTML source for the current page you can use this Javascript snippet: var htmlSource = document.getElementsByTagName('html')[0].innerHTML; Another piece of information you might want to save is of course the current URL. You can send all this to the server using jQuery.post, e.g. $.post("<?php echo CController::createUrl(...); ?>", { url: document.location.href, html: document.getElementsByTagName('html')[0].innerHTML, }); I don't think you can do more than that without some kind of server-side helper you can call to. What function exactly do you need this bug-reporting feature to fulfill?
{ "language": "en", "url": "https://stackoverflow.com/questions/7522157", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Add rulers to a CDockablePane in a MFC Application How should I add rulers to o CDockablePane? (rulers like these or these) I found two implementations of rulers controlers on the web, but both are made with CView derived classes and, since I need the rulers to be in a dockable pane, I couldn't use neither of them. I've heard of two "strategies" though: (1) make a special class derived from CDockablePane and then derive the controlers' class from it (very difficult to do in this case) or (2) create a CFrameWnd inside the dockable pane that would contain the controlers, what seems easy to do but could unnecessarily add complexity to the project. What should I do? How should I do it? Is there any other option? Can anyone show me a small example of this (maybe just the important parts)? What I have already seen: How can I split a CDockablePane? How can I place a MFC CFormView inside a CDockablePane? Some other links that I'm not allowed to post here because I'm a new user. (But CFormView is not CFrameWnd) PS: Please, tell what I will have problems with, details, MFC peculiarities... PS2: I don't want links to the BCGsoft's page because I belive they don't give any code, just the executables (which don't have any use for me). Thanks A: I think it is easier for you to begin with http://www.codeproject.com/Articles/187/Implementing-Rulers-inside-of-Splitter-Panes And I had posted an answer that could be useful for you in How can I split a CDockablePane?
{ "language": "en", "url": "https://stackoverflow.com/questions/7522158", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: resizing UIImage the fastest and efficient way I wanted to resize a UIImage to a certain width and height keeping the proportion in place. The simplest way to do this is: CGSize newSize = CGSizeMake(726, 521); UIGraphicsBeginImageContext(newSize); [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)]; UIImage * newImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); Does the method above have any drawbacks in terms of image quality and the time it takes? What is a better way than the method above? EDITED: How about this one: - (UIImage *)imageByScalingProportionallyToSize:(CGSize)targetSize { UIImage *sourceImage = self; UIImage *newImage = nil; CGSize imageSize = sourceImage.size; CGFloat width = imageSize.width; CGFloat height = imageSize.height; CGFloat targetWidth = targetSize.width; CGFloat targetHeight = targetSize.height; CGFloat scaleFactor = 0.0; CGFloat scaledWidth = targetWidth; CGFloat scaledHeight = targetHeight; CGPoint thumbnailPoint = CGPointMake(0.0,0.0); if (CGSizeEqualToSize(imageSize, targetSize) == NO) { CGFloat widthFactor = targetWidth / width; CGFloat heightFactor = targetHeight / height; if (widthFactor < heightFactor) scaleFactor = widthFactor; else scaleFactor = heightFactor; scaledWidth = width * scaleFactor; scaledHeight = height * scaleFactor; // center the image if (widthFactor < heightFactor) { thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5; } else if (widthFactor > heightFactor) { thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5; } } // this is actually the interesting part: UIGraphicsBeginImageContext(targetSize); CGRect thumbnailRect = CGRectZero; thumbnailRect.origin = thumbnailPoint; thumbnailRect.size.width = scaledWidth; thumbnailRect.size.height = scaledHeight; [sourceImage drawInRect:thumbnailRect]; newImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); if(newImage == nil) NSLog(@"could not scale image"); return newImage ; } A: In a performance sample of Image Resizing Techniques the score was * *0.1420 UIKit *0.1722 Core Graphics *0.1616 Image I/O *2.4983 Core Image *2.3126 vImage so the fastest and simplest way is: let renderer = UIGraphicsImageRenderer(size: size) let resized = renderer.image { (context) in image.draw(in: CGRect(origin: .zero, size: size)) } Resize a UIImage the right way is from 2009 but contains useful talk about interpolation quality and preserving the aspect ratio. Additionally, to preserve the ratio within a max size: let image: UIImage = ... let maxSize = CGSize(width: 726, height: 521) let newSize = AVMakeRect(aspectRatio: image.size, insideRect: CGRect(origin: .zero, size: maxSize)).size let resized = UIGraphicsImageRenderer(size: newSize).image { _ in image.draw(in: CGRect(origin: .zero, size: newSize)) } To change the pixels per point density (default is the ppp of the current screen): let format = UIGraphicsImageRendererFormat() format.scale = 1 UIGraphicsImageRenderer(size: newSize, format: format) ... A: Here is a simple way: UIImage * image = [UIImage imageNamed:@"image"]; CGSize sacleSize = CGSizeMake(10, 10); // scale image to 10 x 10 UIGraphicsBeginImageContextWithOptions(sacleSize, NO, 0.0); [image drawInRect:CGRectMake(0, 0, sacleSize.width, sacleSize.height)]; UIImage * resizedImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); resizedImage is a new image.
{ "language": "en", "url": "https://stackoverflow.com/questions/7522159", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Web services response in client language - how to? I am developing a SOAP web service in Java using metro. I want to deliver the response in in the client language. My idea is to return all the string fields translates. This is not the main purpose for the web service, but is a needed convenience. The ResourceBundle is a java class that handles the loading of the correct set of strings according the client Location. Is this class the best approacher? And the real question: in a WS environment how to know the client location? EDIT: I like @Volker idea, let decide what language will be used. How to send the intentions to the service? * *Header parameter? *Method (body) parameter? *Any other option? A: Is the translation the main purpose of your service or is it just seen as a convenience to the user? For the latter case I would kind of go about the problem the other way round: Is it, in your application design, in any way possible to send language-neutral messages (like service.fail or something like that) to the client, and have the client translate them due to a local resource bundle? This would allow independent users of your service allow to transform your answer into anything they want, including translation using ResourceBundle. It is, in my eyes the job of the client interface to show the appropriate message, not the job of your service. Of course, the downside of this is that you won't have your resource bundles all in one place anymore. As to the other side of your question: ResourceBundle is the way to go, it has been specifically designed for the task. Also: I am not aware of any way for a web-service to know anything about it's clients other directly intercepting the Http-Request and reading it's fields, specifically Accept-Language. These fields encode languages like en-US. A: Generally, I would say, if possible, let the client explicitly tell you what language he wants and deliver it according to his needs. This may be an additional web method "getSupportedLanguages" which delivers a list of enUS, deDE or whatever and your other methods may accept those languages and deliver the correct response. Or deliver all language versions and let the client sort it out. But this may be a bit network overkill depending on the number of supported locales... In my opinion, WebServices should "stand on their own", the clients should be thin and not require lots of information to process the content. Imagine a C#-client, who may not be able to work with your Ressources or whatever. Or a new client without ressources not being able to work with your data... Additionally, it could be different to really get the clients locale - a non-english person may use an english system or may be in an english country, but would like to see data in his native language. But if you really need to do this, I'm not aware of anything to enable this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7522161", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why is $facebook->getUser() returning 0? I have read all the other similar questions, but none are the situation that I am experiencing. I have a server side script which does: $this->facebook = new Facebook(array( 'appId' => FACEBOOK_APP_ID, 'secret' => FACEBOOK_SECRET, )); $user = $this->facebook->getUser(); This code works fine in firefox, but in IE, $user always is 0. Why? I logged in first with firefox, if that makes a difference. Does this have something to do with cookies or sessions? If so, how do I clean that up? I tried session_destroy() and the setcookie() with a negative time but those didnt help. Any ideas? Thanks! EDIT: if I reregister, then it works once meaning that I cant tell that I have registered already. EDIT 2: Now this is happening in Firefox too....sigh. Using plugins, I can verify that a cookie is present though. (Deleting it doesnt help) A: Sounds like it is a P3P headers issue, take a look at the following thread: http://forum.developers.facebook.net/viewtopic.php?id=452 to workaround iframe cross-site security in IE which blocks cookies you need to implement P3P hope this helps
{ "language": "en", "url": "https://stackoverflow.com/questions/7522168", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is it possible to "override" just the workflow from a product? I have mynamespace.myproduct and mynamespace.myproduct2. mynamespace.myproduct2 is defined as a dependency in mynamespace.myproduct's metadata.xml. mynamespace.myproduct2 has some workflows that I would like to override, without having to customize mynamespace.myproduct2 as a whole. I know I can change it using the portal_workflow at ZMI, but I need to keep these changes, in both situations when mynamespace.myproduct and mynamespace.myproduct2 are reinstalled in portal_quickinstaller. The workflows would have the same name, but my customized one will have different states, and I need mynamespace.myproduct to override mynamespace.myproduct2's workflows. Summarizing: I need to just change a workflow from a product, (keeping the content-types, etc) but don't want to customize the whole package. I tought about overrides.zcml (an example), but this overrides the profile completely, and I just want to override the workflow (and dont even know if this approach works. adding this file is going to be always used instead of the original profile? How do I properly test it?). And according to plone community guide: Note Difference between ZCML and GenericSetup ZCML changes affect loaded Python code in all sites inside Zope whereas GenericSetup XML files affect only one Plone site and its database. GenericSetup XML files are always database changes. Relationship between ZCML and site-specific behavior is usually done using layers. ZCML directives, like viewlets and views, are registered to be active on a certain layer only using layer attribute. When GenericSetup XML is imported through portal_setup, or the product add-on installer is run for a Plone site, the layer is activated for the particular site only, enabling all views registered for this layer. I don't want this to affect all Plone sites, just one. So, is this possible/feasible, or will I have to do a fork and edit the xml files from the original workflow to work? A: to override any workflow defined in mynamespace.myproduct2 you have to add a new workflow definition in mynamespace.myproduct and bind it to your desired content type. So you have to add this structure: <myproduct>/ |-- ... `-- profiles/ `-- default/ |-- ... |-- workflows.xml `-- workflows/ `-- mycustom_workflow/ `-- definition.xml and in workflows.xml you will have: <?xml version="1.0"?> <object name="portal_workflow" meta_type="Plone Workflow Tool"> <!-- This registers the new workflow --> <object name="mycustom_workflow" meta_type="Workflow"/> <!-- This binds the new wf with MyContent content type --> <bindings> <type type_id="MyContent"> <bound-workflow workflow_id="mycustom_workflow"/> </type> </bindings> </object> This will affect only the site where your product is installed. In the end remember to restart zope and to re-install your product to apply the new genericsetup configuration.
{ "language": "en", "url": "https://stackoverflow.com/questions/7522173", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: WebSharper Interface Generator - Records How do I go about defining a record that would be serialized to a JSON object... I've been trying to build the oConfig parameter for YUI2 constructor, something like: type TreeParameter = { Type : string Label : string Expanded : bool Children : TreeParameter array } Thanks! David A: I guess we could implement this but it has not yet made it into the interface generator. For now you can do: let TreeParameter = let self = Type.New() Pattern.Config "TreeParameter" { Required = [ "Type", T<string> "Label", T<string> "Expanded", T<bool> "Children", Type.ArrayOf self ] Optional = [] } |=> self From F# point of view the generated type will look like this: type TreeParameter(t: string, l: string, e: bool, c: TreeParameter[]) = member this.Type = t member this.Label = l member this.Expanded = e member this.Children = c From JavaScript perspective, the values would look like this: {Type:t,Label:l,Expanded:e,Children:c} In essence it is like a record without the benefit of record syntax and functional extension. A: WebSharper has now implemented this feature. Just use TSelf. Example: let TreeParameter = Pattern.Config "TreeParameter" { Required = [ "Type", T<string> "Label", T<string> "Expanded", T<bool> "Children", Type.ArrayOf TSelf ] Optional = [] }
{ "language": "en", "url": "https://stackoverflow.com/questions/7522175", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: mysql command with the -H flag is translating column values to HTML safe strings There seems to be a feature that has been added in mysql's client command line v14.12 which causes the output columns to be converted to web safe output when the -H flag is being used. This is clearly a safety feature but in my case I am using CONCAT to create intentional html links etc. within some of the columns. Is there a way to turn this apparently new feature off? This problem has arisen in a set of scripts in a shared hosting environment. Extracting a simpler example: echo select \'\<a\>\'\; Results desirably in: select '<a>'; echo select \'\<a\>\'\; | /usr/bin/mysql -s -D database -ppassword Results desirably in: <a> echo select \'\<a\>\'\; | /usr/bin/mysql -H -s -D database -ppassword Results UNDESIRABLY in: <TABLE BORDER=1><TR><TH>&lt;a&gt;</TH></TR><TR><TD>&lt;a&gt;</TD></TR></TABLE> WHAT I WANT, AND USE TO GET IS <TABLE BORDER=1><TR><TH><a></TH></TR><TR><TD><a></TD></TR></TABLE> which I know isn't valid HTML in this example but in my more complex real examples it is a full set of matched anchor tags with labels not just a single <a> in the cell. I want to continue to use the -H flag as I have a large number of scripts yielding simple internal web readable reports that have links to related reports etc. built with CONCAT in the SQL results. It seems to me that the behavior of -H has changed in 14.12 and I can find no mechanism to switch it off. The --raw/-r flag has no effect on the behavior. Is the -H flag irrecoverably broken or is there a workaround? I'm currently using sed -e 's/\&lt;/</g' | sed -e 's/\&gt;/>/g' but there must be a better way within the options of the mysql command itself? For reference: /usr/bin/mysql -V /usr/bin/mysql Ver 14.12 Distrib 5.0.51a, for debian-linux-gnu (i486) using readline 5.2 mysql> status; -------------- /usr/bin/mysql Ver 14.12 Distrib 5.0.51a, for debian-linux-gnu (i486) using readline 5.2 Connection id: 117586 Current database: database Current user: database@localhost SSL: Not in use Current pager: stdout Using outfile: '' Using delimiter: ; Server version: 5.0.51a-3ubuntu5.8 (Ubuntu) Protocol version: 10 Connection: Localhost via UNIX socket Server characterset: latin1 Db characterset: utf8 Client characterset: latin1 Conn. characterset: latin1 UNIX socket: /var/run/mysqld/mysqld.sock Uptime: 1 day 8 hours 22 min 47 sec Threads: 1 Questions: 4222310 Slow queries: 171 Opens: 122761 Flush tables: 1 Open tables: 64 Queries per second avg: 36.222 A: I think you're out of luck. This bug against MySQL is about adding escaping for HTML special characters in output. According to the bug report, this fix has landed in essentially all the 5.x series. (As an aside, though I appreciate that you were relying on this behavior, I'd say that I would consider the old, no-escaping behavior to be a bug.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7522176", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How would I Evaluate a certain formula? I have a multidimension arrayList and I ask the user for a formula and than I evaluate it. The problem is that I get user input like this: ((a1+a2)/12)*a3 the problem is that a1 and a2 and a3 refer to columns and I have to evaluate it to a certain value to it and I am totally lost on how to approach this problem any advice or guidance would be great. Also this calculate value has to update every time the value in any of the columns Update. The thing is the formula isn't hard coded. A: A possibility is write a sort of parser. It's better to use a binary tree structure to represent an expression, rather than a list. Each non-leaf node is an operation and every leaf is operand. A: Personally, I'd try really hard to avoid all the parsing stuff, and look for an EL library that allows you to use your own variable resolver. All you'd need to do then is hook up the variables to your backing model. (In your case, splitting on word/letter boundary, and looking up cell contents.) This would also allow you to include arbitrary functions by simply exposing them to the EL engine. Something like OGNL, MVEL, etc. might be a good starting point. Seems much easier. A: An alternative to Heisenbug's suggestion is to try Dijkstra's shunting-yard algorithm. Instead of relying on a tree structure, you use stacks and queues. The advantage is that these data structures involved are not terribly complicated. The downside is that any errors in implementing the algorithm could be easily missed, as you need to thoroughly understand the operations involved to know if your implementation is correct. A: You will need to turn the formula into something like a Binary Expression Tree. This should be not that difficult. Then you will need to traverse this tree to evaluate the expression value at the start and each time a value in the arrayList changes. Concentrate first on building the tree and getting correct values when you evaluate it. Don't forget negative numbers and variables! Watching the arrayList for changes should be trivial after that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7522178", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Practical (Django) Caching Strategy & Implementation? Cache long, Invalidate cache upon data change I have a Django app that gets near-realtime data (tweets and votes), although updates occur only every minute or two on average. However we want to show the data by updating the site and api results right when it comes in. We might see a whole ton of load on this site, so my initial thought is of course caching! Is it practical to have some sort of Memcached cache that gets invalidated manually by another process or event? In other words, I would cache views for a long time, and then have new tweets and votes invalidate the entire view. * *Do the perhaps modest performance enhancements justify the added complexity? *Is there a practical implementation I could create (I work with other developers, so hacking tons of stuff around each response call isn't a good option)? I'm not concerned about invalidating only some of the objects, and I considered subclassing the MemcachedCache backend to add some functionality following this strategy. But of course, Django's sessions also use Memcached as a write through cache, and I don't want to invalidate that. A: Cache invalidation is probably the best way to handle the stuff you're trying to do. Based on your question's wording, I'm going to assume the following about your app: * *You have some sort of API in place that is receiving new information updates and NOT doing polling. EG: Every minute or two you get an API request, and you store some information in your database. *You are already using Memcached to cache stuff for reading. Probably via a cronjob or similar process that periodically scans your database and updates your cache. Assuming the above two things are true, cache invalidation is definitely the way to go. Here's the best way to do it in Django: * *A new API request comes into your server that contains new data to be stored. You save it in the database, and use a post save signal on your model class (EG: Tweet, Poll, etc.) to update your memcached data. *A user visits your site and requests to read their most recent tweets, polls, or whatever. *You pull the tweet, poll, etc., data out of memcached, and display it to them. This is essentially what Django signals are meant for. They'll run automatically after your object is saved / updated, which is a great time to update your cache stores with the freshest information. Doing it this way means that you'll never need to run a background job that periodically scans your database and updates your cache--your cache will always be up-to-date instantly with the latest data. A: Thanks to @rdegges suggestions, I was able to figure out a great way to do this. I follow this paradigm: * *Cache rendered template fragments and API calls for five minutes (or longer) *Invalidate the cache each time new data is added. * *Simply invalidating the cache is better than recaching on save, because new cached data is generated automatically and organically when no cached data is found. *Manually invalidate the cache after I have done a full update (say from a tweet search), not on each object save. * *This has the benefit of invalidating the cache a fewer number of times, but on the downside is not as automatic. Here's all the code you need to do it this way: from django.conf import settings from django.core.cache import get_cache from django.core.cache.backends.memcached import MemcachedCache from django.utils.encoding import smart_str from time import time class NamespacedMemcachedCache(MemcachedCache): def __init__(self, *args, **kwargs): super(NamespacedMemcachedCache, self).__init__(*args, **kwargs) self.cache = get_cache(getattr(settings, 'REGULAR_CACHE', 'regular')) self.reset() def reset(self): namespace = str(time()).replace('.', '') self.cache.set('namespaced_cache_namespace', namespace, 0) # note that (very important) we are setting # this in the non namespaced cache, not our cache. # otherwise stuff would get crazy. return namespace def make_key(self, key, version=None): """Constructs the key used by all other methods. By default it uses the key_func to generate a key (which, by default, prepends the `key_prefix' and 'version'). An different key function can be provided at the time of cache construction; alternatively, you can subclass the cache backend to provide custom key making behavior. """ if version is None: version = self.version namespace = self.cache.get('namespaced_cache_namespace') if not namespace: namespace = self.reset() return ':'.join([self.key_prefix, str(version), namespace, smart_str(key)]) This works by setting a version, or namespace, on each cached entry, and storing that version in the cache. The version is just the current epoch time when reset() is called. You must specify your alternate non-namspaced cache with settings.REGULAR_CACHE, so the version number can be stored in a non-namespaced cache (so it doesn't get recursive!). Whenever you add a bunch of data and want to clear your cache (assuming you have set this one as the default cache), just do: from django.core.cache import cache cache.clear() You can access any cache with: from django.core.cache import get_cache some_cache = get_cache('some_cache_key') Finally, I recommend you don't put your session in this cache. You can use this method to change the cache key for your session. (As settings.SESSION_CACHE_ALIAS).
{ "language": "en", "url": "https://stackoverflow.com/questions/7522180", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: General Ledger Account Code Format I have added a general ledger account table to my database to store account codes and their descriptions. I have asked three potential clients, two use a 4 digit numeric code the other a 3 digit numeric code. I have been unsuccessful in finding any standards for the account code, can anyone recommend a format based on their experience with general ledger? Numeric(4), Varchar(5) etc... A: There is no standard format. I've worked with upwards of 10 financial systems, all have used different GL code formats. Have a look at the data being used currently and, if possible, check any restrictions imposed by the front-end software (ie numeric only, up to 10 characters long etc) and then set your field accordingly. Anecdotally (just for reference) the systems I have dealt with have been (from memory) obviously unique, between 4 and 8 characters in length and only numeric - but that's certainly not a hard and fast rule. And I've always stored them as varchars because often the front-ends allow non-numeric codes (even thought I've never come across them being used). A: There is no standard format or length for Accounting Codes. The length depends on the number of accounts you want to have in your system. One thing you can do, Assign the different series to different types of accounts. ex. Asset NACs like 1XXX, Liability NACs 2XXX, Revenue NACs 3XXX, Expense NACs 4XXX to identify the account from initial number.
{ "language": "en", "url": "https://stackoverflow.com/questions/7522182", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Adding a custom page dynamically (at runtime) I'm writing an install script utilizing the NSIS installer scripting language. I have a few custom pages that I am able to load without hassle, but I was wondering if it would be possible to insert pages dynamically. What I want to do is have a page with additional configuration options on it and on the bottom have a checkbox that says "Add more settings" or something similar. If the checkbox is ticked, it will show another custom page that's an exact copy of the first one. As long as the user keeps checking the checkbox, more pages should be shown. Is there some method of recycling the same page over and over again? I really don't think I should need to generate a whole new page because it's just the same page again and again, but I'm not sure how to show a new instance of the same page during runtime. A quick Google and stackoverflow search did not warrant any results. Thanks guys. A: The number of pages is fixed at compile time. If you need different "hidden" pages or just a couple instances of the same page I would say that you should just skip the pages when required in the create callback for the page by calling abort but this is not going to work if the page count is unlimited. It is also possible to go directly to a page: Outfile test.exe Requestexecutionlevel user !include nsDialogs.nsh Page Custom mypagecreate mypageleave Page Directory dirpagecreate Page Instfiles Function mypagecreate Var /Global MyCheckBox nsDialogs::Create /NOUNLOAD 1018 Pop $0 ${NSD_CreateCheckBox} 10% 20u 80% 12u "Again?" Pop $MyCheckBox nsDialogs::Show FunctionEnd Function mypageleave ${NSD_GetState} $MyCheckBox $0 StrCpy $MyCheckBox $0 ; This is a bit of a hack, we reuse the HWND var to store the state FunctionEnd Function dirpagecreate ${If} $MyCheckBox <> 0 ; Was the checkbox checked? SendMessage $HWNDPARENT 0x408 -1 "" ; If so, go back ${EndIf} FunctionEnd Section SectionEnd A: page custom page1 option page instfiles Function page1 initpluginsdir file /oname=$PLUGINSDIR\dlg.ini dlg.ini installoptions::dialog "$PLUGINSDIR\dlg.ini" FunctionEnd Function Options ReadINIStr $0 "$PLUGINSDIR\dlg.ini" "Field 1" "State" # Field Must have value 0 or 1. Maybe Text or Chechbox StrCmp $0 0 0 +2 abort FunctionEnd
{ "language": "en", "url": "https://stackoverflow.com/questions/7522185", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Undefined Index errror with $code = $_REQUEST["code"]; for Facebook auth Every time I go to the canvas page of my facebook app it briefly shows an error saying undefined index on the line with $code = $_REQUEST["code"]; at line 9. After this code shows it looks like it does a quick redirect and everything works fine. Does anyone know how to solve this? Here's my code at the top of the canvas: <?php $app_id = "244958008880978"; $app_secret = "xxxxxxxxxxxxxxxxxxxxxxxxx"; $my_url = "https://apps.facebook.com/guessyguesser/"; session_register(); session_start(); $code = $_REQUEST["code"]; if(empty($code)) { $_SESSION['state'] = md5(uniqid(rand(), TRUE)); //CSRF protection $dialog_url = "http://www.facebook.com/dialog/oauth?client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url) . "&state=" . $_SESSION['state']; echo("<script> top.location.href='" . $dialog_url . "'</script>"); } { $token_url = "https://graph.facebook.com/oauth/access_token?" . "client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url) . "&client_secret=" . $app_secret . "&code=" . $code; $response = file_get_contents($token_url); $params = null; parse_str($response, $params); $graph_url = "https://graph.facebook.com/me?access_token=" . $params['access_token']; $user = json_decode(file_get_contents($graph_url)); } ?> Thank you! A: Either add an @ to the beginning of line 9, or move line 9 below the if block and change line 11 to if (!isset($_REQUEST["code"])) { Oh, and also add an exit statement right after that echo.
{ "language": "en", "url": "https://stackoverflow.com/questions/7522189", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }