Posts

Showing posts from January, 2013

url rewriting - Recommended Lists Of Reserved Words For User-Generated URL Components -

i in process of creating web app. since admire directness of twitter's url scheme user pages, i'm trying emulate them. i'd users' profile pages available @ http://myapp.com/user_chosen_identifier. right have basic code ensuring rfc3305 compliance put in url, i'm more worried words should reserve. there question year ago that almost, not quite, addressed problem . i'm using routes , it's pretty trivial implement - i'm not sure implement. i've done brainstorming session think of identifiers prohibit (default.anything, about, admin, , on), that's not work done, i'm asking community tell me best practices , consensus. words should prohibit users using in identifiers if use http://myapp.com/user_chosen_identifier url scheme ? there list of recommendations can start from? alternatively, fundamentally intractable problem the clbuttic error , curseword filtering in general ? * here's words think about: account(s) an...

inheritance - Avoid repeated imports in Java: Inherit imports? -

is there way "inherit" imports? example: common enum: public enum constant{ one, two, 3 } base class using enum: public class base { protected void register(constant c, string t) { ... } } sub class needing import use enum constants convenient (without enum name): import static constant.*; // want avoid line! public sub extends base { public sub() { register(two, "blabla"); // without import: constant.two } } and class same import ... import static constant.*; // want avoid line! public anothersub extends base { ... } i use classic static final constants maybe there way use common enum same convenience. import s aid compiler find classes. active single source file , have no relation whatsoever java's oop mechanisms. so, no, cannot “inherit” import s

c# - Remote monitoring design -

i need monitor several systems going thru stress testing. want make client-server .net(c#) application ping systems check temperature, memory usage etc. the client provide system info (cpu-mem-hdd configuration) @ start undergo through several benchmark/stress tests. server keep track of been executed , able detect system crashes. pretty have code client (have been running on system, using wmi) i have no experience .net remoting nor wcf, think great opportunity learn them. what technology use? wcf meant unify .net remoting handful of other microsoft technologies. wcf gives lot of flexibility change design of client-server architecture changing few .net attributes. i recommend proceed caution , make sure have wcf reference @ hand. spend lot of time spinning wheels in mud without one.

c# - how to create multi language windows installer? -

whats best way create multi language installer office addin deployment setup? is possible using vs.net 2008, c# or need use 3rd party tool or install shield 2009 ?? i suggest using innosetup, free , supports multiple languages. http://www.jrsoftware.org/isinfo.php

.net - Entity framework specify string for dependant column without database key -

in ef there way specify relationship between 2 tables when there no relationship defined in database , 1 of related columns specific string/hard-coded value? lets have document object , can have various stages of approval , category. table might like documentid, documentname, documentstate, documentcategory with following document data: 1, test document, 0, 0 2, doc, 2, 1 i have key/lookup table in database , table might like: lookupkey, lookupvalue, lookuptext with following data lookupkey , lookupvalue primary key (not defined in db): documentstatus, 0, draft documentstatus, 1, inreview documentstatus, 2, final documentcategory, 0, resume documentcategory, 1, cover letter the tables have 2 relationships based on: documentstatus = lookupvalue , lookupkey = "documentstatus" and second relationship documentcategory = lookupvalue , lookupkey = "documentcategory" can define type of r...

How did Java programmers survive before annotations? -

before introduction of annotations in java, how same functionality achieved? such huge portion of every day in java involves annotations can't imagine program without them. what alternative way of achieving same functionality without annotations? xdoclet - code generator takes information java source code , custom javadoc tags. marker interfaces serializable naming conventions (test methods in junit) and yes, lots of xml config files. glad haven't had live those.

compiler construction - Markdown blockquote parsing with ANTLR -

this has been that's been bothering me while. how 1 go parsing following text html below using antlr? can't seem wrap head around @ all. any ideas? markdown: > first line > second line > &gt nested quote output html: <blockquote> <p>first line second line</p> <blockquote> <p>nested quote</p> </blockquote> </blockquote> funny mention because tackling problem last week. see jmd, markdown , brief overview of parsing , compilers . i'm working on true markdown parser , tried antlr. there couple of ways can deal this. firstly parse: block_quote : '>' (' ' | '\t')? ; and work out in parsing step, possibly rewrite rule. thing these important when appear @ beginning of line here approach: @members { int quotedepth = 0; } block_quote : '\n' (q+='>' (' ' | '\t')?)+ { if ($q.size() > quotedepth) /* emit 1 or...

refactoring - refactor dilemma -

i want extract guard statement following method private void createproxy() { //extract following guard statement. host selected = this.combobox1.selecteditem host; if (selected == null) { return; } this.searchproxy = serviceproxy.proxyfactory.createsearchproxy(getselectedip().tostring()); this.streamproxy = serviceproxy.proxyfactory.createplayerproxy(getselectedip().tostring()); } //extracted guard method public bool ishostselected() { host selected = this.combobox1.selecteditem host; if (selected == null) { return false; } return true; } see? have add return value extracted method, kinda ugly? any better solution avoid adding return value extracted method? i don't see big deal. first, rewrite as: static bool selecteditemishost(combobox box) { return box.selecteditem host; } note rename, combobox para...

c# - How to create an Expression<Func<dynamic, dynamic>> - Or is it a bug? -

during work expression trees few days now, came across find difficult understand; able shed light here. if code expression<func<dynamic, dynamic>> expr1 = x => 2 * x; compiler complain , won't anywhere. however, seems if create 1 such expression through method compiler seems happy , resulting app works. doesn't make sense, i'm wondering goes on behind curtains. i suppose that, under hood, expression returned convertexpression perhaps of type expression<func<object, object>> , valid type, puzzles me can't use expression<func<dynamic, dynamic>> type in declaration , yet can use return type of method. see example below. thanks lot! public class expressionexample { public void main() { // doesn't compile: //expression<func<dynamic, dynamic>> expr1 = x => 2 * x; // compiles , works - ok expression<func<double, double>> expr2 = x => 2 * x; ...

WPF: Best way to get a snapshot of what is under a Canvas control -

i have wpf app, , use canvas 50% opacity cropping rect can resized , moved on image, , every time moves, use croppedbitmap show live preview of image, makes app become slow create new croppedbitmap every time... what's best way image of area canvas is? thanks! you can use visualbrush , point canvas <stackpanel > <canvas x:name="mycanvas" width="10" height="10" horizontalalignment="left" cliptobounds="true"> <ellipse fill="black" width="10" height="20" /> </canvas> <border height="30" width="30" horizontalalignment="left"> <border.background> <visualbrush visual="{binding elementname=mycanvas}" /> </border.background> </border> </stackpanel>

python - Write conditions based on a list -

i'm writing if statement in python lot of or conditions. there elegant way list, within in condition rather looping through list? in other words, prettier following: if foo == 'a' or foo == 'b' or foo == 'c' or foo == 'd': i've taken python, , language has me wanting write better. if foo in ('a', 'b', 'c', 'd'): #... i note answer wrong several reasons: you should remove parentheses.. python need outer ones , takes room. you're using assignment operator, not equality operator (=, not ==) what meant write foo == 'a' or foo == 'b' or ..., wrote wasn't quite correct.

How can i publish a message to a list using facebook's graph api -

after user has provided me oauth credentials, allow them post message group of friends. say have created list of 10 friends , called "my soccer buddies", want able allow them post message list "my soccer buddies" within web application using graph api. how ? looking @ http://developers.facebook.com/docs/reference/api/post seems possible providing "to" parameter in http://developers.facebook.com/docs/api#publishing says must post /profile_id/feed - desc: - write given profile's feed/wall - args: - message, picture, link, name, caption, description, source note param not available in args above. so how done? also: reccomended way web app using graph api allow user send send message 10 of friends? it not possible. new groups feature provides access via graph api , looked alternative.

perforce - How Can I View the Files Synced Since a Given Date in P4? -

so, i'm trying troubleshoot error, , being able see files synced given server since date go long way toward helping me figure things out. feel there should way through "p4 have", can't figure out or find in documentation. important: not looking files submitted p4 during time. want see files synced server. thanks! "p4 have" indeed tell files sync'd workspace. won't tell when sync'd. sounds 1 of questions if told little bit why thought wanted know information, suggest different technique, address problem.

equals - How to calculate axis ticks at a uniform distribution? -

given data range minimum , maximum value, how can 1 calculate distribution of buckets on axis? the requirements are: - axis ticks shall evenly distributed (equal size). - further, ticks shall appear numbers 10, 20, 30, ... or -0.3, 0.1, 0.2, 0.4, ... - calculation shall accept parameter defines number of buckets wanted. the following example calculates maximum of 10 buckets or less. num buckets = 10 range length = 500 500 / 10 = 50 log_10(50) = 1,69 round up(1,69) = 2 10^2 = 100 bucket size 500 / 100 = 5 buckets result: there 5 buckets each @ size of 100. steps produce buckets based on 10^x 0.01, 0.1, 1, 10, 100, 1000 ... how can 1 calculate buckets size 42 buckets? i not sure think code can (adapted javascript yui yahoo.util.dragdrop.js ) var initposition = 0; var rangelength = 500; var maxposition = (initposition + rangelength); getticks: function(bucketsize) { var axisticks = []; var tickmap = {}; (i = initposition; <= maxposition; = +...

java - Converting a set of strings to a byte[] array -

i tring convert set of strings byte[] array. @ first, convert byte array string: public string convertbyte(byte[] msg) { string str = ""; for(int = 0; < msg.length; i++) { str += (msg[i] + " * "); } return str; } when try convert byte[] array, don't same values ones when converted string. had gave me incorrect values. i trying along lines of: public static byte[] convertstr(string ln) { system.out.println(ln); string[] st = ln.split(" * "); byte[] bytearray = new byte[23]; for(int = 0; < st.length; i++) { bytearray[i] = st[i].get byte value or something; } return bytearray; } if try use getbytes() method string api, returns byte array rather byte , problem. any appreciated. using byte.parsebyte may making second snippet work. but, unless have specific reason use kind of representation, i'd encode strings byte arrays using java methods ment...

javascript - Loop within a function to alt color table rows -

i have query building form built in php. results of query returned , placed in 2 different tables 1 above other. (table id's results, , results2) each record returned builds 2 tables display data. (soon three) i'm using following code change class tags of <tr> 's provide alternate row coloring: <script type="text/javascript"> function alternate(id){ if(document.getelementsbytagname){ var table = document.getelementbyid(id); var rows = table.getelementsbytagname("tr"); for(i = 0; < rows.length; i++){ if(i % 2 == 0){ rows[i].classname = "row-one"; }else{ rows[i].classname = "row-two"; } } } } </script> then i'm using body onload so: <body onload="alternate('results'); alternate('results2');"> the problem colors first 2 instances of these tables, when depending on amount of records retur...

jinja2 - String concatenation in Jinja -

i want loop through existing list , make comma delimited string out of it. this: my_string = 'stuff, stuff, stuff, stuff' i know loop.last , need know how make third line in code below work. {% set my_string = '' %} {% stuff in stuffs %} {% set my_string = my_string + stuff + ', '%} {% endfor%} if stuffs list of strings, work: {{ stuffs|join(", ") }} link documentation.

php creates folder with 341 permissions -

didn't got luck finding answer on google , last try before trying other methods. i have script this: // current year , month $cur_year = date('y'); $cur_month = date('m'); $long_type = $this->getfile_longtype(); $folder = $_server['document_root']."/".folder_cms."/uploads/$long_type/$cur_year/$cur_month"; // check whether folder exists if(!is_dir($folder)){ // try make folder recursively if(!mkdir($folder,"0777",true)){ logerror($message, __file__, __line__); throw new exception("failure creating proper directories"); } } to make work , chmod'ed uploads directory , it's files , dirs 777 ( beter suggestion here? ) the long type evaluates 'images' , directory has been created on server. now , script create folder named year permissions 341. not wat want...

asp.net - Alert Meassage Box Issue -

i have alert message displaying message of validation. includes 1 - symbol. did not add symbol on code. code shown below. <tr> <td> <font face="verdana, arial, helvetica, sans-serif" size="2">login :</font> </td> <td> <font face="verdana, arial, helvetica, sans-serif" size="2"> <asp:textbox id="txtlogin" runat="server" cssclass="textbox"></asp:textbox> <asp:requiredfieldvalidator id="validator1" runat="server" errormessage="login id required" controltovalidate="txtlogin" display="dynamic">*</asp:requiredfieldvalidator> </font> </td> </tr> <tr> <td> <font face="verdana" size="2">password :</font> </td> <td> <asp:textbox id="txtpassword" runat="se...

.net - Beginning VSTO Development -

i'm quite confused necessary tools vsto develpment. want manipulate excel 2003/2007 documents programmatically. did quite lot of vba before, if want relate answer that. few questions have vsto: can use visual studio 2008 express edition c#/c++ this? do need have .net framework installed? does resulting vsto program need have copy of office installed in same system run? direct links relevant tools/plugins/ide appreciated. note: i'm totally new vsto , .net office power user. have experience com programming. yeah, can confusing, given skip-level naming conventions, etc. essentially, you'll need: full version (not express) of visual studio , .net version you're targetting. one of vsto run times (vsto 2003, vsto 2005, vsto 2005 se, vsto 2008, vsto 2010). asking, vsto 2005 se best bet. when distributing app, you'll need more, pias , .net version you've targetted. vsto 2010, don't need pias (just you're using packaged app automat...

html - Center a div inside another div -

i'm trying set div centered inside div. this html page: <body> <div id="divparent"> <div id="divheader" > <div id="divheadertext"> </div> </div> <div id="divbody"> </div> </div> </body> and style: #divheader { background-color: #c7c7c7; font-family: verdana, geneva, tahoma, sans-serif; height: 80px; margin-bottom: 2px; } #divbody { background-image: url('images/gradientbackground.png'); background-repeat: repeat-x; height: 300px; } #divheadertext { margin: auto; width: 90%; height: 80%; background-color: #00ff00; } why smallest div doesn't left space on top? your question unclear. if you're trying vertically center #divheadertext within #divheader , try adding margin-top: 13px; .

oop - How are objects of subclasses allocated in C++? -

i have confusion concept of inheritance in c++, suppose have class named computer , publicly inherit class named laptop computer class. when create object of class laptop in main function happens in memory? please explain. i'm assuming laptop inherits computer, , explaining happens in general; implementation details of c++ (for optimization reasons) may differ general explanation. logically, laptop class definition has pointer computer class definition. instance of laptop class has pointer laptop class definition (in c++, reference array of function pointers class methods). when laptop object receives message, first looks in own method table corresponding function. if not there, follows inheritance pointer , looks in method table computer class. now, in c++, of happens in compilation phase, in particular believe method table flattened , calls can statically bound shortcut.

xhtml - Is it true images in css background loads before all images in HTML <img>? -

if want load image should use css background not in ? think difference show in low speed internet connection. i saw many articles related css preloading using images in css background. http://perishablepress.com/press/2008/04/15/pure-css-better-image-preloading-without-javascript/ http://perishablepress.com/press/2007/07/22/css-throwdown-preload-images-without-javascript/ http://divitodesign.com/css/create-an-image-pre-loader-with-css-only/ it's order in things happen. browsers @ liberty begin processing things possible, so, in average page css defined in head, able start requesting , recieving images css before able body of document. so in short, answer yes. but... bear in mind doesn't load images faster. doing changing load order, not absolute speed. images still take same amount of time load. if move out of body , css in head, still left priority decisions ones load first. come full circle. can't make faser else.

Has anyone tried literate programming for C#, with Lyx and noweb -

i came across this blog post yesterday, , once again made me want give literate programming try. has else tried doing literate programming c#? i'm wondering trying lyx + noweb , wondered if might have other experience or suggestions. get leo , outlining editor, , make noweb files. noweb can make html can online documentation , can make source files numbered noweb input. can edit noweb or source. if edit source, leo can update changes noweb file. noweb can make tex files pretty printing. noweb simple users guide fits on 1 side of 1 sheet of paper. leo 1 of gui tools know how use ... has lotsa tricks if want them. both free!

A question to Flash experts from a beginner: the flash object within a web page -

here's explanation of question: from javascript, need reference flash player object. there 2 basic flash player versions run in browser: activex , plug-in version. activex version runs natively in internet explorer, while plug-in version used rest of browsers. the activex player controlled object tag in html page, , can retrieve javascript reference using window. objectid objectid value of id attribute of object tag. example, if object tag's id attribute example, reference activex player window.example. the plug-in player controlled embed tag in html page, , can retrieve javascript reference using window.document. embedname, embedname value of name attribute of embed tag. example, if embed tag's name attribute example, reference plug-in player window.document.example. and here's question itself: why flash player object exist window property when embeded via object tag, while, when embeded via embed tag, exists in window.document property? , moder...

objective c - Sorting array of objects by two criterias? -

i have array of objects want sort 2 keys. objects lets of type student , properties i'm intrested in sort grade , name . student { double grade; string name; ... } how can sort objects first grade , name? example if have list: tom 9.9 andrew 9.8 chriestie 10 mat 9.8 allison 10 ada 9.8 after sort should have: allison 10 christie 10 tom 9.9 ada 9.8 andrew 9.8 mat 9.8 and not christie 10 allison 10 tom 9.9 andrew 9.8 ada 9.8 mat 9.8 any pointer helpful. i'm pretty flakey on objective-c knowledge there's pointers here , there's documentation . here's crack @ it... nssortdescriptor *gradesorter = [[nssortdescriptor alloc] initwithkey:@"grade" ascending:yes]; nssortdescriptor *namesorter = [[nssortdescriptor alloc] initwithkey:@"name" ascending:yes]; [personlist sortusingdescriptors:[nsarray arraywithobjects:gradesorter, namesorter, nil]];

Math.pow errors in Java -

i 'obviously' learning programming , can't seem figure out in order rid if error. error on second last line - line before: [system.out.print(+windchill);] here (written below), list of java-generated 'possible hints' errors getting: **')' expected method pow in class java.lang.math cannot applied given types required: double,double found: double method pow in class java.lang.math cannot applied given types required: double,double found: double operator + cannot applied double,pow incompatible types required: doub...** any hints or clarification appreciated. please see code below. thank in advance. shane import java.util.scanner; public class main { public static void main(string[] args) { // todo code application logic here scanner input = new scanner(system.in); system.out.print("enter temperature between -58 , 41 degrees fahrenheit , press enter"); double temperature = input.nextdouble(...

Need help with python list manipulation -

i have 2 seperate lists list1 = ["infantry","tanks","jets"] list2 = [ 10, 20, 30] so in reality, have 10 infantry, 20 tanks , 30 jets i want create class in end, can call this: for unit in units: print unit.amount print unit.name #and produce: # 10 infantry # 20 tanks # 30 jets so goal sort of combine list1 , list2 class can called. been trying many combinations past 3 hrs, nothing turned out :( this should it: class unit: """very simple class track unit name, , associated count.""" def __init__(self, name, amount): self.name = name self.amount = amount # pre-existing lists of types , amounts. list1 = ["infantry", "tanks", "jets"] list2 = [ 10, 20, 30] # create list of unit objects, , initialize using # pairs above lists. units = [] a, b in zip(list1, list2): units.append(unit(a, b))

Initializing a structure in c++ -

g++ 4.4.3 i have following structure api guide: typedef struct network_info { int network_id; int count; } network_info, *network_info; and in source code doing this: network_info net_info = {}; is 2 curly braces initializing object of structure? initialize values to? many advice, this default-initialize fields of variable net_info - set them both zero. that's handy one-liner used initialize struct s don't have user-defined constructor instead of using memset() .

.net - What is the purpose of configSections? -

i've done little research , ran across this: http://msdn.microsoft.com/en-us/library/ms228245.aspx so if i'm understanding correctly, doing including .dlls use within project, like: <add assembly="system.web.extensions, version=1.0.61025.0, culture=neutral, publickeytoken=31bf3856ad364e35"/> and i'm guessing difference if configsections way can set parameters creating 'name' later in webconfig (or other config) xml element. correct, or missing something? also, noticed can remove configsections website's web.config , run fine, following configsections: <configsections> <sectiongroup name="system.web.extensions" type="system.web.configuration.systemwebextensionssectiongroup, system.web.extensions, version=1.0.61025.0, culture=neutral, publickeytoken=31bf3856ad364e35"> <sectiongroup name="scripting" type="system.web.configuration.scriptingsectiongroup, system.web.extensions...

asp.net mvc - Caching user data to avoid excess database trips -

after creating proof of concept asp.net mvc site , making sure appropriate separation of concerns in place, noticed making lot of expensive redundant database calls information current user. being historically desktop , services person, first thought cache db results in static s. didn't take searching see doing persist current user's data across whole appdomain users. next thought of using httpcontext.current . however, if put stuff here when user logged out, when log in cached data out of date. update every time login/logout occurs can't tell if feels right. in absence of other ideas, i'm leaning. what lightweight way accurately cache user details , avoid having make tons of database calls? if information want cache per-user , while active, session right place. http://msdn.microsoft.com/en-us/library/system.web.sessionstate.httpsessionstate.aspx

python - Get only the keys out of a reference property in GAE-Py -

i've got app i'm storing posts , authors. straightforward each post has 1 author model. the problem this: fetch last 10 posts using 1 call, using fetch() limit = 10. when print them out, gae uses 10 gets access author details, because author object reference property on post... classic n+1 query scenario - 1 query 10 posts , 10 queries each author. is there way can iterate on posts collect author object keys, can load them @ 1 go using db.get(all_author_keys) see response this question couple hours ago -- q identical amazing coincidence one, though different poster. in short, this, use get_value_for_datastore of property object.

objective c - How to send email from iPhone app without user interface -

i want app able send email attachment hard-coded recipient no user input required, unlike messageui framework. is there way this? example code appreciated. thanks in advance. as saurabh said, there no low level mail library. smtp library, rather imap one, because don't need mail, sent it. attachments can done mfmailcomposeviewcontroller's via -(void)addattachmentdata:(nsdata *)attachment mimetype:(nsstring *)mimetype filename:(nsstring *)filename which believe base64 encodes data, , attached mime type header , footer. check out question lots on topic: open source cocoa/cocoa-touch pop3/smtp library?

wpf - How to Bind to a Child's Background in Xaml? -

i'm able bind child's background if child explicitly named in elementname: <treeviewitem header="test" background="{binding elementname=testchild, path=background}"> <textbox name="testchild" text="hello?" background="{binding somebinding}" /> </treeviewitem> i'd prefer use relative position rather specific names. possible bind child using relative? in case first child. following doesn't work seems should. <treeviewitem header="test" background="{binding relativesource={relativesource mode=self}, path=children[0].background}"> unless create new control inherits treeview (or other itemscontrol) wont work. reasoning way binding works. when binding set children[0] doesn't exist collection empty. after collection updated include textbox , doesn't raise notify has changed (its not observablecollection). way create new control has children observable...

Android Multitouch - Possible to test in emulator? -

i discovered android 2.0 sdk supports multitouch through new functions in motionevent class. can specify pointer index when retrieving touch properties, , in cases multiple fingers on screen there should multiple pointers provided. unfortunately, have g1 test on , it's running android 1.5 , not 2.0. is there way test multitouch without 2.0 device? in iphone simulator, can hold down option , shift option perform 2 fingered pinch , 2 fingered drag, respectively. there similar functionality in android emulator? should expect see in future, or should suck , buy new test phone? this post guy android team says multitouch in emulator still not supported.

actionscript 3 - 3-D engines in flex -

wanted know if there are 3-d engines available flex other papervision? just out of curosity.... sandy3d away3d these both mature engines @ point have seen use in commercial work.

need some regex help javascript -

i hoping can me, using javascript , asp i have string /folder1/folder2/pagename.asp i need regex strip /pagename.asp string pagetype.replace(/\/.*?\.asp/ig, ''); the regex above halfway there problem strippes beginning / between / , .asp how make regex lazy strip between last / , .asp? any appreciated! try this: pagetype.replace(/\/[^\/]*\.asp/ig, ''); i've used [^\/] group represent symbol not equal / .

python - how can I upload a kml file with a script to google maps? -

i have python script, generates kml files. want upload kml file within script (not per hand) "my maps" section of google maps. have python or other script/code so? summary: can't until issue 2590 fixed, may while because google have closed issue wontfix . there workarounds can try achieve same end result, stands cannot upload kml file using google maps data api. long version: i don't didn't have python code this, google maps data api allows series of http requests. see uploading kml in http protocol section of developers guide documentation on how this. 1 possible python solution use httplib in standard library appropriate http requests you. after various edits , feedback in comments, here script takes google username , password via command line (be careful how use it!) obtain authorization_token variable making clientlogin authentication request . valid username , password, auth token can used in authorization header posting kml data m...

osx - Mac: reloading document in Chrome or Firefox? -

how can tell chrome or firefox reload document in top window? here's i'm using safari: osascript -e ' tell application "safari" activate javascript "history.go(0)" in document 1 end tell ' i not think firefox or chrome have special applescript support, can send keystrokes (cmd-r) refresh page: tell application "firefox" activate tell application "system events" keystroke "r" using command down end tell

actionscript 3 - Problem retrieving pixel color on color picker -

i'm making color picker (pretty standard one, pretty same photoshop less options @ moment: still in stage). here's picture of actual thing : http://i.stack.imgur.com/oevjw.jpg the problem : retrieve color of pixel under color selector (the small one, other mouse), have line thought : _currentcolor = convert.hsbtohex(new hsb(0, ((_colorselector.x + _colorselector.width/2)*100)/_largeur, ((_colorselector.y + _colorselector.height/2)*100)/_hauteur )); just clarify code, use coordinates of selector in order create new hsb color (saturation represented on x axis , brightness (value) on y axis of such color picker). convert hsb color hexadecimal , assign property. hue set 0 @ moment irrelevant work pure red test. it partially wanted, returned color values inversed of corners: (0,0) it's supposed return 0xffffff, returns 0x000000 instead (256, 0) it's supposed return 0xff0000, returns 0x000000 instead (0, 256) it's supposed return 0x000000, returns 0xffffff...

create subdomain programatically in PHP -

i on shared hosting , on add on domain. i need create subdomain each user of website if username jeff should have url jeff.mydomain.com. how can create programatically using php? thanks prady there's 2 parts this. firstly you'll need setup wildcard dns entry . once you've got setup should have requests pointed single domain. there can use php figure out domain you're on: $domain = $_server['http_host']; $base = 'mydomain.com'; $user = substr($domain, 0, -(strlen($base)+1));// user part of domain if(!empty($user)) { $user = sanatiseuser($user); require_once $user.'.php'; }

objective c - Doing something wrong with bindings, can't find out what -

i've mutable array holds instances of model object. model object has several properties 1 being "name". have no problems initialising or populating mutable array. i've window drawer. added table drawer, idea being drawer use table display several instances of model object. i added nsarraycontroller xib of window has drawer. in array controller properties i've set object controller instance of model class. on array controller bindings set controller content point file owner , set model key path name of array. on table, bind content array controller, controller key arrangedobjects , model key path name. my problem although mutable array has been initialised , populated can't see single entry on table on drawer. missing here? two possibilities: first: might have bound wrong thing (your description here bit ambiguous). bind each table column's "values" array controller's @"arrangedobjects.propertyname" (like arr...

latex - Kile runs very slow under ubuntu, when expending the structure -

do 1 has same problem? using ubuntu+kile latex. whenever save file, structure side window expands twice, , slow. know how solve problem?thank much! have tried run kile commandline , debugging outputs during problematic operations? give hints. found not kile commandline parameters, can try append -v or --verbose more verbose info.

javascript - how to POST radio button values through jquery -

i have example code: while ($row = mysql_fetch_object($result1)) { echo '<input type="radio" name="vote" value='.$row->avalue.'/>&nbsp;'; echo '<label >'.$row->atitle.'</label><br>'; } this displays 4 radio buttons alongwith labels. using following jquery function post. $("#submit_js").click(function() { $.post( "user_submit.php", {//how post data?}, function(data){ }); }); i want post value associated radio button. how select value? how determine radio button selected , post it? $("[name='vote']:checked").val() value of selected radio button. $("#submit_js").click(function() { $.post( "user_submit.php", {vote: $("[name='vote']:checked").val()}, function(data){ }); });

ruby - Sinatra enable :sessions not working on passenger/apache -

am having trouble getting enable :sessions persist simple sinatra app hosted on passenger/apache. i'm storing state of session[:authorized] in cookie. works locally when hosted on rack::handler::mongrel can't seem same behaviour on passenger. i've tried 2 methods enabling sessions, both of don't work on passenger/apache installation enable :sessions and use rack::session::pool, :domain => 'example.com', :expire_after => 60 * 60 * 24 * 365 any ideas on how fix? we facing similar although not using apache / passenger (in development mode). resolved - comment out rack::session commands within sinatra app. in config.ru file. , haven enable :sessions in sinatra app. that should work.

php - str_get_html and simply html dom -

way after str_replace function $img empty , secont $img->find('img') function show error: fatal error: cannot use object of type simple_html_dom array in d:\wamp\www\test.php on line 7 <?php require_once('simple_html_dom.php'); $img_html = str_get_html('hhtml tekst html tekst <img src = "img.png" /> ad sad'); foreach($img_html->find('img') $element) $img[] = $element->src . '<br>'; $img_html = str_replace($img[0], 'n-'.$img[0], $img_html); foreach($img_html->find('img') $element2) echo $element2->src . '<br>'; ?> is you're aiming do? foreach($img->find('img') $element) $img[] = $element->src . '<br>'; $img object on first foreach -loop, you're trying access $img array, causing error. accidentally using same variable name 2 different things?

javascript - asp.net date validation with three drop down list -

i have 3 drop down list day month , year want validate selected date in asp.net using javascript or inbuild asp.net validation control. thanks...... this java script code validate date format : <script language="javascript" type="text/javascript"> function validatedate(args) { var date=args.value; var arr=date.split('/'); if(arr.length!=3) { args.isvalid=false; return; } var day; if(arr[1]=='08') { day=parseint('8'); } else if(arr[1]=='09') { day=parseint('9'); } else { day=parseint(arr[1]); } var month; if(arr[0]=='08') { month=parseint('8'); } else if(arr[0]=='09') { month=parseint('9'); } else...

winapi - How does CreateMutex() internally work? -

basically, used make application instance singleton. i wish know, how works internally , how os manage ? it creates system-wide object. how os manages consealed implementation detail, can use mutex trough os-supplied functions (like releasemutex() example).

php - Is there a way to make a table name dynamic in a query? -

i trying create class-inheritance design products. there base table contains common fields. each product type there separate table containing fields product type only so in order data product need join base table whatever table correlates product_type listed in base table. there way make query join on table dynamically? here query try illustrate trying do: select * product_base b inner join <value of b.product_type> t on b.product_base_id = t.product_base_id b.product_base_id = :base_id is there way this? no, there's no way this. table name must known @ time of parsing query, parser can tell if table exists, , contains columns reference. optimizer needs know table , indexes, can come plan of indexes use. what you're asking table determined during execution, based on data found row-by-row. there's no way rdbms know @ parse-time all data values correspond real tables. there's no reason implement class table inheritance . cti s...

sql - MySQL Subquery returning incorrect result? -

i've got following mysql query / subquery: select id, user_id, another_id, myvalue, created, modified, ( select id users_values parentusersvalue parentusersvalue.user_id = usersvalue.user_id , parentusersvalue.another_id = usersvalue.another_id , parentusersvalue.id < usersvalue.id order id desc limit 1 ) old_id users_values usersvalue created >= '2009-12-20' , created <= '2010-01-21' , user_id = 9917 , another_id = 23 given criteria listed, result subquery (old_id) should null (no matches found in table). instead of mysql returning null, seems drop "where parentusersvalue.user_id = usersvalue.user_id" clause , pick first value matches other 2 fields. mysql bug, or reason expected behavior? update: create table users_values ( id int(11) not null auto_increment, user_id int(11) default null, another_id int(11) default null, myvalue double default null, created datetime default null,...

c# - Google Chrome selected text -

i trying selected text browsers(ie,opera, firefox..) using c# application. tried sendkeys.send("^c") reading selected value clipboard method works fine ie , firefox.., doesn't work google chrome. how can selected text google chrome , why sendkeys.send("^c") doesn’t work? not sure how help, guy has chrome extension believe, plus opensource check out. sorry if of no help. auto copy

Count file lines in C# -

i want know how many lines have in file. how can in simple way (i mean, not go through on over file , count each line)? there command that? well: int lines = file.readalllines(path).length; is simple, not efficient huge text files. i'd use textreader in cases, avoid excessive buffering: int lines = 0; using (textreader reader = file.opentext(path)) { while (reader.readline() != null) { lines++; } }

c# - Application Design - Database Tables and Interfaces -

i have database tables each entity in system. e.g. persontable has columns personid, name, homestateid. there table 'reference data' (i.e. states, countries, currencies, etc.) data used fill drop down list boxes. reference table used persontable's homestateid foreign key reference table. in c# application have interfaces , classes defined entity. e.g. personimplementationclass : ipersoninterface. reason having interfaces each entity because actual entity class store data differently depending on 3rd party product may change. the question is, should interface have properties name, homestateid, , homestatename (which retrieved reference table). or should interface not expose structure of database, i.e. not have homestateid, , have name, homestatename? i'd you're on right track when thinking property names! model classes in real world. forget database patterns , naming conventions of stateid , foreign keys in general. person has city, not cityi...

c# - using FileSystemWatcher to fire event, then delete the newly created file? -

i have windows service using filesystemwatcher monitor folder, print added images, delete image after printing. private void bw_dowork(object sender, doworkeventargs e) { filesystemwatcher watcher = new filesystemwatcher(); watcher.path = @"c:\images"; watcher.created += new filesystemeventhandler(watcher_changed); watcher.enableraisingevents = true; } private void watcher_changed(object sender, filesystemeventargs e) { try { printdocument mydoc = new printdocument(); mydoc.printpage += new printpageeventhandler(print); filepath = e.fullpath; mydoc.printersettings.printername = @"\\network printer"; mydoc.print(); using (streamwriter sw = new streamwriter("c:\\error.txt")) { sw.writeline("printed file: " + ...

jquery - How to send only two column values from jqgrid? -

i have jqgrid , on button click want send 2 column values instead of sending whole values...how can achieve using getrowdata ....any suggestion appreciated.. thanks! probably method getcol can halt mostly. if 1 columns want send column id ( key:true ) can receive data need 1 call: var mydata = $('#list').jqgrid('getcol', 'column name 1', true); if no columns has key:true in column definition should make 2 calls: var mydata1 = $('#list').jqgrid('getcol', 'column name 1'); var mydata2 = $('#list').jqgrid('getcol', 'column name 2'); then can combine data or set there separate 2 parameters: $.ajax({ type: "post", url: "/cpsb/internalorderlist.do", data : { jggriddata1: json.stringify(mydata1), jggriddata2: json.stringify(mydata2) }, datatype:"json", contenttype: "application/json; charset=utf-8", success: funct...

Comparing SQL and Prolog -

i've started learning prolog , wondering theoretical difference sql language. for example: both declarative languages both support fact-driven knowledge database both support question-styled data-retrieving both support functional dependencies any more common points? notable differences? most of (earlier) answers here reflection of fact people not know sql (its implementation of relational calculus) or means (that it's form of predicate logic). following statements true of both prolog , sql: they both logic-driven they can both store, express , use relations (logical relationships in prolog) they can both store , express complex logical conditions they both have facts(data in sql) , can derive conclusions facts they both have queries, in fact mean same thing they both have data(facts in prolog) , use them similarly they both programming languages they both turing-complete (though difficult access in both of them) etc, etc.. generally, peop...

java - using eval in groovy -

how can use eval in groovy evaluate following string: {key1=keyval, key2=[listitem1, listitem2], key3=keyval2} all list items , keyval string. doing eval.me("{key1=keyval, key2=[listitem1, listitem2], key3=keyval2}") giving me following error: ambiguous expression either parameterless closure expression or isolated open code block; solution: add explicit closure parameter list, e.g. {it -> ...}, or force treated open block giving label, e.g. l:{...} at i want hashmap you can parse string translating of characters, , writing own binding return variable names when groovy tries them up, so: class evaluator extends binding { def parse( s ) { groovyshell shell = new groovyshell( ); shell.evaluate( s ) } object getvariable( string name ) { name } } def instr = '{key1=keyval, key2=[listitem1, listitem2], key3=keyval2}' def inobj = new evaluator().parse( instr.tr( '{}=', '[]:' ) ) println inobj but very britt...

Facebook Graph API - Post on Group wall as Group -

i trying post facebook group wall via graph api. when make post, owner of post set personal id. know how make group has owner of post. below current code: form_fields = { "message": 'this message title', "link": 'http://facebook.com', "name": 'this message title', "access_token": 'token here' } form_fields['description'] = 'this message body' form_data = urllib.urlencode(form_fields) response = urlfetch.fetch( url="https://graph.facebook.com/%s/feed" % group_id, payload=form_data, method=urlfetch.post, deadline=10 ) you can't it. that's 1 of differences between group , pages, in page when post admin user of post page , not userid, there no way can make group owner of post using graph api. see ...

c# - Behavior of ObservableCollection(IEnumerable) constructor -

according msdn there overload observablecollection constructor can pass ienumerable. according short msdn page make "copy" of ienumerable. how determine how behave? "copy" totally independent of original or changes made ienumerable (such linq query) reflected automatically in observablecollection? msdn page this constructor walks through items in ienumerable , adds each 1 observablecollection . once finished new observablecollection has nothing more ienumerable (except if dealing collection of reference types observablecollection hold references same objects supplied ienumerable ).

web config - Disabling themes in a subdirectory with ASP.NET -

this should simple one. using program has themes defined in web.config file. want turn these off subdirectory. i copied web.config subdirectory , tried removing theme attribute pages element on web.config didn't me anywhere. got bunch of errors elements apparently not allowed in non-root web.config files removed of elements, still getting same error. i tried adding enabletheming="false" in aspx page header, thing defines language=c# , etc., didn't work either. so if can tell me tested, confirmed way make work, appreciate that. using .net framework 2.0 on server 2003. got basic web.config: <?xml version="1.0"?> <configuration> <system.web> <pages theme="" /> </system.web> </configuration>

How to programmatically assign the date to a datetimepicker from a database in c# -

i hav datetimepicker control format have set custom dd/mm/yyyy (with no time). store date in database varchar , not datetime because giving sort of error regarding invalid datetime format. use datagrid display records database. thing need retrive date datagrid (when user selects particular date cell in datagrid) , want display on datetimepicker control (so user can edit it). using following code so: dtdate.value = convert.todatetime(dgdetails.selectedcells[1].formattedvalue); the error getting "string not recognized valid datetime". dtdate datetimepicker control, dgdetails datagrid , selectedcells[1] cell containing date. you shouldn't have reacted error changing type in database inappropriately - if you're trying store dates, should use closest available type in database. the problem querying/updating/inserting putting value directly in sql instead of using parameterized query - right solution use parameterized query. you've done same thing da...

iphone - XCode - touchBegan - Recent Touches/New Touches -

i have been using touches began track many 8 touches, , each triggers event. these touches can occur @ same time, or staggered. - (void)touchesbegan:(nsset *)touches withevent:(uievent *)event { nslog(@"touch began"); nsset *alltouches = [event alltouches]; (int i=0; i<alltouches.count; i++) { uitouch *touch = [[alltouches allobjects] objectatindex:i]; if (/*touch inside button in question*/) { //trigger event. } } } that code works multitouch, , has no problems, except: (see if can guess) due way alltouches works, literally gets of touches. because of this, loops through of touches active when user starts touch, , triggers event of 1 of buttons twice. ex: johnny pressing button 1. event 1 occurs. johnny leaves finger on button 1, , presses button 2. event 2 occurs, button 1 still part of alltouches, , so, event 1 triggered again. so here's question: how new touch? the same touch object ret...

jquery name attribute of map element in IE -

the following jquery works fine in firefox me, failed in ie6: $("<map></map>").attr("name",somevar).appendto("#someelement"); the problem map element never gets name attribute generated can prove calling alert($("#someelement").html()); , fact image associated doesn't have links if use instead, works fine: $("<map name='" + somevar + "'></map>").appendto("#someelement"); i'm happy use second line of code, wondering if else has had problem...or explanation of why didn't work (i'm wondering specific name attribute)... (html output first , second scenario): ie6 using first line: <map><area shape=rect coords=0,0,300,110 href="http://google.com"></map><img height=215 src="include/nav-images/main.png" width=591 usemap=#tehmap> ie6 using second line: <map name=tehmap><area shape=rect coords=0,0,300,1...

python - PyQt4 SIGNAL/SLOT problem when using sub-directories -

thanks in advance taking time read this. apologies verbose. explains problem. stripped code demonstrating issue included. i'm having issue pyqt4 signal/slots. while can make work fine if writing in single file, can't make things work if of functions wish use moved sub-directories/classes. i've looked through python bindings document can see how works when using single file. trying this: main.py file in root dir contains mainwindow __init_ _ code. this file imports number of widgets. each widget stored in own sub-directory. sub-directories contain __init__.py file. these sub-directories inside of directory called 'bin', in root dir some of these widgets need have signal/slot links between them fall down. so file structure is: - main.py - bin/texteditor/__init__.py - bin/texteditor/plugin.py - bin/logwindow/__init__.py - bin/logwindow/plugin.py the following code shows problem. code creates basic main window contains central qtextedit() wid...