text
stringlengths
8
267k
meta
dict
Q: emacsclient: could not get terminal name ssh -X root@localhost "emacsclient -c" Warning: untrusted X11 forwarding setup failed: xauth key data not generated Warning: No xauth data; using fake authentication data for X11 forwarding. emacsclient: could not get terminal name I have googled but i can't find the solution to solve it. Update: I thought that emacs client (on local machine) connect to emacs server (on remote machine) so that emacs client can edit file on local machine. But it doesn't seem to work that way... A: using emacsclient with remote forwarding is a little tricky (and the behavior may have been fixed/changed at some point). one thing you could do is just ssh to the server normally, and pass the current ssh display to emacs explicitly: emacsclient -c -d $DISPLAY also found this on the emacsclient wiki: ssh remote_host -f emacsclient --eval ‘”(make-frame-on-display \”$DISPLAY\”)”’ UPDATE: since emacs doesn't seem to like the ":0" display, try writing it out explicitly: emacsclient -c -d localhost:0
{ "language": "en", "url": "https://stackoverflow.com/questions/7626841", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: why EL functions in jsp must be declared as static? I am reading some JSP text regarding EL user-defined functions, and the author said these kinds of functions must be declared static and gave no other explanation. I have tried to declare non-static functions and got a org.apache.jasper.JasperException: java.lang.NullPointerException..... Can any one elaborate on that, please? A: If they were not static, the runtime would be in charge of creating instances of the classes containing the functions. Resulting in state management on those objects - which in fact means you should have written a custom tag instead. You should treat EL functions as helpers only, in most cases you will want to create custom tags. A: If those functions were not static, you would need some instance to call those methods on. This is what latest version of Expression Language (from JSP 2.1) allows you to do. It can call methods (non-static functions): ${bean.doSomethingGreat('with arguments')} (Original EL allowed you to call getters only, using ${bean.property} syntax). A: Short answer: because the JavaServer Pages Specification, JSP.2.10 Functions said that: Functions are mapped to public static methods in Java classes. Two tips why it has to be static: * *for historical reasons, *for performance reasons. Today it's not a big deal to create a new object instance with a no-arg constructor then call the function method and let the garbage collector to get rid of the instance. If you are using the function in a big loop it could hurt but usually it's not a problem. The instance methods would fit better with the test-driven world since it's easier to mock in tests than static methods.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626845", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: fetching data from celery's backend(redis) How do I get data(all I really need is the state of the task) from a Celery backend? I am using Redis. A: Assuming that you configured the CELERY_RESULT_BACKEND to use redis ( see here ), then you can monitor your application using a variety of methods. I believe that celeryctl should suffice..
{ "language": "en", "url": "https://stackoverflow.com/questions/7626846", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Maximum Python object which can be passed to write() I am looking around the net (so far I have found pickle ) for an explanation for what I am doing wrong I am trying to write a very large data structure (nested dictionary/list) to file. Using the below code I discovered that the problem might be because the passed string is too large: f = open('/path/to/file' , 'w') try: f.write(str(dataStructure)) except: try: f.write('ABC') except: print 'Even smaller strings such as ABC did NOT print to the file' else: print 'Smaller strings such as ABC DID print to the file' the dataStructure dictionary has a great deal of clique information, in this case, around 10,000 - 100,000 floating point values. The whole reason I am dumping everything into a single file, instead of saving in subfiles is because I want to exec a single file to load it, rather than manually load a few dozen subsets of the file. Before I start saving each clique (each neuron has several different incoming clique files, such that for a neuron we are looking at 20 indexed files) I was wondering if the file size was actually the problem, or if the problem must be in something else. Thanks A: I'm gonna guess that your problem is that the string you create is too large to exist in memory. For something that big you should write it out piece by piece to the disk. You could use pickle, json, xml or something which should handle this correctly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626848", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SELECT multiple table i need some help here, table "friends" +------+-------------+-----------+ id | friend_id | user_id | +------+-------------+-----------+ 1 | 1222 | 99999 | +------+-------------+-----------+ 2 | 48989 | 1492 | +------+-------------+-----------+ table "users" +------+-------------+---------------+ id | user_name | user_image | +------+-------------+---------------+ 99999 | Mark | img/abc.jpg | +------+-------------+---------------+ 1222 | Tom | img/xyz.jpg | +------+-------------+---------------+ etc. | etc. | etc.. | +------+-------------+---------------+ i want SELECT table friends and make WHERE statement : etc : ... WHERE user_id=$_SESSION[user_id] ... and will display data from table users ok , let say : my current id is 99999 so in table friends is match only 1222 , so this will display all data(image,etc..) from id 1222(Tom) from table users. So my question here is how i need to write this code for generate users data ? *i try to use UNION and LEFT JOIN..but no luck..still newbie.. A: $user_id = intval($_SESSION['user_id']); $friends_of_user = mysql_query(' SELECT f.*, u.* FROM friends f LEFT JOIN users u ON u.id = f.friend_id WHERE f.user_id = '.$user_id); and to exclude all users which doesn't have profiles in users table, just change LEFT JOIN to JOIN A: I'd use the following code: $user_id = mysql_real_escape_string($_SESSION['user_id']); $sql = "SELECT f.* FROM users u INNER JOIN friends f ON (u.user_id = f.friend_id) WHERE u.user_id = '$user_id' ";
{ "language": "en", "url": "https://stackoverflow.com/questions/7626851", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MATLAB Mex Socket Wrapper Library Have anybody written a POSIX socket wrapping library for MATLAB using Mex? I basically want to open, write and read. Both sync and asynchronous alternatives would be nice. My main target platform is Linux. I know Mex and I know POSIX sockets. I just want to make certain that nobody else has done this already? A: If you want to work with sockets, you have two options: 1) use Java capabilities from inside MATLAB (see this answer here on SO for a quick example): * *TCP/IP Socket Communications in MATLAB *TCP/IP Socket Communications in MATLAB using Java Classes 2) use C MEX-wrappers: * *msocket *TCP/UDP/IP Toolbox I also think that the Instrument Control Toolbox includes support for TCP UDP communication.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626854", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Split by [char] but not by [char]{2} via regex I need do it, basically: Parameter | Expected Result (array) a | [a] a_b | [a, b] a_b_c | [a, b, c] a__b | [a_b] <-- note that the double underline be unique a_b__c | [a, b_c] I know how I do it with the methods explode and str_replace and using a foreach to converts __ to _. Basically this: <?php $parameter = 'a_b__c'; $expected = str_replace( '__', "\0", $parameter ); # "a_b\0c" $expected = explode( '_', $expected ); # ["a", "b\0c"] foreach ( $expected as &$item ) $item = str_replace( "\0", '_', $item ); # ["a", "b_c"] ?> But I guess that with preg_* it can be more fast. Or am I wrong? Well, I accept any better suggestion. :) Help note: the $parameter will be ever a PHP identifier (generally a class identifier). A: You can try the following approach using preg_split: $result = preg_split("/(?<!_)_(?!_)/", $parameter); ?<! and ?! are zero-width negative lookaround assertions. A: I do not think it is possible to split and replace in a single regex operation. Let us say you have input a_b__c. In the first step you can split using the expression (same as what Howard gave) $result = preg_split('/(?<!_)_(?!_)/', $subject); which would give you [a, b__c] Now you can iterate on each of the entry in the array and do the replace using $result = preg_replace('/_(?=_)/', '', $subject); which would help you replace b__c with b_c.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626855", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SCRIPT70: Permission denied on IE9 api error 191 I get an SCRIPT70 error on IE9 after doing FB.login(function(response){}) and I don't use iframes for this script. I get an error at: the popup give me an API Error Code: 191 API Error Description: The specified URL is not owned by the application Error Message: Invalid redirect_uri: Given URL is not allowed by the Application configuration. all.js, line 22 character 4250 the error happens at the setLoadedNode function which contains: FB.provide('', { ui: function (f, b) { if (!f.method) { FB.log('"method" is a required parameter for FB.ui().'); return null; } if ((f.method == 'permissions.request' || f.method == 'permissions.oauth') && (f.display == 'iframe' || f.display == 'dialog')) { var h; var i; if (FB._oauth) { h = f.scope; i = h.split(/\s|,/g); } else { h = f.perms; i = h.split(','); } for (var e = 0; e < i.length; e++) { var g = FB.String.trim(i[e]); if (g && !FB.initSitevars.iframePermissions[g]) { f.display = 'popup'; break; } } } var a = FB.UIServer.prepareCall(f, b); if (!a) return null; var d = a.params.display; if (d === 'dialog') { d = 'iframe'; } else if (d === 'none') d = 'hidden'; var c = FB.UIServer[d]; if (!c) { FB.log('"display" must be one of "popup", ' + '"dialog", "iframe", "touch", "async", "hidden", or "none"'); return null; } c(a); return a.dialog; } }); FB.provide('UIServer', { Methods: {}, _loadedNodes: {}, _defaultCb: {}, _resultToken: '"xxRESULTTOKENxx"', _forceHTTPS: false, genericTransform: function (a) { if (a.params.display == 'dialog' || a.params.display == 'iframe') { a.params.display = 'iframe'; a.params.channel = FB.UIServer._xdChannelHandler(a.id, 'parent.parent'); } return a; }, prepareCall: function (h, b) { var g = h.method.toLowerCase(), f = FB.copy({}, FB.UIServer.Methods[g]), e = FB.guid(), c = (f.noHttps !== true) && (FB._https || (g !== 'auth.status' && g != 'login.status')); FB.UIServer._forceHTTPS = c; FB.copy(h, { api_key: FB._apiKey, app_id: FB._apiKey, locale: FB._locale, sdk: 'joey', access_token: c && FB.getAccessToken() || undefined }); h.display = FB.UIServer.getDisplayMode(f, h); if (!f.url) f.url = 'dialog/' + g; var a = { cb: b, id: e, size: f.size || FB.UIServer.getDefaultSize(), url: FB.getDomain(c ? 'https_www' : 'www') + f.url, forceHTTPS: c, params: h, name: g, dialog: new FB.Dialog(e) }; var j = f.transform ? f.transform : FB.UIServer.genericTransform; if (j) { a = j(a); if (!a) return; } var d = f.getXdRelation || FB.UIServer.getXdRelation; var i = d(a.params); if (!(a.id in FB.UIServer._defaultCb) && !('next' in a.params)) a.params.next = FB.UIServer._xdResult(a.cb, a.id, i, true); if (i === 'parent') a.params.channel_url = FB.UIServer._xdChannelHandler(e, 'parent.parent'); a = FB.UIServer.prepareParams(a); return a; }, prepareParams: function (a) { var c = a.params.method; if (!FB.Canvas.isTabIframe()) delete a.params.method; if (FB.TemplateUI && FB.TemplateUI.supportsTemplate(c, a)) { if (FB.reportTemplates) console.log("Using template for " + c + "."); FB.TemplateUI.useCachedUI(c, a); } else { a.params = FB.JSON.flatten(a.params); var b = FB.QS.encode(a.params); if (FB.UIServer.urlTooLongForIE(a.url + b)) { a.post = true; } else if (b) a.url += '?' + b; } return a; }, urlTooLongForIE: function (a) { return a.length > 2000; }, getDisplayMode: function (a, b) { if (b.display === 'hidden' || b.display === 'none') return b.display; if (FB.Canvas.isTabIframe() && b.display !== 'popup') return 'async'; if (FB.UA.mobile() || b.display === 'touch') return 'touch'; if (!FB.getAccessToken() && b.display == 'dialog' && !a.loggedOutIframe) { FB.log('"dialog" mode can only be used when the user is connected.'); return 'popup'; } if (a.connectDisplay && !FB._inCanvas) return a.connectDisplay; return b.display || (FB.getAccessToken() ? 'dialog' : 'popup'); }, getXdRelation: function (b) { var a = b.display; if (a === 'popup' || a === 'touch') return 'opener'; if (a === 'dialog' || a === 'iframe' || a === 'hidden' || a === 'none') return 'parent'; if (a === 'async') return 'parent.frames[' + window.name + ']'; }, popup: function (b) { var a = typeof window.screenX != 'undefined' ? window.screenX : window.screenLeft, i = typeof window.screenY != 'undefined' ? window.screenY : window.screenTop, g = typeof window.outerWidth != 'undefined' ? window.outerWidth : document.documentElement.clientWidth, f = typeof window.outerHeight != 'undefined' ? window.outerHeight : (document.documentElement.clientHeight - 22), k = FB.UA.mobile() ? null : b.size.width, d = FB.UA.mobile() ? null : b.size.height, h = (a < 0) ? window.screen.width + a : a, e = parseInt(h + ((g - k) / 2), 10), j = parseInt(i + ((f - d) / 2.5), 10), c = []; if (k !== null) c.push('width=' + k); if (d !== null) c.push('height=' + d); c.push('left=' + e); c.push('top=' + j); c.push('scrollbars=1'); if (b.name == 'permissions.request' || b.name == 'permissions.oauth') c.push('location=1,toolbar=0'); c = c.join(','); if (b.post) { FB.UIServer.setLoadedNode(b, window.open('about:blank', b.id, c)); FB.Content.submitToTarget({ url: b.url, target: b.id, params: b.params }); } else FB.UIServer.setLoadedNode(b, window.open(b.url, b.id, c)); if (b.id in FB.UIServer._defaultCb) FB.UIServer._popupMonitor(); }, setLoadedNode: function (a, b) { FB.UIServer._loadedNodes[a.id] = b; if (a.params) b.fbCallID = a.id; }, getLoadedNode: function (a) { return FB.UIServer._loadedNodes[a.id]; }, hidden: function (a) { a.className = 'FB_UI_Hidden'; a.root = FB.Content.appendHidden(''); FB.UIServer._insertIframe(a); }, iframe: function (a) { a.className = 'FB_UI_Dialog'; var b = function () { FB.UIServer._triggerDefault(a.id); }; a.root = FB.Dialog.create({ onClose: b, closeIcon: true, classes: (FB.UA.iPad() ? 'centered' : '') }); if (!a.hideLoader) FB.Dialog.showLoader(b, a.size.width); FB.Dom.addCss(a.root, 'fb_dialog_iframe'); FB.UIServer._insertIframe(a); }, async: function (a) { a.frame = window.name; delete a.url; delete a.size; FB.Arbiter.inform('showDialog', a); }, getDefaultSize: function () { if (FB.UA.mobile()) if (FB.UA.iPad()) { return { width: 500, height: 590 }; } else { var a = window.innerWidth / window.innerHeight > 1.2; return { width: window.innerWidth, height: Math.max(window.innerHeight, (a ? screen.width : screen.height)) }; } return { width: 575, height: 240 }; }, _insertIframe: function (b) { FB.UIServer._loadedNodes[b.id] = false; var a = function (c) { if (b.id in FB.UIServer._loadedNodes) FB.UIServer.setLoadedNode(b, c); }; if (b.post) { FB.Content.insertIframe({ url: 'about:blank', root: b.root, className: b.className, width: b.size.width, height: b.size.height, id: b.id, onInsert: a, onload: function (c) { FB.Content.submitToTarget({ url: b.url, target: c.name, params: b.params }); } }); } else FB.Content.insertIframe({ url: b.url, root: b.root, className: b.className, width: b.size.width, height: b.size.height, id: b.id, name: b.frameName, onInsert: a }); }, _handleResizeMessage: function (b, a) { var c = FB.UIServer._loadedNodes[b]; if (a.height) c.style.height = a.height + 'px'; if (a.width) c.style.width = a.width + 'px'; FB.Arbiter.inform('resize.ack', a || {}, 'parent.frames[' + c.name + ']', true); if (!FB.Dialog.isActive(c)) FB.Dialog.show(c); }, _triggerDefault: function (a) { FB.UIServer._xdRecv({ frame: a }, FB.UIServer._defaultCb[a] || function () {}); }, _popupMonitor: function () { var a; for (var b in FB.UIServer._loadedNodes) if (FB.UIServer._loadedNodes.hasOwnProperty(b) && b in FB.UIServer._defaultCb) { var c = FB.UIServer._loadedNodes[b]; try { if (c.tagName) continue; } catch (d) {} try { if (c.closed) { FB.UIServer._triggerDefault(b); } else a = true; } catch (e) {} } if (a && !FB.UIServer._popupInterval) { FB.UIServer._popupInterval = window.setInterval(FB.UIServer._popupMonitor, 100); } else if (!a && FB.UIServer._popupInterval) { window.clearInterval(FB.UIServer._popupInterval); FB.UIServer._popupInterval = null; } }, _xdChannelHandler: function (b, c) { var a = (FB.UIServer._forceHTTPS && FB.UA.ie() !== 7); return FB.XD.handler(function (d) { var e = FB.UIServer._loadedNodes[b]; if (!e) return; if (d.type == 'resize') { FB.UIServer._handleResizeMessage(b, d); } else if (d.type == 'hide') { FB.Dialog.hide(e); } else if (d.type == 'rendered') { var f = FB.Dialog._findRoot(e); FB.Dialog.show(f); } else if (d.type == 'fireevent') FB.Event.fire(d.event); }, c, true, null, a); }, _xdNextHandler: function (a, b, d, c) { if (c) FB.UIServer._defaultCb[b] = a; return FB.XD.handler(function (e) { FB.UIServer._xdRecv(e, a); }, d) + '&frame=' + b; }, _xdRecv: function (b, a) { var c = FB.UIServer._loadedNodes[b.frame]; try { if (FB.Dom.containsCss(c, 'FB_UI_Hidden')) { window.setTimeout(function () { c.parentNode.parentNode.removeChild(c.parentNode); }, 3000); } else if (FB.Dom.containsCss(c, 'FB_UI_Dialog')) { FB.Dialog.remove(c); if (FB.TemplateUI && FB.UA.mobile()) FB.TemplateUI.populateCache(); } } catch (d) {} try { if (c.close) { c.close(); FB.UIServer._popupCount--; } } catch (e) {} delete FB.UIServer._loadedNodes[b.frame]; delete FB.UIServer._defaultCb[b.frame]; a(b); }, _xdResult: function (a, b, d, c) { return (FB.UIServer._xdNextHandler(function (e) { a && a(e.result && e.result != FB.UIServer._resultToken && FB.JSON.parse(e.result)); }, b, d, c) + '&result=' + encodeURIComponent(FB.UIServer._resultToken)); } }); I added the entire line 22 beautified Has anyone had this problem? thank you A: It seems the current url path must be under the "canvas url" you set in your facebook application settings for the auth dialog to work. This is strange, because a like widget will work ok anywhere !
{ "language": "en", "url": "https://stackoverflow.com/questions/7626858", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: about linux v0.01 bootsect.S Recently I'm looking at the linux 0.01 source code, since the bootsect.S in 2.6.11 and upper version is useless and it is a good place to start learning linux code, therefore I choose to trace the first version of linux. :P I have some question in bootsect.S. The following is some of the code in bootsect.S linux v 0.01. P.S the first version assembly code is using intel syntax instead of at&t. mov ax,#0x0001 | protected mode (PE) bit lmsw ax | This is it! jmpi 0,8 | jmp offset 0 of segment 8 (cs) which is the second entry of the gdt. gdt: .word 0,0,0,0 | dummy .word 0x07FF | 8Mb - limit=2047 (2048*4096=8Mb) .word 0x0000 | base address=0 .word 0x9A00 | code read/exec .word 0x00C0 | granularity=4096, 386 .word 0x07FF | 8Mb - limit=2047 (2048*4096=8Mb) .word 0x0000 | base address=0 .word 0x9200 | data read/write .word 0x00C0 | granularity=4096, 386 The booting process seems to be like the following: * *move the bootloader code from 0x7c00 to 0x9000 *jumps to 0x9000 *set the segment registers. *load the system code to 0x10000 (the system code contains boot/head.S and init/main.c according to the Makefile) *load temporary gdt and idt with lgdt and lidt *enable A20 to access the 16mb physical memory. *set cr0 PE bit to go to protected mode *jump to 0x000000 the following is the Makefile for system: tools/system: boot/head.o init/main.o \ $(ARCHIVES) $(LIBS) $(LD) $(LDFLAGS) boot/head.o init/main.o \ $(ARCHIVES) \ $(LIBS) \ -o tools/system > System.map It seems like that the head.S and main.c is link together as the system binary which the bootsect loads into memory. My question is if the system code(which entry is head.S/startup_32 ) is loaded in 0x10000 than why not jumps to 0x10000 instead jumps to 0x000000? Isn't it weird to jump to 0x0 since there is no code loaded inside there?? the following is the link to download the source code: https://docs.google.com/viewer?a=v&pid=explorer&chrome=true&srcid=0B1F0m2rUn8BYMjQ4ZDQxZTUtODI5My00MGZiLTgwZDQtM2ZiZWQ2ZWQxYzIx A: Here's the answer: | It then loads the system at 0x10000, using BIOS interrupts. Thereafter | it disables all interrupts, moves the system down to 0x0000, ... and here's the code that goes with it: cli | no interrupts allowed ! | first we move the system to it's rightful place mov ax,#0x0000 cld | 'direction'=0, movs moves forward do_move: mov es,ax | destination segment add ax,#0x1000 cmp ax,#0x9000 jz end_move mov ds,ax | source segment sub di,di sub si,si mov cx,#0x8000 rep movsw j do_move If you look closely at the code, you'll notice that it indeed starts doing REP MOVSW with ES=0,DI=0 (destination) and DS=0x1000,SI=0 (source), that is, it moves stuff from 0x10000(=DS*0x10+SI) to 0(=ES*0x10+DI).
{ "language": "en", "url": "https://stackoverflow.com/questions/7626861", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Query optimization using primary key I have a database with two tables: one that keeps information about each user and one that keeps information about the games each user is currently playing. Each user row and each game row has a unique primary ID so that whenever I want to fetch a particular row, I can obtain it by querying with the unique ID (which to my understanding is faster since the row can be fetched through indexing instead of going through each row in the table) Now, each entry in the game table contains information about the user, so if I wanted to fetch every game for a particular user I would be able to. However, this is how I am currently fetching each game for a user: I save every unique ID for each game for each user delimited by ':'. I then split this list and do a separate query for EACH game ID. So my question is, is it more efficient to do a separate query using the primary ID for each individual game, or is it better just to do a "SELECT * FROM games WHERE userID='theUsersID'". To put it in a more general form, is it better in the long run to do several queries against several unique IDs, or doing one query but having to look through every entry in the database? Just to give an idea of my database load, I typically have 10,000 users, each with about 10 games at once. So the comparison is 100,000 queries using a primary key for each query, or 10,000 queries but having to go through all rows for each query. Thanks. A: When you do "SELECT * FROM games WHERE userID='theUsersID'", the database engine shouldn't have to actually lookup ALL of the database entries. If this is a common query, then the userID column should have an index, so that the restriction on the where can be processed quickly. In the long run, it'll be much more efficient to do only one query then one for each game. A: MySQL won't even skip a beat with the low volume you are considering. Allow future flexibility. Your "games per user" table should be UniqueID, UserID, GameID --- plus anything else you might want to track on a per user, per game combination... which is most frequent, last time played for a particular game, etc. I would NEVER suggest concatenation of unique games by any delimiter. This way, you can easily query... Who likes a particular game by querying on the game ID, or how many distinct games does the average person like to play... What are the top common games among users. Simple to have multiple indexes on the table.. One on the Primary ID (required), one by User ID and Game ID (for optimized search for game by user first), another by Game ID and User ID (for searching for particular games) A: So to the best of my understanding, there is a many to many relation between Users and Games. Each User play many games Each Game has many users. and you are currently storing the games played by each user in the users table User ID | Games ID's 1 | 45:23:12 2 | 23:66:11 So your tables are not normalized. Not even 1NF. Consider Normalizing your Data. One table for Games, which you already have. One table for users, you have this too. One Glue Table, users_games, with : ID | userID | GameID 1 | 1 | 45 2 | 1 | 23 3 | 1 | 12 4 | 2 | 23 5 | 2 | 66 6 | 2 | 11 So for retrieving Data about one user, you will use Joins Select GameID from users u join users_games ug on u.id=ug.userID where u.id='2'; and you can extend columns in the users_games table. This model will be scalable and more manageable. Hope that makes sense :) A: SELECT * FROM games WHERE userID=userID would be the best model; if you nedd to connect multiple games to one user use LEFT JOIN, so you will be able to do it with one query in the games table have foloving columns id | userID | on id put Unique AI and userID can be simple index A: As far as i understand, your tables are built like this: Table_User: UserId (PK); UserInformation; UserInformation2; ... Table_Games: GameId (PK); UserId (PK); GameInformation; ... So, doing a LEFT-Join: SELECT * FROM Table_Games G LEFT JOIN Table_User U on (U.UserId = G.UserId) WHERE UserId = 'MyUserId' might help you. Here, you can also SELECT the User by an unique Name or sth. else based on Table_User! Regards! A: Performing one big query instead of many small ones is usually preferable because: * *It can be performed in just one database round-trip instead of many. This is especially important when database round-trips need to go over the network. *Allows database engine to use more advanced query plan than simple NESTED LOOPS that you are emulating in your code ("big" databases such as Oracle are also capable of doing MERGE or HASH JOINs, not sure about MySQL). Doing a JOIN on your two tables should do the trick.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626867", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Skype API or Google Talk/Voice in Java, Android It will use Skype's API or Google Talk/Voice. The app's front screen is very simple. The app is meant to be an intercom through skype, so it will have its own skype account and will call another specific skype account. At the top will be a status bar. It could say: Not Connected, Calling, Connected, and No Answer. Below that should be the spot where the video comes in through the skype api. At the bottom should be a "Push to Call" button and when in the middle of a conversation, a "Push to End" button. In the bottom right of the screen should be an invisible button to enter the admin backend. When clicked, a passcode will popup (set the first time the app is opened). On the backend, the app will allow the user to enter the app's skype username and password. It will also ask for the skype username it should be contacting. Below that is should ask for an email address. The email address should be used when the app says no answer, an envelope should popup and say "Send Message". If the user clicks on it, the app uses the androids default email address to send an email to the email address entered in the admin section. The last part is there should be two boxes on it. If the first one is checked, the front page should remain the same. If the second one is checked, the front page should change a little. Everything should remain the same but shrink a little and at the top should be a search bar and a scrollable list of all the skype user's contacts. If skype won't work, I would want it built through Google Talk/Voice. Can I do that using Skype API or Google Talk? A: Skype does have an API but I am not sure how good it is. Here is the link: https://developer.skype.com/ Google Voice has an api and there is an unofficial java library that you can use in Android. Here is the link: http://code.google.com/p/google-voice-java/ So you can look into those and see if they work for the app idea that you have.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626869", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Mobile Data connection is a battery killer if there is no data transfering? I'm developing an app that use Mobile Data connection (always GPRS) to upload in a loop each 5 minutes 300 kb of data. Between two upload i see that the data connection remains up (gprs logo on status bar) even if there aren't data transferring.... In this time (between two upload) the battery is used by the Mobile Data connection? Do you think that i should use this method to disable and enable connection between uploads to save the batterylife or is not helpfull? If is it so...how can i use that code in my Service Class such as a function, without create a new class? THanx from a noob! EDIT The app is for my personal use and the app have the entire control of phone (the phone is alone and it doesn't interact with the user). So i can sto all data connection...but i can't use that code as i want (as a function!) Help me! EDIT 2 Anyway i'm able to enable and disable "airplane mode", but the reconnection require minim 13-14 seconds. May be this help to save battery in the "dead time"? A: Since Android 1.5, the AlarmManagers supports what is known as inexact repeating (setInexactRepeating). It's basically a mechanism that allows to minimize the number of times the phone has to wake up for data by collecting the desired intervals from all applications on the device and ensuring that they all communicate at the same time. Five minutes is pretty frequent though, maybe you can reduce it to 15 or 30 minutes, that will save a lot of battery. A: GPRS costs a bit of battery, but generally, most phones are on "always on" data anyway. Other things that are really draining the battery are wake-locks. Are you keeping any of those? Why is it GPRS and not UTMS, for another matter? For the link you provided, that's a method to turn on mobile data usage for all apps. that's something you really don't want to do, as your users will be quite unhappy. There might be specific cases, (restricted deployment to tightly controlled handsets) were this makes sense, but overall, it won't matter. Btw, in your android settings (Settings->System->Battery) you can find out how much your app is draining the battery. [edit] in the case you describe, the best thing would be to really turn of the mobile data usage while you're not using it. But this will be rather tricky (without rooting your phone, i'm not even sure it's possible) and it'll take you a long time. Make sure you will really need that extrac percentage of juice. As said in the post you linked, you'll need to have an Android Version <2.3 (up to 2.2) and the MODIFY_PHONE_STATE Permission to disable network. It's not possible on Gingerbread. A: I'm developing an app that use Mobile Data connection (always GPRS) to upload in a loop each 5 minutes 300 kb of data. You are using whatever the user's chosen data connection is. You can elect to skip doing the work on WiFi if you want, though I am not quite sure why. In this time (between two upload) the battery is used by the Mobile Data connection? The GSM or CDMA radio is always consuming battery. It consumes more during active data transfer, but it is always powered on (except when the device is in airplane mode). Do you think that i should use this method to disable and enable connection between uploads to save the batterylife or is not helpfull? Only if the only person who will ever run the application is you, you are running an Android 2.2 device (or older), and you don't mind messing up your phone. The code you link to is pathetic -- it might break on some devices and might break in the future, since it is bypassing the SDK. Moreover, if it is not your phone, I am not quite certain why you think you have the right to foul up other people's devices. And, to top it off, you can no longer hold the permission necessary to use that hack, as of Android 2.3.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626871", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Dns.GetHostByAddress() works but Dns.GetHostEntry() doesn't I changed my code so it no longer uses the deprectaed: Dns.GetHostByAddress(ipaddress); to use: Dns.GetHostEntry(ipaddress); The problem is I get an exception from Dns.GetHostEntry No such host is known SOURCE: System TARGETSITE: System.Net.IPHostEntry GetAddrInfo(System.String) If I go back to the deprecated Dns.GetHostByAddress it correctly looks up the hostname from the IP address I give it. I see this problem on XP 64bit and Windows 7. Haven't tried it on anything else. I'm using .Net 2.0. A: I think the problem is that Dns.GetHostEntry does a reverse lookup and Dns.GetHostByAddress doesn't. Try other ip address / hostnames and you will see that sometimes it works. I don't know of any solution, but maybe there is. You can stick with the obsolete function until you found a solution.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626876", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Match if several identical characters in a string I would like to match if a string contains more than 1 identical character, for example : Using PHP preg_match or similar function. the character would be "-" Something-or other : no match Test-tes-t : match Basically what I want to do is disallow the use of more than 1 "-" in a user input. A: Isn't just substr_count($text, '-') > 1 enough?
{ "language": "en", "url": "https://stackoverflow.com/questions/7626877", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: django RadioSelect widget list id I currently have a RadioSelect widget on one of my form classes that I want to style with css. However the rendered widget is contained in an ul and the list has no id. What is the easiest way to add an id to the rendered list? A: Subclass RadioFieldRenderer and override render method. RadioFieldRenderer is an object used by RadioSelect to enable customization of radio widgets. Example implementation that adds class to ul element: from django.utils.encoding import force_unicode from django.utils.safestring import mark_safe class MyRadioFieldRenderer(forms.widgets.RadioFieldRenderer): def render(self): """Outputs a <ul> for this set of radio fields.""" return mark_safe(u'<ul class="inputs-list">\n%s\n</ul>' % u'\n'.join([u'<li>%s</li>' % force_unicode(w) for w in self])) Usage: field = forms.ChoiceField(label=_('field'), choices=FIELD_CHOICES, widget=forms.widgets.RadioSelect( renderer=MyRadioFieldRenderer ) ) A: I have no solution to modify rendered html. But you can put rendered html inside a tag with id (or a class in my case): <td class="tria_tag" > <ul> <li><label for="id_935591-estat_0"><input checked="checked" name="935591-estat" value="2" id="id_935591-estat_0" type="radio" class="presenciaEstat" /> Present</label></li> <li><label for="id_935591-estat_1"><input value="3" type="radio" class="presenciaEstat" name="935591-estat" id="id_935591-estat_1" /> Falta</label></li> <li><label for="id_935591-estat_2"><input value="4" type="radio" class="presenciaEstat" name="935591-estat" id="id_935591-estat_2" /> Justificada</label></li> <li><label for="id_935591-estat_3"><input value="5" type="radio" class="presenciaEstat" name="935591-estat" id="id_935591-estat_3" /> Retràs</label></li> </ul> </td> and then with jquery you can access to : $('.tria_tag').each( function(index) { ul=$(this).children().first(); ...
{ "language": "en", "url": "https://stackoverflow.com/questions/7626878", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: UINavigationBar - How to change the position of UIBarButtonItem? I've subclassed a UINavigationBar. NavigationBar has two buttons of type UIBarButtonItem. Is it possible to move these button? For example I would like to move "left button" 50px right and "right button" 50px left. Is LayoutSubViews the right place to move these button? This is the NavigationBar class (created in MT): [MonoTouch.Foundation.Register("NavigationBar")] public class NavigationBar : UINavigationBar { public NavigationBar (IntPtr handle) : base (handle) { Initialize (); } [Export ("initWithCoder:")] public NavigationBar (NSCoder coder) : base (coder) { Initialize (); } public NavigationBar(RectangleF frame, string title) : base (frame) { InitializeWithStyleAndTitle(title); } void Initialize() { } void InitializeWithStyleAndTitle(string title) { //- title UINavigationItem navItem = new UINavigationItem(title); //- left button UIBarButtonItem leftBarButtonItem = new UIBarButtonItem("back", UIBarButtonItemStyle.Plain, this, new Selector("backAction")); navItem.LeftBarButtonItem = leftBarButtonItem; //- right button UIBarButtonItem rightBarButtonItem = new UIBarButtonItem("update", UIBarButtonItemStyle.Plain, this, new Selector("updateAction")); navItem.RightBarButtonItem = rightBarButtonItem; //- style BarStyle = UIBarStyle.Black; PushNavigationItem(navItem, false); } //- selectors omitted } A: I'm setting the frame of a custom button and place the button in a view CustomButton *menu = [[CustomButton alloc] initWithFrame:CGRectMake(7, 3, 35, 35)]; [menu setImage:[UIImage imageNamed:@"sliding_drawer_white_icons"] forState:UIControlStateNormal]; UIView * menuButtonView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 46.0f, 40.0f)]; [menuButtonView addSubview:menu]; self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:menuButtonView]; A: No, UINavigation has a specific behavior, left and right buttons only. You should use UIToolbar instead if you need to position the buttons. Add spacers in between to adjust the positioning of the buttons.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626886", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Creating an Android search result list I am trying to implement the following logic: User enters a search string in a text box (an activity) -> Web service is called to perform the search asynchronously -> Search results are displayed in a list (another activity) So far I have the following: An activity to enter the search string and click a "Search" button: public class Search extends Activity { // ... // called when "Search" button is clicked private void runSearch() { ProgressDialog progressDialog = ProgressDialog.show( this, "Search", "Search..."); searchAsyncTask = new SearchAsyncTask(); SearchAsyncTaskParam param = new SearchAsyncTaskParam(); param.SearchString = getSearchCode(); // gets input from text box param.ProgressDialog = progressDialog; searchAsyncTask.execute(param); } } Then I have a class to perform the asynchronous search: public class SearchAsyncTask extends AsyncTask<SearchAsyncTaskParam, Void, SearchAsyncTaskResult> { private SearchAsyncTaskParam param; @Override protected SearchAsyncTaskResult doInBackground( SearchAsyncTaskParam... params) { if (params.length > 0) param = params[0]; SearchAsyncTaskResult result = new SearchAsyncTaskResult(); // call Webservice and fill result object with status (success/failed) // and a list of hits (each hit contains name, city, etc.) return result; } @Override protected void onPostExecute(SearchAsyncTaskResult result) { param.ProgressDialog.dismiss(); if (!result.Success) // throw an AlertBox else { // this part is incomplete and doesn't look good, does it? // And how would I pass my result data to the new activity? Intent intent = new Intent(param.ProgressDialog.getContext(), SearchResultList.class); param.ProgressDialog.getContext().startActivity(intent); } } } And the last element is an activity to display a list with the search results: public class SearchResultList extends ListActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setListAdapter(new ArrayAdapter<String>( this, android.R.layout.simple_list_item_1, data)); // String was only for testing, should be a class with holds the data // for each item, i.e. Name, City, etc. And where do I get "data" from? } // ... } Now my questions: * *Is it a good idea to start the activity for the result list in the onPostExecute method of the AsyncTask instance? I have tested it with the simple test sketched above and it seems to work. But is this safe, am I on the right thread (UI thread) at all? If this is bad practice what is the alternative to start the result activity? *It looks especially weird to use the context of the ProgressDialog for the Intent and to start the activity. It is just the only context I have available in the AsyncTask instance. Can this be a problem because the ProgressDialog is already dismissed? What context else could I use? *How do I pass my result data into the SearchResultList activity? *In case of a successful search (the else case in the onPostExecute method above) I would like to close the Search activity with the text box so that, if the back button is hit, the user returns to the main screen (which the search activity was opened from) and not the Search activity. Is this possible and how can I do that? A: * *Yes, because you are on the UI thread. The alternative would be if you aren't using AsyncTask but just a simple thread. In that case you would use a Handler to notify the UI thread that work is complete. This is one of the reasons Asynctask exists, so you don't have to do the latter version. * "It looks especially weird to use the context of the ProgressDialog for the Intent and to start the activity." It's not weird at all because when you created the ProgressDialog you passed the context of Search, so when you retrieve the context of the ProgressDialog you actually get the context of the Search activity. No problem at all. *This depends on what data you want to pass. If you just want to pass an array of Strings you could do it like this: String [] data = getData(); Intent intent = new Intent(param.ProgressDialog.getContext(), SearchResultList.class); intent.putExtra("key1", data); param.ProgressDialog.getContext().startActivity(intent); Then in the SearchResultList activity you would do: String [] data = this.getIntent().getStringArrayExtra("key1"); If you would like to pass an object of your own, see this question: How to declare global variables in Android? *Is it possible? Yes. There's two ways to do this in your case. Either you can, as I would do it, write the SearchAsyncTask as a inner class in your Search class and the just call Search.this.finish(); If some condition holds, or you can check out the accepted anwser to this question: android how to finish an activity from other activity Good Luck!
{ "language": "en", "url": "https://stackoverflow.com/questions/7626889", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Joomla Frontend AND Backend Down after Installing Extension I recently tried to install an extension for Joomla, and as soon as it had been enabled, the site (both frontend and backend) went blank. From researching online, it sounds like this might be due to a PHP error- but how would I go about fixing this problem, especially now that I am essentially locked out of the site. (I am working on ftp to the backend- but what should I do once there?) A: First things first: I assume this is urgent because it's on a live site. After fixing this, it would be a good idea to set up a dev/test site, so you can try things like this, and play around without breaking the live site ;). Also, start some backups from now (before doing the below). It depends somewhat on what type the extension the extension is, but you can generally remove a Joomla extension by just removing its files. Even if it leaves remnants in the database, those generally won't actually run. * *If it's a plugin, those files are in /plugins/PLUGINGROUP/PLUGINNAME, and maybe /language/LANG/ *If it's a component, those files are in /components/COMPONENTNAME, /administrator/components/COMPONENTNAME, and maybe /language/LANG/ *If it's a module, those files are in /modules/MODULENAME, and maybe /language/LANG/ However, if the extension is question modifies core Joomla files (it shouldn't, and this is bad practice, but several do...) then all bets are off. You'll either have to go through the install script and analyze what it does on install, or you'll have to rebuild your Joomla site (might be doable by uploading core Joomla over the top). Moral of the story: test first, then put changes live! A: Login to site database and query all extensions. Disable this extension and let your Live site start working without this extension. Try on a local machine figuring out what goes wrong when you install this extension. There can be a number of things simple one like some of the php extension is disabled etc.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626890", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: JPQL/HQL - Is it possible to specify the order, by providing a list of IDs? (Note: I'm using the Play! framework, which uses Hibernate as the JPA implementation.) I have a list of IDs and I want to get the Items from the database by keeping the order that is used in my ID list. Let's say my list is: 444,222,333,111 I want the JPQL/HQL to return the Item with id #444 first, then the one with id #222, etc. I tried something like: id in (444,222,333,111) order by id=444 DESC, id=222 DESC, id=333 DESC, id=111 DESC But it doesn't seem to work. Is it possible or will I have to forget the "order by" part and manually re-order the Items once returned? A: If there's no "natural" order then it's likely you'll need to order manually; you might be able to rely on DB ordering depending on the DB and query construction, but IMO that's risky. On the plus side, unless you have a huge number of objects, the overhead is trivial. A: I think you'll have to sort the items in Java: public void sortItems(List<Item> items, final List<Long> ids) { Collections.sort(items, new Comparator<Item>() { @Override public int compare(Item i1, Item i2) { int index1 = ids.indexOf(i1.getId()); int index2 = ids.indexOf(i2.getId()); return Integer.valueOf(index1).compareTo(Integer.valueOf(index2)); } }); } A: Even old questions are asked much later again. I solved this using a mapping: @Override public List<MyItem> fetch(List<Long> ids) { // Create an identity map using the generic fetch. Rows are returned, but not necessarily in the same order Map<Long, MyItem> resultMap = super.fetch(ids).stream().collect(Collectors.toMap(MyItem::getId, Function.identity())); // Now return the rows in the same order as the ids, using the map. return ids.stream().map(id -> resultMap.get(id)).collect(Collectors.toList()); } A: This particular case would be easily handled using ORDER BY id DESC, but I'm guessing that it's only a poorly chosen example. I'd say it's not possible unless you can find a way to take advantage of SQL to do it. You should have a persistence layer to map objects from a database into Java (you should not be passing ResultSet out of the persistence layer). It'd be trivial to do it there. A: A little easier items.sort(Comparator.comparingLong(i -> ids.indexOf(i.getId())));
{ "language": "en", "url": "https://stackoverflow.com/questions/7626894", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Remove/Insert code at compile time without duplication in C++ I have a template class that is taking in a couple of types. One type is there just to determine policies. That class determines how a function may work in certain cases. Let's say this is one of the function: /* this code is part of a class */ template <typename T, typename T_Policy> // Not important but just showing the template parameters of the class void Allocate(unsigned int numElements) { // Some code here while (someCondition) // Other functions don't have the loop, this is just an example { // Some code here if (T_Policy::trackElements) { /* some code here */ } if (T_Policy::verbose) { /* some code here */ } if (T_Policy::customManager) { /* some code here */ } /* and a few other policies */ } // Some more code here } I would like the lines of code that are using the policies to be compiled out instead of relying on if statements. One obvious way is to put the while loop in overloaded functions each taking a dummy object with a specific policy type. But that means a lot of code duplication. Similar approaches with template specialization will result in code duplication as well. Is there a way to compile out the code without code duplication? A: If the values in the policy are const, the compiler can optimize the generate code because it can see which if is always true or always false. A: You can always change code if (T_Policy::trackElements) { /* some code here */ } into template <bool b> void trackElementPhase() { /* some code here */ } template <> void trackElementPhase<false>() {} // empty body ... later in the code trackElementPhase<T_Policy::track_elements>(); Of course T_Policy::track_elements has to be compile time constant for this. However, I wouldn't bother. The compiler is likely clever enough to optimize out code in if (T_Policy::trackElements) { /* some code here */ } if the condition is compile time constant. A: You can use recursive templates to make a list of policies, which all get applied, e.g.: #include <iostream> template <typename Policy, typename Next=void> struct policy_list { static void apply() { Policy::implement(); Next::apply(); } }; template <typename Policy> struct policy_list<Policy, void> { static void apply() { Policy::implement(); } }; struct first_policy { static void implement() { std::cout << "Policy 1" << std::endl; } }; struct second_policy { static void implement() { std::cout << "Policy 2" << std::endl; } }; int main() { typedef policy_list<first_policy, policy_list<second_policy> > policy; while (1) { policy::apply(); } } For three policies you would need to change the typedef to: typedef policy_list<first_policy, policy_list<second_policy, policy_list<third_policy> > > policy; Then all you need to do is produce the right policy list at compile time. This could be done by an external part of your build system that generates a header file with a typedef, or it could be done with either preprocessor or template magic, depending on what exactly dictates what your policies are. If you have C++11 available you can simplify the policy_list somewhat using variadic templates.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626895", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How can I build a 'has-many-through' relation linking more than 2 models? I have 3 models eg; TABLE `users` `id` INT `username` VARCHAR(32) ... TABLE `books` `id` INT `title` VARCHAR(100) `author` INT (foreign ket constraint) TABLE `rights` `id` INT `name` VARCHAR(32) Now I want a user to have particular rights to eg. read or edit a book. So the rights table should look like (much like ORM roles table): |----|------| | id | name | |----|------| | 1 | view | | 2 | edit | | .. | ... | And I would have a fourth table linking all three; TABLE user_book_rights |---------|---------|----------| | user_id | book_id | right_id | |---------|---------|----------| | 1 | 1 | 2 | | 1 | 2 | 1 | | 2 | 1 | 1 | | ... | ... | ... | So if a user wants to, say, read a book, I want to check if the logged in user with id 1, has the right with id 1 for book with id 2. But how the heck can I achieve this with ORM? Of course I can just write my own query; SELECT COUNT(*) as `has_right` FROM `user_book_rights` WHERE user_id=1 AND book_id=2 AND right_id=1 if($result['has_right']) { echo 'Yeah, read the book!'; } else { echo 'Sorry mate, this book is not for dummies...'; } But I'd rather do something like: $has_right = $user->has('book_rights', ORM::factory('user_book_right', array('book_id' => '2', 'right_id' => 1)); Or even better: $book = ORM::factory('book', 1); $right = ORM::factory('right', array('name' => 'view')); $has_right = $user->has('book_rights', ORM::factory('user_book_right', array($book, $right))); I could not find an answer to my question. Is it weird to want to link three models as a many_through realtionship? Or is ORM just not capable and should I write my own query? Thanks ia. for your insights! A: Maybe my answer does not help you a lot. But i suggest that you encode the right in bit representation. READ = 00000001 = 1 EDIT = 00000010 = 2 DELETE = 0000100 = 4 than, if a user has the write to read, edit and delete you just do READ | EDIT | DELETE = 0000111 = 7 If you want to test if a user has a particular right you just do: if ($user_write & READ) { // he can read} Maybe if you use this design, and eliminate the rights table with those constants, it may help you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626902", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: first character truncated when committing hgsub I'm trying to create a mercurial repository containing subrepositores. I have the following entry in my .hgsub file: subrepo1 = http://hgserver.domain.com/subrepo1 However, when committing, I get the following message: B:\>hg commit committing subrepository ubrepo1 Why is the first character removed? A: This is clearly a bug. But StackOverflow is not the Mercurial bugtracker, and the best you can hope for here is a workaround. You should instead report the issue to the Mercurial BTS, which the developers actually read, and which may result in someone actually fixing the bug: https://www.mercurial-scm.org/wiki/BugTracker But today is your lucky day: the Mercurial project leader happened to follow a link to Stack Overflow, got annoyed that people were reporting bugs in a place that doesn't ever make it to his inbox and weren't promptly getting redirected to the right place, so he filed a proper bug report, then fixed the bug: https://www.mercurial-scm.org/bts/issue3033 Turns out this particular bug is caused by the highly unusual pattern of committing to a repo at the root of the drive on a Windows machine with a subrepo. It's harmless and the fix will be in the next release on Nov 1.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626904", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can I fire a Button Click event when PageDown key pressed in c# winform i write some code in a Button Click event, private void sabt_btn_Click(object sender, EventArgs e) { some code.... } i want fire this button action when PageDown" key is pressed in form. private void myform_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.PageUp) { how to fire sabt_btn_Click } } A: You should move that code to a separate method, then call that method from both event handlers.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626907", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get a reference to an object (COM) in JavaScript that can be passed outside the browser I have a hyrid type application (web and forms). It's a .net compact framework app. On one of the forms I have a WebBrowser control. I want to communicate between the WebBrowser control and the form that host/contains the WebBrowser control. To do this I plan to create an Activex (COM) object in C++ compiled for the windows mobile device. I plan to use JavaScript to create an instance of the ActiveX control on the web page that is displayed in the WebBrowser control. How can I get a reference to this ActiveX control that I can then send to the form? My objective is to send a reference of the ActiveX control instance to the windows mobile form that contains the WebBrowser control so that both the web page and form can use/access the same instance of the ActiveX control. I created a way to send strings from the ActiveX control to the form. Is there a way to convert a reference of the ActiveX control to a string then pass the string to the form and re-create a reference to the object instance on the form side? I hope this makes sense. A: You can get an IDispatch reference to the window using something like this: CComPtr<IWebBrowser2> m_webBrowser(/* create, assign, whatever to get the pointer */ CComQIPtr<IHTMLWindow2> m_htmlWin; CComPtr<IDispatch> m_htmlDocDisp; CComQIPtr<IDispatch> m_htmlWindDisp; m_webBrowser->get_Document(&m_htmlDocDisp); CComQIPtr<IHTMLDocument2> doc(m_htmlDocDisp); assert(doc); doc->get_parentWindow(&m_htmlWin); assert(m_htmlWin); m_htmlWindDisp = m_htmlWin; assert(m_htmlWin); Once you have that, you can use IDispatch methods to either query the value of a property on the window object or you can set the value of such a property. For example, if you create an IDispatch object that exposes methods and properties then you use the m_htmlWindDisp object to Invoke with PROPERTYPUTREF that object as "foo" then you could access that object from javascript using "window.foo". Alternatley, using Invoke with PROPERTYGET you can get the IDispatch handle for an object that you set on window, such as "window.foo = someFooBaredObject" Hope that makes sense.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626911", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How does tokenization and pattern matching work in Chinese.? This question involves computing as well as knowledge of Chinese. I have chinese queries and I have a separate list of phrases in Chinese I need to be able to find which of these queries have any of these phrases. In english, it is a very simple task. I don't understand Chinese at all, its semantics, grammar rules etc. and if somebody in this forum who also understands Chinese can help me with some basic understanding and how pattern matching is done for Chinese. I have a basic perception that in Chinese one unit (without any space in between) can actually mean more than one word(Is this correct?). So are there any rules on how more than one word combine among themselves to stand out as a unit. It is confusing because there are spaces in Chinese writing yet even a unit without space has more than one word in it. Any links which explain Chinese from computational point of view, pattern matching etc would be very useful.. A: I have a basic perception that in Chinese one unit (without any space in between) can actually mean more than one word(Is this correct?). In Chinese spaces are rarely used, eg: 递归(英语:Recursion),又譯為遞迴,在数学与计算机科学中,是指在函数的定义中使用函数自身的方法。递归一词还较常用于描述以自相似方法重复事物的过程。例如,当两面镜子相互之间近似平行时,镜中嵌套的图像是以无限递归的形式出现的。 You'll notice what appear to be spaces actually are just Chinese punctuation characters, which just have more padding than usual. So are there any rules on how more than one word combine among themselves to stand out as a unit. It is confusing because there are spaces in Chinese writing yet even a unit without space has more than one word in it. Think of it this way: one Chinese character is very, very roughly similar to one English word. Often times two or more characters need to be combined to form one word, and each separate character may mean something completely different depending on context. To meaningfully tokenize Chinese text you'd have to segment words taking that in consideration. See Chinese Natural Language Processing and Speech Processing, from the Stanford NLP group. A: Ken Lunde's book CJKV Information Processing is probably worth a look. The basic word order is subject - verb - object, but see also "Topic prominence" in http://en.wikipedia.org/wiki/Chinese_grammar
{ "language": "en", "url": "https://stackoverflow.com/questions/7626912", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Could you please suggest on a simple drawing program? I am new to C++. I try to draw a polygon. My code can be built, but nothing shows in the form when I run it. Could anyone please give me some help. Thanks (Most of the stuff below was from the default VS template, I added a few lines only) namespace DrawMyShape { using namespace System; using namespace System::ComponentModel; using namespace System::Collections; using namespace System::Windows::Forms; using namespace System::Data; using namespace System::Drawing; public ref class Form1 : public System::Windows::Forms::Form { public: Form1(void) { InitializeComponent(); } protected: /// <summary> /// Clean up any resources being used. /// </summary> ~Form1() { if (components) { delete components; } } private: System::ComponentModel::Container ^components; void InitializeComponent(void) { this->components = gcnew System::ComponentModel::Container(); this->Size = System::Drawing::Size(800,800); this->Text = L"Form1"; this->Padding = System::Windows::Forms::Padding(0); this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font; } private: System::Void Form1_Paint(System::Object^ sender, System::Windows::Forms::PaintEventArgs^ e) { Graphics ^g = e->Graphics; //require for drawing SolidBrush^ blackPen = gcnew SolidBrush( Color::Blue ); // Create points that define polygon. Point point1 = Point(50,50); Point point2 = Point(100,25); Point point3 = Point(200,5); Point point4 = Point(250,50); Point point5 = Point(300,100); Point point6 = Point(350,200); Point point7 = Point(250,250); array<Point>^ curvePoints = {point1,point2,point3,point4,point5,point6,point7}; // Draw polygon to screen. e->Graphics->FillPolygon( blackPen, curvePoints ); } }; } A: You forgot to subscribe the Paint event: this->Paint += gcnew System::Windows::Forms::PaintEventHandler(this, &Form1::Form1_Paint); Click the lightning bolt icon in the Properties window and double-click Paint. The proper way to do this is to override the OnPaint() method.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626913", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using jBCrypt to salt passwords in Android App causes a long hang I am using the jBCrypt Library to hash user passwords when they register using my app. I am using the basic hash function, with a salt, like so: String pass = BCrypt.hashpw(rawPass, BCrypt.gensalt()); I noticed a one to two minute hang when registering, and checked the debugger, confirming BCrypt was responsible. Does salting the password really take that much processing power? If so, would a good alternative be to send the plaintext password out to the server to hash it? My original thought on the matter was to hash it before it got sent anywhere. Any ideas? A: Here is an article which lists the times taken on a Mac laptop with a Core 2 Duo processor. So, yes, Bcrypt is likely to be very slow on a mobile device. Another common problem is the initialization of SecureRandom which can be very slow and may also hang due to the lack of enough random data. This will vary between different machines and operating systems. You'll find plenty of discussion of that elsewhere, but it's something you might want to test either initializing it yourself using new SecureRandom() or by calling gensalt separately to isolate the random data generation and then just time the call to hashpw. Another question is why you actually want to hash it on the client? If you are storing it on the client and logging in locally, then that may make some sense, but if it is being sent to a server and a normal login involves sending a plaintext password to the server then you aren't gaining anything. Also, a common misconception is that hashing a password before sending it to the server (when logging in) offers some protection, when in fact it is equivalent to sending the plaintext password. An attacker only has obtain the hash to be able to gain access. Hashing passwords is a means of preventing an attacker from gaining access (or at least slowing them down) should the password store itself be compromised. So if the password is stored on the server, it should be sent in plaintext (over a secure channel) and the server should make the decision on how it is hashed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626914", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Where to find library? import common.money.MonetaryAmount; import common.money.Percentage; googled, the only result I found is: "Actually no, its maven dependencies packaged under common-aux.1.0.1.RELEASE.jar" which I also couldn't really find. has variation of: import common.datetime.SimpleDate; It is related to SpringSource projects, I can't really believe the jar does not exist. Thank You, A: I believe that the common-aux.#.#.#.jar is a JAR file which is provided by SpringSource as a separate JAR file to be used within classroom examples. You would need to pull it from the files provided as part of the class and then have your IDE reference the JAR file. A: FindJar can't find it, either. I'd check the package name. It can't be a Spring class, produced by SpringSource. Their packages start with org.springframework. Do you mean that it's a dependency? Google found this, but no JARs: http://git.springsource.org/spring-payment/spring-payment/blobs/6434aa3f9b9e5fce917d4ecf6ecc03387e1ba86a/core/src/main/java/org/springframework/payment/common/money/MonetaryAmount.java I think this means that you'll need to access the Git repository, check out the code, and build the JARs yourself. Here's the repository: http://git.springsource.org/spring-payment It should be easy to sort out if you have a Git client.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626919", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: iOS Wrong UITableView size I am building an iPad application, and I added a simple UITableView to an inner view, somewhere in a XIB file. The problem is, as you can see in the image, the UITableView doesn't have the right size. Of course, I set it in IB (should be 360x243, as I recall), but no matter what I do, it still shows up wrong. If I increase the size to, let's say 600 pixels width, it displays OK, but, then, it'll be a little hack-ish and will be a nightmare to maintain. Does anybody here have an explanation to this behavior? I don't have enough reputation, so here is the link to the image : http://imageshack.us/photo/my-images/13/screenshot20111002at413.png/ On the image, the UITableView background is set to white to be able to see it. A: Check your autoresizing masks. Those can mess up view structures easily.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626925", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: php why is basic super global failing? i am using globals to share variables between functions like this <?php $whatyear; $whatfirstname; $whatlastname; function mycustom_user_register_submit($form, &$form_state) { $GLOBALS["whatyear"]=$form_state['values']['yearofstudy']; $GLOBALS["whatfirstname"]=$form_state['values']['firstname']; $GLOBALS["whatlastname"]=$form_state['values']['lastname']; } function course_registration_user_insert(&$edit, $account, $category) { $newuserid=$account->uid; $yearofstudy=$GLOBALS["whatyear"]; $fname=$GLOBALS["whatfirstname"]; $lname=$GLOBALS["whatlastname"]; //now use vars drupal_set_message('dear '.$fname.' '.$lname.' ,'.'account uid is '.$account->uid); } But the variables fname,lname,yearofstudy are shockingly empty! please help me figure out why. am getting errors like Notice: Undefined index: whatyear in course_registration_user_insert() (line 110 of C:\wamp\www\drupal-7.1\sites\all\modules\course_registration\course_registration.module). A: Try using global variables like this: <?php function mycustom_user_register_submit($form, &$form_state) { global $whatyear; global $whatfirstname; global $whatlastname; $whatyear=$form_state['values']['yearofstudy']; $whatfirstname=$form_state['values']['firstname']; $whatlastname=$form_state['values']['lastname']; } function course_registration_user_insert(&$edit, $account, $category) { global $whatyear; global $whatfirstname; global $whatlastname; $newuserid=$account->uid; $yearofstudy=$whatyear; $fname=$whatfirstname; $lname=$whatlastname; //now use vars drupal_set_message('dear '.$fname.' '.$lname.' ,'.'account uid is '.$account->uid); } ?> If this doesn't work, make sure these functions are called in the same php instance in the right order. If the first one is called on one page, and then insert is called on another page, a new copy of php will be opened, and you will lose your environment variables.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626926", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Can a variable in c++ add its old value plus its new value? Is there a way in c++ for a single variable to maintain its same value and when added to, it will add its last value with the new one? for example, I am writing a program where the user can enter as many "checks" and "deposits" they received through the day, and at the end of the day the program will let the user know how much he made throughout the day here is what I have so far #include <cstdlib> #include <iostream> using namespace std; int main(int argc, char *argv[]) { system("Color 0E"); int cashBalance = 1000; int check; int depo; double toDepo = depo * 0.3; double totalDepo = depo - toDepo; int loop = 5; int choice; cout << "check = 1, deposit = 2, add = 3, clear the screen = 4, close = 0\n" << endl; while (loop == 5){ cout << "Would you like to enter a depoist or a check?\n" << endl; cin >> choice; //determines whether or not to close the program if(choice == 0 || depo == 0 || check == 0){ return 0; }//end close if //choses which type of input to make if( choice == 1){ cout << "Please enter check\n" << endl; cin >> check; } else if(choice == 2){ cout << "Please enter deposit\n" << endl; cin >> depo; }//end if if(choice == 3 || depo == 3 || check == 3){ cout << "Total = " << (cashBalance - check) + totalDepo << endl; } //clear the console screen if(choice == 4 || depo == 4 || check == 4){ system("cls"); cout << "check = 1, deposit = 2, add = 3, clear the screen = 4, close = 0\n" << endl; } }//end while loop system("PAUSE"); return EXIT_SUCCESS; }//end of program the problem is that i need the variable "check" and "depo" to be able to add the users first value and the second value to get the new value. right now all it does is display the last value the user inserted. A: Yes. You can add new values to old value as: oldValue += newValue; Or alternatively, you can also do this: oldValue = oldValue + newValue; A: A variable can only display the last value the user inserted.suppose int a=5; a=a+5; cout<<a; the output will be 10 as the new value overwrites the previous one at the address of a.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626929", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Validate an url with parameters I’m trying to determine whether or not a given string is a valid url or not. And in my scenario, the url can have parameters: * *www.example.com -> OK *example.test -> OK (although there’s no .test TLD) *example.com/page.htm?abc=123 -> OK *xxx/xxx.jpg -> Not OK *xxx -> Not OK I’ve tried the Uri.TryCreate method, Uri.TryCreate(url, UriKind.Absolute, null);, but it accepts pretty much anything that has an http:// prefix, i.e. “http://xxx/” is OK. I can’t use an HTTP request to check/ping the site for performance reasons. Any suggestions? A: It sounds like you want to call Uri.TryCreate(url, UriKind.Absolute, out result), then check that result.HostName contains a .
{ "language": "en", "url": "https://stackoverflow.com/questions/7626930", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to slideTo() only if the loadmore button is clicked using jQuery? In my script I load some posts from external RSS feeds. I have a "load more" button that when it is clicked, calls the loadfeed() function and shows some 10 more posts. When this happens, there is a slideTo() that slides the browser to the first of the new posts list. In addition to the "load more" button, I have a timer that checks for any new posts of those feeds. This happens every 3 minutes. As I said, if you click on the "load more" button, the page is moved with the first new post on the top of your screen. The problem here is that this sliding happens also if you clicked once the "load more" button, you read the articles, and as you read the 3 minutes are passed, you slide back to the first post of the new list you loaded. More specific, when you load (from the default 20) +10 more posts, you will be slided to the 21st post after 3 minutes. So my question here it is how to avoid this? this is the #loadmore button that calls loadfeed() $("#loadmore").click(function() { cap += 10; loadfeed(); }); and this is a part of loadfeed() that handles sliding. I have an if statement for the sliding to happen after the default 20 posts. Without this you will be slide to the 11 post after 3 minutes and no "load more" is clicked. if (cap > 20) { $(".p" + (cap-9)).slideto({ slide_duration : 'slow' }); } A: Forgive me if I've misunderstood, but can't you just pass a parameter to loadfeed()? In $("#loadmore").click, call loadfeed(true) and for the timer call setTimeout(function () { loadfeed(false); }, 12000);. Or similar. Edit: I don't know which slideto plugin you're using. I've downloaded 2 of them, but neither works as yours seems to. I have got this to work with the scrollTo plugin. In this code, I've removed all of the AJAX bits and some other things that didn't seem relevant to the question. The basic changes are to add a parameter to loadfeed() that tells it whether or not to scroll when adding new content. Clicking the button makes it scroll to the bottom; waiting for the timer does not. (I've also added a clearTimeout to stop the timer triggering multiple times if someone goes crazy with the load button.) <!DOCTYPE html> <html lang="en"> <head> <title>Testing</title> <style type="text/css"> .Top { background-color: #ccc; padding: 10px; position: fixed; } </style> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script> <script type="text/javascript" src="jquery.scrollTo.js"></script> <script type="text/javascript"> $(function () { var cap = 0; var timerId = null; function loadfeed(scroll) { cap++; $("#loadmore").hide(); $('#feed') .addClass('loading') .append("<div class=\"p" + cap + "\"><p>Biodiesel put a bird on it pitchfork beard cosby sweater tattooed, 3 wolf moon skateboard thundercats. Craft beer irony sartorial DIY. Portland photo booth trust fund, mlkshk yr you probably haven't heard of them salvia. Trust fund marfa food truck Austin etsy synth. Seitan chambray williamsburg, thundercats american apparel cardigan four loko letterpress food truck cosby sweater. Art party Austin biodiesel, single-origin coffee etsy organic mlkshk yr PBR. Skateboard master cleanse 3 wolf moon, freegan Austin tumblr messenger bag vinyl dreamcatcher.</p><p>Tumblr before they sold out helvetica, chambray iphone yr DIY cosby sweater PBR synth stumptown keytar. Letterpress you probably haven't heard of them iphone, keffiyeh photo booth chambray american apparel lomo artisan. Hoodie beard quinoa locavore four loko mixtape. Tofu stumptown viral you probably haven't heard of them, readymade thundercats echo park etsy 8-bit. Pitchfork ethical before they sold out, freegan keffiyeh yr marfa banh mi echo park williamsburg tofu PBR twee. Keffiyeh pitchfork food truck, gluten-free bicycle rights iphone fixie banh mi vinyl craft beer tofu keytar +1 brooklyn. Synth echo park letterpress locavore, chambray butcher banh mi vinyl tofu twee four loko food truck beard mustache fap.</p></div>") .removeClass('loading'); if (timerId !== null) clearTimeout(timerId); timerId = setTimeout(function () { loadfeed(false); }, 12000); $("#loadmore").show(); if (scroll) $(window).scrollTo(".p" + cap); } loadfeed(); $("#loadmore").click(function () { loadfeed(true); }); }); </script> </head> <body> <div class="Top"><button id="loadmore">Load</button></div> <div id="feed">Feed</div> </body> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/7626934", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: AuthLogic sessions only work on localhost:3000 I'm running pow locally along with localhost:3000 (for debugging purposes). For some time I was able to create user sessions fine with authLogic on http://app.dev. At some point however, I discovered that I was only able to login using http://localhost:3000. The login also doesn't work on Heroku. I've tried messing with Rails.application.config.session_store :domain, setting it to 'app.dev'. No luck. Any thoughts? A: Just figured this out. I had http_basic_auth turned on and AuthLogic wasn't happy. Simply turning it off solved the problem. Figures.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626940", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: returning code of function instead of result I saved a function created in jQuery in clean.js file.. jQuery.fn.singleDotHyphen = function(){ return this.each(function(){ var $this = $(this); $this.val(function(){ return $this.val() .replace(/\.{2,}/g, '.') .replace(/-{2,}/g, '-'); }); }); }; My action file is.. <script type="text/javascript"> $(document).ready(function() { $.noConflict(); $('#title').limitkeypress ({ rexp:/^[A-Za-z.\-\s`]*$/ }); $('#title').blur(function() { $(this).singleDotHyphen(); }); }); </script> Issue is onblur its returning me code of the function where as I want to return the string that reject continuous hyphen and dots... A: The version of the .val() method that accepts a function argument exists only in jQuery 1.4 and above. However, in this case you don't need that version, since you can simply pass the new value to val(): $this.val($this.val().replace(/\.{2,}/g, '.') .replace(/-{2,}/g, '-'));
{ "language": "en", "url": "https://stackoverflow.com/questions/7626945", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Launching new Intents with SingleInstance I have two activities. One activity has the main game and the other activity has the game over screen which is truly just a custom alert dialog. In the game over screen there is a button that when clicked launches a new Activity. String authUrl = httpOauthprovider.retrieveRequestToken(httpOauthConsumer, OAUTH_CALLBACK_URL); Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)); intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY ); startActivity(intent); The page is a twitter authorization page but the problem I am having is that when I click the Authorize App button the activity with the alert dialog launches again (Calling create instead of onNewIntent). I have tried different launch modes (singleInstance,singleTask and singleTop). Each of them have their problems. singleInstance and singleTask will clear the original calling activity so when the AlertDialog slides in the original activity is changed to the menu page. singleTop always calls create again first (eventhough it doesn't call onDestroy) Does anyone have any recommendations or examples on how I can get this done? Incidentally, the activity that calls the game activity is a standard launchmode Thanks in Advance A: What I ended up doing was make the call to the the new activity from the original caller. So when I choose to to tweet the message from the custom alert dialog I close the alert dialog activity with the result requesting a tweet and from the original activity I make the call to the third activity (twitter authorization). It's not the answer I was looking for but this is how I solved the problem. If anyone knows a better more eloquent solution I'd love to know it. SO The flow now goes A->B->A->C->A->B instead of A->B->C->B
{ "language": "en", "url": "https://stackoverflow.com/questions/7626950", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Where can I find the source code examples for "Introduction to 3D game programming with DirectX 9.0c"? I have a book : "Introduction to 3D game programming with DirectX 9.0c– a shader approach" by Frank Luna. The official site is dead and I can't seem to find 3 main files used for all the projects. * *d3dApp.h *d3dApp.cpp *d3dUtil.h Does someone know where can I get them? All I have found was this : * *http://www.d3dcoder.net/ *http://www.d3dcoder.net/phpBB/ But there is no source there. Also I've found some fragments //A sample directX demo outputting some flashing color text #include "d3dApp.h" #include <tchar.h> #include <crtdbg.h> //Our application is derived from the D3DAPP class, making setup for a game //or other program easier in the long run class HelloD3DApp : public D3DApp { public: HelloD3DApp(HINSTANCE hInstance, std::string winCaption, D3DDEVTYPE devType, DWORD requestedVP); ~HelloD3DApp(); bool checkDeviceCaps(); void onLostDevice(); void onresetDevice(); void updateScene(float dt); void drawScene(); private: ID3DXFont* mFont; }; int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE prevInstance, PSTR cmdLine, int showCmd) { // Enable run-time memory check for debug builds. #if defined(DEBUG) | defined(_DEBUG) _CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); #endif HelloD3DApp app(hInstance, "Hello Direct3D", D3DDEVTYPE_HAL, D3DCREATE_HARDWARE_VERTEXPROCESSING); gd3dApp = &app; return gd3dApp->run(); } HelloD3DApp::HelloD3DApp(HINSTANCE hInstance, std::string winCaption, D3DDEVTYPE devType, DWORD requestedVP) : D3DApp(hInstance, winCaption, devType, requestedVP) { srand(time_t(0)); if(!checkDeviceCaps()) { MessageBox(0, "checkDeviceCaps() Failed", 0, 0); PostQuitMessage(0); } LOGFONTA font; font.lfHeight = 80; font.lfWidth = 40; font.lfEscapement = 0; font.lfOrientation = 0; font.lfWeight = FW_BOLD; font.lfItalic = true; font.lfUnderline = false; font.lfStrikeOut = false; font.lfCharSet = DEFAULT_CHARSET; font.lfOutPrecision = OUT_DEFAULT_PRECIS; font.lfClipPrecision = CLIP_CHARACTER_PRECIS; font.lfQuality = DEFAULT_QUALITY; font.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE; _tcscpy(font.lfFaceName, _T("Times New Roman")); HR(D3DXCreateFontIndirect(gd3dDevice, &font, &mFont)); } HelloD3DApp::~HelloD3DApp() { ReleaseCOM(mFont); } bool HelloD3DApp::checkDeviceCaps() { // Nothing to check. return true; } void HelloD3DApp::onLostDevice() { HR(mFont->OnLostDevice()); } void HelloD3DApp::onresetDevice() { HR(mFont->onresetDevice()); } void HelloD3DApp::updateScene(float dt) { } void HelloD3DApp::drawScene() { HR(gd3dDevice->Clear(0, 0, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(255, 255, 255), 1.0f, 0)); RECT formatRect; GetClientRect(mhMainWnd, &formatRect); HR(gd3dDevice->BeginScene()); mFont->DrawText(TEXT("Hello </DIC>!"), -1, &formatRect, DT_CENTER | DT_VCENTER, D3DCOLOR_XRGB(rand() % 256, rand() % 256, rand() % 256)); HR(gd3dDevice->EndScene()); HR(gd3dDevice->Present(0, 0, 0, 0)); } But these does not help me either. A: d3dApp.h d3dApp.cpp d3dUtil.h These are the same files as in the zip file.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626954", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Dropshadow with css I want to add a transparent dropshadow to my div. I have a container, and behind it I want to place a dropshadow. I don't want the dropshadow to have a color. This is what I have so far: .content_right1{ background:#fff; -moz-border-radius: 10px; -webkit-border-radius: 10px; border-radius:10px; -moz-box-shadow: 5px 5px 5px #99CCFF; -webkit-box-shadow: 5px 5px 5px #99CCFF ; box-shadow: 5px 5px 5px #99CCFF; /* other styles of the class */ width:380px; float:left; margin-left:3px; padding:15px; min-height:450px; margin-left:15px; } I want to add the opacity, but when I do the opacity of the whole div changes. A: If you want a dropshadow with a level of opacity, you should use rgba() for its shadow color : http://css-tricks.com/2151-rgba-browser-support/ edit: -moz-box-shadow:5px 5px 5px rgba(0,0,0,0.3); -webkit-box-shadow:5px 5px 5px rgba(0,0,0,0.3); box-shadow:5px 5px 5px rgba(0,0,0,0.3); A: While your question is ultimately a little opaque (pun intended), does the following do what you are expecting? -moz-box-shadow: 5px 5px 5px #dddddd; -webkit-box-shadow: 5px 5px 5px #dddddd; box-shadow: 5px 5px 5px #dddddd; http://jsfiddle.net/zCTC8/2/ All I essentially did was adjust the color value of the shadow, which is the last value in the declaration (#dddddd, or #ddd). These are hex values. See here for more examples: http://html-color-codes.com/ #ddd/#dddddd represents a light grey color; #eee is lighter, #ccc is darker, #fff is white, and #000 is black. The value #000 represents RGB, with valid values of 0-9A-F (dark->light), so that: #f00 = red (R) #0f0 = green (G) #00f = blue (B) The value #99CCFF from your question is equivalent to #9CF, which gives a middle red (9), a light green (C), and white (F). The mix of these values gives you the light blue shade you were seeing, which is why you were getting a color instead of a "shadow-like" color (gray shade). My color theory is a little rusty here, so anyone correct me if I've flubbed something.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626963", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Linq - Creating Expression from Expression I have a predicate Expression<Func<T1, bool>> I need to use it as a predicate Expression<Func<T2, bool>> using the T1 property of T2 I was trying to think about several approches, probably using Expression.Invoke but couln;t get my head around it. For reference: class T2 { public T1 T1; } And Expression<Func<T1, bool>> ConvertPredicates(Expression<Func<T2, bool>> predicate) { //what to do here... } Thanks a lot in advance. A: Try to find the solution with normal lambdas before you think about expression trees. You have a predicate Func<T1, bool> p1 and want a predicate Func<T2, bool> p2 = (x => p1(x.T1)); You can build this as an expression tree as follows: Expression<Func<T2, bool>> Convert(Expression<Func<T1, bool>> predicate) { var x = Expression.Parameter(typeof(T2), "x"); return Expression.Lambda<Func<T2, bool>>( Expression.Invoke(predicate, Expression.PropertyOrField(x, "T1")), x); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7626965", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: VBA variable/array default values Consider the declarations Dim x As Double Dim avg(1 To 10) As Double What are the default values in x and avg? Through testing, I want to say that x is initialized to zero. Likewise, I want to say that all elements in avg were initialized to zero. However, can I write code that depends on this? Or are the default initialization values actually indeterminate? A: You can write code that implicitly depends on a given data type's default value, but that doesn't mean you always should, because it isn't quite as obvious what you're doing, which may confuse the next person reading your code (and that person could be you a year from now). You can't go wrong with explicitly assigning an initial value to your variables. If you want, you can do that on the same line as the declaration: Dim x As Double: x = 0 Of course, it's a little more involved for arrays, but usually there's a convenient place to initialize them further down in your code, where you're traversing them anyway. A: If you specify a data type but do not specify an initializer, Visual Basic initializes the variable to the default value for its data type, which for all numeric types is 0 (zero). When you run a macro, all the variables are initialized to a value. A numeric variable is initialized to zero, a variable length string is initialized to a zero-length string (""), and a fixed length string is filled with the ASCII code 0. Variant variables are initialized to Empty. An Empty variable is represented by a zero in a numeric context and a zero-length string ("") in a string context. Ref. A: Yes, you should be able to depend on number types being initialize to 0 in VBA since that's their default value. However, if it makes you worry, and the starting values are so important, then my reccomendation is that you just explicitly assign the value 0 to them (although you really don't need to).
{ "language": "en", "url": "https://stackoverflow.com/questions/7626967", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: how to use data from 2 tables and combine it in one? I have 2 tables 1 is Lookup and another is Details. Lookup Table Identity Type Value 200 Entity A 201 Entity B 202 Entity C 203 Entity D 300 SOURCE X 301 SOURCE y Details Table Sender(int) Reciever(int) Source(int) State(varchar) 200 203 300 hongkong In the Details table Sender, Reciever are the Entity in Lookup table with Identity as their ids. My problem is that when I write the query as Select Sender,Reciever,Source,State from Details I am getting 200,203,300,hongkong but I want the result as A,D,X,hongkong. Please help. A: SELECT tSen.[Value] as [Sender], tRec.[Value] as [Reciever] , tSou.[Value] as [Source], D.[State] FROM Details as D JOIN Lookup as tSen ON D.Sender = tSen.Identity JOIN Lookup as tRec ON D.Reciever = tRec.Identity JOIN Lookup as tSou ON D.Source = tSou.Identity A: Use JOIN for both tables. It's base SQL syntax
{ "language": "en", "url": "https://stackoverflow.com/questions/7626970", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SSIS FlatFile Access via Jet Is there a way to access FlatFiles with the Microsoft.Jet.OLEDB.4.0 driver in SSIS ? The acces via the FlatFile Source is much better, it´s just about if there exists a way to do it with the Jet driver. A: This seemed an interesting question so I piddled around a bit with it. Yes, you can definitely use the JET driver to read a flat file. HOW TO: Use Jet OLE DB Provider 4.0 to Connect to ISAM Databases See Open Text section By default, it expects the file to be a CSV but you can specify the formatting in a Schema.INI which would be in the same folder as the connection manager is pointing to. One thing to note about the CM, it points to the folder of the text files, not a particular file. When you create your Connection Manager, you will need to go into the All tab (after selecting the Native OLE DB\Microsoft Jet 4.0 OLE DB Provider) and then add Extended Properties. I was able to make it work with a FMT of CSVDelimited and just Delimited (as my sample file was a csv). Exchanging the commas for tabs in the source file and setting the FMT at TabDelimited did not appear to work in the connection manager property but I did not try creating a schema.ini file as the BOL article indicated. You cannot define all characteristics of a text file through the connection string. For example, if you want to open a fixed-width file, or you want to use a delimiter other than the comma, you must specify all these settings in a Schema.INI file. The full value of the ConnectionString on my CM is below Data Source=C:\tmp\so\;Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties="text;HDR=Yes;FMT=CSVDelimited;"; If the package works fine at design time but goes belly up once it runs, the JET driver is only available as 32 bit so on a 64bit machine as the error message would indicate. SSIS Error Code DTS_E_CANNOTACQUIRECONNECTIONFROMCONNECTIONMANAGER. The AcquireConnection method call to the connection manager "OLEDB_JET" failed with error code 0xC0209303. There may be error messages posted before this with more information on why the AcquireConnection method call failed. The solution to this is to run it from the command-line in 32bit mode like C:\Program Files (x86)\Microsoft SQL Server\100\DTS\Binn>.\dtexec /file C:\sandbox\SSISHackAndSlash\SSISHackAndSlash\so_JetFlatFile.dtsx
{ "language": "en", "url": "https://stackoverflow.com/questions/7626971", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Data reading and storing in c#, (Concept..no code) I want to translate my Matlab code (least squares plane fitting) into C#. I have many problems in understanding c#. Let me ask here. Reading a text file and storing data in xyz format in matrix (e.g., xyzdata= xyz) in Matlab is quite easy. Translating it into CSharp? How can I read [x y z] without knowing length of file and how can I store it in Matrix form? Thank you very much for your help and If someone has plane fitting code / link, please guide me. A: I don't know the content of your text file, but File.ReadAllLines is the easiest way to read a text file into a string array representing all lines in the file. No trouble with having to know the length of the file. If the lines contain the entries of your matrix, the next step would be looping through the lines and for each line use String.Split to get the individual elements. When you've got that far, you have all information for creating a matrix of the required size. To fill its elements you're going to need Int32.Parse or Decimal.Parse to convert the elements as string into numbers. However, hard to tell from your post what kind of matrix you'll need (probably a multi dimensional array). Search "[matrix] [c#]" here at stack overflow. And try "[math] [.net]" to find posts on math libraries for .net.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626972", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Make parent DIV enclose floating chid DIVs I've been having trouble creating parent DIVs that encloses the floating child DIVs. <div id="parent"> <div class="child1">content</div> <div class="child2">content</div> <div class="child3">taller content</div> </div> ...where #parent would expand vertically (with padding if it was styled that way) to accomodate .child3. And If I added a border around #parent it would enclose all three child DIVs. What's the best way to style this arrangement to ensure this behavior? Looking for the best practice. A: You can add a "wrapper" div inside the parent, and a "clear: both" element in there as well. Check this jsFiddle http://jsfiddle.net/yvVP8/ <div id="parent"> <div id="wrapper"> <div class="child1">content</div> <div class="child2">content</div> <div class="child3">taller content lala lala lalal lala</div> </div> <div class="clear"></div> </div> And the css: #parent { border: 1px solid #000; width: 300px; } #wrapper .child1, #wrapper .child2, #wrapper .child3 { float: left; padding: 5px; width: 90px; } div.clear { clear: both; } A: A simple #parent { overflow:hidden; } will do the job : http://jsfiddle.net/XAbhY/ A: You can simply add float:left; to the parent div. It should force the parent's size/border to wrap all siblings. Not sure if it's valid, but works for me.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626975", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Strange Behavior in F# Parallel Sequence I have written the following code to generate all possible combinations of some numbers: let allCombinations (counts:int[]) = let currentPositions = Array.create (counts.Length) 0 let idx = ref (counts.Length-1) seq{ while currentPositions.[0]<counts.[0] do yield currentPositions currentPositions.[!idx]<-currentPositions.[!idx]+1 while currentPositions.[!idx] >= counts.[!idx] && !idx>=1 do currentPositions.[!idx]<-0 idx:=!idx-1 currentPositions.[!idx]<-currentPositions.[!idx]+1 idx:=counts.Length-1 } I am consuming the sequence in some other part of the program like this: allCombinations counts |> Seq.map (fun idx -> buildGuess n digitsPerPos idx) ... So far so good. The programs runs as expected and generates the combinations. For input [|2;2;2|] it generates the eight values: [|0; 0; 0|] [|0; 0; 1|] [|0; 1; 0|] [|0; 1; 1|] [|1; 0; 0|] [|1; 0; 1|] [|1; 1; 0|] [|1; 1; 1|] However when I use PSeq to parallelise the generated sequence all values to be consumed change to [|2;0;0|] which is the last value of the currentPositions array in the while loop above. If i use yield (currentPositions|>Array.copy) instead of yield currentPositions everything works ok in both sequential and parallel versions. Why does this happen; Is there a most efficient way to yield the result; Thank you in advance; A: The problem is that you're creating a single array which you're mutating between iterations. You can take the parallelism out of the equation by building a list of the results instead of printing them out one by one - if you build the list first and then print them all, you'll see the same result; the list will contain the same reference 8 times, always to the same array instance. Basically to avoid side-effects, you need each result to be independent of the other - so you should create a separate array each time.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626978", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Creating a dynamic js file and caching it? I have a JavaScript which is currently being re-used in over 5 websites, and will prolly be used by alot more websites as time progresses, the thing is - that javascript runs some checks according to the server name, and I was wondering what's the best way to create some JS file which has some server side variables in it, such as: js-functions.php: <script type='text/javascript'> var myServer = <?php echo $_SERVER['SERVER_NAME'] ?>; </script> as currently, this file will be downloaded every time, so how can I make it send out a 304 Unmodified, and use the browser caching to my advantage A: Use .htaccess RewriteEngine on RewriteRule javascript.js javascript.php [L] Name your php file javascript.php and direct your requests to javascript.js Note: You need to set correct cache headers in your php file before sending any output A: I would not create a dynamic JS file at all. If at all possible, put all the dynamic stuff into the main document; then load the main chunk of JavaScript from a static resource. Put the code you already have into the head section of each HTML page: <script type='text/javascript'> var myServer = "<?php echo $_SERVER['SERVER_NAME'] ?>"; </script> then link to a static JavaScript file: <script src="http://domain.com/js/script.js"> inside the JavaScript file, do not use any PHP; use the myServer variable to do your checks. The advantage of this is that if the web server is configured correctly, the static JS file will be loaded only once and you don't have to worry about caching. You could even share the same JavaScript URL between all 5 sites.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626980", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Various Odd Errors in Xcode In Xcode, I am getting some various odd errors that should build normally. First, In - (void)touchesMoved:(NSSet *)touches withEvent(UIEvent *)event { [self touchesBegan:touches withEvent:event]; marblebeingdragged = NO; } it gives me the errors: error: Semantic Issue: Use of undeclared identifier 'touchesMoved' in the first line: `expected ';' before ':' token` Also, in my switch statement: (Note the errors that are commented in the case and break statements) switch (marblecolor) { case 1: //Aqua plusone.image = [UIImage imageNamed: @"Aqua/+1"]; //Parse Issue: Extraneous ']' before ';' plustwo.image = [UIImage imageNamed: @"Aqua/+2"]; plusthree.image = [UIImage imageNamed: @"Aqua/+3"]; minusone.image = [UIImage imageNamed: @"Aqua/-1"]; minustwo.image = [UIImage imageNamed: @"Aqua/-2"]; minusthree.image = [UIImage imageNamed: @"Aqua/-3"]; break; //Semantic Issue: 'break' statement not in loop or switch statement case 2: //Blue //Semantic Issue: 'case' statement not in switch statement plusone.image = [UIImage imageNamed: @"Blue/+1"]; plustwo.image = [UIImage imageNamed: @"Blue/+2"]; plusthree.image = [UIImage imageNamed: @"Blue/+3"]; minusone.image = [UIImage imageNamed: @"Blue/-1"]; minustwo.image = [UIImage imageNamed: @"Blue/-2"]; minusthree.image = [UIImage imageNamed: @"Blue/-3"]; break; //Semantic Issue: 'break' statement not in loop or switch statement case 3: //Green //Semantic Issue: 'case' statement not in switch statement plusone.image = [UIImage imageNamed: @"Green/+1"]; plustwo.image = [UIImage imageNamed: @"Green/+2"]; plusthree.image = [UIImage imageNamed: @"Green/+3"]; minusone.image = [UIImage imageNamed: @"Green/-1"]; minustwo.image = [UIImage imageNamed: @"Green/-2"]; minusthree.image = [UIImage imageNamed: @"Green/-3"]; break; //Semantic Issue: 'break' statement not in loop or switch statement case 4: //Semantic Issue: 'case' statement not in switch statement plusone.image = [UIImage imageNamed: @"Grey/+1"]; plustwo.image = [UIImage imageNamed: @"Grey/+2"]; plusthree.image = [UIImage imageNamed: @"Grey/+3"]; minusone.image = [UIImage imageNamed: @"Grey/-1"]; minustwo.image = [UIImage imageNamed: @"Grey/-2"]; minusthree.image = [UIImage imageNamed: @"Grey/-3"]; break; //Semantic Issue: 'break' statement not in loop or switch statement case 5: //Pink //Semantic Issue: 'case' statement not in switch statement plusone.image = [UIImage imageNamed: @"Pink/+1"]; plustwo.image = [UIImage imageNamed: @"Pink/+2"]; plusthree.image = [UIImage imageNamed: @"Pink/+3"]; minusone.image = [UIImage imageNamed: @"Pink/-1"]; minustwo.image = [UIImage imageNamed: @"Pink/-2"]; minusthree.image = [UIImage imageNamed: @"Pink/-3"]; break; } Lastly, in my @end it gives the error: expected declaration or statement at end of input. Any clues to the errors? A: For starters, your - (void)touchesMoved:(NSSet *)touches withEvent(UIEvent *)event { line needs a colon after withEvent, so it should be - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {. Fix that and we'll see what works. (EDIT: Looking at your other errors, they may go away after you've fixed the method declaration typo. I would certainly expect the @end error to go away.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7626983", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Moving app between appstore accounts I have published an app that have sold pretty OK and i have since then started a company where i will do my development. I checked with Apple to change the name of my account but that seemed to be very complicated and time consuming. The problem I have is that I would like to move this app to my new company and by that register a new account at iTunes Connect. Does anyone know what the best strategy for this is as i do not want the current people that have bought the app to lose it. Cheers A: You can't move apps between accounts. The only reports of this being done are when a developer incorporates (and has all the paperwork to prove this), changes their developer account to a individual company enrollment, and then has their corporation get acquired by another company (with all the paperwork to prove such a corporate acquisition to Apple). Best you can do otherwise is to delete the app from one account, and (re)submit it from another, which will involve changing the Bundle ID, and thus losing the app's previous customers, reviews, ratings, etc. ADDED: The above information is now obsolete. In 2013, Apple added the capability to move apps (in normal status/states) between accounts in iTunes Connect, retaining users and reviews.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626984", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: jQuery - Why are `li a` and `li:has(a)` different? In applying li a and li:has(a) different results show up. But, why is that? Aren't they supposed to do the same thing? A: Aren't they supposed to do the same thing? No. In the first example, you are selecting all a inside a li; in the second one, you are selecting all the li that have an a. From the manual, emphasis mine: Description: Selects elements which contain at least one element that matches the specified selector. The expression $('div:has(p)') matches a <div> if a <p> exists anywhere among its descendants, not just as a direct child.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626996", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: javascript convert string to safe class name for css I am sure this must of been asked before but can't find any in the search. What is the fastest way to ensure all non safe characters are removed from a string allowing it to be used in a CSS class name? A: I use this for my selectors, IDs or classes names: String.prototype.safeCSSId = function() { return encodeURIComponent(this) .toLowerCase() .replace(/\.|%[0-9a-z]{2}/gi, ''); } console.log("The dæmon is in the detail.".safeCSSId()); A: I would replace anything that is not a lowercase letter or digit, and then I would add a special prefix to avoid collisions with class names you have used for other purposes. For example, here is one possible way: function makeSafeForCSS(name) { return name.replace(/[^a-z0-9]/g, function(s) { var c = s.charCodeAt(0); if (c == 32) return '-'; if (c >= 65 && c <= 90) return '_' + s.toLowerCase(); return '__' + ('000' + c.toString(16)).slice(-4); }); } // shows "prefix_c_a_p_s-numb3rs-__0024ymbols" alert("prefix" + makeSafeForCSS("CAPS numb3rs $ymbols")); A: If you mean the following symbols !"#$%&'()*+,./:;<=>?@[\]^`{|}~ then just replace them with nothing: names = names.replace(/[!\"#$%&'\(\)\*\+,\.\/:;<=>\?\@\[\\\]\^`\{\|\}~]/g, ''); (I may have added an extra, or not enough, escape characters in there) Here is a quick demo. But just so you know, not all of those symbols are "unsafe", you could just escape the symbol when targeting the class name (ref). A: You can try the urlify.js from django. Get it from: https://github.com/django/django/blob/master/django/contrib/admin/static/admin/js/urlify.js A: If anyone is interested in the coffee way of this: window.make_safe_for_css = (name) -> name.replace /[^a-z0-9]/g, (s) -> c = s.charCodeAt(0) if c == 32 then return '-' if c >= 65 && c <= 90 then return '_' + s.toLowerCase() '__' + '000' + c.toString(16).slice -4 A: with jQuery: $.escapeSelector(stringToEscape); Edit: Misunderstood the original question. This can be used e.g. when querying an element by class name but not for generating the class names.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627000", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "25" }
Q: How to reference external set of permissions in an XACML policy? Originally, I asked "How do you write a policy that requires a subject be granted access to a requested permission, where the set of allowed permissions is in an external attribute store. Can you reference an external set of permissions in a policy?" The second question has been answered in the affirmative, so I'm revising the question a bit to focus on the "how". Can someone provide a xacml policy snippet (or even pseudo-xacml) that requires a role attribute id (will be provided by the request) to be within a set of roles which are identified by another attribute id (managed by external attribute store). For the sake of providing a starting point, the following is an example from http://docs.oasis-open.org/xacml/2.0/XACML-2.0-OS-ALL.zip. In this case, the role is inline. <Subject> <SubjectMatch MatchId="urn:oasis:names:tc:xacml:1.0:function:string-equal"> <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">administrator</AttributeValue> <SubjectAttributeDesignator AttributeId="urn:oasis:names:tc:xacml:2.0:example:attribute:role" DataType="http://www.w3.org/2001/XMLSchema#string"/> </SubjectMatch> </Subject> A: Yes, policies can be written to reference attributes that come from an external attribute store. However, where the attributes actually come from is usually not specified in the policy itself, other than perhaps by a naming pattern in the attribute ID. In the XACML PDP reference architecture, it's the responsibility of the request context handler to resolve attribute IDs and produce values for the PDP. It goes something like this: While evaluating a request against a set of policies, the PDP encounters an attributeID in a policy rule that it needs to form a decision about the request. The PDP asks the request context handler to get the value of that attributeID "from whereever" - the PDP doesn't care where it comes from. The request context handler may look for the attribute in the attributes provided with the request, or in any number of external attribute providers, such as LDAP or AD or SAML or plain old databases. The request handler might recognize naming patterns (like, namespace prefixes) in the attributeID to know where to obtain it. You want your attributeIDs to be specific enough to know what they are and what they mean, but not so specific that all of your policies break when you move your attribute provider to a different machine. Policies should be configuration independent. Ultimately, where the request handler looks for attributes is a matter of configuration of the request handler / PDP server, and will vary by product vendor. Update: To answer the 2nd revision to this question You would write your policy to perform a comparison between the attribute value(s) provided in the request and a list of values provided by an external source. Keep in mind that an attribute designator returns a list of values, since the request could contain multiple attribute values for the same attributeID. You can accommodate that by either by wrapping the attribute designator in a "one-and-only" reduction function, or by using a many-to-many cross product match function that will test every member of list1 for a match in list2. Unless you have a specific design requirement that the request is only allowed to contain one role attribute, it's best to avoid the "one-and-only" reduction since it really limits your options. Your Xacml 2.0 policy could look something like this: (forgive syntax errors, my Xacml 2.0 is a little rusty) <Policy [...] RuleCombiningAlgorithm="deny-unless-permit"> <Rule [...]> <Effect>Permit</Effect> <Condition> <Apply FunctionId=”urn:oasis:names:tc:xacml:1.0:function:string-at-least-one-member-of”> <SubjectAttributeDesignator AttributeId="urn:oasis:names:tc:xacml:2.0:example:attribute:role" DataType="http://www.w3.org/2001/XMLSchema#string"/> <SubjectAttributeDesignator AttributeId="list-of-acceptable-roles-from-external-provider-attribute-id" DataType="http://www.w3.org/2001/XMLSchema#string"/> </Apply> </Condition> </Rule> </Policy> The Xacml function "at-least-one-member-of" takes two lists as parameters. For every item in the first list, it tests to see if that item exists in the second list. It returns true as soon as it finds at least one match. The attribute "...example:attribute:role" from your example is the attribute you're expecting to be provided in the request. If you want to enforce that the attribute must be provided in the request, you can set MustBePresent="true" in the attribute designator. The "list-of-acceptable-roles..." attribute is an attribute id that your PDP context handler recognizes and retrieves from some external provider. What prefix or pattern the context handler looks for and which provider it fetches from is a matter of PDP configuration. Ideally, the naming pattern on the attribute id indicates a conceptual domain or namespace the id is associated with, but the id does not explicitly indicate the physical location or provider of the attribute value(s). For longer app lifetime with lower maintenance costs, you want to be able to change your provider implementation details without having to rewrite all of your policies. You can have vendor-specific attribute ids that will probably only come from a single provider, you can have application-specific attribute ids that could be supplied by multiple providers but only make sense for a particular application, and you can have generic or standardized attribute ids that could come from multiple providers and be used in multiple applications. The Oasis standards body and domain-specific profiles are a good starting point for finding standardized attribute ids and their semantics or getting ideas on how to organize your own app specific ids. Depending on your PDP and context handler implementation, it may also possible to use the "Issuer" field as a way to constrain the list of providers for an attribute. The Xacml spec doesn't say much about use of the Issuer field, but the same goals of decoupling policy from provider implementation details still holds.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627003", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Can't fire click event on the elements with same id Could you help me to understand - where I made the mistake. I have the following html code: <div id="container"> <a href="#info-mail.ru" id="getInfo" onClick="return false;">Info mail.ru</a> </div> <div id="container"> <a href="#info-mail.com" id="getInfo" onClick="return false;">Info mail.com</a> </div> <div id="container"> <a href="#info-mail.net" id="getInfo" onClick="return false;">Info mail.net</a> </div> and the following js code (using jQuery): $('#getInfo').click(function(){ alert('test!'); }); example here "Click" event fired only on first link element. But not on others. I know that each ID in html page should be used only one time (but CLASS can be used a lot of times) - but it only should (not must) as I know. Is it the root of my problem? TIA! upd: Big thx to all for explanation!:) A: While you must, according to the W3 specifications, have only one element with a given id within any document, you can bypass this rule, and the issues arising from the consequences if document.getElementById(), if you're using jQuery, by using: $('a[id="getInfo"]').click(function() { alert('test!'); return false; }); JS Fiddle demo. But, please, don't. Respect the specs, they make everybody's life easier when they're followed. The above is a possibility, but using html correctly is much, much better for us all. And reduces the impact of any future changes within the browser engines, jQuery or JavaScript itself. A: Use a class for this (and return false in your handler, not inline): <div id="container"> <a href="#info-mail.ru" class="getInfo">Info mail.ru</a> </div> <div id="container"> <a href="#info-mail.com" class="getInfo">Info mail.com</a> </div> <div id="container"> <a href="#info-mail.net" class="getInfo">Info mail.net</a> </div> $('.getInfo').click(function(){ alert('test!'); return false; }); http://jsfiddle.net/Xde7K/2/ The reason you're having this problem is that elements are retrieved by ID using document.getElementById(), which can only return one element. So you only get one, whichever the browser decides to give you. A: You can use the same id for several element (although the page won't validate), but then you can't use the id to find the elements. The document.getElementById method only returns a single element for the given id, so if you would want to find the other elements you would have to loop through all elements and check their id. The Sizzle engine that jQuery uses to find the elements for a selector uses the getElementById method to find the element when given a selector like #getInfo. A: It must only be used once or it will be invalid so use a class instead, return false can also be added to your jQuery code as so: - $('.getInfo').click(function(){ alert('test!'); return false; }); <a href="#info-mail.net" **class**="getInfo" .... A: First id's are for one element only, you should have same id for several divs. you can make it class instead. your example changed: <div class="container"> <a href="#info-mail.ru" class="getInfo" >Info mail.ru</a> </div> <div class="container"> <a href="#info-mail.com" class="getInfo" >Info mail.com</a> </div> <div class="container"> <a href="#info-mail.net" class="getInfo" >Info mail.net</a> </div> $('.getInfo').click(function(ev){ ev.preventDefault(); //this is for canceling your code : onClick="return false;" alert('test!'); }); A: I know this is an old question and as everyone suggested, there should not be elements with duplicate IDs. But sometimes it cannot be helped as someone else may have written the HTML code. For those cases, you can just expand the selector used to force jQuery to use querySelectorAll internally instead of getElementById. Here is a sample code to do so: $('body #getInfo').click(function(){ alert('test!'); }); <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> </head> <body> <div id="container"> <a href="#info-mail.ru" id="getInfo" onClick="return false;">Info mail.ru</a> </div> <div id="container"> <a href="#info-mail.com" id="getInfo" onClick="return false;">Info mail.com</a> </div> <div id="container"> <a href="#info-mail.net" id="getInfo" onClick="return false;">Info mail.net</a> </div> </body> However as David Thomas said in his answer But, please, don't. Respect the specs, they make everybody's life easier when they're followed. The above is a possibility, but using html correctly is much, much better for us all. And reduces the impact of any future changes within the browser engines, jQuery or JavaScript itself.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627004", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Java Simple Line Drawing Program I want to create a simple java application for drawing only lines. My program is like that now; User can draw everything by draggin his mouse, but by the time he release his finger, I deleted everything from the screen and I draw a line withrespect to first mouse coordinates and the last mouse coordinates. However, because everytime I cleared the screen, user can only draw one line. If I dont clean the screen, there are lines but also curves and etc which are created while user dragging his mouse. How should I find a solution for that problem ? Thanks. A: One straightforward way to solve your problem is to retain state in the program. Every time a line is drawn, store it in an ArrayList of point-pairs. When the user successsfully draws one line, store the start point and end point for that line into the ArrayList. Each time the user draws another line, add that pair of points to the ArrayList. Then, when it is time to draw "all the lines", clear the screen and then use a loop, and draw one line for each stored pair of points. Somewhere in your program there is a class that has a lifetime that is "as long as a drawing", or "as long as the application runs." That's a good place to keep state. A: * *On mouse down, store the position. *On mouse up, make a new line object (define your own class) with the up and down points. *Remove the stored mouse down (Since you don't need it anymore!) *Add your new line object to a list of lines you define *When you paint, always clear everything and draw each line you have stored. *Optionally, if you're on mouse down, also draw a line between current stored mouse down position and the current mouse position. A: Store the start and end points of the lines in an object that is put in an expandable collection such as an ArrayList. When it comes time to draw, draw all the lines in the list. A: Custom Painting Approaches suggest two approaches. The first to store/redraw the lines as already suggested here. The second approach is to draw directly to a BufferedImage.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627006", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: config git proxy through 127.0.0.1:8087 I can't git clone https://code.google.com/my-repo, so I want set git through my local client proxy 127.0.0.1:8087. How to config? Thank you. A: Try setting the https_proxy environment variable before cloning. For example: export https_proxy=127.0.0.1:8087 git clone https://wherever/whatever.git ... as suggested in the answer to this question and in the comments on GitHub's announcement of Smart HTTP support.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627010", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: wicked_pdf: footer height/styling I'm using the awesome wicked_pdf gem to generate a PDF, but I can't figure out how to change certain styles within the footer. I'm having a HAML template for the footer looking roughly like this: !!! %html %head %meta{:charset => "utf-8"} = wicked_pdf_stylesheet_link_tag "pdf" %body .footer %p Line 1 %p Line 2 %p Line 3 And some styles: .footer { padding-top: 1em; border-top: 1px solid #ccc; } The styles are applied just fine, but the due to a small height of the footer, only the first line is visible. I've tried to set the height via CSS, but no dice so far. If I set a footer using e.g the center, attributes or right supplying text directly, line breaks cause the footer to "grow" as expected. Any idea on how to modify the footer height? A: You'll have to adjust the bottom margin of the PDF to make room for the footer if it is over a certain size. respond_to do |format| format.pdf do render :pdf => 'some_pdf', :margin => { :bottom => 30 }, :footer => { :html => { :template => 'pdfs/footer.pdf.erb' } } end end or you can throw that margin value in your config/initializers/wicked_pdf.rb file if it is a site-wide thing.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627012", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: cookieManager outside of activity I'm trying to do some post request to a webpage containing json data... but there are cookies involved. cookies are working fine but aren't persistent.... I'm doing the request from a separate class(object). I pass the activity context to that class but I'm still not able to store the cookies. I tried using cookiessyncmanager to sync the cookies but this requires a cookiemanger. and that's where I'm stuck because the cookiemanager doesn't allow me to create a context like the cookiesyncmanager does... here's my code: for(Cookie cookie : cookieStore.getCookies()){ String cookieString = cookie.getName() + "=" + cookie.getValue() + "; domain=" + cookie.getDomain(); CookieManager.getInstance().setCookie(cookie.getDomain(), cookieString); } CookieSyncManager.createInstance(baseContext).sync(); as you can see CookieManager allow allows the getInstance() method, but this just results in "failure" as the object obviously doesn't have a context....
{ "language": "en", "url": "https://stackoverflow.com/questions/7627013", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I call an editor command from a vimscript? I want to remove an unwanted scrollbar from taglist. I created a function and a command like this: function s:TlistWaToggle() normal :TlistToggle<cr> " <- this does not work set guioptions-=r endfunction command! -nargs=0 -bar TlistWaToggle call s:TlistWaToggle() I want to wrap the call to :TlistToggle together with the command to remove the right scrollbar (I have that setting of course, but it always reappears, so this is a workaround). Currently my :TlistWaToggle doesn't do anything. How can I make it work? A: Vim script uses ex commands, and apparently :TlistToggle is an ex command… function! s:TlistWaToggle() TlistToggle set guioptions-=r endfunction A: In addition to @sidyll's answer: :normal is not a :*map, it accepts only raw character strings. Correct command will be execute "normal! :TlistToggle\<CR>" (or execute "normal! :TlistToggle\n"). Note that you should not use non-banged version in your scripts. I don't think you will ever use :normal! to execute an ex command, but my answer would be useful when you want to pass any other special character. It also applies to feedkeys() call. By the way, comments and other commands will be considered part of string passed to :normal command.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627014", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Change a number of products to a product pack I have this problem : i'm working on a small e-shop and I have about 60 products in the database . all the products have a code , like : 4444, 5334, 3244 and so on . The problem is that there are also product packs and they are made out of several products . I have to do this : everytime there is an update to the CART there must be a script checking if the products in CART can make a PRODUCT PACK and replace all the products from the CART with that product pack . What do you think would be the best way to do this check / change ? A: Assuming $packs is an array of arrays of items, and $cart is an array of items: foreach($packs as $pack) { $diff = array_diff($pack, $cart); if (empty($diff)) { // $cart contains this pack } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7627015", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to find issue in XAML that causes code crash I wrote a Radio Button style. When a page containing a Radio button, that has the style implementation I wrote. is shown I get crash and I don't know why. After I examined the xaml more than 8 times - I found the bug. But I still want to ask some important question ==> How can i find bugs like this in the future ? There are no place to add 'breakpoints' in the code to stop the code and look if my input is wrong or to look for some algorithm flow. Thanks for help.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627020", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Sending Batch Request to Facebook Open Graph Beta I am trying to submit a batch request to add objects via Open Graph Beta to a user's Timeline but no matter what I do I get this: The action you're trying to publish is invalid because it does not specify any reference objects. At least one of the following properties must be specified: egg. I am specifying an egg property though. My requests look like this: https://graph.facebook.com/?batch=[{'method':'POST','relative_url':'/me/my_namespace:find','egg':'http%3A%2F%2Fwww.mydomain.com%2Fmy_namespace%2Fog%2Fegg.php%3Ftypeid%3D-966','start_time':'1317439270','end_time':'1317439270'}]&access_token=<<snipped>>&method=post I am sending egg as a url-encoded reference string to a URL that contains my open graph data -- the URL does work if I send it not as a batch but since when setting up a user's Timeline I will in some cases have to post up to 1000 actions I am trying to speed things up by batching them. I was able to successfully delete via a batch request. A: Instead of sending the 'egg' as a param of the batch object, you need to format this like a query string and send it in the body param. Also, relative_url should not begin with a '/' Try posting this instead... https://graph.facebook.com/batch?access_token=TOKEN&method=post&batch= [ { "method": "post", "relative_uri": "me/your_namespace:find", "body": "egg=http%3A%2F%2Fwww.mydomain.com%2Fmy_namespace%2Fog%2Fegg.php%3Ftypeid%3D-966&start_time= 1317439270&end_time= 1317439270 } ] I've tested this and it works. When Posting data to the batch API, the data must be formatted like a querysting and sent in the 'body' param as a string.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627021", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: File upload after model save on Django admin I am using a file upload in my Django model like this : def upload_path(self, filename): return 'upload/actualities/%s/%s' % (self.id, filename) photo = models.ImageField(upload_to=upload_path) and my adminModel is : from actualities.models import * from django.contrib import admin class ActualityAdmin(admin.ModelAdmin): class Media: js = ('/static/js/tiny_mce/tiny_mce.js', '/static/js/textareas.js') admin.site.register(Actuality, ActualityAdmin) Everything works fine except when i edit mu model because it has an id. But when I create it, the file upload happens before the model saving... So i put my file in /media/actualities/None/filename.jpg, and I want /media/2/filename.jpg How can I force to make the file upload after the model saving? Thank you!!! A: You will probably want to override the Model's save() method, and maybe come up with a custom "don't do anything" UploadHandler, then switch back to the original one and call save again. https://docs.djangoproject.com/en/dev/topics/http/file-uploads/ https://docs.djangoproject.com/en/dev/topics/db/models/ What I would do in this situation however, is make a custom upload handler that saves the file off into some temp space. Then I'd override the save method (in a mixin or something) that moves the file from temp to wherever you wanted it. @Tomek's answer is also another way. If you have your model generate it's own id, then you can use that. A second to last suggestion which is what I do with my photo blog is instead of saving all the images in a directory like media/2/filename.jpg I save the image by date uploaded. 2011/10/2/image.jpg This kind of helps any directory from getting too unwieldy. Finally, you could hash the file names and store them in directories of hash name to kind of equally spread out the images in a directory. I've picked the date style because that's meaningful for me with that project. Perhaps there is another way you can name an image for saving that would mean something more than "model with id 2's pics" that you could use for this problem. Good Luck! A: As workaround, try generating UUID for file name (instead of using self.id).
{ "language": "en", "url": "https://stackoverflow.com/questions/7627024", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How can I configure gem install to use "install" from the right place? When I try to install rails using gem on my Arch Linux machine, I get the following error: $ gem install rails ... ... make install /usr/bin/install -c -m 0755 bcrypt_ext.so /home/gphilip/.rvm/gems/ruby-1.9.3-preview1/gems/bcrypt-ruby-3.0.1/lib make: /usr/bin/install: Command not found make: * [/home/gphilip/.rvm/gems/ruby-1.9.3-preview1/gems/bcrypt-ruby-3.0.1/lib/bcrypt_ext.so] Error 127 It turns out that on Arch Linux, the "install" binary is located at /bin/install. So on my system I have: $which install /bin/install $ Since I have root access (it is my laptop!), I could easily "fix" this by creating a symlink at /usr/bin/install , but how would I do this otherwise? How do I configure gem to use the "install" command from /bin/ instead of insisting on using the one in /usr/bin/ ? I am asking this in case I am in a situation where I face the same problem and I don't have permissions to create symlinks in arbitrary places. A: Find rbconfig.rb file in your ruby installation dir (example for my machine): $ which ruby /home/valentin/.rvm/rubies/ruby-1.8.7-p352/bin/ruby $ find /home/valentin/.rvm/rubies/ruby-1.8.7-p352 -name rbconfig.rb /home/valentin/.rvm/rubies/ruby-1.8.7-p352/lib/ruby/1.8/x86_64-linux/rbconfig.rb In that file change line CONFIG["INSTALL"] = '/usr/bin/install -c' to CONFIG["INSTALL"] = '/bin/install -c' (Or whichever is the correct install path, I've had to change it back to /usr/bin, for example) You might want to update other paths as well. Or, you can just reinstall ruby.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627027", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Django admin - Keep updating a model and do not create more than one Im not sure how to put this title. But what I need is a simple model that I can just update everytime. Lets say I have a Settings model ,and these settings I just want to update or change every now and again. So there is no need to add another object to that model. Is there suck a field or type of admin-model that I can use? I could otherwise just keep updating the same object, but I do not want the user to be able to just "Add Setting". A: in admin you can specify various permissions. to remove the "add" functionality: class MyModelAdmin(admin.ModelAdmin): def has_add_permission(self, request): return False make sure you create your first and only settings object when you deploy the application. here is a discussion about singleton models in django: How about having a SingletonModel in Django?
{ "language": "en", "url": "https://stackoverflow.com/questions/7627030", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using PIM, how to detect what is the attribute which is retrieved using Contact.TEL and index? I'm looping over all attributes of the Contact.TEL field to retrieve names and data, so that I can display something like this: HOME: +2034953213 WORK: +2033923959 MOBILE: +20179083008 I've retrived the values (+2034953213, +2033923959, +20179083008) successfully using PIM api, but I didn't know how to detect what are the attributes corresponding to the values which I retrieved: (HOME, WORK or MOBILE ...etc) ? How Can I detect that +2034953213 is either the 'HOME' or 'WORK' or 'MOBILE' ? Same question for the other retrieved values ? Here's my code: ContactList contactList = (ContactList)PIM.getInstance().openPIMList(PIM.CONTACT_LIST, PIM.READ_WRITE); Enumeration contactListItems = contactList.items(); while (contactListItems.hasMoreElements()) { Contact contact = (Contact)contactListItems.nextElement(); int telephonesCount = contact.countValues(Contact.TEL); for(int i=0; i< telephonesCount; ++i) { String number = contact.getString(Contact.TEL, i); // I want here to know what is the current attribute that i retrieved its value ? // I mean its value not its index (either HOME, WORK or MOBILE ...etc) } } A: Here's the answer for those who are interested: ContactList contactList = (ContactList)PIM.getInstance().openPIMList(PIM.CONTACT_LIST, PIM.READ_WRITE); Enumeration contactListItems = contactList.items(); while (contactListItems.hasMoreElements()) { Contact contact = (Contact)contactListItems.nextElement(); int telephonesCount = contact.countValues(Contact.TEL); for(int i=0; i< telephonesCount; ++i) { String number = contact.getString(Contact.TEL, i); int attribute = contact.getAttributes(BlackBerryContact.TEL, i); if (attribute == Contact.ATTR_MOBILE) // It's a mobile phone number, do whatever you want here ... else if (attribute == Contact.ATTR_HOME) // It's a home phone number, do whatever you want here ... else if (attribute == Contact.ATTR_WORK) // It's a work phone number, do whatever you want here ... // check other types the same way ... } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7627031", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: belongsTo and hasMany with inline data Is it possible to use the Ext.data.Model associations belongsTo and hasMany with without explicitly using a Ext.data.Proxy? I have Stores that use the inline data attribute to create Model objects. Should associations work with this type of setup? Thanks in advance!
{ "language": "en", "url": "https://stackoverflow.com/questions/7627033", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Any possible way for CoreGraphics to not lag when drawrect is being called from touches moved? I am calling setNeedsDisplay from touches moved (and have also tried not calling from touches moved, but instead from a 0.05 timer) and the drawrect method is always laggy. Is their anyway to change this? I am doing a lot of drawing in drawrect but I have no idea for a solution to fix the lag. Even when the timer was called at a 1.0 interval than it still lagged when the timer called the selector. Also, I have no leaks (I checked using Xcode analyze feature ). Please help!! EDIT: I am calling setNeedsDisplay, not drawRect from my timer/method EDIT: It seems that wherever core graphics does somethings with a lot of drawing it always lags. I am positive I have no memory leaks and I even created another painting app and it lags (what is the fix to this?? Please help mee) A: Slightly edited transcript of comments on one of the other answers: I am drawing a color a hue based color picker (in draw rect a line for each hue value is drawn) … Are you drawing 360 rectangles? Yes, I am …. I draw the images of 360 rectangles of different colors into the image of one UIImageView. than I release the rectangles. (I use a for loop for the rectangle allocation/releasing) So, you are doing this 360 times: * *Create an image. *Draw a rectangle into this image. (Or not, if step 1 loads the image from a file.) *Draw that image into another image. *Release the image. And then you pass the image that you drew all the smaller images into to a UIImageView for the actual display? It sounds like you're trying to cache this in the image, which should help after the first time if you do it right, but this doesn't need to be slow in the first place. You already have a custom view. Drop the image view, and cut out all this rectangle-drawing (or image-drawing) code. If you have image files with the individual colored rectangles, delete them. In your view's drawRect:, create a gradient and draw that. Your drawRect: will be three lines long and should be much, much, much faster. A: You should NEVER call drawRect explicitly. Use setNeedsDisplay instead and the drawing will be performed when the system is ready for it. EDIT: Based on the fact that you were already doing this. Your problem is then your drawRect is just too slow. What are you trying to draw? A: I am calling drawrect from touches moved don't do that. (and have also tried not calling from touches moved, but instead from a 0.05 timer) don't do that. and the drawrect method is always laggy. Is their anyway to change this? I am doing a lot of drawing in drawrect but I have no idea for a solution to fix the lag. Even when the timer was called at a 1.0 interval than it still lagged when the timer called the selector. Also, I have no leaks (I checked using Xcode analyze feature ). Please help!! Yes! A: If you can figure out which parts of the screen needs change, you can call setNeedsDisplayInRect to speed it up by just redrawing the changed rect instead of the whole screen. You can also run a background thread to prepare frames in a buffer and use that to draw on screen. It depends on the kind of drawing you are doing. Here is a blog post I found on this topic. Or you can use OpenGL ES to draw.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627035", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to insert data in table using select statement in sql server I have two tables Login table and userinfo table. UserInfo table is primary key(UserId) table and login table is foreign key(UserId) table. So my problem is when i insert data in login table value of userid column should come from Userinfo table and value of other columns of log in table like username and password should be inserted directly . Is it possible in single insert statement. i did the following but it didnt work insert into login(Userid,username,password) values(select max(userid) from userinfo,sumit,sumit123) A: insert into login(Userid,username,password) values((select max(userid) from userinfo),'sumit','sumit123'); A: insert into login (Userid, username, password) select max(userid), 'sumit', 'sumit123' from userinfo [Please note: while that is syntactically correct, I probably wouldn't do it that way.] A: Have you tried using a inner JOIN? INSERT INTO Insurance (Name) SELECT Employee.Username FROM Employee INNER JOIN Project ON Employee.EmployeeID = Project.EmployeeID WHERE Project.ProjectName = 'Hardwork';
{ "language": "en", "url": "https://stackoverflow.com/questions/7627037", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Will this javascript cause memory leak? function outer(){ var a, b, c; function inner1(){ ... } function inner2(){ ... } inner1(); inner2(); ... } I want to keep the global namespace clean so I wrote above code. Inner functions are only used by code inside Outer. But after that I begin to thought if this will cause any memory problem. I'm not sure whether the inner functions are created beforehand or created each time the outer() is called? And will them cause memory leak? Could someone help explain what will happen when outer() is called and when it returns? And please refer me if there are any good books or articles about javascript memory management. I always get confused by such problems. Thanks. A: Not sure about first part but there is a similar question about the second part: Do you know what may cause memory leaks in JavaScript? How do I track and debug JavaScript memory leaks in Firefox? A: The main problem that causes memory leaks in browsers with JavaScript is the fact, that the DOM and JS have two independet garbage collectors. If you begin to have references to DOM elements in your closure function and then again backreference to something inside the function you will face problems. Your structure is not leaking, but you want to do some more stuff and that maybe leaking. A: Unless you put some other code inside - you should not worry about leaks in such simple closures. Modern javascript engines handle those very well. A: In answer to your question about the creation of the inner functions: I believe your inner functions are created/defined every time you run outer(), and most JS interpreters should garbage-collect them after outer() runs, along with all the other variables in the function scope - unless outer() "exports" these inner functions outside of its own scope, e.g. assigning them as event handlers or including them in a return statement for later use.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627038", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: EF switching from one db to another .edmx settings how to? I have an mvc3/EF4.1 model that has an .edmx bound to a Db locally. I have to move this model to Database to another server. Q: What steps do I need to make so that when I right click on the .edmx and "Update Model/Database" that it selects and picks up that same model but on the new server? Thx! A: Open your web.config and look at your block. The connection information to the server is listed in there. Simply change it to the new server. The full format is listed here: http://msdn.microsoft.com/en-us/library/cc716756.aspx If the new server is using the same authentication, just change the server name (the 'Data Source=localhost' section) to be your new server name.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627042", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: bazaar bind branches In my project , i have local branch for working and branch on network drive i did "bind branch" between local one and network one My idea is to use the bind option for auto backup of each local commit. After i commit files in the local branch , i receive a message in network branch " Working tree is out of date, please run 'bzr update'." my question is : * *Log on network branch will show the updated tree . Does the files are updated ? or i must do "update" ? *automirror plugin will help me for this scenario? thanks A: Binding a local branch to a remote branch means that commits to the local branch will automatically push that commit to the remote branch. If the remote branch and the local branch are not in sync, the commit will fail and neither the local or remote branch will be affected and your changes will still be sitting in your working tree. To get your local branch in sync with the remote branch, use bzr update. If your network branch has a working tree, then the working tree is not automatically updated when commits are pushed from the local branch into the network branch. The network branch's working tree has to be updated with bzr update or plugins like automirror or push-and-update. Unless you actually need the working tree in the network branch, I would recommend that you reconfigure the branch to be tree-less using bzr reconfigure --branch. If you have a shared repository that the network branch belongs to, you will also need to use bzr reconfigure --with-no-trees on the repository to stop it creating trees on new branches. A: The 'bind branch' feature will succeed only if your local and network branches are up-to-date. So the commit failed as there is a difference between these 2 working copies.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627046", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Azure Table Storage OnStart Constructor Query I've been looking at some Azure samples and doing some general searching around Table Storage. I've noticed a bit of a pattern using OnStart and a static constructor. For example the following type of code is found in both locations: // Get connection string and table name from settings. connectionString = RoleEnvironment.GetConfigurationSettingValue("StorageConnectionString"); tableName = RoleEnvironment.GetConfigurationSettingValue("TableName"); // Reference storage account from connection string. storageAccount = CloudStorageAccount.Parse(connectionString); // Create Table service client. tableClient = storageAccount.CreateCloudTableClient(); My question is why on both locations? Surely this is just duplication? The static constructor will be called once we start working with the data type, while OnStart will run when during application start-up. Personally I think the static constructor makes more sense. I just want to make sure I'm understanding things correctly, Mark A: In the example you shared, I can find two places where there's similar code. One is in OnStart (in the RoleEntryPoint), and one is in a static constructor in a class called DataLayer. DataLayer appears to be used in the web application (running under IIS), so a different class in a different process from the RoleEntryPoint. The one in RoleEntryPoint appears to be initializing storage (creating the table) before the application starts up. The one in DataLayer seems to be initializing some variables to avoid code repetition in the other methods (parsing the connection string, instantiating the client).
{ "language": "en", "url": "https://stackoverflow.com/questions/7627048", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to check whether the path is relative or absolute in java? I am developing a tool, which takes a path of an xml file. Now that path can be either relative or absolute. Inside the code, when I have only a string, is there a way to identify that the path is absolute or relative? A: How about File.isAbsolute(): File file = new File(path); if (file.isAbsolute()) { ... } A: There is another very similar way using Paths operations: Path p = Paths.get(pathName); if (p.isAbsolute()) { ... }
{ "language": "en", "url": "https://stackoverflow.com/questions/7627049", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "41" }
Q: cassandra data model for web logging Been playing around with Cassandra and I am trying to evaluate what would be the best data model for storing things like views or hits for unique page id's? Would it best to have a single column family per pageid, or 1 Super-column (logs) with columns pageid? Each page has a unique id, then would like to store date and some other metrics on the view. I am just not sure which solution handles better scalability, lots of column family OR 1 giant super-column? page-92838 { date:sept 2, browser:IE } page-22939 { date:sept 2, browser:IE5 } OR logs { page-92838 { date:sept 2, browser:IE } page-22939 { date:sept 2, browser:IE5 } } And secondly, how to handle lots of different date: entries for page-92838? A: You don't need a column-family per pageid. One solution is to have a row for each page, keyed on the pageid. You could then have a column for each page-view or hit, keyed and sorted on time-UUID (assuming having the views in time-sorted order would be useful) or other unique, always-increasing counter. Note that all Cassandra columns are time-stamped anyway, so you would have a precise timestamp 'for free' regardless of what other time- or date- stamps you use. Using a precise time-UUID as the key also solves the problem of storing many hits on the same date. The value of each column could then be a textual value or JSON document containing any other metadata you want to store (such as browser). page-12345 -> {timeuuid1:metadata1}{timeuuid2:metadata2}{timeuuid3:metadata3}... page-12346 -> ... A: With cassandra, it is best to start with what queries you need to do, and model your schema to support those queries. Assuming you want to query hits on a page, and hits by browser, you can have a counter column for each page like, stats { #cf page-id { #key hits : # counter column for hits browser-ie : #counts of views with ie browser-firefox : .... } } If you need to do time based queries, look at how twitters rainbird denormalizes as it writes to cassandra.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627050", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What Web app chores, can be eliminated using Plugins/Gems in Rails I've been building Rails Application Prototypes and Loving it. I'm aware that there are many pre-build libraries to utilize in projects. While, I'm not a fan of using plugins for managing login and user authentication, which is core part of the app, aside from that what other chores can be dealt with plugins/gems, like pagination etc. What do you use in your day to day rails development. A: There are times when using freely available plugins/gems (libraries) may not be suitable but since it is quite trivial to review the code of these, in the long run you will find that many of these gems can be quite handy. A lot of these are also actively kept up to date by the community and this is also an important point as Rails in particular has been evolving at a fairly rapid pace. For example, Devise has been around for quite sometime and if you look at the amount of support this tends to translate into a commensurate number of blog articles and how-to's on the web; even here on SO Devise in particular gets many questions. It also has many modules that you can incorporate within your app, or just disable if you do not require their functionality. Rather than going into the benefits of plugins, I suggest you visit http://rubygems.org/ as it let's you go through the various gems based on their particular functionality. Personally, I use Devise as well as authentication from scratch, Omniauth, Kaminari (pagination), CanCan for ACL and quite a bit more. This is the Gemfile from one of my recent apps and it should give you a decent idea of what I use. Being familiar with popular gems is quite handy as it means rather than having to 're-invent the wheel', when it simply comes to getting the job done... you do have options - especially when it's not the sole purpose of your app. Certainly though, if you're up to creating custom plugins or decide to pull out reusable code into plugins, do share them with the community. Hope this helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/7627054", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to determine Internet Connection in Cocoa? I need to determine if Internet Connection is available or not. I don't care how it is connected (WI-FI, Lan,etc..) . I need to determine, is Internet Connection available at all . P.S. I found a way to check WI-FI connection. But I don't care how it is connected (I need to check all the ways that can be connected to Internet). Something like (isConnected) A: This code works for both iOS and OSX platforms, I hope. #include <SystemConfiguration/SystemConfiguration.h> static BOOL isInternetConnection() { BOOL returnValue = NO; #ifdef TARGET_OS_MAC struct sockaddr zeroAddress; bzero(&zeroAddress, sizeof(zeroAddress)); zeroAddress.sa_len = sizeof(zeroAddress); zeroAddress.sa_family = AF_INET; SCNetworkReachabilityRef reachabilityRef = SCNetworkReachabilityCreateWithAddress(NULL, (const struct sockaddr*)&zeroAddress); #elif TARGET_OS_IPHONE struct sockaddr_in address; size_t address_len = sizeof(address); memset(&address, 0, address_len); address.sin_len = address_len; address.sin_family = AF_INET; SCNetworkReachabilityRef reachabilityRef = SCNetworkReachabilityCreateWithAddress(NULL, (const struct sockaddr*)&address); #endif if (reachabilityRef != NULL) { SCNetworkReachabilityFlags flags = 0; if(SCNetworkReachabilityGetFlags(reachabilityRef, &flags)) { BOOL isReachable = ((flags & kSCNetworkFlagsReachable) != 0); BOOL connectionRequired = ((flags & kSCNetworkFlagsConnectionRequired) != 0); returnValue = (isReachable && !connectionRequired) ? YES : NO; } CFRelease(reachabilityRef); } return returnValue; } A: Take a look at the SCNetworkReachability reference. This is a C API, so it's not as easy to use as a single method call, but it does a great job of notifying your app when a particular address becomes reachable or unreachable over the network. The broad outline is you'll create an object with SCNetworkReachabilityCreateWithAddress or SCNetworkReachabilityCreateWithName, and then add it to the run loop with SCNetworkReachabilityScheduleWithRunLoop. When the reachability is determined and when it changes, the callback function you supply will be called. You can use that to update the state of your application. Apple supplies an example app that shows how to use this (although it's designed for iOS, not Mac OS X) A: One way to do it is : // Check whether the user has internet - (bool)hasInternet { NSURL *url = [[NSURL alloc] initWithString:@"http://www.google.com"]; NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:5.0]; BOOL connectedToInternet = NO; if ([NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]) { connectedToInternet = YES; } //if (connectedToInternet) //NSLog(@"We Have Internet!"); [request release]; [url release]; return connectedToInternet; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7627058", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Python's logging module misses "captureWarnings" function Python's standard logging module is supposed to contain a useful captureWarnings function that allows integration between the logging and the warnings modules. However, it seems that my installation misses this function: Python 2.6.5 (r265:79096, Mar 19 2010, 21:48:26) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import logging >>> logging.captureWarnings Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'module' object has no attribute 'captureWarnings' >>> import logging.captureWarnings Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named captureWarnings >>> import warnings >>> import logging.captureWarnings Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named captureWarnings >>> What am I doing wrong? A: Unfortunately, there is no such method in Python 2.6.5's logging module. You need Python 2.7.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627075", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: NullReferenceException while storing data to session in an ASP.NET MVC 3 Controller I have a following View Method in an ASP.NET MVC 3 Controller that retrieves data from Amazon SimpleDb, stores it in a list and then stores that list object in a session. But at the line where I am storing the userBox object in a session (Session["userBox"] = userBox), I am getting a NullReferenceException. I am sure that userBox is not null. Even if I try to store a simple string in a session (like Session["userBox"] = "test") I still get NullReferenceException. Here is the code: public ActionResult SetSidebarAccountBoxSessions(string id) { string selectExpression = "select * from MySimpleDBDomain where itemName()='" + id + "'"; SelectRequest sreq = new SelectRequest().WithSelectExpression(selectExpression); SelectResponse sres = sdb.Select(sreq); List<User> userBox = new List<User>(); if (sres.IsSetSelectResult()) { SelectResult selectresult = sres.SelectResult; foreach (Item item in selectresult.Item) { string a = item.Name; userBox.Add(new User { imageThug = item.Attribute[0].Value, name = item.Attribute[3].Value, bio = item.Attribute[1].Value }); } } Session["userBox"] = userBox; return View(); } I am calling this SetSideBarAccountBoxSessions(id) method from another controller method: HomeController hc = new HomeController(); hc.SetSidebarAccountBoxSessions(item.Name); Can this be the problem? Please help. A: I think this problem is related to the fact that you create HomeController by yourself. You can try to use TransferToRouteResult to transfer the action to HomeController. You an find the code of TransferToRouteResult in this link: How to simulate Server.Transfer in ASP.NET MVC?
{ "language": "en", "url": "https://stackoverflow.com/questions/7627079", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: iOS maps GPS location implementing blue-ball location and arrow sign on the map 1.) I need to have a blue ball circle/location dot on a map as shown below. * *What is it called? *How can I implement it? 2.) How do I get the arrow on the pop-up screen as below? A: I think what you're after is the MKMapView; if so you just need to add it in interface builder and there is an option (checkbox) in the Attributes Inspector panel that allows you to 'Shows users location'. By checking that box it will make the blue dot appear on the map (if you're using the iPhone Simulator it will only show up as Cupertio). Theres lots of simple tutorials on getting started with map views for iPhone. Here is a pretty good one. If you don't like it then I suggest you Google 'MkMapView tutorials' and you should find plenty of useful information. In order to get the location of the user (latitude & longitude) you will need to do a few things: 1) Make sure you've imported the CoreLocation framework (CoreLocation.framework) 2) You need add the following to your .h file: #import <CoreLocation/CoreLocation.h> @interface exampleViewController : UIViewController <CLLocationManagerDelegate> { CLLocationManager *locationManager; } @property(nonatomic, retain)CLLocationManager *locationManager; 3) You need to add the following to your .m file (wherever is appropriate for your app) This part will create an instance of the CLLocationManager: self.locationManager = [[CLLocationManager alloc] init]; locationManager.delegate = self; locationManager.desiredAccuracy = kCLLocationAccuracyBest; [locationManager startUpdatingLocation]; You can then get the current latitude & longitude using the delegate method: - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { NSLog(@"New latitude: %f", newLocation.coordinate.latitude); NSLog(@"New longitude: %f", newLocation.coordinate.longitude); } You should also look at this existing question and this one too, I think it should help you with the second part of your question. Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627084", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: django check which users approved document I have two models class Document(models.Model): name = models.CharField(max_length=250, blank=True) class Approval(models.Model): document = models.ForeignKey(Document) user = models.ForeignKey(User, related_name='approval user') status = models.IntegerField(choices=APPROVELS, default=1, help_text="Approved") i want to list all document with current login user approval status, when a user approve/Abstain/Not Approved a document i am recording in Approval table otherwise there is no record about current user approval status in Approval table Please help me with the view and template. A: On view: userApprovals = Approval.objects.filter( user = request.user ) or userApprovals = request.user.approval_user_set.all() forYourApproval = Document.objects.exclude( pk__in = [ a.document.pk for a in userApprovals ] ) and don't forget to include userApprovals on render_to_response: return render_to_response( "yourPage.html", { "userApprovals": userApprovals, "forYourApproval": forYourApproval, }, context_instance=RequestContext(request)) On template: {% for approval in userApprovals %} {{ approval.document.name }} status {{ approval.get_status_display }} {% endfor %} {% for document in forYourApproval %} {{ document.name }} waiting for your approval. {% endfor %} Note: change related name to 'approval_user'. A: It's not clear whether your requirements allow any user to approve a document, but I'm inferring that this is the case based on your models. If a Document can only be approved by a specific user, or set of users, or if a document is approved by multiple users, you will need to make some substantial changes to your model design. If not, I would write a view like this: from django.db.models import Q def approval_view(request): documents = Document.objects.filter( Q(approval__id__isnull=True) | Q(approval__user=request.user)) return render_to_response(template_name, {'documents': documents}) This will return a context with documents that have no Approval record in the approval table OR who have been approved by request.user. You will likely need some additional code to display the appropriate information for each document in documents. For example, a custom template filter that displays a document status ("For your Approval" or "Approved" or whatever) might be necessary. An example template fragment: {% for document in documents %} <li>{{ document.name }} - {{ document|approval_status }}</li> {% endfor %} As I said at the beginning, your requirements are not clear. Is every user to be given an opportunity to approve a document? Or do all documents get a single opportunity to be approved by any user? There is a big difference and this code reflects the latter assumption. If every user is to be given an opportunity to approve a document and you need to display the current user's approval decision, then the above code will work with slight modification. I would probably modify the view to display all documents in some order: documents = Document.objects.all() And then use a custom template filter as above to display the approval status for the current user (passing in the user as an argument): <li>{{ document.name }} - {{ document|approval_status:request.user }}</li>
{ "language": "en", "url": "https://stackoverflow.com/questions/7627091", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Encryption in Dropbox-like Java application I'm thinking about encryption in an application. The architecture consists of: * *Server *Desktop client *Web client *mobile client The goal is to allow user to store his data on the server, and access it from all clients, but to guarantee data privacy by encrypting data on the client. Dropbox is an example of such an architecture, but as far as I know they don't do that - they must store plaintext data on their servers, otherwise they wouldn't be able to save on space by storing the same file only once, even if it was stored by multiple users. How would you implement such an application? I'm thinking about using Java for desktop client; the same encryption code could theoretically be reused in GWT web client (compiled to Javascript) and in Android client. However, that's only in theory. * *Is there an encryption library that's available on all these platforms? *What algorithms to use? *What about private keys? I can ask user for the password every time, but how do I ensure that private keys are the same for the same user in all clients? *I'd like to avoid multiple passwords; but if I use the same password for both data and authentication, how do I prevent server from giving data to a hacker which supplied the wrong password, or server from being able to decrypt user data because it has user's password? *What possible gotchas are there? A: You actually need a few different pieces of cryto. First, you want the client to encrypt the file for upload, and upon retrieving the encrypted payload back decrypt it. Second, you want some method to transmitting the encrypted file for upload in a manner that insures that only the correct user can access his files. The first problem requires a symmetric encryption algorithm. There are a bunch out there, but your best bet is probably AES. If you take a look at gwt-crypto at they have a wrapper for the java bouncy castle implementation. That takes care of two of three of your platforms. I don't work with android platform, but I'd be surprised if there wasn't an AES implementation floating around. As for the key, you'll probably end up with a hash of a password. Just keep in mind the possibility of rainbow tables and take appropriate measures. The password used to encrypt the file need never go over the wire, as I understand your model all encryption and deception is done on the client. Since you mentioned system administrators as a potential attacker, you really need to look into key loggers, memory dumps and the like, but that's beyond the scope of the specific question you asked. The second problem is a solved problem using TLS with client and server side certificates. Clients for such are available for all three platforms you are looking at. Whether you want make your users go through the hassle of installing client side certificates, though, is up to you. There are various fallback options but none are as well vetted.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627097", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is a lambda expression in C++11? What is a lambda expression in C++11? When would I use one? What class of problem do they solve that wasn't possible prior to their introduction? A few examples, and use cases would be useful. A: What is a lambda function? The C++ concept of a lambda function originates in the lambda calculus and functional programming. A lambda is an unnamed function that is useful (in actual programming, not theory) for short snippets of code that are impossible to reuse and are not worth naming. In C++ a lambda function is defined like this []() { } // barebone lambda or in all its glory []() mutable -> T { } // T is the return type, still lacking throw() [] is the capture list, () the argument list and {} the function body. The capture list The capture list defines what from the outside of the lambda should be available inside the function body and how. It can be either: * *a value: [x] *a reference [&x] *any variable currently in scope by reference [&] *same as 3, but by value [=] You can mix any of the above in a comma separated list [x, &y]. The argument list The argument list is the same as in any other C++ function. The function body The code that will be executed when the lambda is actually called. Return type deduction If a lambda has only one return statement, the return type can be omitted and has the implicit type of decltype(return_statement). Mutable If a lambda is marked mutable (e.g. []() mutable { }) it is allowed to mutate the values that have been captured by value. Use cases The library defined by the ISO standard benefits heavily from lambdas and raises the usability several bars as now users don't have to clutter their code with small functors in some accessible scope. C++14 In C++14 lambdas have been extended by various proposals. Initialized Lambda Captures An element of the capture list can now be initialized with =. This allows renaming of variables and to capture by moving. An example taken from the standard: int x = 4; auto y = [&r = x, x = x+1]()->int { r += 2; return x+2; }(); // Updates ::x to 6, and initializes y to 7. and one taken from Wikipedia showing how to capture with std::move: auto ptr = std::make_unique<int>(10); // See below for std::make_unique auto lambda = [ptr = std::move(ptr)] {return *ptr;}; Generic Lambdas Lambdas can now be generic (auto would be equivalent to T here if T were a type template argument somewhere in the surrounding scope): auto lambda = [](auto x, auto y) {return x + y;}; Improved Return Type Deduction C++14 allows deduced return types for every function and does not restrict it to functions of the form return expression;. This is also extended to lambdas. A: The lambda's in c++ are treated as "on the go available function". yes its literally on the go, you define it; use it; and as the parent function scope finishes the lambda function is gone. c++ introduced it in c++ 11 and everyone started using it like at every possible place. the example and what is lambda can be find here https://en.cppreference.com/w/cpp/language/lambda i will describe which is not there but essential to know for every c++ programmer Lambda is not meant to use everywhere and every function cannot be replaced with lambda. It's also not the fastest one compare to normal function. because it has some overhead which need to be handled by lambda. it will surely help in reducing number of lines in some cases. it can be basically used for the section of code, which is getting called in same function one or more time and that piece of code is not needed anywhere else so that you can create standalone function for it. Below is the basic example of lambda and what happens in background. User code: int main() { // Lambda & auto int member=10; auto endGame = [=](int a, int b){ return a+b+member;}; endGame(4,5); return 0; } How compile expands it: int main() { int member = 10; class __lambda_6_18 { int member; public: inline /*constexpr */ int operator()(int a, int b) const { return a + b + member; } public: __lambda_6_18(int _member) : member{_member} {} }; __lambda_6_18 endGame = __lambda_6_18{member}; endGame.operator()(4, 5); return 0; } so as you can see, what kind of overhead it adds when you use it. so its not good idea to use them everywhere. it can be used at places where they are applicable. A: Answers Q: What is a lambda expression in C++11? A: Under the hood, it is the object of an autogenerated class with overloading operator() const. Such object is called closure and created by compiler. This 'closure' concept is near with the bind concept from C++11. But lambdas typically generate better code. And calls through closures allow full inlining. Q: When would I use one? A: To define "simple and small logic" and ask compiler perform generation from previous question. You give a compiler some expressions which you want to be inside operator(). All other stuff compiler will generate to you. Q: What class of problem do they solve that wasn't possible prior to their introduction? A: It is some kind of syntax sugar like operators overloading instead of functions for custom add, subrtact operations...But it save more lines of unneeded code to wrap 1-3 lines of real logic to some classes, and etc.! Some engineers think that if the number of lines is smaller then there is a less chance to make errors in it (I'm also think so) Example of usage auto x = [=](int arg1){printf("%i", arg1); }; void(*f)(int) = x; f(1); x(1); Extras about lambdas, not covered by question. Ignore this section if you're not interest 1. Captured values. What you can to capture 1.1. You can reference to a variable with static storage duration in lambdas. They all are captured. 1.2. You can use lambda for capture values "by value". In such case captured vars will be copied to the function object (closure). [captureVar1,captureVar2](int arg1){} 1.3. You can capture be reference. & -- in this context mean reference, not pointers. [&captureVar1,&captureVar2](int arg1){} 1.4. It exists notation to capture all non-static vars by value, or by reference [=](int arg1){} // capture all not-static vars by value [&](int arg1){} // capture all not-static vars by reference 1.5. It exists notation to capture all non-static vars by value, or by reference and specify smth. more. Examples: Capture all not-static vars by value, but by reference capture Param2 [=,&Param2](int arg1){} Capture all not-static vars by reference, but by value capture Param2 [&,Param2](int arg1){} 2. Return type deduction 2.1. Lambda return type can be deduced if lambda is one expression. Or you can explicitly specify it. [=](int arg1)->trailing_return_type{return trailing_return_type();} If lambda has more then one expression, then return type must be specified via trailing return type. Also, similar syntax can be applied to auto functions and member-functions 3. Captured values. What you can not capture 3.1. You can capture only local vars, not member variable of the object. 4. Сonversions 4.1 !! Lambda is not a function pointer and it is not an anonymous function, but capture-less lambdas can be implicitly converted to a function pointer. p.s. * *More about lambda grammar information can be found in Working draft for Programming Language C++ #337, 2012-01-16, 5.1.2. Lambda Expressions, p.88 *In C++14 the extra feature which has named as "init capture" have been added. It allow to perform arbitarily declaration of closure data members: auto toFloat = [](int value) { return float(value);}; auto interpolate = [min = toFloat(0), max = toFloat(255)](int value)->float { return (value - min) / (max - min);}; A: Well, one practical use I've found out is reducing boiler plate code. For example: void process_z_vec(vector<int>& vec) { auto print_2d = [](const vector<int>& board, int bsize) { for(int i = 0; i<bsize; i++) { for(int j=0; j<bsize; j++) { cout << board[bsize*i+j] << " "; } cout << "\n"; } }; // Do sth with the vec. print_2d(vec,x_size); // Do sth else with the vec. print_2d(vec,y_size); //... } Without lambda, you may need to do something for different bsize cases. Of course you could create a function but what if you want to limit the usage within the scope of the soul user function? the nature of lambda fulfills this requirement and I use it for that case. A: C++ 11 introduced lambda expression to allow us write an inline function which can be used for short snippets of code [ capture clause ] (parameters) -> return-type { definition of method } Generally return-type in lambda expression are evaluated by compiler itself and we don’t need to specify that explicitly and -> return-type part can be ignored but in some complex case as in conditional statement, compiler can’t make out the return type and we need to specify that. // C++ program to demonstrate lambda expression in C++ #include <bits/stdc++.h> using namespace std; // Function to print vector void printVector(vector<int> v) { // lambda expression to print vector for_each(v.begin(), v.end(), [](int i) { std::cout << i << " "; }); cout << endl; } int main() { vector<int> v {4, 1, 3, 5, 2, 3, 1, 7}; printVector(v); // below snippet find first number greater than 4 // find_if searches for an element for which // function(third argument) returns true vector<int>:: iterator p = find_if(v.begin(), v.end(), [](int i) { return i > 4; }); cout << "First number greater than 4 is : " << *p << endl; // function to sort vector, lambda expression is for sorting in // non-decreasing order Compiler can make out return type as // bool, but shown here just for explanation sort(v.begin(), v.end(), [](const int& a, const int& b) -> bool { return a > b; }); printVector(v); // function to count numbers greater than or equal to 5 int count_5 = count_if(v.begin(), v.end(), [](int a) { return (a >= 5); }); cout << "The number of elements greater than or equal to 5 is : " << count_5 << endl; // function for removing duplicate element (after sorting all // duplicate comes together) p = unique(v.begin(), v.end(), [](int a, int b) { return a == b; }); // resizing vector to make size equal to total different number v.resize(distance(v.begin(), p)); printVector(v); // accumulate function accumulate the container on the basis of // function provided as third argument int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int f = accumulate(arr, arr + 10, 1, [](int i, int j) { return i * j; }); cout << "Factorial of 10 is : " << f << endl; // We can also access function by storing this into variable auto square = [](int i) { return i * i; }; cout << "Square of 5 is : " << square(5) << endl; } Output 4 1 3 5 2 3 1 7 First number greater than 4 is : 5 7 5 4 3 3 2 1 1 The number of elements greater than or equal to 5 is : 2 7 5 4 3 2 1 Factorial of 10 is : 3628800 Square of 5 is : 25 A lambda expression can have more power than an ordinary function by having access to variables from the enclosing scope. We can capture external variables from enclosing scope by three ways : * *Capture by reference *Capture by value *Capture by both (mixed capture) The syntax used for capturing variables : * *[&] : capture all external variable by reference *[=] : capture all external variable by value *[a, &b] : capture a by value and b by reference A lambda with empty capture clause [ ] can access only those variable which are local to it. #include <bits/stdc++.h> using namespace std; int main() { vector<int> v1 = {3, 1, 7, 9}; vector<int> v2 = {10, 2, 7, 16, 9}; // access v1 and v2 by reference auto pushinto = [&] (int m) { v1.push_back(m); v2.push_back(m); }; // it pushes 20 in both v1 and v2 pushinto(20); // access v1 by copy [v1]() { for (auto p = v1.begin(); p != v1.end(); p++) { cout << *p << " "; } }; int N = 5; // below snippet find first number greater than N // [N] denotes, can access only N by value vector<int>:: iterator p = find_if(v1.begin(), v1.end(), [N](int i) { return i > N; }); cout << "First number greater than 5 is : " << *p << endl; // function to count numbers greater than or equal to N // [=] denotes, can access all variable int count_N = count_if(v1.begin(), v1.end(), [=](int a) { return (a >= N); }); cout << "The number of elements greater than or equal to 5 is : " << count_N << endl; } Output: First number greater than 5 is : 7 The number of elements greater than or equal to 5 is : 3 A: A lambda function is an anonymous function that you create in-line. It can capture variables as some have explained, (e.g. http://www.stroustrup.com/C++11FAQ.html#lambda) but there are some limitations. For example, if there's a callback interface like this, void apply(void (*f)(int)) { f(10); f(20); f(30); } you can write a function on the spot to use it like the one passed to apply below: int col=0; void output() { apply([](int data) { cout << data << ((++col % 10) ? ' ' : '\n'); }); } But you can't do this: void output(int n) { int col=0; apply([&col,n](int data) { cout << data << ((++col % 10) ? ' ' : '\n'); }); } because of limitations in the C++11 standard. If you want to use captures, you have to rely on the library and #include <functional> (or some other STL library like algorithm to get it indirectly) and then work with std::function instead of passing normal functions as parameters like this: #include <functional> void apply(std::function<void(int)> f) { f(10); f(20); f(30); } void output(int width) { int col; apply([width,&col](int data) { cout << data << ((++col % width) ? ' ' : '\n'); }); } A: Lambda expressions are typically used to encapsulate algorithms so that they can be passed to another function. However, it is possible to execute a lambda immediately upon definition: [&](){ ...your code... }(); // immediately executed lambda expression is functionally equivalent to { ...your code... } // simple code block This makes lambda expressions a powerful tool for refactoring complex functions. You start by wrapping a code section in a lambda function as shown above. The process of explicit parameterization can then be performed gradually with intermediate testing after each step. Once you have the code-block fully parameterized (as demonstrated by the removal of the &), you can move the code to an external location and make it a normal function. Similarly, you can use lambda expressions to initialize variables based on the result of an algorithm... int a = []( int b ){ int r=1; while (b>0) r*=b--; return r; }(5); // 5! As a way of partitioning your program logic, you might even find it useful to pass a lambda expression as an argument to another lambda expression... [&]( std::function<void()> algorithm ) // wrapper section { ...your wrapper code... algorithm(); ...your wrapper code... } ([&]() // algorithm section { ...your algorithm code... }); Lambda expressions also let you create named nested functions, which can be a convenient way of avoiding duplicate logic. Using named lambdas also tends to be a little easier on the eyes (compared to anonymous inline lambdas) when passing a non-trivial function as a parameter to another function. Note: don't forget the semicolon after the closing curly brace. auto algorithm = [&]( double x, double m, double b ) -> double { return m*x+b; }; int a=algorithm(1,2,3), b=algorithm(4,5,6); If subsequent profiling reveals significant initialization overhead for the function object, you might choose to rewrite this as a normal function. A: The problem C++ includes useful generic functions like std::for_each and std::transform, which can be very handy. Unfortunately they can also be quite cumbersome to use, particularly if the functor you would like to apply is unique to the particular function. #include <algorithm> #include <vector> namespace { struct f { void operator()(int) { // do something } }; } void func(std::vector<int>& v) { f f; std::for_each(v.begin(), v.end(), f); } If you only use f once and in that specific place it seems overkill to be writing a whole class just to do something trivial and one off. In C++03 you might be tempted to write something like the following, to keep the functor local: void func2(std::vector<int>& v) { struct { void operator()(int) { // do something } } f; std::for_each(v.begin(), v.end(), f); } however this is not allowed, f cannot be passed to a template function in C++03. The new solution C++11 introduces lambdas allow you to write an inline, anonymous functor to replace the struct f. For small simple examples this can be cleaner to read (it keeps everything in one place) and potentially simpler to maintain, for example in the simplest form: void func3(std::vector<int>& v) { std::for_each(v.begin(), v.end(), [](int) { /* do something here*/ }); } Lambda functions are just syntactic sugar for anonymous functors. Return types In simple cases the return type of the lambda is deduced for you, e.g.: void func4(std::vector<double>& v) { std::transform(v.begin(), v.end(), v.begin(), [](double d) { return d < 0.00001 ? 0 : d; } ); } however when you start to write more complex lambdas you will quickly encounter cases where the return type cannot be deduced by the compiler, e.g.: void func4(std::vector<double>& v) { std::transform(v.begin(), v.end(), v.begin(), [](double d) { if (d < 0.0001) { return 0; } else { return d; } }); } To resolve this you are allowed to explicitly specify a return type for a lambda function, using -> T: void func4(std::vector<double>& v) { std::transform(v.begin(), v.end(), v.begin(), [](double d) -> double { if (d < 0.0001) { return 0; } else { return d; } }); } "Capturing" variables So far we've not used anything other than what was passed to the lambda within it, but we can also use other variables, within the lambda. If you want to access other variables you can use the capture clause (the [] of the expression), which has so far been unused in these examples, e.g.: void func5(std::vector<double>& v, const double& epsilon) { std::transform(v.begin(), v.end(), v.begin(), [epsilon](double d) -> double { if (d < epsilon) { return 0; } else { return d; } }); } You can capture by both reference and value, which you can specify using & and = respectively: * *[&epsilon, zeta] captures epsilon by reference and zeta by value *[&] captures all variables used in the lambda by reference *[=] captures all variables used in the lambda by value *[&, epsilon] captures all variables used in the lambda by reference but captures epsilon by value *[=, &epsilon] captures all variables used in the lambda by value but captures epsilon by reference The generated operator() is const by default, with the implication that captures will be const when you access them by default. This has the effect that each call with the same input would produce the same result, however you can mark the lambda as mutable to request that the operator() that is produced is not const. A: One of the best explanation of lambda expression is given from author of C++ Bjarne Stroustrup in his book ***The C++ Programming Language*** chapter 11 (ISBN-13: 978-0321563842): What is a lambda expression? A lambda expression, sometimes also referred to as a lambda function or (strictly speaking incorrectly, but colloquially) as a lambda, is a simplified notation for defining and using an anonymous function object. Instead of defining a named class with an operator(), later making an object of that class, and finally invoking it, we can use a shorthand. When would I use one? This is particularly useful when we want to pass an operation as an argument to an algorithm. In the context of graphical user interfaces (and elsewhere), such operations are often referred to as callbacks. What class of problem do they solve that wasn't possible prior to their introduction? Here i guess every action done with lambda expression can be solved without them, but with much more code and much bigger complexity. Lambda expression this is the way of optimization for your code and a way of making it more attractive. As sad by Stroustup : effective ways of optimizing Some examples via lambda expression void print_modulo(const vector<int>& v, ostream& os, int m) // output v[i] to os if v[i]%m==0 { for_each(begin(v),end(v), [&os,m](int x) { if (x%m==0) os << x << '\n'; }); } or via function class Modulo_print { ostream& os; // members to hold the capture list int m; public: Modulo_print(ostream& s, int mm) :os(s), m(mm) {} void operator()(int x) const { if (x%m==0) os << x << '\n'; } }; or even void print_modulo(const vector<int>& v, ostream& os, int m) // output v[i] to os if v[i]%m==0 { class Modulo_print { ostream& os; // members to hold the capture list int m; public: Modulo_print (ostream& s, int mm) :os(s), m(mm) {} void operator()(int x) const { if (x%m==0) os << x << '\n'; } }; for_each(begin(v),end(v),Modulo_print{os,m}); } if u need u can name lambda expression like below: void print_modulo(const vector<int>& v, ostream& os, int m) // output v[i] to os if v[i]%m==0 { auto Modulo_print = [&os,m] (int x) { if (x%m==0) os << x << '\n'; }; for_each(begin(v),end(v),Modulo_print); } Or assume another simple sample void TestFunctions::simpleLambda() { bool sensitive = true; std::vector<int> v = std::vector<int>({1,33,3,4,5,6,7}); sort(v.begin(),v.end(), [sensitive](int x, int y) { printf("\n%i\n", x < y); return sensitive ? x < y : abs(x) < abs(y); }); printf("sorted"); for_each(v.begin(), v.end(), [](int x) { printf("x - %i;", x); } ); } will generate next 0 1 0 1 0 1 0 1 0 1 0 sortedx - 1;x - 3;x - 4;x - 5;x - 6;x - 7;x - 33; [] - this is capture list or lambda introducer: if lambdas require no access to their local environment we can use it. Quote from book: The first character of a lambda expression is always [. A lambda introducer can take various forms: • []: an empty capture list. This implies that no local names from the surrounding context can be used in the lambda body. For such lambda expressions, data is obtained from arguments or from nonlocal variables. • [&]: implicitly capture by reference. All local names can be used. All local variables are accessed by reference. • [=]: implicitly capture by value. All local names can be used. All names refer to copies of the local variables taken at the point of call of the lambda expression. • [capture-list]: explicit capture; the capture-list is the list of names of local variables to be captured (i.e., stored in the object) by reference or by value. Variables with names preceded by & are captured by reference. Other variables are captured by value. A capture list can also contain this and names followed by ... as elements. • [&, capture-list]: implicitly capture by reference all local variables with names not men- tioned in the list. The capture list can contain this. Listed names cannot be preceded by &. Variables named in the capture list are captured by value. • [=, capture-list]: implicitly capture by value all local variables with names not mentioned in the list. The capture list cannot contain this. The listed names must be preceded by &. Vari- ables named in the capture list are captured by reference. Note that a local name preceded by & is always captured by reference and a local name not pre- ceded by & is always captured by value. Only capture by reference allows modification of variables in the calling environment. Additional Lambda expression format Additional references: * *Wiki *open-std.org, chapter 5.1.2 A: One problem it solves: Code simpler than lambda for a call in constructor that uses an output parameter function for initializing a const member You can initialize a const member of your class, with a call to a function that sets its value by giving back its output as an output parameter.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627098", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1736" }
Q: How to use list from sys/queue.h? Currently, I have implemented a singly linked list, like so: struct PeerNode { struct Peer* cargo; struct PeerNode* next; }; ...and I have a struct that contains a couple of these linked lists, like so: struct Torrent { ... struct PeerNode* peer_list; struct PeerNode* unchoked_peers; ... } I would like to replace this by using the macros provided by sys/queue.h. I gather that I could replace my code with something like this: struct Torrent { ... LIST_ENTRY(PeerNode, Peer) peer_list; struct PeerNode* unchoked_peers; ... } Then, from looking at man queue, I believe I would initialize the lists by doing something like this: LIST_INIT(&peer_list); LIST_INIT(unchoked_peers); However, I don't understand how LIST_ENTRY factors into usage of the list. From the man page, it says: "The macro LIST_ENTRY declares a structure that connects the elements in the list," but I don't really understand what this means. Why would I want to declare a structure to connect the elements in the list? Shouldn't each node be connected to the next node via a pointer, like my initial linked list implementation? How would I replace my linked lists with the implementation provided by sys/queue.h? How would I insert an element into the list? A: LIST_ENTRY creates fields to put into your structure that are suitable for linking the elements, so you do not have to concern yourself with the specifics of those pointers. struct foo { int a, b, c; /* This is instead of "struct foo *next" */ LIST_ENTRY(foo) pointers; }; To then create a list you'd use LIST_HEAD(): struct Torrent { LIST_HEAD(foo_list, foo) bar; }; You can initialise the list header using LIST_INIT(): struct Torrent t; LIST_INIT(&t.bar); You can insert elements using the LIST_INSERT_*() macros: struct foo *item = malloc(sizeof(struct foo)); LIST_INSERT_HEAD(&t.bar, item, pointers); This was all taken from the list example in the man pages at http://www.manpagez.com/man/3/queue/ For a full example: http://infnis.wikidot.com/list-from-sys-queue-h A: try to use the man instruction: man queue Or this site
{ "language": "en", "url": "https://stackoverflow.com/questions/7627099", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "27" }
Q: Android reading from InputStream not consistent I have a rooted android phone. I am trying to read the output of "ls" via my program: Process p = null; p = Runtime.getRuntime().exec(new String[]{"su", "-c", "system/bin/sh"}); DataOutputStream stdin = new DataOutputStream(p.getOutputStream()); stdin.writeBytes("ls / \n"); stdin.flush(); InputStream stdout = p.getInputStream(); and after that when I do read() , the read call blocks sometimes, sometimes it doesn't get blocked and I am able to read from the stream. Sometime i have to wait for the buffer to be filled. read = stdout.read(buffer); Isn't there any consistent way in which this read could happen. I am doing ls on the same directory and i am noting different delays. or Is it better to use pseudo terminal?
{ "language": "en", "url": "https://stackoverflow.com/questions/7627100", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Toast showing up twice I have a program that sends pre-defined text messages to a group of people at a push of a button. I have it working well but the problem I have is that when it sends the messages, it pops up with 2 toasts per message sent. Code: package com.mfd.alerter; //imports public class homeScreen extends Activity { //buttons /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //vars // Grab the time final Date anotherCurDate = new Date(); SimpleDateFormat formatter = new SimpleDateFormat("km"); final String formattedTime = formatter.format(anotherCurDate); // Contacts final String[] numbers = getResources().getStringArray(R.array.numbers); // Start messages. Only 1 is given to shorten post callStructureFire.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { String msgText = "MFD PAGE OUT:\nStructure Fire\nTimeout:"+formattedTime; for (int i = 0; i < numbers.length; i++) { sendSMS(numbers[i], msgText); } } }); //more call types. not important. } //---sends a SMS message to another device--- private void sendSMS(String numbers, String message) { String SENT = "SMS_SENT"; PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(SENT), 0); //---when the SMS has been sent--- registerReceiver(new BroadcastReceiver(){ @Override public void onReceive(Context arg0, Intent arg1) { switch (getResultCode()) { case Activity.RESULT_OK: Toast.makeText(getBaseContext(), "SMS sent", Toast.LENGTH_SHORT).show(); break; case SmsManager.RESULT_ERROR_GENERIC_FAILURE: Toast.makeText(getBaseContext(), "Generic failure", Toast.LENGTH_SHORT).show(); break; case SmsManager.RESULT_ERROR_NO_SERVICE: Toast.makeText(getBaseContext(), "No service", Toast.LENGTH_SHORT).show(); break; case SmsManager.RESULT_ERROR_NULL_PDU: Toast.makeText(getBaseContext(), "Null PDU", Toast.LENGTH_SHORT).show(); break; case SmsManager.RESULT_ERROR_RADIO_OFF: Toast.makeText(getBaseContext(), "Radio off", Toast.LENGTH_SHORT).show(); break; } } }, new IntentFilter(SENT)); SmsManager sms = SmsManager.getDefault(); sms.sendTextMessage(numbers, null, message, sentPI, null); } //action bar stuff. not important. } More in detail: Lets say I send the text to 3 people, 6 toast messages will pop up saying "SMS Sent". How do I make it so only 3 will show up? Also, Is there a way to maybe add a counter of the messages sent? Ex: "Message 1/10 sent", "Message 2/10 sent", etc? A: I didn't really look at your code or asked myself why this happens but here's a trick to stop toasts show up twice: Create a Toast instance using makeToast(), before showing it you call cancel(), set your text and then call show(). This will dismiss the previous toast. You won't even notice that a toast is displayed twice. That's a stupid workaround, but it works for me ;-) A: Aren't you supposed to register the receiver only once and not every time you call sendSMS. You get 6 Toasts with three sms messages because you have 3 BroadCastReceivers. So in the first run you get 1 Toast. In the second run you get 2 Toasts (the receiver that was registered in the first run is called, and the one in the second). In the third run all three receivers are called, so you get three more toasts. All in sum - 6 Toasts... so I guess, you have to register only one receiver before the for loop where you call sendSMS, or if you want the registration in sendSMS, then you have to unregister at the end of the method. I hope this helps, cheers!
{ "language": "en", "url": "https://stackoverflow.com/questions/7627102", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: OpenGL rotation and scaling Does rotation always occur about the origin (0,0,0)? Does translation always occur relative to previous translation? Does scaling increase the coordinates axes size? A: I suggest that a good way for a beginner is to start by thinking about points rather than 3D objects. Then all the transformation can be thought of as functions to change a point position to a new position. First imagine an XYZ cartesian coordinate space, then imagine a point (X,Y,Z) in space with origin (0, 0, 0). All OpenGL knows at this stage is the point X,Y,Z. Now you are ready to begin: Rotation requires an angle and a center of rotation. glRotate allows you to only specify the angles. By virtue of mathematics, conceptually, the center of rotation is at the location (X-X,Y-Y,Z-Z) or (0,0,0). Translation is just an offset from the current position. Since OpenGL knows your point (X,Y,Z) it simply adds the offest to the position vector. It is therefore more correct to say it is relative to the current position rather than previous translation. Scaling is a multiplication of the point vector (X.m,Y.m,Z.m) hence it simply just translating that point by a factor of m. Hence conceptually one can say it doesn't change the coordinate axes size. However, when you start to think in 3D things get abit tricky because you will realise that if you are not careful, the all the points in a single 3D object doesn't always change position in the way you desire relative to each other. You will learn for example that if you want to rotate about the object's center, you will have to "move it to the origin, rotate, and then move it back again". This process of moving it back an forth can be thought as specifying the center of rotation. These are actually mathematical "tricks" that you apply. A: Does rotation always occur about the origin (0,0,0)? Indeed this is the case. Does translation always occur relative to previous translation? Does scaling increase the coordinates axes size? This requires some explanation: OpenGL, and so many other software operating with geometry data don't build a list of chained transformations. What they maintain is one single homogenous transformation matrix. "Appending" a transformation is done by multiplying the current transformation matrix with the transformation matrix describing the "next" transformation, replacing the old transformation. This also means that a compound transformation matrix, like what you end up having in the OpenGL modelview, may be applied as transformation as well. To make a long story short, it depends all on the transformation applied. Old OpenGL gives you some basic matrix manipulations. In OpenGL-3 they have been removed, because OpenGL is not a math library, but draws stuff. So how does such a transformation matrix look like? Like this: Xx Yx Zx Tx Xy Yy Zy Ty Xz Yz Zz Tz _x _y _z w Maybe you noticed that there are 3 major columns designated by capital X, Y, Z. Those columns form vectors. And in the case of 3D transformations those are the base vectors of a coordinate system, relative the one the transformation is applied upon. However vectors only give "directions" and a length. So what's needed as well is the relative point of origin of the new coordinate system, and that's what the T vector contains. Most of the time _x = _y = _z = 0 and w = 1 Transforming a point of geometry happens by multiplying the points vector with the matrix. Let such a matrix be M, the point p, then p' = M * p Now assume we chain transformations: p'' = M' * p' = M' * M * p We can substitute M_ = M' * M, so p'' = M_ * p It's easy to see, that we can chain this arbitrarily long To answer your two last questions: Transformations (not just translations) do chain. And yes, applying a scaling transform will "scale" the axes. And to clear up some commong misunderstanding: OpenGL is not a scene graph, it does not deal with "objects", but just lists of geometry. glScale, glTranslate, glRotate don't transform objects, but "chain up" transformation operations. A: someone with more experience will surely point you to a good tutorial but your question reflect that you don't understand the 3D graphical pipeline and more precisely the concept of projection matrix (I might have the wrong name here since I studied this ages ago in French lol). Basically whenever you apply a rotation/translation/scaling you are modifying the same matix therefor when you each operation modifies the existing state. For example doing rotation then a translation will give you a different result that translation then rotaiton (try doing the solar system sun earth moon it will help you understand) regarding your questions: * *No the basic rotation will not always occur in 0,0,0. for example if you first translate to 2,3,4 then the rotation will happen in 2,3,4. *the simple answer is yes, you are moving your matrice form its last position.(read my comment at the end for the not the simple answer ^^) *scaling will affect all the transformations done after. example scale 1,2,2 followed by a translation 2,3,4 could be seen as a a global translation 2,6,8 now for the not so simple part: as explained each change will be affected by the previous changes (example of the scale) also there is a lot of ways to do the same thing or to alter the behavior, for example: achieving absolute translation can be done like this -translate -create an object -indentity (reset the matrix to 0) -translate2 -create object2 My advice is read tutorials but also global 3D programing blogs or a book (red book is good when you start lol)
{ "language": "en", "url": "https://stackoverflow.com/questions/7627106", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How To Define Function From Closure This question is related to one I asked recently. If I rewrite (fn [n] (fn [x] (apply * (repeat n x)))) as (defn power [n] (fn [x] (apply * (repeat n x))))` it works just fine when used like this ((power 2) 16) I can substitute 2 with another power, but I'd like to make a function just for squares, cubed, and so on. What is the best way to do that? I've been fiddling with it in the REPL, but no luck so far. A: Using a macro for this goes entirely around his question, which was "I have a function that generates closures, how do I give those closures names?" The simple solution is: (letfn [(power [n] (fn [x] (apply * (repeat n x))))] (def square (power 2)) (def cube (power 3))) If you really truly hate repeating def and power a few times, then and only then is it time to get macros involved. But the amount of effort you'll spend on even the simplest macro will be wasted unless you're defining functions up to at least the tenth power, compared to the simplicity of doing it with functions. A: Not quite sure if this is what you're searching for, but macro templates might be it. Here's how I would write your code: (use 'clojure.template) (do-template [name n] (defn name [x] (apply * (repeat n x))) square 2 cube 3) user> (cube 3) ;=> 27 For more complex type of similar tasks, you could write a macro that wrap do-template to perform some transformation on its arguments, e.g.: (defmacro def-powers-of [& ns] (let [->name #(->> % (str "power") symbol)] `(do-template [~'name ~'n] (defn ~'name [~'x] (apply * (repeat ~'n ~'x))) ~@(->> ns (map #(vector (->name %) %)) flatten)))) (def-powers-of 2 3 4 5) user> (power3 3) ;=> 27 user> (power5 3) ;=> 243 P.S.: That macro might look awkward if you're just starting with Clojure though, don't give up because of it! ;-)
{ "language": "en", "url": "https://stackoverflow.com/questions/7627110", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Save the console.log in Chrome to a file Does anyone know of a way to save the console.log output in Chrome to a file? Or how to copy the text out of the console? Say you are running a few hours of functional tests and you've got thousands of lines of console.log output in Chrome. How do you save it or export it? A: This may or may not be helpful but on Windows you can read the console log using Event Tracing for Windows http://msdn.microsoft.com/en-us/library/ms751538.aspx Our integration tests are run in .NET so I use this method to add the console log to our test output. I've made a sample console project to demonstrate here: https://github.com/jkells/chrome-trace --enable-logging --v=1 doesn't seem to work on the latest version of Chrome. A: For Google Chrome Version 84.0.4147.105 and higher, just right click and click 'Save as' and 'Save' then, txt file will be saved A: A lot of good answers but why not just use JSON.stringify(your_variable) ? Then take the contents via copy and paste (remove outer quotes). I posted this same answer also at: How to save the output of a console.log(object) to a file? A: I have found a great and easy way for this. * *In the console - right click on the console logged object *Click on 'Store as global variable' *See the name of the new variable - e.g. it is variableName1 *Type in the console: JSON.stringify(variableName1) *Copy the variable string content: e.g. {"a":1,"b":2,"c":3} *Go to some JSON online editor: e.g. https://jsoneditoronline.org/ A: There is an open-source javascript plugin that does just that, but for any browser - debugout.js Debugout.js records and save console.logs so your application can access them. Full disclosure, I wrote it. It formats different types appropriately, can handle nested objects and arrays, and can optionally put a timestamp next to each log. You can also toggle live-logging in one place, and without having to remove all your logging statements. A: There is another open-source tool which allows you to save all console.log output in a file on your server - JS LogFlush (plug!). JS LogFlush is an integrated JavaScript logging solution which include: * *cross-browser UI-less replacement of console.log - on client side. *log storage system - on server side. Demo A: If you're running an Apache server on your localhost (don't do this on a production server), you can also post the results to a script instead of writing it to console. So instead of console.log, you can write: JSONP('http://localhost/save.php', {fn: 'filename.txt', data: json}); Then save.php can do this <?php $fn = $_REQUEST['fn']; $data = $_REQUEST['data']; file_put_contents("path/$fn", $data); A: * *Right-click directly on the logged value you want to copy *In the right-click menu, select "Store as global variable" *You'll see the value saved as something like "temp1" on the next line in the console *In the console, type copy(temp1) and hit return (replace temp1 with the variable name from the previous step). Now the logged value is copied to your clipboard. *Paste the values to wherever you want This is especially good as an approach if you don't want to mess with changing flags/settings in Chrome and don't want to deal with JSON stringifying and parsing etc. Update: I just found this explanation of what I suggested with images that's easier to follow https://scottwhittaker.net/chrome-devtools/2016/02/29/chrome-devtools-copy-object.html A: Good news Chrome dev tools now allows you to save the console output to a file natively * *Open the console *Right-click *Select "save as.." Chrome Developer instructions here. A: These days it's very easy - right click any item displayed in the console log and select save as and save the whole log output to a file on your computer. A: On Linux (at least) you can set CHROME_LOG_FILE in the environment to have chrome write a log of the Console activity to the named file each time it runs. The log is overwritten every time chrome starts. This way, if you have an automated session that runs chrome, you don't have a to change the way chrome is started, and the log is there after the session ends. export CHROME_LOG_FILE=chrome.log A: I needed to do the same thing and this is the solution I found: * *Enable logging from the command line using the flags: --enable-logging --v=1 This logs everything Chrome does internally, but it also logs all the console.log() messages as well. The log file is called chrome_debug.log and is located in the User Data Directory which can be overridden by supplying --user-data-dir=PATH (more info here). *Filter the log file you get for lines with CONSOLE(\d+). Note that console logs do not appear with --incognito. A: For better log file (without the Chrome-debug nonsense) use: --enable-logging --log-level=0 instead of --v=1 which is just too much info. It will still provide the errors and warnings like you would typically see in the Chrome console. update May 18, 2020: Actually, I think this is no longer true. I couldn't find the console messages within whatever this logging level is. A: the other solutions in this thread weren't working on my mac. Here's a logger that saves a string representation intermittently using ajax. use it with console.save instead of console.log var logFileString=""; var maxLogLength=1024*128; console.save=function(){ var logArgs={}; for(var i=0; i<arguments.length; i++) logArgs['arg'+i]=arguments[i]; console.log(logArgs); // keep a string representation of every log logFileString+=JSON.stringify(logArgs,null,2)+'\n'; // save the string representation when it gets big if(logFileString.length>maxLogLength){ // send a copy in case race conditions change it mid-save saveLog(logFileString); logFileString=""; } }; depending on what you need, you can save that string or just console.log it and copy and paste. here's an ajax for you in case you want to save it: function saveLog(data){ // do some ajax stuff with data. var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function(){ if (this.readyState == 4 && this.status == 200) {} } xhttp.open("POST", 'saveLog.php', true); xhttp.send(data); } the saveLog.php should append the data to a log file somewhere. I didn't need that part so I'm not including it here. :) https://www.google.com/search?q=php+append+to+log A: This answer might seem specifically related, but specifically for Network Log, you can visit the following link. The reason I've post this answer is because in my case, the console.log printed a long truncated text so I couldn't get the value from the console. I solved by getting the api response I was printing directly from the network log. chrome://net-export/ There you may see a similar windows to this, just press the Start Logging to Disk button and that's it: A: Create a batch file using below command and save it as ChromeDebug.bat in your desktop. start chrome --enable-logging --v=1 Close all other Chrome tabs and windows. Double click ChromeDebug.bat file which will open Chrome and a command prompt with Chrome icon in taskbar. All the web application logs will be stored in below path. Run the below path in Run command to open chrome log file %LocalAppData%\Google\Chrome\User Data\chrome_debug.log
{ "language": "en", "url": "https://stackoverflow.com/questions/7627113", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "229" }
Q: perl ftp not working Script works fine, but ftp code uploading the xls but uploading with 0 byte, but if ftp code present in before of the following snippet, FTP Works Fine, What is the error in code, my $workbook = Spreadsheet::WriteExcel->new('TestRPT.xls'); my $worksheet = $workbook->add_worksheet('TestRPT Report'); #!/usr/bin/perl use strict; use warnings; use DBI; use Spreadsheet::WriteExcel; use POSIX qw(strftime); my $CurTimeStamp=time; my $LastSunTimestamp=($CurTimeStamp - 168*60*60); my $row; my $PinNumber; my $PinAmount; my $get_date; my $get_time; my $get_time_stamp; my $DoFTPFlg = "yes"; # Create a new workbook and add a worksheet. my $workbook = Spreadsheet::WriteExcel->new('TestRPT.xls'); my $worksheet = $workbook->add_worksheet('TestRPT Report'); # Write some text. in write function First Argument for ROW, Second Argument for COLUMN, Third Argument for Title/Text to display $worksheet->write(0, 0, 'val1'); $worksheet->write(0, 1, 'val2'); $worksheet->write(0, 2, 'val3'); $worksheet->write(0, 3, 'val4'); my $cnt = 1; $get_time_stamp = time; $get_date = strftime("%m/%d/%y",localtime($get_time_stamp)); $get_time = strftime("%H:%M",localtime($get_time_stamp)); # Write some numbers. $worksheet->write($cnt, 0, "val1"); $worksheet->write($cnt, 1, "val2"); $worksheet->write($cnt, 2, "val3"); $worksheet->write($cnt, 3, "val4"); if ($DoFTPFlg eq "yes") { print "DO FTP"; use Net::FTP; my $ftp; $ftp = Net::FTP->new("mysite.in", Debug => 0); $ftp->login("user",'pass'); $ftp->cwd("/www/"); $ftp->put("TestRPT.xls"); $ftp->quit; } A: You should close your $workbook object before trying to do anything with the file. From the documentation: An explicit close() is required if the file must be closed prior to performing some external action on it such as copying it, reading its size or attaching it to an email. A: Try a slight modification on your code. Instead of $ftp->put("TestRPT.xls"); Create another file in the www directory and try to ftp that file. If that file is called test.txt, change your line to: $ftp->put("TestRPT.xls"); Thus, the only change in your code is the name of the file being FTP'd. If your FTP works, the problem isn't with the FTP, but with the Spreadsheet::WriteExcel module. As Mat has already stated, you need to do an explicit close on your object. If your FTP doesn't work, it probably is an issue with the FTP call (although it looks fine to me).
{ "language": "en", "url": "https://stackoverflow.com/questions/7627114", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Movable dashboard-like panels for web I wonder, is there any free complete solution for implementing web dashboard like this? All I need is to implement such movable widget panels but any additional functional will be useful. A: YUI? GWT? Dojo? Anything with widgets can implement this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627115", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I limit the number of digits in a list? This is a small piece of code that I am writing for an chemistry ab initio program. I am having issues making the C1pos list a number with exactly 6 digits after the decimal place. I have tried several methods such as the decimal function, but so far I am having no luck. Position is a definition that will take a matrix (1,1,1)+(1,1,1) and give you (2,2,2) numpy is not installed on my server. class Position: def __init__(self, data): self.data = data def __repr__(self): return repr(self.data) def __add__(self, other): data = [] #start with an empty list for j in range(len(self.data)): data.append(self.data[j] + other.data[j]) return Position(data) deltaa=2.000001 #Set number of steps +1 numx=2 numy=1 numz=1 Carbon=[1.070000,0.000000,0.000000] startpos=[1.000000,1.000000,1.000000] l=[] top=os.getcwd() lgeom=[] for i in range(numx): for j in range(numy): for h in range(numz): l=i, j, h shift=list(l) shiftdist=[ k*deltaa for k in shift] C1pos=Position(Carbon)+Position(shiftdist)+Position(startpos) ltempl[10]=' C1,'+str(C1pos).strip('[]').replace(' ','') Any suggestions? EG: The output needs to be C1,2.123456,3.123456,4.123456 The number will never surpass 10. A: ','.join("%.6f" % f for f in C1pos) Example C1pos = [2.123, 300.123456, 4.123456789] print ','.join("%.6f" % f for f in C1pos) Output 2.123000,300.123456,4.123457 A: you can use the decimal class to round all your numbers to 6 decimal places. from decimal import Decimal, ROUND_UP Decimal(n).quantize(Decimal('.000001'), rounding=ROUND_UP) or if you are doing this operation on a string (as i suspect from your code): print ('C1,' + ','.join(["%.6f" %x for x in C1pos]))
{ "language": "en", "url": "https://stackoverflow.com/questions/7627116", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Scala underscore - ERROR: missing parameter type for expanded function I know there have been quite a few questions on this, but I've created a simple example that I thought should work,but still does not and I'm not sure I understand why val myStrings = new Array[String](3) // do some string initialization // this works myStrings.foreach(println(_)) // ERROR: missing parameter type for expanded function myStrings.foreach(println(_.toString)) Can someone explain why the second statement does not compile? A: It expands to: myStrings.foreach(println(x => x.toString)) You want: myStrings.foreach(x => println(x.toString)) The placeholder syntax for anonymous functions replaces the smallest possible containing expression with a function.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627117", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "92" }
Q: Posting php over to html form wraped up in my own code Hello i have what i need in side $v->id But i need to get it from this page over to testing.php here is my code echo ' <div class="auction_box" style="height:150px"> <form name="myform" action="http://mysite.net/new_rpg/testing.php?' .$v->id. '" method="POST"> <p> </p> <p> </p> <p> </p> <img src="http://pokemontoxic.net/new_rpg/'.$battle_get['pic'].'" height="96px" width="96px"/><br/> Name:<br/>' .$v->pokemon. '<br/> Level:' .$v->level. '<br/> Exp:' .$v->exp. '<br/> Slot you want to put your pokemon in <select name="mydropdown"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> </select> <select name="hfghfhg"> < option value="' .$v->id. '" input type="hidden"> Please leave</option> </select> <input type="submit" value="Submit" /> </form> </div>'; } } I am submitting the form and getting the result from mydropdown which i want but am not getting the result from $v->id how would i make a hidden field with $v->id in side ? so when the form is submitted it will be posted onto testing and i could do i post to get it on testing ?? Has you can see i have tryied to make a drop down which would hold the variable and then post it over to the other page and make it hidden but it ent hidden ..... <select name="hfghfhg"> < option value="' .$v->id. '" input type="hidden"> Please leave</option> </select> A: Use hidden text field which it's value is $v->id A: You should add a field to the form like this: '<input type="hidden" name="myName" value="' . $v->id . '" />' Then set myName to whatever you want your value to be on the server, and access $v->id by using $_POST['myName'] on your target page.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627121", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: JSJaC + Openfire: no connection with some users ok, I'm finally at my wits' end. I have a have an XMPP server (Openfire) running, and trying to connect via JavaScript using JSJaC. The strange thing is that I can establish a connection for some users, but not for all. I can reproduce the following behavior: create two accounts (username/password), namely r/pwd and rr/pwd with the result: r/pwd works rr/pwd doesn't work. So far, each account with a user name consisting of only one character works. This is strange enough. On the other side, old accounts, e.g., alice/a work. The whole connection problem is quite new, and I cannot trace it to any changes I've made. And to make my confusion complete with any instant messenger supporting XMPP, all accounts work, incl., e.g., rr/pwd. So assume, the error must be somewhere in my JavaScript code. Here's he relevant snippet: ... oArgs = new Object(); oArgs.domain = this.server; oArgs.resource = this.resource; oArgs.username = "r"; oArgs.pass = "pwd"; this.connection.connect(oArgs); The code above works, but setting oArgs.username = "rr", and it fails. I would be grateful for any hints. I'm quite sure that it must be something really stupid I miss here. Christian A: Adding oArgs.authtype = 'nonsasl' to the argument list when creating the xmpp connection using JSJaC solved my problem. I haven't tried Joe's command to alter the SASL settings in Openfire; I'm scared to ruing my running system :).
{ "language": "en", "url": "https://stackoverflow.com/questions/7627122", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Online calculator or accurate formula to calculate the number of milliseconds since 1970 to a given date? Can anyone give me the link to an online calculator or an accurate formula to calculate the number of milliseconds since 1970 to a given date? i have a function which calculates this. But I want to compare the output of my function with the output of some inbuilt function in java or the output of some online calculator which does this same computation? I've tried out this Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT-4")); cal.set(2000, 01, 21, 04, 33, 44); long mynum=cal.getTimeInMillis(); System.out.println(mynum); The problem is that the "mynum" value keeps changing for every run.. So i can't do a correct comparison. Can anyone direct me in the correct path? A: They keep changing because you set all the fields except the milliseconds, which are thus the number of milliseconds at the current time. Call cal.set(Calendar.MILLISECOND, 0) or cal.clear() before setting the other fields, and the values shouldn't vary anymore.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627123", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Selecting with a limit, but also a limit on the amount of times a column can have a specific value I've got the following SQL query. I want to get 5 posts from this query, but I also want to limit it so that I can, at most, get two posts per user. Only two users in this case, would mean a maximum of four posts. SELECT DISTINCT * FROM posts WHERE (user_id IN (2,1000001) AND NOT track_id = 34) GROUP BY track_id ORDER BY id desc LIMIT 5 A: Add a condition to your WHERE clause in which you count the number of rows for that user with a greater id, and make sure there are only 1 or 0 rows. SELECT DISTINCT * FROM posts P1 WHERE user_id IN (2,1000001) AND NOT track_id = 34 AND (SELECT COUNT(*) FROM posts P2 WHERE P2.user_id = P1.user_id AND P2.id > P1.id AND P2.track_id <> 34) <= 1 GROUP BY track_id ORDER BY id desc LIMIT 5 A: SELECT sub.* FROM (SELECT p1.* FROM posts p1 LEFT JOIN posts p2 ON (p1.user_id = p2.user_id AND p1.id < p2.id) LEFT JOIN posts p3 ON (p1.user_id = p3.user_id AND p2.id < p3.id) WHERE user_id IN ('2','1000001') AND NOT track_id = '34' AND p3.id IS NULL ORDER BY user_id) sub GROUP BY sub.track_id ORDER BY sub.id DESC LIMIT 5 The subselect only allows the posts with the top 2 users.id to be selected, this forces only 2 rows to be selected. It does however force the outcome in a certain way, so you may want to see if this fits your use case.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627124", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Javascript + Prevent printing out duplicate values from listbox to label I am trying to prevent printing duplicated values from a listbox to a label, this is what I did but apparently it's not right, there's not errors but nothing is printed out to my label, if I remove this line: if (arSelected.indexOf(selectBox.option[i].selected == -1)) it prints out the values but apparently everytime I click and highlight on the values in the listbox, it's going to print them out again to my label. Please kindly advice. Thanks! <select multiple size="8" style="width: 135px" onBlur="selectAl ('QualMemTypeToBox',true)" id="QualMemTypeToBox"></select> function selectAll(selectBox, selectAll) { var arSelected = ""; // have we been passed an ID if (typeof selectBox == "string") { selectBox = document.getElementById(selectBox); } // is the select box a multiple select box? if (selectBox.type == "select-multiple") { for (var i = 0; i < selectBox.options.length; i++) { selectBox.options[i].selected = selectAll; if (arSelected.indexOf(selectBox.option[i].selected == -1)) { document.getElementById('<%=uilblDestinationQualMemType.ClientID%>').innerHTML += selectBox.options[i].value + " | "; arSelected += selectBox.options[i].selected; } } } } A: try: function selectAll(selectBox, selectAll) { var arSelected = ""; // have we been passed an ID if (typeof selectBox == "string") { selectBox = document.getElementById(selectBox); } //reset the label every time the function is called document.getElementById('<%=uilblDestinationQualMemType.ClientID%>').innerHTML=""; // is the select box a multiple select box? if (selectBox.type == "select-multiple") { for (var i = 0; i < selectBox.options.length; i++) { selectBox.options[i].selected = selectAll; //make sure you process only items that have been checked //AND you need to track the VALUE of the <option> //NOT the "selected" attribute if (selectBox.options[i].selected && arSelected.indexOf(selectBox.options[i].value) == -1) { document.getElementById('<%=uilblDestinationQualMemType.ClientID%>').innerHTML += selectBox.options[i].value + " | "; //here is where you actually update the variable with the VALUE //of the <option>, not the "selected" attribute arSelected += selectBox.options[i].value; } } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7627129", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to change the location of a minimized mdichild form? In my MDI application i have changed the size of its MDI client to avoid the scrollbars that appear when a portion of an MDI child form is moved out of the view of the client area of the MDI parent form (i made the MDI client size bigger than the size of the screen). I know i can use an API using ShowScrollBar to hide these scrollBars but it flickers and i prefere not to use an API. Now i have a problem that when minimizing any of the MDI child Forms its location is set by default to the bottom of the MDI client (which its size is bigger than the size of the screen) so the minimized MDI child form doesn't appear. So how can i change the location of a minimized mdichild form? Thanks in advance. A: Try to read the ClientRectangle from the parent and apply the location to the child accordingly before minimizing. I think you ca implement the Form Minimized or minimizing events.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627130", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to set tooltip with many rows for each (dynamic) listbox item in Silverlight I would like to set in Silverlight for each item in a ListBox a tooltip with many rows. In XAML i have a listbox and a button: <ListBox Height="100" HorizontalAlignment="Left" Margin="24,136,0,0" Name="listBox1" VerticalAlignment="Top" Width="109" ItemsSource="{Binding}"> <Button Content="Add" Name="button_add" VerticalAlignment="Top" Width="118" Click="add_Click"> in c# private void button_add_Click(object sender, RoutedEventArgs e) { ObservableCollection<Person> obs1 = new ObservableCollection<Person>(); obs1.Add(new Person(){Name="Name1", Age=1}); obs1.Add(new Person(){Name="Name2", Age=2}); listBox1.ItemsSource = obs1; // This Line of Code MUST NOT BE USED!! listBox1.DisplayMemberPath = "Name"; } public class Person { public String Name { get; set; } public int Age { get; set; } public override string ToString() { return Name; } } I would like to show for each item the Age as my tooltip. Edit: Ok, this is the Solution for showing only AGE as tooltip. That is one Line/Row. <ListBox Height="100" HorizontalAlignment="Left" Margin="24,136,0,0" Name="listBox1" VerticalAlignment="Top" Width="109" ItemsSource="{Binding}"> <ListBox.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding Name}" ToolTipService.ToolTip="{Binding Age}"/> </DataTemplate> </ListBox.ItemTemplate> </ListBox> But what if i want to show a Tooltip with 2 Lines? something like: Name: Name1 Age: 1 Edit: 3 rows, 2 columns. i also added public String Comment { set; get; } to class Person <ListBox Height="100" HorizontalAlignment="Left" Margin="24,136,0,0" Name="listBox1" VerticalAlignment="Top" Width="109" ItemsSource="{Binding}"> <ListBox.ItemTemplate> <DataTemplate> <StackPanel> <ToolTipService.ToolTip> <ToolTip> <Grid> <Grid.RowDefinitions> <RowDefinition Height="20"></RowDefinition> <RowDefinition Height="20"></RowDefinition> <RowDefinition Height="40"></RowDefinition> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="80"/> <ColumnDefinition Width="250"/> </Grid.ColumnDefinitions> <TextBlock Text="Name: " Grid.Row="0" Grid.Column="0" /> <TextBlock Text="{Binding Name}" Grid.Row="0" Grid.Column="1"/> <TextBlock Text="Age: " Grid.Row="1" Grid.Column="0"/> <TextBlock Text="{Binding Age}" Grid.Row="1" Grid.Column="1"/> <TextBlock Text="Comment: " Grid.Row="2" Grid.Column="0"/> <TextBlock Text="{Binding Comment}" Grid.Row="2" Grid.Column="1" TextWrapping="Wrap" /> </Grid> </ToolTip> </ToolTipService.ToolTip> <TextBlock Text="{Binding Name}" /> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox> But there is stil a problem. The comment can be short or long, so i would like to make the ROWS/LINES/SPACE for Comment to be variable or else Text is cut off. A: You can use any controls for tooltip content: <ToolTipService.ToolTip> <StackPanel Orientation="Vertical"> <TextBlock Text="{Binding Name}" /> <TextBlock Text="{Binding Age}" /> </StackPanel> </ToolTipService.ToolTip> Other possibility would be to use a converter, that returns the Name and Age separated by \r\n.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627131", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I do a context menu with logo on the left side I've looking for 4 hours how can I do a context menu with logo. I mean something which looks like daemon tools context menu. For these who dont know how it looks like: Is there any option to do it in simple way in XAML? A: You will have to adjust ContextMenu's control template. Just copy the whole thing and and wrap this StackPanel in Grid or DockPanel to which you add the image: <StackPanel ClipToBounds="True" Orientation="Horizontal" IsItemsHost="True" /> Once you understand and learn not to fear control templates, they are really not a big deal. No C# necessary, all is pure XAML. Brief tutorial.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627134", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Javascript regex that matches a decimal that is polluted with other characters I'm trying to match the first set of digits in the following examples. some stuff (6 out of 10 as a rating) needs to return 6 some stuff (2.3 out of 10 as a rating) needs to return 2.3 some stuff (10 out of 10 as a rating) needs to return 10 Also, sometimes the string won't have a number some stuff but nothing else A: var match = /\d+(\.\d+)?/.exec("some stuff (10 out of 10 as a rating)"); alert(match[0]); * *\d matches any numner, 0-9 *+ means 1 or more *\. matches a . *? means 0 or 1 so overall it means any number of digits (0-9) optionally followed by, a decimal point followed by 1 or more digits. As a function: var getFirstNumber = function(input){ var match = /\d+(\.\d+)?/.exec(input); return match[0]; }; A: You can try this 'some stuff (2.3 out of 10 as a rating)'.match(/\D*(\d\.?(\d)*)/)[1]
{ "language": "en", "url": "https://stackoverflow.com/questions/7627145", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }