qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
185,448
<p>Imagine in the Global.asax.cs file I had an instance class as a private field. Let's say like this:</p> <pre><code>private MyClass _myClass = new MyClass(); </code></pre> <p>And I had a static method on Global called GetMyClass() that gets the current HttpApplication and returns that instance.</p> <pre><code>public static MyClass GetMyClass() { return ((Global)HttpContext.Current.ApplicationInstance)._myClass; } </code></pre> <p>So I could get the instance on the current requests httpapplication by calling Global.GetMyClass().</p> <p>Keep in mind that there is more than one (Global) HttpApplication. There is an HttpApplication for each request and they are pooled/shared, so in the truest sense it is not a real <a href="http://en.wikipedia.org/wiki/Singleton_pattern" rel="nofollow noreferrer">singleton</a>. But it does follow the pattern to a degree.</p> <p>So as the question asked, would you consider this at the very least the singleton pattern?</p> <p>Would you say it should not be used? Would you discourage its use? Would you say it's a <strong><em>possibly</em></strong> bad practice like a true singleton.</p> <p>Could you see any problems that may arise from this type of usage scenario?</p> <p>Or would you say it's not a true singleton, so it's OK, and not bad practice. Would you recommend this as a semi-quasi singleton where an instance per request is required? If not what other pattern/suggestion would you use/give?</p> <p>Have you ever used anything such as this?</p> <p>I have used this on past projects, but I am unsure if it's a practice I should stay away from. I have never had any issues in the past though.</p> <p>Please give me your thoughts and opinions on this.</p> <p>I am not asking what a singleton is. And I consider a singleton bad practice when used improperly which is in many many many cases. That is me. However, that is not what I am trying to discuss. I am trying to discuss THIS scenario I gave.</p>
[ { "answer_id": 185670, "author": "Kevin Dostalek", "author_id": 22732, "author_profile": "https://Stackoverflow.com/users/22732", "pm_score": 2, "selected": false, "text": "public SomeClassType SomeProperty\n{\n get\n {\n if (HttpContext.Current.Cache[\"SomeKey\"] == null)\n {\n HttpContext.Current.Cache.Add(\"SomeKey\", new SomeClass(), null,\n System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromDays(1),\n CacheItemPriority.NotRemovable, null);\n }\n return (SomeClassType) HttpContext.Current.Cache[\"SomeKey\"];\n }\n}\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/185448", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14642/" ]
185,451
<p>What's a quick-and-dirty way to make sure that only one instance of a shell script is running at a given time?</p>
[ { "answer_id": 169969, "author": "Alex B", "author_id": 23643, "author_profile": "https://Stackoverflow.com/users/23643", "pm_score": 8, "selected": false, "text": "flock(1) #!/bin/bash\n\n(\n # Wait for lock on /var/lock/.myscript.exclusivelock (fd 200) for 10 seconds\n flock -x -w 10 200 || exit 1\n\n # Do stuff\n\n) 200>/var/lock/.myscript.exclusivelock\n ( ) util-linux" }, { "answer_id": 185466, "author": "Aupajo", "author_id": 10407, "author_profile": "https://Stackoverflow.com/users/10407", "pm_score": 0, "selected": false, "text": "#!/bin/sh\n\nif [ -f sometempfile ]\n echo \"Already running... will now terminate.\"\n exit\nelse\n touch sometempfile\nfi\n\n..do what you want here..\n\nrm sometempfile\n" }, { "answer_id": 185467, "author": "Drew Stephens", "author_id": 17339, "author_profile": "https://Stackoverflow.com/users/17339", "pm_score": 1, "selected": false, "text": "ps" }, { "answer_id": 185473, "author": "bmdhacks", "author_id": 14032, "author_profile": "https://Stackoverflow.com/users/14032", "pm_score": 8, "selected": true, "text": "LOCKFILE=/tmp/lock.txt\nif [ -e ${LOCKFILE} ] && kill -0 `cat ${LOCKFILE}`; then\n echo \"already running\"\n exit\nfi\n\n# make sure the lockfile is removed when we exit and then claim it\ntrap \"rm -f ${LOCKFILE}; exit\" INT TERM EXIT\necho $$ > ${LOCKFILE}\n\n# do stuff\nsleep 1000\n\nrm -f ${LOCKFILE}\n kill -0 trap kill -9" }, { "answer_id": 187304, "author": "dmckee --- ex-moderator kitten", "author_id": 2509, "author_profile": "https://Stackoverflow.com/users/2509", "pm_score": 2, "selected": false, "text": "lockfile flock" }, { "answer_id": 327991, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "while ! ln -s . lock; do :; done\n while ! ln -s ${f} ${f}.lock; do :; done\n mv lock deleteme && rm deleteme\n mv ${f}.lock ${f}.deleteme && rm ${f}.deleteme\n" }, { "answer_id": 731634, "author": "lhunath", "author_id": 58803, "author_profile": "https://Stackoverflow.com/users/58803", "pm_score": 7, "selected": false, "text": "mkdir mkdir if ! mkdir /tmp/myscript.lock 2>/dev/null; then\n echo \"Myscript is already running.\" >&2\n exit 1\nfi\n # mutex file\n#\n# Open a mutual exclusion lock on the file, unless another process already owns one.\n#\n# If the file is already locked by another process, the operation fails.\n# This function defines a lock on a file as having a file descriptor open to the file.\n# This function uses FD 9 to open a lock on the file. To release the lock, close FD 9:\n# exec 9>&-\n#\nmutex() {\n local file=$1 pid pids \n\n exec 9>>\"$file\"\n { pids=$(fuser -f \"$file\"); } 2>&- 9>&- \n for pid in $pids; do\n [[ $pid = $$ ]] && continue\n\n exec 9>&- \n return 1 # Locked by a pid.\n done \n}\n mutex /var/run/myscript.lock || { echo \"Already running.\" >&2; exit 1; }\n" }, { "answer_id": 901221, "author": "Jason Weathered", "author_id": 3736, "author_profile": "https://Stackoverflow.com/users/3736", "pm_score": 2, "selected": false, "text": "lockfile-progs procmail lockfile mkdir exclusive_lock_require exclusive_lock_try exclusive_lock_retry function exclusive_lock_try() # [lockname]\n{\n\n local LOCK_NAME=\"${1:-`basename $0`}\"\n\n LOCK_DIR=\"/tmp/.${LOCK_NAME}.lock\"\n local LOCK_PID_FILE=\"${LOCK_DIR}/${LOCK_NAME}.pid\"\n\n if [ -e \"$LOCK_DIR\" ]\n then\n local LOCK_PID=\"`cat \"$LOCK_PID_FILE\" 2> /dev/null`\"\n if [ ! -z \"$LOCK_PID\" ] && kill -0 \"$LOCK_PID\" 2> /dev/null\n then\n # locked by non-dead process\n echo \"\\\"$LOCK_NAME\\\" lock currently held by PID $LOCK_PID\"\n return 1\n else\n # orphaned lock, take it over\n ( echo $$ > \"$LOCK_PID_FILE\" ) 2> /dev/null && local LOCK_PID=\"$$\"\n fi\n fi\n if [ \"`trap -p EXIT`\" != \"\" ]\n then\n # already have an EXIT trap\n echo \"Cannot get lock, already have an EXIT trap\"\n return 1\n fi\n if [ \"$LOCK_PID\" != \"$$\" ] &&\n ! ( umask 077 && mkdir \"$LOCK_DIR\" && umask 177 && echo $$ > \"$LOCK_PID_FILE\" ) 2> /dev/null\n then\n local LOCK_PID=\"`cat \"$LOCK_PID_FILE\" 2> /dev/null`\"\n # unable to acquire lock, new process got in first\n echo \"\\\"$LOCK_NAME\\\" lock currently held by PID $LOCK_PID\"\n return 1\n fi\n trap \"/bin/rm -rf \\\"$LOCK_DIR\\\"; exit;\" EXIT\n\n return 0 # got lock\n\n}\n\nfunction exclusive_lock_retry() # [lockname] [retries] [delay]\n{\n\n local LOCK_NAME=\"$1\"\n local MAX_TRIES=\"${2:-5}\"\n local DELAY=\"${3:-2}\"\n\n local TRIES=0\n local LOCK_RETVAL\n\n while [ \"$TRIES\" -lt \"$MAX_TRIES\" ]\n do\n\n if [ \"$TRIES\" -gt 0 ]\n then\n sleep \"$DELAY\"\n fi\n local TRIES=$(( $TRIES + 1 ))\n\n if [ \"$TRIES\" -lt \"$MAX_TRIES\" ]\n then\n exclusive_lock_try \"$LOCK_NAME\" > /dev/null\n else\n exclusive_lock_try \"$LOCK_NAME\"\n fi\n LOCK_RETVAL=\"${PIPESTATUS[0]}\"\n\n if [ \"$LOCK_RETVAL\" -eq 0 ]\n then\n return 0\n fi\n\n done\n\n return \"$LOCK_RETVAL\"\n\n}\n\nfunction exclusive_lock_require() # [lockname] [retries] [delay]\n{\n if ! exclusive_lock_retry \"$@\"\n then\n exit 1\n fi\n}\n" }, { "answer_id": 1560651, "author": "Gunstick", "author_id": 15653, "author_profile": "https://Stackoverflow.com/users/15653", "pm_score": 5, "selected": false, "text": "if mkdir /var/lock/.myscript.exclusivelock\nthen\n # do stuff\n :\n rmdir /var/lock/.myscript.exclusivelock\nfi\n" }, { "answer_id": 4689326, "author": "thecowster", "author_id": 575389, "author_profile": "https://Stackoverflow.com/users/575389", "pm_score": 1, "selected": false, "text": "## Test the lock\nLOCKFILE=/tmp/singleton.lock \nif [ -e ${LOCKFILE} ] && kill -0 `cat ${LOCKFILE}`; then\n echo \"Script already running. bye!\"\n exit \nfi\n\n## Set the lock \necho $$ > ${LOCKFILE}\n" }, { "answer_id": 5112787, "author": "Mikel", "author_id": 102182, "author_profile": "https://Stackoverflow.com/users/102182", "pm_score": 5, "selected": false, "text": "noclobber set -C > set -C\nlockfile=\"/tmp/locktest.lock\"\nif echo \"$$\" > \"$lockfile\"; then\n echo \"Successfully acquired lock\"\n # do work\n rm \"$lockfile\" # XXX or via trap - see below\nelse\n echo \"Cannot acquire lock - already locked by $(cat \"$lockfile\")\"\nfi\n open(pathname, O_CREAT|O_EXCL)\n ksh88 $ strace -e trace=creat,open -f /bin/bash /home/mikel/bin/testopen 2>&1 | grep -F testopen.lock\nopen(\"/tmp/testopen.lock\", O_WRONLY|O_CREAT|O_EXCL|O_LARGEFILE, 0666) = 3\n\n$ strace -e trace=creat,open -f /bin/zsh /home/mikel/bin/testopen 2>&1 | grep -F testopen.lock\nopen(\"/tmp/testopen.lock\", O_WRONLY|O_CREAT|O_EXCL|O_NOCTTY|O_LARGEFILE, 0666) = 3\n\n$ strace -e trace=creat,open -f /bin/pdksh /home/mikel/bin/testopen 2>&1 | grep -F testopen.lock\nopen(\"/tmp/testopen.lock\", O_WRONLY|O_CREAT|O_EXCL|O_TRUNC|O_LARGEFILE, 0666) = 3\n\n$ strace -e trace=creat,open -f /bin/dash /home/mikel/bin/testopen 2>&1 | grep -F testopen.lock\nopen(\"/tmp/testopen.lock\", O_WRONLY|O_CREAT|O_EXCL|O_LARGEFILE, 0666) = 3\n pdksh O_TRUNC rm # acquire lock\n# do work (code here may call exit, etc.)\nrm \"$lockfile\"\n trap 'rm \"$lockfile\"' EXIT\n" }, { "answer_id": 7935037, "author": "Mark Stinson", "author_id": 407989, "author_profile": "https://Stackoverflow.com/users/407989", "pm_score": 4, "selected": false, "text": "mkdir flock set -e #=======================================================================\n# Predefined Global Variables\n#=======================================================================\n\nTMPDIR=/tmp/myapp\n[[ ! -d $TMP_DIR ]] \\\n && mkdir -p $TMP_DIR \\\n && chmod 700 $TMPDIR\n\nLOCK_DIR=$TMP_DIR/lock\n\n#=======================================================================\n# Functions\n#=======================================================================\n\nfunction mklock {\n __lockdir=\"$LOCK_DIR/$(date +%s.%N).$$\" # Private Global. Use Epoch.Nano.PID\n\n # If it can create $LOCK_DIR then no other instance is running\n if $(mkdir $LOCK_DIR)\n then\n mkdir $__lockdir # create this instance's specific lock in queue\n LOCK_EXISTS=true # Global\n else\n echo \"FATAL: Lock already exists. Another copy is running or manually lock clean up required.\"\n exit 1001 # Or work out some sleep_while_execution_lock elsewhere\n fi\n}\n\nfunction rmlock {\n [[ ! -d $__lockdir ]] \\\n && echo \"WARNING: Lock is missing. $__lockdir does not exist\" \\\n || rmdir $__lockdir\n}\n\n#-----------------------------------------------------------------------\n# Private Signal Traps Functions {{{2\n#\n# DANGER: SIGKILL cannot be trapped. So, try not to `kill -9 PID` or \n# there will be *NO CLEAN UP*. You'll have to manually remove \n# any locks in place.\n#-----------------------------------------------------------------------\nfunction __sig_exit {\n\n # Place your clean up logic here \n\n # Remove the LOCK\n [[ -n $LOCK_EXISTS ]] && rmlock\n}\n\nfunction __sig_int {\n echo \"WARNING: SIGINT caught\" \n exit 1002\n}\n\nfunction __sig_quit {\n echo \"SIGQUIT caught\"\n exit 1003\n}\n\nfunction __sig_term {\n echo \"WARNING: SIGTERM caught\" \n exit 1015\n}\n\n#=======================================================================\n# Main\n#=======================================================================\n\n# Set TRAPs\ntrap __sig_exit EXIT # SIGEXIT\ntrap __sig_int INT # SIGINT\ntrap __sig_quit QUIT # SIGQUIT\ntrap __sig_term TERM # SIGTERM\n\nmklock\n\n# CODE\n\nexit # No need for cleanup code here being in the __sig_exit trap function\n __sig_exit" }, { "answer_id": 10437121, "author": "presto8", "author_id": 307413, "author_profile": "https://Stackoverflow.com/users/307413", "pm_score": 2, "selected": false, "text": "#!/bin/bash\n\n{\n # exit if we are unable to obtain a lock; this would happen if \n # the script is already running elsewhere\n # note: -x (exclusive) is the default\n flock -n 100 || exit\n\n # put commands to run here\n sleep 100\n} 100>/tmp/myjob.lock \n" }, { "answer_id": 12892370, "author": "NickSoft", "author_id": 676439, "author_profile": "https://Stackoverflow.com/users/676439", "pm_score": 2, "selected": false, "text": "lockfile=/var/lock/myscript.lock\n\nif ( set -o noclobber; echo \"$$\" > \"$lockfile\") 2> /dev/null ; then\n trap 'rm -f \"$lockfile\"; exit $?' INT TERM EXIT\nelse\n # or you can decide to skip the \"else\" part if you want\n echo \"Another instance is already running!\"\nfi\n noclobber" }, { "answer_id": 15921192, "author": "Znik", "author_id": 2261349, "author_profile": "https://Stackoverflow.com/users/2261349", "pm_score": 3, "selected": false, "text": " #!/bin/bash\n #set -e this is useful only for very stupid scripts because script fails when anything command exits with status more than 0 !! without possibility for capture exit codes. not all commands exits >0 are failed.\n\n( #start subprocess\n # Wait for lock on /var/lock/.myscript.exclusivelock (fd 200) for 10 seconds\n flock -x -w 10 200\n if [ \"$?\" != \"0\" ]; then echo Cannot lock!; exit 1; fi\n echo $$>>/var/lock/.myscript.exclusivelock #for backward lockdir compatibility, notice this command is executed AFTER command bottom ) 200>/var/lock/.myscript.exclusivelock.\n # Do stuff\n # you can properly manage exit codes with multiple command and process algorithm.\n # I suggest throw this all to external procedure than can properly handle exit X commands\n\n) 200>/var/lock/.myscript.exclusivelock #exit subprocess\n\nFLOCKEXIT=$? #save exitcode status\n #do some finish commands\n\nexit $FLOCKEXIT #return properly exitcode, may be usefull inside external scripts\n" }, { "answer_id": 18670656, "author": "Majal", "author_id": 2756066, "author_profile": "https://Stackoverflow.com/users/2756066", "pm_score": 4, "selected": false, "text": "[[ $(pgrep -c \"`basename \\\"$0\\\"`\") -gt 1 ]] && exit\n" }, { "answer_id": 20862433, "author": "rouble", "author_id": 215120, "author_profile": "https://Stackoverflow.com/users/215120", "pm_score": 2, "selected": false, "text": "#!/usr/bin/env sh\n# Author: rouble\n\nLOCKFILE=/var/tmp/lockfile #customize this line\n\ntrap release INT TERM EXIT\n\n# Creates a lockfile. Sets global variable $ACQUIRED to true on success.\n# \n# Returns 0 if it is successfully able to create lockfile.\nacquire () {\n set -C #Shell noclobber option. If file exists, > will fail.\n UUID=`ps -eo pid,ppid,lstart $$ | tail -1`\n if (echo \"$UUID\" > \"$LOCKFILE\") 2>/dev/null; then\n ACQUIRED=\"TRUE\"\n return 0\n else\n if [ -e $LOCKFILE ]; then \n # We may be dealing with a stale lock file.\n # Bring out the magnifying glass. \n CURRENT_UUID_FROM_LOCKFILE=`cat $LOCKFILE`\n CURRENT_PID_FROM_LOCKFILE=`cat $LOCKFILE | cut -f 1 -d \" \"`\n CURRENT_UUID_FROM_PS=`ps -eo pid,ppid,lstart $CURRENT_PID_FROM_LOCKFILE | tail -1`\n if [ \"$CURRENT_UUID_FROM_LOCKFILE\" == \"$CURRENT_UUID_FROM_PS\" ]; then \n echo \"Script already running with following identification: $CURRENT_UUID_FROM_LOCKFILE\" >&2\n return 1\n else\n # The process that created this lock file died an ungraceful death. \n # Take ownership of the lock file.\n echo \"The process $CURRENT_UUID_FROM_LOCKFILE is no longer around. Taking ownership of $LOCKFILE\"\n release \"FORCE\"\n if (echo \"$UUID\" > \"$LOCKFILE\") 2>/dev/null; then\n ACQUIRED=\"TRUE\"\n return 0\n else\n echo \"Cannot write to $LOCKFILE. Error.\" >&2\n return 1\n fi\n fi\n else\n echo \"Do you have write permissons to $LOCKFILE ?\" >&2\n return 1\n fi\n fi\n}\n\n# Removes the lock file only if this script created it ($ACQUIRED is set), \n# OR, if we are removing a stale lock file (first parameter is \"FORCE\") \nrelease () {\n #Destroy lock file. Take no prisoners.\n if [ \"$ACQUIRED\" ] || [ \"$1\" == \"FORCE\" ]; then\n rm -f $LOCKFILE\n fi\n}\n\n# Test code\n# int main( int argc, const char* argv[] )\necho \"Acquring lock.\"\nacquire\nif [ $? -eq 0 ]; then \n echo \"Acquired lock.\"\n read -p \"Press [Enter] key to release lock...\"\n release\n echo \"Released lock.\"\nelse\n echo \"Unable to acquire lock.\"\nfi\n" }, { "answer_id": 22427524, "author": "tiian", "author_id": 3423812, "author_profile": "https://Stackoverflow.com/users/3423812", "pm_score": 0, "selected": false, "text": "flom -- command1\n flom -- command2\n" }, { "answer_id": 23625689, "author": "Stefan Rogin", "author_id": 1342199, "author_profile": "https://Stackoverflow.com/users/1342199", "pm_score": 0, "selected": false, "text": "#!/bin/bash\n\nfunction sh_lock_init {\n sh_lock_scriptName=$(basename $0)\n sh_lock_dir=\"/tmp/${sh_lock_scriptName}.lock\" #lock directory\n sh_lock_file=\"${sh_lock_dir}/lockPid.txt\" #lock file\n}\n\nfunction sh_acquire_lock {\n if mkdir $sh_lock_dir 2>/dev/null; then #check for lock\n echo \"$sh_lock_scriptName lock acquired successfully.\">&2\n touch $sh_lock_file\n echo $$ > $sh_lock_file # set current pid in lockFile\n return 0\n else\n touch $sh_lock_file\n read sh_lock_lastPID < $sh_lock_file\n if [ ! -z \"$sh_lock_lastPID\" -a -d /proc/$sh_lock_lastPID ]; then # if lastPID is not null and a process with that pid exists\n echo \"$sh_lock_scriptName is already running.\">&2\n return 1\n else\n echo \"$sh_lock_scriptName stopped during execution, reacquiring lock.\">&2\n echo $$ > $sh_lock_file # set current pid in lockFile\n return 2\n fi\n fi\n return 0\n}\n\nfunction sh_check_lock {\n [[ ! -f $sh_lock_file ]] && echo \"$sh_lock_scriptName lock file removed.\">&2 && return 1\n read sh_lock_lastPID < $sh_lock_file\n [[ $sh_lock_lastPID -ne $$ ]] && echo \"$sh_lock_scriptName lock file pid has changed.\">&2 && return 2\n echo \"$sh_lock_scriptName lock still in place.\">&2\n return 0\n}\n\nfunction sh_remove_lock {\n rm -r $sh_lock_dir\n}\n #!/bin/bash\n. /path/to/sh_lock_functions.sh # load sh lock functions\n\nsh_lock_init || exit $?\n\nsh_acquire_lock\nlockStatus=$?\n[[ $lockStatus -eq 1 ]] && exit $lockStatus\n[[ $lockStatus -eq 2 ]] && echo \"lock is set, do some resume from crash procedures\";\n\n#monitoring example\ncnt=0\nwhile sh_check_lock # loop while lock is in place\ndo\n echo \"$sh_scriptName running (pid $$)\"\n sleep 1\n let cnt++\n [[ $cnt -gt 5 ]] && break\ndone\n\n#remove lock when process finished\nsh_remove_lock || exit $?\n\nexit 0\n" }, { "answer_id": 25133391, "author": "user3132194", "author_id": 3132194, "author_profile": "https://Stackoverflow.com/users/3132194", "pm_score": 3, "selected": false, "text": "[ \"${FLOCKER}\" != \"$0\" ] && exec env FLOCKER=\"$0\" flock -en \"$0\" \"$0\" \"$@\" || :\n [ \"${FLOCKER}\" != \"$0\" ] && { echo \"Trying to start build from queue... \"; exec bash -c \"FLOCKER='$0' flock -E $E_LOCKED -en '$0' '$0' '$@' || if [ \\\"\\$?\\\" -eq $E_LOCKED ]; then echo 'Locked.'; fi\"; } || echo \"Lock is free. Completing.\"\n flock" }, { "answer_id": 25243837, "author": "bk138", "author_id": 361413, "author_profile": "https://Stackoverflow.com/users/361413", "pm_score": 3, "selected": false, "text": "#!/bin/dash\n\nSCRIPTNAME=$(basename $0)\nLOCKDIR=\"/var/lock/${SCRIPTNAME}\"\nPIDFILE=\"${LOCKDIR}/pid\"\n\nif ! mkdir $LOCKDIR 2>/dev/null\nthen\n # lock failed, but check for stale one by checking if the PID is really existing\n PID=$(cat $PIDFILE)\n if ! kill -0 $PID 2>/dev/null\n then\n echo \"Removing stale lock of nonexistent PID ${PID}\" >&2\n rm -rf $LOCKDIR\n echo \"Restarting myself (${SCRIPTNAME})\" >&2\n exec \"$0\" \"$@\"\n fi\n echo \"$SCRIPTNAME is already running, bailing out\" >&2\n exit 1\nelse\n # lock successfully acquired, save PID\n echo $$ > $PIDFILE\nfi\n\ntrap \"rm -rf ${LOCKDIR}\" QUIT INT TERM EXIT\n\n\necho hello\n\nsleep 30s\n\necho bye\n" }, { "answer_id": 25288106, "author": "Sadhun", "author_id": 3455684, "author_profile": "https://Stackoverflow.com/users/3455684", "pm_score": -1, "selected": false, "text": "ab=`ps -ef | grep -v grep | grep -wc processname`\n" }, { "answer_id": 29123275, "author": "Tim Bunce", "author_id": 77193, "author_profile": "https://Stackoverflow.com/users/77193", "pm_score": 1, "selected": false, "text": "flock" }, { "answer_id": 31691826, "author": "Jabir Ahmed", "author_id": 1058505, "author_profile": "https://Stackoverflow.com/users/1058505", "pm_score": 0, "selected": false, "text": "pgrep -f $cmd || $cmd\n" }, { "answer_id": 33999807, "author": "Rudolf Lörcks", "author_id": 5621457, "author_profile": "https://Stackoverflow.com/users/5621457", "pm_score": 0, "selected": false, "text": "if [ 1 -ne $(/bin/fuser \"$0\" 2>/dev/null | wc -w) ]; then\n exit 1\nfi\n" }, { "answer_id": 35772112, "author": "Gianluca Casati", "author_id": 1217468, "author_profile": "https://Stackoverflow.com/users/1217468", "pm_score": 0, "selected": false, "text": "#!/bin/bash\n\nMY_FILENAME=`basename \"$BASH_SOURCE\"`\n\nMY_PROCESS_COUNT=$(ps a -o pid,cmd | grep $MY_FILENAME | grep -v grep | grep -v $$ | wc -\nl)\n\nif [ $MY_PROCESS_COUNT -ne 0 ]; then\n echo found another process\n exit 0\nif\n\n# Follows the code to get the job done.\n" }, { "answer_id": 37303133, "author": "Mark Setchell", "author_id": 2836621, "author_profile": "https://Stackoverflow.com/users/2836621", "pm_score": 5, "selected": false, "text": "GNU Parallel sem sem --id SCRIPTSINGLETON yourScript\n sem --id SCRIPTSINGLETON --semaphoretimeout -10 yourScript\n --id GNU Parallel" }, { "answer_id": 38717423, "author": "biocyberman", "author_id": 588867, "author_profile": "https://Stackoverflow.com/users/588867", "pm_score": 0, "selected": false, "text": "#!/bin/bash\n\n# if [ $(pgrep -c $(basename $0)) -lt 2 ]; then # this works but requires script name to be unique\nif [ $(pidof -x \"$0\"|wc -w ) -lt 3 ]; then\n echo -e \"Starting $(basename $0)\"\n emacsclient --alternate-editor=\"\" -c \"$@\"\nelse\n echo -e \"$0 is running already\"\nfi\n" }, { "answer_id": 39649227, "author": "rubo77", "author_id": 1069083, "author_profile": "https://Stackoverflow.com/users/1069083", "pm_score": -1, "selected": false, "text": "#!/bin/bash\nif [ $(pgrep -c $(basename $0)) -gt 1 ]; then \n echo $(basename $0) is already running\n exit 0\nfi\n #!/bin/bash\nexec 9>/tmp/my_lock_file\nif ! flock -n 9 ; then\n echo \"another instance of this script is already running\";\n exit 1\nfi\n" }, { "answer_id": 40145228, "author": "one-liner", "author_id": 3130850, "author_profile": "https://Stackoverflow.com/users/3130850", "pm_score": 2, "selected": false, "text": "pidof if if [[ $(ps axf | awk -v pid=$$ '$1!=pid && $6~/'$(basename $0)'/{print $1}') ]]; then echo \"Already running\"; exit; fi\n" }, { "answer_id": 44296058, "author": "David M. Syzdek", "author_id": 903194, "author_profile": "https://Stackoverflow.com/users/903194", "pm_score": 3, "selected": false, "text": "flock mkemp(3) mkemp(1) obtain_lock() obtain_lock()\n{\n LOCK=\"${1}\"\n LOCKDIR=\"$(dirname \"${LOCK}\")\"\n LOCKFILE=\"$(basename \"${LOCK}\")\"\n\n # create temp lock file\n TMPLOCK=$(mktemp -p \"${LOCKDIR}\" \"${LOCKFILE}XXXXXX\" 2> /dev/null)\n if test \"x${TMPLOCK}\" == \"x\";then\n echo \"unable to create temporary file with mktemp\" 1>&2\n return 1\n fi\n echo \"$$\" > \"${TMPLOCK}\"\n\n # attempt to obtain lock file\n ln \"${TMPLOCK}\" \"${LOCK}\" 2> /dev/null\n if test $? -ne 0;then\n rm -f \"${TMPLOCK}\"\n echo \"unable to obtain lockfile\" 1>&2\n if test -f \"${LOCK}\";then\n echo \"current lock information held by: $(cat \"${LOCK}\")\" 1>&2\n fi\n return 2\n fi\n rm -f \"${TMPLOCK}\"\n\n return 0;\n};\n #!/bin/sh\n\n. /path/to/locking/profile.sh\nPROG_LOCKFILE=\"/tmp/myprog.lock\"\n\nclean_up()\n{\n rm -f \"${PROG_LOCKFILE}\"\n}\n\nobtain_lock \"${PROG_LOCKFILE}\"\nif test $? -ne 0;then\n exit 1\nfi\ntrap clean_up SIGHUP SIGINT SIGTERM\n\n# bulk of script\n\nclean_up\nexit 0\n# end of script\n clean_up" }, { "answer_id": 47578176, "author": "sivann", "author_id": 848547, "author_profile": "https://Stackoverflow.com/users/848547", "pm_score": 2, "selected": false, "text": "#!/bin/bash\n\nexec 9<> /tmp/foo\nflock -n 9\nRET=$?\nif [[ $RET -ne 0 ]] ; then\n echo \"lock failed, exiting\"\n exit\nfi\n\n#Now we are inside the \"critical section\"\necho \"inside lock\"\nsleep 5\nexec 9>&- #close fd 9, and release lock\n\n#The part below is outside the critical section (the lock)\necho \"lock released\"\nsleep 5\n" }, { "answer_id": 49338826, "author": "WinEunuuchs2Unix", "author_id": 6929343, "author_profile": "https://Stackoverflow.com/users/6929343", "pm_score": 2, "selected": false, "text": "[ \"${FLOCKER}\" != \"$0\" ] && exec env FLOCKER=\"$0\" flock -en \"$0\" \"$0\" \"$@\" || :\n# This is useful boilerplate code for shell scripts. Put it at the top of\n# the shell script you want to lock and it'll automatically lock itself on\n# the first run. If the env var $FLOCKER is not set to the shell script\n# that is being run, then execute flock and grab an exclusive non-blocking\n# lock (using the script itself as the lock file) before re-execing itself\n# with the right arguments. It also sets the FLOCKER env var to the right\n# value so it doesn't run again.\n" }, { "answer_id": 49920240, "author": "Filidor Wiese", "author_id": 3964328, "author_profile": "https://Stackoverflow.com/users/3964328", "pm_score": 1, "selected": false, "text": "LOCK_FILE=\"/var/lock/$(basename \"$0\").pid\"\ntrap \"rm -f ${LOCK_FILE}; exit\" INT TERM EXIT\nif [[ -f $LOCK_FILE && -d /proc/`cat $LOCK_FILE` ]]; then\n // Process already exists\n exit 1\nfi\necho $$ > $LOCK_FILE\n" }, { "answer_id": 50373642, "author": "untore", "author_id": 2229761, "author_profile": "https://Stackoverflow.com/users/2229761", "pm_score": 0, "selected": false, "text": "exec 3<>/file && exec 4</file ## gives locks\nlocker() {\n locked=false\n while read l; do\n case \"$l\" in\n lock)\n if $locked; then\n echo false\n else\n locked=true\n echo true\n fi\n ;;\n unlock)\n if $locked; then\n locked=false\n echo true\n else\n echo false\n fi\n ;;\n *)\n echo false\n ;;\n esac\n done\n}\n## locks\nlock() {\n local response\n echo lock >&${locker[1]}\n read -ru ${locker[0]} response\n $response && return 0 || return 1\n}\n\n## unlocks\nunlock() {\n local response\n echo unlock >&${locker[1]}\n read -ru ${locker[0]} response\n $response && return 0 || return 1\n}\n" }, { "answer_id": 54321529, "author": "Sudhir Kumar", "author_id": 10954104, "author_profile": "https://Stackoverflow.com/users/10954104", "pm_score": 1, "selected": false, "text": "lock_file=/tmp/`basename $0`.lock\n\nif fuser $lock_file > /dev/null 2>&1; then\n echo \"WARNING: Other instance of $(basename $0) running.\"\n exit 1\nfi\nexec 3> $lock_file \n" }, { "answer_id": 59494571, "author": "Z KC", "author_id": 11167486, "author_profile": "https://Stackoverflow.com/users/11167486", "pm_score": 1, "selected": false, "text": "#!/bin/bash\n\nif [[ $(pgrep -afc \"$(basename \"$0\")\") -gt \"1\" ]]; then echo \"Another instance of \"$0\" has already been started!\" && exit; fi\n.\nthe_beginning_of_actual_script\n" }, { "answer_id": 70285077, "author": "AnyDev", "author_id": 2742342, "author_profile": "https://Stackoverflow.com/users/2742342", "pm_score": 0, "selected": false, "text": "$0 $BASH_SOURCE man flock flock flock #!/bin/bash\n\nLOCKFILE=/var/lock/TODO\n\nset -o noclobber\nexec {lockfd}<> \"${LOCKFILE}\" || exit 1\nset +o noclobber # depends on what you need\nflock --exclusive --nonblock ${lockfd} || exit 1\n #!/bin/bash\n\n# TODO Set a lock file name\nLOCKFILE=/var/lock/myprogram.lock\n\n# Set noclobber option to ensure lock file is not REPLACED.\nset -o noclobber\n\n# Open lock file for R+W on a new file descriptor\n# and assign the new file descriptor to \"lockfd\" variable.\n# This does NOT obtain a lock but ensures the file exists and opens it.\nexec {lockfd}<> \"${LOCKFILE}\" || {\n echo \"pid=$$ failed to open LOCKFILE='${LOCKFILE}'\" 1>&2\n exit 1\n}\n\n# TODO!!!! undo/set the desired noclobber value for the remainder of the script\nset +o noclobber\n\n# Lock on the allocated file descriptor or fail\n# Adjust flock options e.g. --noblock as needed\nflock --exclusive --nonblock ${lockfd} || {\n echo \"pid=$$ failed to obtain lock fd='${lockfd}' LOCKFILE='${LOCKFILE}'\" 1>&2\n exit 1\n}\n\n# DO work here\necho \"pid=$$ obtained exclusive lock fd='${lockfd}' LOCKFILE='${LOCKFILE}'\"\n\n# Can unlock after critical section and do more work after unlocking\n#flock -u ${lockfd};\n# if unlocking then might as well close lockfd too\n#exec {lockfd}<&-\n" }, { "answer_id": 72634429, "author": "Keyless", "author_id": 19345335, "author_profile": "https://Stackoverflow.com/users/19345335", "pm_score": 1, "selected": false, "text": "flock flock https://lockable.dev/api/acquire/my-lock-name\n https://lockable.dev/api/release/my-lock-name\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/185451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7598/" ]
185,461
<p>I would like MATLAB to tell me if I have an input file (.m file) that contains some variables with their numbers (i.e., <code>a = 5</code>, <code>b = 6</code>, <code>c = 7</code>) so that I can then use that .m file in another program (main .m file) that uses these variables to calculate <code>S = a + b + c</code>. How can I then read the input file from the main file? Assume the input file is called INP and the main MAIN.</p>
[ { "answer_id": 185469, "author": "Scottie T", "author_id": 6688, "author_profile": "https://Stackoverflow.com/users/6688", "pm_score": 2, "selected": false, "text": "% File: inputs.m\na = 5;\nb = 6;\nc = 7;\n % File: main.m\ninputs;\nS = a + b + c;\n" }, { "answer_id": 185660, "author": "KennyMorton", "author_id": 4135, "author_profile": "https://Stackoverflow.com/users/4135", "pm_score": 3, "selected": false, "text": "function [a,b c] = inputs\na = 5;\nb = 6;\nc = 7;\n % main.m\n[a,b,c] = inputs;\ns = a+b+c;\n" }, { "answer_id": 189482, "author": "b3.", "author_id": 14946, "author_profile": "https://Stackoverflow.com/users/14946", "pm_score": 0, "selected": false, "text": "eval(char(textread(fullfile(ctfroot, INP), '%s', 'whitespace', '');\n" }, { "answer_id": 309162, "author": "Todd", "author_id": 30841, "author_profile": "https://Stackoverflow.com/users/30841", "pm_score": 0, "selected": false, "text": "%mydata.m\na = 1;\nb = 2;\n\n\n%mymain.m\nmydata\nwhos\nmymain\n >> >>" }, { "answer_id": 356821, "author": "Jason S", "author_id": 44330, "author_profile": "https://Stackoverflow.com/users/44330", "pm_score": 2, "selected": false, "text": "function S = zark\n S.wheels = 24;\n S.mpg = 13.2;\n S.name = 'magic bus';\n S.transfer_fcn = @(x) x+7;\n S.K = [1 2; -2 1];\n >> f = 'wheels';\n>> S.(f)\n\nans =\n\n 24\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/185461", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
185,463
<p>I have a view that supports landscape and portrait viewing, with the controls all moving around when you switch from one to the other. I'm currently doing this by setting the .center of each one of my controls when the user rotates the phone. The problem is that this is tedious, and requires a lot of code, and seems to defeat the purpose of using Interface Builder in the first place.</p> <p>My question is: is there a way in Interface Builder for one view to support multiple looks (one for landscape one for portrait)? If not how do other people do this with IB? Do you set up 2 views?</p> <p>Edit: Just to clarify my landscape and portrait views look different, I don't want a straight transform, I actually display the data differently in landscape mode</p>
[ { "answer_id": 401061, "author": "Ed Marty", "author_id": 36007, "author_profile": "https://Stackoverflow.com/users/36007", "pm_score": 1, "selected": false, "text": "UIView UILabel UIView ViewDidLoad CGRect" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/185463", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6044/" ]
185,474
<p>I have a connection string being passed to a function, and I need to create a DbConnection based object (i.e. SQLConnection, OracleConnection, OLEDbConnection etc) based on this string.</p> <p>Is there any inbuilt functionality to do this, or any 3rd party libraries to assist. We are not necessarily building this connection string, so we cannot rely on a format the string is written in to determine its type, and I would <em>prefer</em> not to have to code up all combinations and permutations of possible connection strings</p>
[ { "answer_id": 185482, "author": "Eric Tuttleman", "author_id": 25677, "author_profile": "https://Stackoverflow.com/users/25677", "pm_score": 4, "selected": false, "text": "DbProviderFactory dbProviderFactory = DbProviderFactories.GetFactory(myDriverClass);\nDbConnection dbConnection = dbProviderFactory.CreateConnection();\ndbConnection.ConnectionString = myConnectionString;\n" }, { "answer_id": 185488, "author": "Bryant", "author_id": 10893, "author_profile": "https://Stackoverflow.com/users/10893", "pm_score": 1, "selected": false, "text": "providerName=\"System.Data.SqlClient\"\n" }, { "answer_id": 185571, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 6, "selected": true, "text": "DbConnection GetConnection(string connStr)\n{\n string providerName = null;\n var csb = new DbConnectionStringBuilder { ConnectionString = connStr };\n \n if (csb.ContainsKey(\"provider\")) \n {\n providerName = csb[\"provider\"].ToString();\n } \n else\n {\n var css = ConfigurationManager\n .ConnectionStrings\n .Cast<ConnectionStringSettings>()\n .FirstOrDefault(x => x.ConnectionString == connStr);\n if (css != null) providerName = css.ProviderName;\n }\n \n if (providerName != null) \n {\n var providerExists = DbProviderFactories\n .GetFactoryClasses()\n .Rows.Cast<DataRow>()\n .Any(r => r[2].Equals(providerName));\n if (providerExists) \n {\n var factory = DbProviderFactories.GetFactory(providerName);\n var dbConnection = factory.CreateConnection();\n \n dbConnection.ConnectionString = connStr;\n return dbConnection;\n }\n }\n \n return null;\n}\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/185474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5302/" ]
185,483
<p>How do I prevent my users from accessing directly pages meant for ajax calls only?</p> <p>Passing a key during ajax call seems like a solution, whereas access without the key will not be processed. But it is also easy to fabricate the key, no? Curse of View Source...</p> <p>p/s: Using Apache as webserver.</p> <p>EDIT: To answer why, I have jQuery ui-tabs in my index.php, and inside those tabs are forms with scripts, which won't work if they're accessed directly. Why a user would want to do that, I don't know, I just figure I'd be more user friendly by preventing direct access to forms without validation scripts.</p>
[ { "answer_id": 185562, "author": "Eran Galperin", "author_id": 10585, "author_profile": "https://Stackoverflow.com/users/10585", "pm_score": 6, "selected": true, "text": " if($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {\n //Request identified as ajax request\n }\n" }, { "answer_id": 5032338, "author": "foxybagga", "author_id": 95350, "author_profile": "https://Stackoverflow.com/users/95350", "pm_score": 1, "selected": false, "text": "define('IS_AJAX', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');\n\nif(IS_AJAX) {\n //Request identified as ajax request\n}\n" }, { "answer_id": 21524330, "author": "Jeroenv3", "author_id": 1573574, "author_profile": "https://Stackoverflow.com/users/1573574", "pm_score": 0, "selected": false, "text": "var url = \"http://website.com/ajax.php?say=hello+world\";\nxmlHttp.open(\"GET\", url, true);\nxmlHttp.setRequestHeader('X-Requested-With', 'XMLHttpRequest');\n if($_SERVER['HTTP_X_REQUESTED_WITH'] != \"XMLHttpRequest\") {\n header(\"Location: http://website.com\");\n die();\n}\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/185483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15345/" ]
185,487
<p>Assuming I have three tables : TableA (key, value) TableB (key, value) TableC (key, value)</p> <p>and I want to return a value for all keys. If the key exists in TableC return that value else if the key exists in B return that value else return the value from table A</p> <p>The best I have come up with so far is</p> <pre><code>SELECT key,Value FROM TableA WHERE key NOT IN (SELECT key FROM TableB) AND key NOT IN (SELECT key FROM TableC) UNION SELECT key,Value FROM TableB WHERE key NOT IN (SELECT key FROM TableC) UNION SELECT key,Value FROM TableC </code></pre> <p>But this seems pretty brute force. Anyone know a better way?</p> <p>Edit: Here is a more concrete example. Consider TableA as a standard work schedule where the key is a date and the value is the assigned shift. Table B is a statutory holiday calendar that overrides the standard work week. Table C is an exception schedule that is used to override the other two schedules when someone is asked to come in and work either an extra shift or a different shift.</p>
[ { "answer_id": 185509, "author": "Alexander Kojevnikov", "author_id": 712, "author_profile": "https://Stackoverflow.com/users/712", "pm_score": 0, "selected": false, "text": "SELECT key, value, 2 AS priority\nFROM TableA\nUNION\nSELECT key, value, 1 AS priority\nFROM TableB\nUNION\nSELECT key, value, 0 AS priority\nFROM TableC\nORDER BY key, priority\n" }, { "answer_id": 185527, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 0, "selected": false, "text": "DECLARE @MyTable TABLE\n(\n Key int PRIMARY KEY,\n Value int\n)\n\n --Grab from TableC\nINSERT INTO @MyTable(Key, Value)\nSELECT Key, Value\nFROM TableC\n\n --Grab from TableB\nINSERT INTO @MyTable(Key, Value)\nSELECT Key, Value\nFROM TableB\nWHERE Key not in (SELECT Key FROM @MyTable)\n\n --Grab from TableA \nINSERT INTO @MyTable(Key, Value)\nSELECT Key, Value\nFROM TableA\nWHERE Key not in (SELECT Key FROM @MyTable)\n --Pop the result\nSELECT Key, Value\nFROM @MyTable\n" }, { "answer_id": 185556, "author": "WW.", "author_id": 14663, "author_profile": "https://Stackoverflow.com/users/14663", "pm_score": 1, "selected": false, "text": "SELECT\n ALL_KEYS.KEY,\n NVL( TABLEC.VALUE, NVL( TABLEB.VALUE, TABLEA.VALUE)) AS VALUE\nFROM\n (SELECT KEY AS KEY FROM TABLEA\n UNION\n SELECT KEY FROM TABLEB\n UNION\n SELECT KEY FROM TABLEC) ALL_KEYS,\n TABLEA,\n TABLEB,\n TABLEC\nWHERE\n ALL_KEYS.KEY = TABLEA.KEY(+) AND\n ALL_KEYS.KEY = TABLEB.KEY(+) AND\n ALL_KEYS.KEY = TABLEC.KEY(+);\n" }, { "answer_id": 185783, "author": "JeremyDWill", "author_id": 12603, "author_profile": "https://Stackoverflow.com/users/12603", "pm_score": 3, "selected": true, "text": "CREATE TABLE [dbo].[StandardSchedule](\n [scheduledate] [datetime] NOT NULL,\n [shift] [varchar](25) NOT NULL,\n CONSTRAINT [PK_StandardSchedule] PRIMARY KEY CLUSTERED \n( [scheduledate] ASC ));\n\nCREATE TABLE [dbo].[HolidaySchedule](\n [holidaydate] [datetime] NOT NULL,\n [shift] [varchar](25) NOT NULL,\n CONSTRAINT [PK_HolidaySchedule] PRIMARY KEY CLUSTERED \n( [holidaydate] ASC ));\n\nCREATE TABLE [dbo].[ExceptionSchedule](\n [exceptiondate] [datetime] NOT NULL,\n [shift] [varchar](25) NOT NULL,\n CONSTRAINT [PK_ExceptionDate] PRIMARY KEY CLUSTERED \n( [exceptiondate] ASC ));\n\nINSERT INTO ExceptionSchedule VALUES ('2008.01.06', 'ExceptionShift1');\nINSERT INTO ExceptionSchedule VALUES ('2008.01.08', 'ExceptionShift2');\nINSERT INTO ExceptionSchedule VALUES ('2008.01.10', 'ExceptionShift3');\nINSERT INTO HolidaySchedule VALUES ('2008.01.01', 'HolidayShift1');\nINSERT INTO HolidaySchedule VALUES ('2008.01.06', 'HolidayShift2');\nINSERT INTO HolidaySchedule VALUES ('2008.01.09', 'HolidayShift3');\nINSERT INTO StandardSchedule VALUES ('2008.01.01', 'RegularShift1');\nINSERT INTO StandardSchedule VALUES ('2008.01.02', 'RegularShift2');\nINSERT INTO StandardSchedule VALUES ('2008.01.03', 'RegularShift3');\nINSERT INTO StandardSchedule VALUES ('2008.01.04', 'RegularShift4');\nINSERT INTO StandardSchedule VALUES ('2008.01.05', 'RegularShift5');\nINSERT INTO StandardSchedule VALUES ('2008.01.07', 'RegularShift6');\nINSERT INTO StandardSchedule VALUES ('2008.01.09', 'RegularShift7');\nINSERT INTO StandardSchedule VALUES ('2008.01.10', 'RegularShift8');\n SELECT DISTINCT\n COALESCE(e2.exceptiondate, e.exceptiondate, holidaydate, scheduledate) AS ShiftDate,\n COALESCE(e2.shift, e.shift, h.shift, s.shift) AS Shift\nFROM standardschedule s\nFULL OUTER JOIN holidayschedule h ON s.scheduledate = h.holidaydate\nFULL OUTER JOIN exceptionschedule e ON h.holidaydate = e.exceptiondate\nFULL OUTER JOIN exceptionschedule e2 ON s.scheduledate = e2.exceptiondate\nORDER BY shiftdate\n" }, { "answer_id": 186820, "author": "AJ.", "author_id": 7211, "author_profile": "https://Stackoverflow.com/users/7211", "pm_score": 0, "selected": false, "text": "SELECT isnull( c.key, isnull( b.key, a.key) ) , \n isnull( c.value, isnull( b.value, a.value ) ) \nFROM TableA a \nLEFT JOIN TableB b \nON a.key = b.key\nLEFT JOIN TableC c \nON b.key = c.key\n" }, { "answer_id": 186828, "author": "Unsliced", "author_id": 2902, "author_profile": "https://Stackoverflow.com/users/2902", "pm_score": 0, "selected": false, "text": "COALESCE" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/185487", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6819/" ]
185,510
<p>Is it possible to do something like this?</p> <pre><code>var pattern = /some regex segment/ + /* comment here */ /another segment/; </code></pre> <p>Or do I have to use new <code>RegExp()</code> syntax and concatenate a string? I'd prefer to use the literal as the code is both more self-evident and concise.</p>
[ { "answer_id": 185529, "author": "Jerub", "author_id": 14648, "author_profile": "https://Stackoverflow.com/users/14648", "pm_score": 9, "selected": true, "text": "var segment_part = \"some bit of the regexp\";\nvar pattern = new RegExp(\"some regex segment\" + /*comment here */\n segment_part + /* that was defined just now */\n \"another segment\");\n var regex1 = /foo/g;\nvar regex2 = /bar/y;\nvar flags = (regex1.flags + regex2.flags).split(\"\").sort().join(\"\").replace(/(.)(?=.*\\1)/g, \"\");\nvar regex3 = new RegExp(expression_one.source + expression_two.source, flags);\n// regex3 is now /foobar/gy\n" }, { "answer_id": 752169, "author": "Praesagus", "author_id": 58013, "author_profile": "https://Stackoverflow.com/users/58013", "pm_score": -1, "selected": false, "text": "eval('your expression') / / ='new RegExp'" }, { "answer_id": 2065588, "author": "Alex", "author_id": 250873, "author_profile": "https://Stackoverflow.com/users/250873", "pm_score": 5, "selected": false, "text": "var xxx = /abcd/;\nvar yyy = /efgh/;\nvar zzz = new RegExp(eval(xxx)+eval(yyy));\n var zzz = new RegExp(xxx.source+yyy.source);\n" }, { "answer_id": 22543432, "author": "Japheth Salva", "author_id": 3157637, "author_profile": "https://Stackoverflow.com/users/3157637", "pm_score": 5, "selected": false, "text": "var r1 = /abc/g;\nvar r2 = /def/;\nvar r3 = new RegExp(r1.source + r2.source, \n (r1.global ? 'g' : '') \n + (r1.ignoreCase ? 'i' : '') + \n (r1.multiline ? 'm' : ''));\nconsole.log(r3);\nvar m = 'test that abcdef and abcdef has a match?'.match(r3);\nconsole.log(m);\n// m should contain 2 matches" }, { "answer_id": 23230231, "author": "ph7", "author_id": 2955894, "author_profile": "https://Stackoverflow.com/users/2955894", "pm_score": 2, "selected": false, "text": "var re_final = new RegExp(\"\\\\\" + \".\", \"g\"); // constructor can have 2 params!\nconsole.log(\"...finally\".replace(re_final, \"!\") + \"\\n\" + re_final + \n \" works as expected...\"); // !!!finally works as expected\n\n // meanwhile\n\nre_final = new RegExp(\"\\\\\" + \".\" + \"g\"); // appends final '/'\nconsole.log(\"... finally\".replace(re_final, \"!\")); // ...finally\nconsole.log(re_final, \"does not work!\"); // does not work\n" }, { "answer_id": 27191354, "author": "Mikaël Mayer", "author_id": 1287856, "author_profile": "https://Stackoverflow.com/users/1287856", "pm_score": 3, "selected": false, "text": "var r = /(a|b)\\1/ // Matches aa, bb but nothing else.\nvar p = /(c|d)\\1/ // Matches cc, dd but nothing else.\n var rp = /(a|b)\\1(c|d)\\1/\nrp.test(\"aadd\") // Returns false\n function concatenate(r1, r2) {\n var count = function(r, str) {\n return str.match(r).length;\n }\n var numberGroups = /([^\\\\]|^)(?=\\((?!\\?:))/g; // Home-made regexp to count groups.\n var offset = count(numberGroups, r1.source); \n var escapedMatch = /[\\\\](?:(\\d+)|.)/g; // Home-made regexp for escaped literals, greedy on numbers.\n var r2newSource = r2.source.replace(escapedMatch, function(match, number) { return number?\"\\\\\"+(number-0+offset):match; });\n return new RegExp(r1.source+r2newSource,\n (r1.global ? 'g' : '') \n + (r1.ignoreCase ? 'i' : '')\n + (r1.multiline ? 'm' : ''));\n}\n var rp = concatenate(r, p) // returns /(a|b)\\1(c|d)\\2/\nrp.test(\"aadd\") // Returns true\n" }, { "answer_id": 41870726, "author": "antoni", "author_id": 2012407, "author_profile": "https://Stackoverflow.com/users/2012407", "pm_score": 3, "selected": false, "text": "/this/g new RegExp('this', 'g') var regexParts =\n [\n /\\b(\\d+|null)\\b/,// Some comments.\n /\\b(true|false)\\b/,\n /\\b(new|getElementsBy(?:Tag|Class|)Name|arguments|getElementById|if|else|do|null|return|case|default|function|typeof|undefined|instanceof|this|document|window|while|for|switch|in|break|continue|length|var|(?:clear|set)(?:Timeout|Interval))(?=\\W)/,\n /(\\$|jQuery)/,\n /many more patterns/\n ],\n regexString = regexParts.map(function(x){return x.source}).join('|'),\n regexPattern = new RegExp(regexString, 'g');\n string.replace(regexPattern, function()\n{\n var m = arguments,\n Class = '';\n\n switch(true)\n {\n // Numbers and 'null'.\n case (Boolean)(m[1]):\n m = m[1];\n Class = 'number';\n break;\n\n // True or False.\n case (Boolean)(m[2]):\n m = m[2];\n Class = 'bool';\n break;\n\n // True or False.\n case (Boolean)(m[3]):\n m = m[3];\n Class = 'keyword';\n break;\n\n // $ or 'jQuery'.\n case (Boolean)(m[4]):\n m = m[4];\n Class = 'dollar';\n break;\n\n // More cases...\n }\n\n return '<span class=\"' + Class + '\">' + m + '</span>';\n})\n .replace(/(\\b\\d+|null\\b)/g, '<span class=\"number\">$1</span>')\n.replace(/(\\btrue|false\\b)/g, '<span class=\"bool\">$1</span>')\n.replace(/\\b(new|getElementsBy(?:Tag|Class|)Name|arguments|getElementById|if|else|do|null|return|case|default|function|typeof|undefined|instanceof|this|document|window|while|for|switch|in|break|continue|var|(?:clear|set)(?:Timeout|Interval))(?=\\W)/g, '<span class=\"keyword\">$1</span>')\n.replace(/\\$/g, '<span class=\"dollar\">$</span>')\n.replace(/([\\[\\](){}.:;,+\\-?=])/g, '<span class=\"ponctuation\">$1</span>')\n" }, { "answer_id": 43010821, "author": "Neil Strain", "author_id": 4840721, "author_profile": "https://Stackoverflow.com/users/4840721", "pm_score": 2, "selected": false, "text": "function concatRegex(...segments) {\n return new RegExp(segments.join(''));\n}\n" }, { "answer_id": 57980801, "author": "Jeff Lowery", "author_id": 591529, "author_profile": "https://Stackoverflow.com/users/591529", "pm_score": 2, "selected": false, "text": "var xxx = new RegExp(/abcd/);\nvar zzz = new RegExp(xxx.source + /efgh/.source);\n" }, { "answer_id": 58732513, "author": "Daniel Aragão", "author_id": 6287060, "author_profile": "https://Stackoverflow.com/users/6287060", "pm_score": 1, "selected": false, "text": "a = /\\d+/\nb = /\\w+/\nc = new RegExp(a.source + b.source)\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/185510", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17964/" ]
185,520
<p>I have months stored in SQL Server as 1,2,3,4,...12. I would like to display them as January,February etc. Is there a function in SQL Server like MonthName(1) = January? I am trying to avoid a CASE statement, if possible.</p>
[ { "answer_id": 185548, "author": "Alexander Kojevnikov", "author_id": 712, "author_profile": "https://Stackoverflow.com/users/712", "pm_score": 8, "selected": true, "text": "SELECT DATENAME(month, DATEADD(month, @mydate-1, CAST('2008-01-01' AS datetime)))\n" }, { "answer_id": 185574, "author": "Jim Burger", "author_id": 20164, "author_profile": "https://Stackoverflow.com/users/20164", "pm_score": 3, "selected": false, "text": "SELECT DATENAME(month, STR(YEAR(GETDATE()), 4) + REPLACE(STR(@month, 2), ' ', '0') + '01') \n" }, { "answer_id": 188390, "author": "leoinfo", "author_id": 6948, "author_profile": "https://Stackoverflow.com/users/6948", "pm_score": 8, "selected": false, "text": "Select DateName( month , DateAdd( month , @MonthNumber , 0 ) - 1 )\n Select DateName( month , DateAdd( month , @MonthNumber , -1 ) )\n" }, { "answer_id": 626025, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "CONVERT select CONVERT(varchar(3), Date, 100) as Month from MyTable.\n" }, { "answer_id": 3138377, "author": "Dharamvir", "author_id": 378697, "author_profile": "https://Stackoverflow.com/users/378697", "pm_score": 7, "selected": false, "text": "SELECT DATENAME(month, GETDATE()) AS 'Month Name'\n" }, { "answer_id": 4129448, "author": "Nori", "author_id": 255497, "author_profile": "https://Stackoverflow.com/users/255497", "pm_score": 2, "selected": false, "text": "CONVERT(VARCHAR(3), DATENAME(MM, GETDATE()), 100)\n" }, { "answer_id": 6712227, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "SELECT DATENAME(m, str(2) + '/1/2011') SELECT DATENAME(m, str([column_name]) + '/1/2011') DECLARE @integer int;\n\nSET @integer = 6;\n\nSELECT DATENAME(m, str(@integer) + '/1/2011')\n" }, { "answer_id": 6963137, "author": "Roadrunner327", "author_id": 345314, "author_profile": "https://Stackoverflow.com/users/345314", "pm_score": 1, "selected": false, "text": "@MetricMonthNumber (some number)\n\nSELECT \n(DateName( month , DateAdd( month , @MetricMonthNumber - 1 , '1900-01-01' ) )) AS MetricMonthName\nFROM TableName\n" }, { "answer_id": 7583543, "author": "Cedricve", "author_id": 969111, "author_profile": "https://Stackoverflow.com/users/969111", "pm_score": -1, "selected": false, "text": "SELECT TO_CHAR(current_date,'dd MONTH yyyy') FROM dual\n" }, { "answer_id": 8218454, "author": "Darryl Martin", "author_id": 1058597, "author_profile": "https://Stackoverflow.com/users/1058597", "pm_score": 6, "selected": false, "text": "SUBSTRING('JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC ', (@intMonth * 4) - 3, 3)\n" }, { "answer_id": 11417240, "author": "shailesh", "author_id": 1515362, "author_profile": "https://Stackoverflow.com/users/1515362", "pm_score": -1, "selected": false, "text": "to_char(to_date(V_MONTH_NUM,'MM'),'MONTH')\n V_MONTH_NUM SELECT to_char(to_date(V_MONTH_NUM,'MM'),'MONTH') from dual;\n" }, { "answer_id": 11574461, "author": "Wafa Abbas", "author_id": 1458809, "author_profile": "https://Stackoverflow.com/users/1458809", "pm_score": 1, "selected": false, "text": "Declare @MonthNumber int\nSET @MonthNumber=DatePart(Month,GETDATE())\nSelect DateName( month , DateAdd( month , @MonthNumber , 0 ) - 1 )\n MonthNumber DatePart" }, { "answer_id": 12724184, "author": "Benazir", "author_id": 1719560, "author_profile": "https://Stackoverflow.com/users/1719560", "pm_score": 2, "selected": false, "text": "SELECT DATENAME(month ,GETDATE())\n" }, { "answer_id": 15088927, "author": "unitario", "author_id": 308645, "author_profile": "https://Stackoverflow.com/users/308645", "pm_score": 3, "selected": false, "text": "CAST(GETDATE() AS CHAR(3))\n" }, { "answer_id": 16463285, "author": "gvila", "author_id": 2366489, "author_profile": "https://Stackoverflow.com/users/2366489", "pm_score": 2, "selected": false, "text": "SELECT DATENAME(MONTH,dateadd(month, -3,getdate()))\n" }, { "answer_id": 18205547, "author": "Asif", "author_id": 1386158, "author_profile": "https://Stackoverflow.com/users/1386158", "pm_score": 5, "selected": false, "text": "Select DateName( month , DateAdd( month , @MonthNumber , -1 ))\n" }, { "answer_id": 20579907, "author": "Piyush", "author_id": 3101531, "author_profile": "https://Stackoverflow.com/users/3101531", "pm_score": 2, "selected": false, "text": "select monthname(curdate());\n select monthname('2013-12-12');\n" }, { "answer_id": 20583939, "author": "Kashif Aslam", "author_id": 3102280, "author_profile": "https://Stackoverflow.com/users/3102280", "pm_score": 2, "selected": false, "text": "SELECT MONTHNAME(<fieldname>) AS \"Month Name\" FROM <tablename> WHERE <condition>\n" }, { "answer_id": 24585186, "author": "Shyam Sa", "author_id": 3807478, "author_profile": "https://Stackoverflow.com/users/3807478", "pm_score": 2, "selected": false, "text": "select datename(M,GETDATE())\n" }, { "answer_id": 28671252, "author": "Ashish Singh", "author_id": 2017212, "author_profile": "https://Stackoverflow.com/users/2017212", "pm_score": 3, "selected": false, "text": "SELECT CONVERT(CHAR(3), DATENAME(MONTH, GETDATE()))\n" }, { "answer_id": 30635960, "author": "user4972370", "author_id": 4972370, "author_profile": "https://Stackoverflow.com/users/4972370", "pm_score": 0, "selected": false, "text": "DECLARE @date datetime\nSET @date='2015/1/4 00:00:00'\n\nSELECT CAST(DATENAME(month,@date ) AS CHAR(3))AS 'Month Name'\n" }, { "answer_id": 31031373, "author": "lancepants28", "author_id": 2414620, "author_profile": "https://Stackoverflow.com/users/2414620", "pm_score": 0, "selected": false, "text": "datename(month,dateadd(month,datepart(month,Help_HelpMain.Ticket_Closed_Date),-1)) as monthname\n" }, { "answer_id": 32854250, "author": "Geoffrey Fuller", "author_id": 5390636, "author_profile": "https://Stackoverflow.com/users/5390636", "pm_score": 2, "selected": false, "text": "print datename(month,dateadd(month,-month(getdate()) + 9,getdate()))\n" }, { "answer_id": 36925160, "author": "Isaiah", "author_id": 5947614, "author_profile": "https://Stackoverflow.com/users/5947614", "pm_score": 2, "selected": false, "text": "SELECT DateName(M, DateAdd(M, @MONTHNUMBER, -1))\n" }, { "answer_id": 41193009, "author": "Charlie Brown", "author_id": 7308559, "author_profile": "https://Stackoverflow.com/users/7308559", "pm_score": 0, "selected": false, "text": "--Create the user-defined function\nCREATE FUNCTION getmonth (@num int)\nRETURNS varchar(9) --since 'September' is the longest string, length 9\nAS\nBEGIN\n\nDECLARE @intMonth Table (num int PRIMARY KEY IDENTITY(1,1), month varchar(9))\n\nINSERT INTO @intMonth VALUES ('January'), ('February'), ('March'), ('April'), ('May')\n , ('June'), ('July'), ('August') ,('September'), ('October')\n , ('November'), ('December')\n\nRETURN (SELECT I.month\n FROM @intMonth I\n WHERE I.num = @num)\nEND\nGO\n\n--Use the function for various months\nSELECT dbo.getmonth(4) AS [Month]\nSELECT dbo.getmonth(5) AS [Month]\nSELECT dbo.getmonth(6) AS [Month]\n" }, { "answer_id": 41875950, "author": "Saeed ur Rehman", "author_id": 4856329, "author_profile": "https://Stackoverflow.com/users/4856329", "pm_score": 4, "selected": false, "text": "select DATENAME(month, getdate())\n" }, { "answer_id": 42626048, "author": "M2012", "author_id": 1522823, "author_profile": "https://Stackoverflow.com/users/1522823", "pm_score": 2, "selected": false, "text": "declare @month smallint = 1\nselect DateName(mm,DATEADD(mm,@month - 1,0))\n" }, { "answer_id": 46357846, "author": "Janaka Pushpakumara", "author_id": 4465118, "author_profile": "https://Stackoverflow.com/users/4465118", "pm_score": 1, "selected": false, "text": "id name created_at\n1 abc 2017-09-16\n2 xyz 2017-06-10\n select year(created_at), monthname(created_at) from users;\n +-----------+-------------------------------+\n| year(created_at) | monthname(created_at) |\n+-----------+-------------------------------+\n| 2017 | september |\n| 2017 | june |\n" }, { "answer_id": 49454712, "author": "Paul", "author_id": 2109512, "author_profile": "https://Stackoverflow.com/users/2109512", "pm_score": 4, "selected": false, "text": "en-US select FORMAT(DATEFROMPARTS(1900, @month_num, 1), 'MMMM', 'en-US')\n select FORMAT(DATEFROMPARTS(1900, @month_num, 1), 'MMM', 'en-US')\n CREATE FUNCTION fn_month_num_to_name\n(\n @month_num tinyint\n)\nRETURNS varchar(20)\nAS\nBEGIN\n RETURN FORMAT(DATEFROMPARTS(1900, @month_num, 1), 'MMMM', 'en-US')\nEND\n" }, { "answer_id": 53341050, "author": "Seth Winters", "author_id": 4149921, "author_profile": "https://Stackoverflow.com/users/4149921", "pm_score": 0, "selected": false, "text": "\n/****** Object: UserDefinedFunction [dbo].[fn_GetMonthFromDate] Script Date: 11/16/2018 10:26:33 AM ******/\nSET ANSI_NULLS ON\nGO\nSET QUOTED_IDENTIFIER ON\nGO\nCREATE FUNCTION [dbo].[fn_GetMonthFromDate] \n(@date datetime)\nRETURNS varchar(50)\nAS\nBEGIN\n DECLARE @monthPart int\n\nSET @monthPart = MONTH(@date)\n\nIF @monthPart = 1\n BEGIN\n RETURN 'January'\n END\nELSE IF @monthPart = 2\n BEGIN\n RETURN 'February'\n END\nELSE IF @monthPart = 3\n BEGIN\n RETURN 'March'\n END\nELSE IF @monthPart = 4\n BEGIN\n RETURN 'April'\n END\nELSE IF @monthPart = 5\n BEGIN\n RETURN 'May'\n END\nELSE IF @monthPart = 6\n BEGIN\n RETURN 'June'\n END\nELSE IF @monthPart = 7\n BEGIN\n RETURN 'July'\n END\nELSE IF @monthPart = 8\n BEGIN\n RETURN 'August'\n END\nELSE IF @monthPart = 9\n BEGIN\n RETURN 'September'\n END\nELSE IF @monthPart = 10\n BEGIN\n RETURN 'October'\n END\nELSE IF @monthPart = 11\n BEGIN\n RETURN 'November'\n END\nELSE IF @monthPart = 12\n BEGIN\n RETURN 'December'\n END\nRETURN NULL END\n" }, { "answer_id": 56238864, "author": "Armand Mamitiana Rakotoarisoa", "author_id": 10403715, "author_profile": "https://Stackoverflow.com/users/10403715", "pm_score": -1, "selected": false, "text": "MONTHNAME(your_date)" }, { "answer_id": 60226167, "author": "Atanu Samanta", "author_id": 9779410, "author_profile": "https://Stackoverflow.com/users/9779410", "pm_score": -1, "selected": false, "text": "SELECT MONTHNAME(concat('1970-',[Month int val],'-01')) SELECT MONTHNAME(concat('1970-',4,'-01'))" }, { "answer_id": 70213009, "author": "CodeByAk", "author_id": 8195540, "author_profile": "https://Stackoverflow.com/users/8195540", "pm_score": -1, "selected": false, "text": " SELECT MONTH(STR_TO_DATE('November', '%M'))\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/185520", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23667/" ]
185,521
<p>I run into similar codes like this all the time in aspx pages:</p> <pre><code>&lt;asp:CheckBox Runat="server" ID="myid" Checked='&lt;%# DataBinder.Eval(Container.DataItem, "column").Equals(1) %&gt;'&gt; </code></pre> <p>I was wondering what other objects I have access to inside of that &lt;%# %> tag. How come DataBinder.Eval() and Container.DataItem are not visible anywhere inside .CS code?</p>
[ { "answer_id": 185612, "author": "Fung", "author_id": 8280, "author_profile": "https://Stackoverflow.com/users/8280", "pm_score": 4, "selected": true, "text": "<%#DirectCast(Container.DataItem, DataRow)(\"some_column\")%>\n <%#((DataRow)Container.DataItem)[\"some_column\"].ToString()%>\n" }, { "answer_id": 1287615, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<%#((System.Data.DataRow)Container.DataItem)[\"ColumnName\"].ToString()%>\n" }, { "answer_id": 1287673, "author": "Robert Koritnik", "author_id": 75642, "author_profile": "https://Stackoverflow.com/users/75642", "pm_score": 1, "selected": false, "text": "<%# %> page.DataBind()" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/185521", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10088/" ]
185,524
<p>I'm trying to build the example described at <a href="http://support.microsoft.com/kb/178749/EN-US/" rel="nofollow noreferrer">http://support.microsoft.com/kb/178749/EN-US/</a> in order to build an application that programatically accesses Excel using Automation. I have Visual C++ 2005/Visual Studio 2005. Some of the instructions don't exactly match up (classwizard, mostly), but the general idea seems to be the same.</p> <p>Problems: I don't end up with an excel.h file after using the "new class" to create my wrapper classes. So I can' t #include that file as it specifies in step 13. I do get a excel.tlh and an excel.tli in my windebug directory, but that doesn't seem to work. I tried all orders for </p> <pre><code>#include "stdafx.h" #include "debug/excel.tli" #include "debug/excel.tlh" </code></pre> <p>... including leaving one of those files out of the compile, but I still end up with a ton of compile errors.</p> <p>Here's the top 5 compile errors with the above #includes:</p> <pre><code>1&gt;c:\users\sniles\documents\visual studio 2005\source10\testole\testole\debug\excel.tli(14) : error C2653: 'Adjustments' : is not a class or namespace name 1&gt;c:\users\sniles\documents\visual studio 2005\source10\testole\testole\debug\excel.tli(14) : error C2146: syntax error : missing ';' before identifier 'GetParent' 1&gt;c:\users\sniles\documents\visual studio 2005\source10\testole\testole\debug\excel.tli(14) : error C2433: 'IDispatchPtr' : 'inline' not permitted on data declarations 1&gt;c:\users\sniles\documents\visual studio 2005\source10\testole\testole\debug\excel.tli(14) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int 1&gt;c:\users\sniles\documents\visual studio 2005\source10\testole\testole\debug\excel.tli(14) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int 1&gt;c:\users\sniles\documents\visual studio 2005\source10\testole\testole\debug\excel.tli(16) : error C3861: 'get_Parent': identifier not found </code></pre> <p>Here's the top 5 errors with these includes:</p> <pre><code>#include "stdafx.h" #include "debug/excel.tlh" 1&gt;c:\users\sniles\documents\visual studio 2005\source10\testole\testole\debug\excel.tlh(550) : error C3121: cannot change GUID for class 'IFilter' 1&gt; c:\program files\microsoft sdks\windows\v6.0\include\comdef.h(483) : see declaration of 'IFilter' 1&gt;c:\users\sniles\documents\visual studio 2005\source10\testole\testole\debug\excel.tlh(1541) : error C2786: 'BOOL (__stdcall *)(HDC,int,int,int,int)' : invalid operand for __uuidof 1&gt;c:\users\sniles\documents\visual studio 2005\source10\testole\testole\debug\excel.tlh(1541) : error C2923: '_com_IIID' : 'Rectangle' is not a valid template type argument for parameter '_Interface' 1&gt; c:\program files\microsoft sdks\windows\v6.0\include\wingdi.h(3667) : see declaration of 'Rectangle' 1&gt;c:\users\sniles\documents\visual studio 2005\source10\testole\testole\debug\excel.tlh(1541) : error C3203: '_com_IIID' : unspecialized class template can't be used as a template argument for template parameter '_IIID', expected a real type </code></pre> <p>Here's the top 5 errors with these includes:</p> <pre><code>#include "stdafx.h" #include "debug/excel.tli" 1&gt;c:\users\sniles\documents\visual studio 2005\source10\testole\testole\debug\excel.tli(14) : error C2653: 'Adjustments' : is not a class or namespace name 1&gt;c:\users\sniles\documents\visual studio 2005\source10\testole\testole\debug\excel.tli(14) : error C2146: syntax error : missing ';' before identifier 'GetParent' 1&gt;c:\users\sniles\documents\visual studio 2005\source10\testole\testole\debug\excel.tli(14) : error C2433: 'IDispatchPtr' : 'inline' not permitted on data declarations 1&gt;c:\users\sniles\documents\visual studio 2005\source10\testole\testole\debug\excel.tli(14) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int 1&gt;c:\users\sniles\documents\visual studio 2005\source10\testole\testole\debug\excel.tli(14) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int </code></pre> <p>Thanks in advance.</p>
[ { "answer_id": 186009, "author": "Nick", "author_id": 26240, "author_profile": "https://Stackoverflow.com/users/26240", "pm_score": 1, "selected": false, "text": ".tlh .tlh .tli CComPtr<>" }, { "answer_id": 186029, "author": "jmatthias", "author_id": 2768, "author_profile": "https://Stackoverflow.com/users/2768", "pm_score": 0, "selected": false, "text": "#import #include #import #import IDispatch" }, { "answer_id": 193332, "author": "Steve", "author_id": 1965047, "author_profile": "https://Stackoverflow.com/users/1965047", "pm_score": 0, "selected": false, "text": "vbe6ext.tlh ********************* Build output:\n\n1>------ Build started: Project: testole, Configuration: Debug Win32 ------\n1>Compiling...\n1>testoleDlg.cpp\n1>c:\\users\\sniles\\documents\\visual studio 2005\\source10\\testole\\testole\\debug\\vbe6ext.tlh(463) : error C2061: syntax error : identifier '__missing_type__'\n1>c:\\users\\sniles\\documents\\visual studio 2005\\source10\\testole\\testole\\testoledlg.cpp(164) : error C2065: '_Application' : undeclared identifier\n1>c:\\users\\sniles\\documents\\visual studio 2005\\source10\\testole\\testole\\testoledlg.cpp(164) : error C2146: syntax error : missing ';' before identifier 'app'\n1>c:\\users\\sniles\\documents\\visual studio 2005\\source10\\testole\\testole\\testoledlg.cpp(164) : error C2065: 'app' : undeclared identifier\n1>c:\\users\\sniles\\documents\\visual studio 2005\\source10\\testole\\testole\\testoledlg.cpp(166) : error C2228: left of '.CreateDispatch' must have class/struct/union\n1> type is ''unknown-type''\n1>c:\\users\\sniles\\documents\\visual studio 2005\\source10\\testole\\testole\\testoledlg.cpp(172) : error C2228: left of '.SetVisible' must have class/struct/union\n1> type is ''unknown-type''\n1>Build log was saved at \"file://c:\\Users\\sniles\\Documents\\Visual Studio 2005\\Source10\\testole\\testole\\Debug\\BuildLog.htm\"\n1>testole - 6 error(s), 0 warning(s)\n========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========\n\n******************* vbe6ext.tlh\n// Created by Microsoft (R) C/C++ Compiler Version 14.00.50727.42 (e112bc16).\n//\n// c:\\users\\sniles\\documents\\visual studio 2005\\source10\\testole\\testole\\debug\\vbe6ext.tlh\n//\n// C++ source equivalent of Win32 type library C:\\Program Files\\Common Files\\Microsoft Shared\\VBA\\VBA6\\VBE6EXT.OLB\n// compiler-generated file created 10/10/08 at 14:03:16 - DO NOT EDIT!\n\n#pragma once\n#pragma pack(push, 8)\n\n#include <comdef.h>\n\nnamespace VBIDE {\n\n//\n// Forward references and typedefs\n//\n\nstruct __declspec(uuid(\"0002e157-0000-0000-c000-000000000046\"))\n/* LIBID */ __VBIDE;\nstruct __declspec(uuid(\"0002e158-0000-0000-c000-000000000046\"))\n/* dual interface */ Application;\nenum vbextFileTypes;\nstruct __declspec(uuid(\"0002e166-0000-0000-c000-000000000046\"))\n/* dual interface */ testVBE;\nenum vbext_WindowType;\nenum vbext_WindowState;\nstruct __declspec(uuid(\"0002e16b-0000-0000-c000-000000000046\"))\n/* dual interface */ Window;\nstruct __declspec(uuid(\"0002e16a-0000-0000-c000-000000000046\"))\n/* dual interface */ _Windows_old;\nstruct __declspec(uuid(\"f57b7ed0-d8ab-11d1-85df-00c04f98f42c\"))\n/* dual interface */ _Windows;\nstruct /* coclass */ Windows;\nstruct __declspec(uuid(\"0002e16c-0000-0000-c000-000000000046\"))\n/* dual interface */ _LinkedWindows;\nstruct /* coclass */ LinkedWindows;\nstruct __declspec(uuid(\"0002e167-0000-0000-c000-000000000046\"))\n/* dual interface */ Events;\nstruct __declspec(uuid(\"0002e113-0000-0000-c000-000000000046\"))\n/* interface */ _VBProjectsEvents;\nstruct __declspec(uuid(\"0002e103-0000-0000-c000-000000000046\"))\n/* dispinterface */ _dispVBProjectsEvents;\nstruct __declspec(uuid(\"0002e115-0000-0000-c000-000000000046\"))\n/* interface */ _VBComponentsEvents;\nstruct __declspec(uuid(\"0002e116-0000-0000-c000-000000000046\"))\n/* dispinterface */ _dispVBComponentsEvents;\nstruct __declspec(uuid(\"0002e11a-0000-0000-c000-000000000046\"))\n/* interface */ _ReferencesEvents;\nstruct __declspec(uuid(\"0002e118-0000-0000-c000-000000000046\"))\n/* dispinterface */ _dispReferencesEvents;\nstruct /* coclass */ ReferencesEvents;\nstruct __declspec(uuid(\"0002e130-0000-0000-c000-000000000046\"))\n/* interface */ _CommandBarControlEvents;\nstruct __declspec(uuid(\"0002e131-0000-0000-c000-000000000046\"))\n/* dispinterface */ _dispCommandBarControlEvents;\nstruct /* coclass */ CommandBarEvents;\nstruct __declspec(uuid(\"0002e159-0000-0000-c000-000000000046\"))\n/* dual interface */ _ProjectTemplate;\nstruct /* coclass */ ProjectTemplate;\nenum vbext_ProjectType;\nenum vbext_ProjectProtection;\nenum vbext_VBAMode;\nstruct __declspec(uuid(\"0002e160-0000-0000-c000-000000000046\"))\n/* dual interface */ _VBProject_Old;\nstruct __declspec(uuid(\"eee00915-e393-11d1-bb03-00c04fb6c4a6\"))\n/* dual interface */ _VBProject;\nstruct /* coclass */ VBProject;\nstruct __declspec(uuid(\"0002e165-0000-0000-c000-000000000046\"))\n/* dual interface */ _VBProjects_Old;\nstruct __declspec(uuid(\"eee00919-e393-11d1-bb03-00c04fb6c4a6\"))\n/* dual interface */ _VBProjects;\nstruct /* coclass */ VBProjects;\nstruct __declspec(uuid(\"be39f3d4-1b13-11d0-887f-00a0c90f2744\"))\n/* dual interface */ SelectedComponents;\nenum vbext_ComponentType;\nstruct __declspec(uuid(\"0002e161-0000-0000-c000-000000000046\"))\n/* dual interface */ _Components;\nstruct /* coclass */ Components;\nstruct __declspec(uuid(\"0002e162-0000-0000-c000-000000000046\"))\n/* dual interface */ _VBComponents_Old;\nstruct __declspec(uuid(\"eee0091c-e393-11d1-bb03-00c04fb6c4a6\"))\n/* dual interface */ _VBComponents;\nstruct /* coclass */ VBComponents;\nstruct __declspec(uuid(\"0002e163-0000-0000-c000-000000000046\"))\n/* dual interface */ _Component;\nstruct /* coclass */ Component;\nstruct __declspec(uuid(\"0002e164-0000-0000-c000-000000000046\"))\n/* dual interface */ _VBComponent_Old;\nstruct __declspec(uuid(\"eee00921-e393-11d1-bb03-00c04fb6c4a6\"))\n/* dual interface */ _VBComponent;\nstruct /* coclass */ VBComponent;\nstruct __declspec(uuid(\"0002e18c-0000-0000-c000-000000000046\"))\n/* dual interface */ Property;\nstruct __declspec(uuid(\"0002e188-0000-0000-c000-000000000046\"))\n/* dual interface */ _Properties;\nstruct /* coclass */ Properties;\nstruct __declspec(uuid(\"da936b62-ac8b-11d1-b6e5-00a0c90f2744\"))\n/* dual interface */ _AddIns;\nstruct /* coclass */ Addins;\nstruct __declspec(uuid(\"da936b64-ac8b-11d1-b6e5-00a0c90f2744\"))\n/* dual interface */ AddIn;\nenum vbext_ProcKind;\nstruct __declspec(uuid(\"0002e16e-0000-0000-c000-000000000046\"))\n/* dual interface */ _CodeModule;\nstruct /* coclass */ CodeModule;\nstruct __declspec(uuid(\"0002e172-0000-0000-c000-000000000046\"))\n/* dual interface */ _CodePanes;\nstruct /* coclass */ CodePanes;\nenum vbext_CodePaneview;\nstruct __declspec(uuid(\"0002e176-0000-0000-c000-000000000046\"))\n/* dual interface */ _CodePane;\nstruct /* coclass */ CodePane;\nstruct __declspec(uuid(\"0002e17a-0000-0000-c000-000000000046\"))\n/* dual interface */ _References;\nenum vbext_RefKind;\nstruct __declspec(uuid(\"0002e17e-0000-0000-c000-000000000046\"))\n/* dual interface */ ignorethis;\nstruct __declspec(uuid(\"cdde3804-2064-11cf-867f-00aa005ff34a\"))\n/* dispinterface */ _dispReferences_Events;\nstruct /* coclass */ References;\n\n//\n// Smart pointer typedef declarations\n//\n\n_COM_SMARTPTR_TYPEDEF(Application, __uuidof(Application));\n_COM_SMARTPTR_TYPEDEF(_VBProjectsEvents, __uuidof(_VBProjectsEvents));\n_COM_SMARTPTR_TYPEDEF(_dispVBProjectsEvents, __uuidof(_dispVBProjectsEvents));\n_COM_SMARTPTR_TYPEDEF(_VBComponentsEvents, __uuidof(_VBComponentsEvents));\n_COM_SMARTPTR_TYPEDEF(_dispVBComponentsEvents, __uuidof(_dispVBComponentsEvents));\n_COM_SMARTPTR_TYPEDEF(_ReferencesEvents, __uuidof(_ReferencesEvents));\n_COM_SMARTPTR_TYPEDEF(_dispReferencesEvents, __uuidof(_dispReferencesEvents));\n_COM_SMARTPTR_TYPEDEF(_CommandBarControlEvents, __uuidof(_CommandBarControlEvents));\n_COM_SMARTPTR_TYPEDEF(_dispCommandBarControlEvents, __uuidof(_dispCommandBarControlEvents));\n_COM_SMARTPTR_TYPEDEF(_ProjectTemplate, __uuidof(_ProjectTemplate));\n_COM_SMARTPTR_TYPEDEF(Events, __uuidof(Events));\n_COM_SMARTPTR_TYPEDEF(_Component, __uuidof(_Component));\n_COM_SMARTPTR_TYPEDEF(SelectedComponents, __uuidof(SelectedComponents));\n_COM_SMARTPTR_TYPEDEF(_dispReferences_Events, __uuidof(_dispReferences_Events));\n_COM_SMARTPTR_TYPEDEF(testVBE, __uuidof(testVBE));\n_COM_SMARTPTR_TYPEDEF(Window, __uuidof(Window));\n_COM_SMARTPTR_TYPEDEF(_Windows_old, __uuidof(_Windows_old));\n_COM_SMARTPTR_TYPEDEF(_LinkedWindows, __uuidof(_LinkedWindows));\n_COM_SMARTPTR_TYPEDEF(_VBProject_Old, __uuidof(_VBProject_Old));\n_COM_SMARTPTR_TYPEDEF(_VBProject, __uuidof(_VBProject));\n_COM_SMARTPTR_TYPEDEF(_VBProjects_Old, __uuidof(_VBProjects_Old));\n_COM_SMARTPTR_TYPEDEF(_VBProjects, __uuidof(_VBProjects));\n_COM_SMARTPTR_TYPEDEF(_Components, __uuidof(_Components));\n_COM_SMARTPTR_TYPEDEF(_VBComponents_Old, __uuidof(_VBComponents_Old));\n_COM_SMARTPTR_TYPEDEF(_VBComponents, __uuidof(_VBComponents));\n_COM_SMARTPTR_TYPEDEF(_VBComponent_Old, __uuidof(_VBComponent_Old));\n_COM_SMARTPTR_TYPEDEF(_VBComponent, __uuidof(_VBComponent));\n_COM_SMARTPTR_TYPEDEF(Property, __uuidof(Property));\n_COM_SMARTPTR_TYPEDEF(_Properties, __uuidof(_Properties));\n_COM_SMARTPTR_TYPEDEF(AddIn, __uuidof(AddIn));\n_COM_SMARTPTR_TYPEDEF(_Windows, __uuidof(_Windows));\n_COM_SMARTPTR_TYPEDEF(_AddIns, __uuidof(_AddIns));\n_COM_SMARTPTR_TYPEDEF(_CodeModule, __uuidof(_CodeModule));\n_COM_SMARTPTR_TYPEDEF(_CodePanes, __uuidof(_CodePanes));\n_COM_SMARTPTR_TYPEDEF(_CodePane, __uuidof(_CodePane));\n_COM_SMARTPTR_TYPEDEF(ignorethis, __uuidof(ignorethis));\n_COM_SMARTPTR_TYPEDEF(_References, __uuidof(_References));\n\n//\n// Type library items\n//\n\nstruct __declspec(uuid(\"0002e158-0000-0000-c000-000000000046\"))\nApplication : IDispatch\n{\n //\n // Raw methods provided by interface\n //\n\n virtual HRESULT __stdcall get_Version (\n /*[out,retval]*/ BSTR * lpbstrReturn ) = 0;\n};\n\nenum __declspec(uuid(\"06a03650-2369-11ce-bfdc-08002b2b8cda\"))\nvbextFileTypes\n{\n vbextFileTypeForm = 0,\n vbextFileTypeModule = 1,\n vbextFileTypeClass = 2,\n vbextFileTypeProject = 3,\n vbextFileTypeExe = 4,\n vbextFileTypeFrx = 5,\n vbextFileTypeRes = 6,\n vbextFileTypeUserControl = 7,\n vbextFileTypePropertyPage = 8,\n vbextFileTypeDocObject = 9,\n vbextFileTypeBinary = 10,\n vbextFileTypeGroupProject = 11,\n vbextFileTypeDesigners = 12\n};\n\nenum __declspec(uuid(\"be39f3db-1b13-11d0-887f-00a0c90f2744\"))\nvbext_WindowType\n{\n vbext_wt_CodeWindow = 0,\n vbext_wt_Designer = 1,\n vbext_wt_Browser = 2,\n vbext_wt_Watch = 3,\n vbext_wt_Locals = 4,\n vbext_wt_Immediate = 5,\n vbext_wt_ProjectWindow = 6,\n vbext_wt_PropertyWindow = 7,\n vbext_wt_Find = 8,\n vbext_wt_FindReplace = 9,\n vbext_wt_Toolbox = 10,\n vbext_wt_LinkedWindowFrame = 11,\n vbext_wt_MainWindow = 12,\n vbext_wt_ToolWindow = 15\n};\n\nenum __declspec(uuid(\"be39f3dc-1b13-11d0-887f-00a0c90f2744\"))\nvbext_WindowState\n{\n vbext_ws_Normal = 0,\n vbext_ws_Minimize = 1,\n vbext_ws_Maximize = 2\n};\n\nstruct __declspec(uuid(\"0002e185-0000-0000-c000-000000000046\"))\nWindows;\n // [ default ] interface _Windows\n\nstruct __declspec(uuid(\"0002e187-0000-0000-c000-000000000046\"))\nLinkedWindows;\n // [ default ] interface _LinkedWindows\n\nstruct __declspec(uuid(\"0002e113-0000-0000-c000-000000000046\"))\n_VBProjectsEvents : IUnknown\n{};\n\nstruct __declspec(uuid(\"0002e103-0000-0000-c000-000000000046\"))\n_dispVBProjectsEvents : IDispatch\n{};\n\nstruct __declspec(uuid(\"0002e115-0000-0000-c000-000000000046\"))\n_VBComponentsEvents : IUnknown\n{};\n\nstruct __declspec(uuid(\"0002e116-0000-0000-c000-000000000046\"))\n_dispVBComponentsEvents : IDispatch\n{};\n\nstruct __declspec(uuid(\"0002e11a-0000-0000-c000-000000000046\"))\n_ReferencesEvents : IUnknown\n{};\n\nstruct __declspec(uuid(\"0002e118-0000-0000-c000-000000000046\"))\n_dispReferencesEvents : IDispatch\n{};\n\nstruct __declspec(uuid(\"0002e119-0000-0000-c000-000000000046\"))\nReferencesEvents;\n // [ default ] interface _ReferencesEvents\n // [ default, source ] dispinterface _dispReferencesEvents\n\nstruct __declspec(uuid(\"0002e130-0000-0000-c000-000000000046\"))\n_CommandBarControlEvents : IUnknown\n{};\n\nstruct __declspec(uuid(\"0002e131-0000-0000-c000-000000000046\"))\n_dispCommandBarControlEvents : IDispatch\n{};\n\nstruct __declspec(uuid(\"0002e132-0000-0000-c000-000000000046\"))\nCommandBarEvents;\n // [ default ] interface _CommandBarControlEvents\n // [ default, source ] dispinterface _dispCommandBarControlEvents\n\nstruct __declspec(uuid(\"0002e159-0000-0000-c000-000000000046\"))\n_ProjectTemplate : IDispatch\n{\n //\n // Raw methods provided by interface\n //\n\n virtual HRESULT __stdcall get_Application (\n /*[out,retval]*/ struct Application * * lppaReturn ) = 0;\n virtual HRESULT __stdcall get_Parent (\n /*[out,retval]*/ struct Application * * lppaReturn ) = 0;\n};\n\nstruct __declspec(uuid(\"32cdf9e0-1602-11ce-bfdc-08002b2b8cda\"))\nProjectTemplate;\n // [ default ] interface _ProjectTemplate\n\nenum __declspec(uuid(\"ffcf3247-debf-11d1-baff-00c04fb6c4a6\"))\nvbext_ProjectType\n{\n vbext_pt_HostProject = 100,\n vbext_pt_StandAlone = 101\n};\n\nenum __declspec(uuid(\"0002e129-0000-0000-c000-000000000046\"))\nvbext_ProjectProtection\n{\n vbext_pp_none = 0,\n vbext_pp_locked = 1\n};\n\nenum __declspec(uuid(\"be39f3d2-1b13-11d0-887f-00a0c90f2744\"))\nvbext_VBAMode\n{\n vbext_vm_Run = 0,\n vbext_vm_Break = 1,\n vbext_vm_Design = 2\n};\n\nstruct __declspec(uuid(\"0002e169-0000-0000-c000-000000000046\"))\nVBProject;\n // [ default ] interface _VBProject\n\nstruct __declspec(uuid(\"0002e167-0000-0000-c000-000000000046\"))\nEvents : IDispatch\n{\n //\n // Raw methods provided by interface\n //\n\n virtual HRESULT __stdcall get_ReferencesEvents (\n /*[in]*/ struct _VBProject * VBProject,\n /*[out,retval]*/ struct _ReferencesEvents * * prceNew ) = 0;\n virtual HRESULT __stdcall get_CommandBarEvents (\n /*[in]*/ IDispatch * CommandBarControl,\n /*[out,retval]*/ struct _CommandBarControlEvents * * prceNew ) = 0;\n};\n\nstruct __declspec(uuid(\"0002e101-0000-0000-c000-000000000046\"))\nVBProjects;\n // [ default ] interface _VBProjects\n\nenum __declspec(uuid(\"be39f3d5-1b13-11d0-887f-00a0c90f2744\"))\nvbext_ComponentType\n{\n vbext_ct_StdModule = 1,\n vbext_ct_ClassModule = 2,\n vbext_ct_MSForm = 3,\n vbext_ct_ActiveXDesigner = 11,\n vbext_ct_Document = 100\n};\n\nstruct __declspec(uuid(\"be39f3d6-1b13-11d0-887f-00a0c90f2744\"))\nComponents;\n // [ default ] interface _Components\n\nstruct __declspec(uuid(\"be39f3d7-1b13-11d0-887f-00a0c90f2744\"))\nVBComponents;\n // [ default ] interface _VBComponents\n\nstruct __declspec(uuid(\"0002e163-0000-0000-c000-000000000046\"))\n_Component : IDispatch\n{\n //\n // Raw methods provided by interface\n //\n\n virtual HRESULT __stdcall get_Application (\n /*[out,retval]*/ struct Application * * lppaReturn ) = 0;\n virtual HRESULT __stdcall get_Parent (\n /*[out,retval]*/ struct _Components * * lppcReturn ) = 0;\n virtual HRESULT __stdcall get_IsDirty (\n /*[out,retval]*/ VARIANT_BOOL * lpfReturn ) = 0;\n virtual HRESULT __stdcall put_IsDirty (\n /*[in]*/ VARIANT_BOOL lpfReturn ) = 0;\n virtual HRESULT __stdcall get_Name (\n /*[out,retval]*/ BSTR * pbstrReturn ) = 0;\n virtual HRESULT __stdcall put_Name (\n /*[in]*/ BSTR pbstrReturn ) = 0;\n};\n\nstruct __declspec(uuid(\"be39f3d8-1b13-11d0-887f-00a0c90f2744\"))\nComponent;\n // [ default ] interface _Component\n\nstruct __declspec(uuid(\"be39f3d4-1b13-11d0-887f-00a0c90f2744\"))\nSelectedComponents : IDispatch\n{\n //\n // Raw methods provided by interface\n //\n\n virtual HRESULT __stdcall Item (\n /*[in]*/ int index,\n /*[out,retval]*/ struct _Component * * lppcReturn ) = 0;\n virtual HRESULT __stdcall get_Application (\n /*[out,retval]*/ struct Application * * lppaReturn ) = 0;\n virtual HRESULT __stdcall get_Parent (\n /*[out,retval]*/ struct _VBProject * * lppptReturn ) = 0;\n virtual HRESULT __stdcall get_Count (\n /*[out,retval]*/ long * lplReturn ) = 0;\n virtual HRESULT __stdcall _NewEnum (\n /*[out,retval]*/ IUnknown * * lppiuReturn ) = 0;\n};\n\nstruct __declspec(uuid(\"be39f3da-1b13-11d0-887f-00a0c90f2744\"))\nVBComponent;\n // [ default ] interface _VBComponent\n\nstruct __declspec(uuid(\"0002e18b-0000-0000-c000-000000000046\"))\nProperties;\n // [ default ] interface _Properties\n\nstruct __declspec(uuid(\"da936b63-ac8b-11d1-b6e5-00a0c90f2744\"))\nAddins;\n // [ default ] interface _AddIns\n\nenum vbext_ProcKind\n{\n vbext_pk_Proc = 0,\n vbext_pk_Let = 1,\n vbext_pk_Set = 2,\n vbext_pk_Get = 3\n};\n\nstruct __declspec(uuid(\"0002e170-0000-0000-c000-000000000046\"))\nCodeModule;\n // [ default ] interface _CodeModule\n\nstruct __declspec(uuid(\"0002e174-0000-0000-c000-000000000046\"))\nCodePanes;\n // [ default ] interface _CodePanes\n\nenum vbext_CodePaneview\n{\n vbext_cv_ProcedureView = 0,\n vbext_cv_FullModuleView = 1\n};\n\nstruct __declspec(uuid(\"0002e178-0000-0000-c000-000000000046\"))\nCodePane;\n // [ default ] interface _CodePane\n\nenum vbext_RefKind\n{\n vbext_rk_TypeLib = 0,\n vbext_rk_Project = 1\n};\n\nstruct __declspec(uuid(\"cdde3804-2064-11cf-867f-00aa005ff34a\"))\n_dispReferences_Events : IDispatch\n{};\n\nstruct __declspec(uuid(\"0002e17c-0000-0000-c000-000000000046\"))\nReferences;\n // [ default ] interface _References\n // [ default, source ] dispinterface _dispReferences_Events\n\nstruct __declspec(uuid(\"0002e166-0000-0000-c000-000000000046\"))\ntestVBE : Application\n{\n //\n // Raw methods provided by interface\n //\n\n virtual HRESULT __stdcall get_VBProjects (\n /*[out,retval]*/ struct _VBProjects * * lppptReturn ) = 0;\n virtual HRESULT __stdcall get_CommandBars (\n /*[out,retval]*/ __missing_type__ * * ppcbs ) = 0;\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/185524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965047/" ]
185,533
<p>I've been looking at the <a href="http://www.getdropbox.com/install?os=mac" rel="noreferrer">DropBox</a> Mac client and I'm currently researching implementing a similar interface for a different service. </p> <p>How exactly do they interface with finder like this? I highly doubt these objects represented in the folder are actual documents downloaded on every load? They must dynamically download as they are needed. So how can you display these items in finder without having actual file system objects? </p> <p><strong>Does anyone know how this is achieved in Mac OS X?</strong> </p> <p>Or any pointer's to Apple API's or other open source projects that have a similar integration with finder? </p>
[ { "answer_id": 7158576, "author": "Wim Leers", "author_id": 80305, "author_profile": "https://Stackoverflow.com/users/80305", "pm_score": 2, "selected": false, "text": "inotify FSEvents django-storages" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/185533", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3415/" ]
185,536
<p>By default it seems that objects are drawn front to back. I am drawing a 2-D UI object and would like to create it back to front. For example I could create a white square first then create a slightly smaller black square on top of it thus creating a black pane with a white border. <a href="http://gpwiki.org/index.php/OpenGL:Tutorials:Tutorial_Framework:Ortho_and_Alpha" rel="noreferrer">This post</a> had some discussion on it and described this order as the "Painter's Algorithm" but ultimately the example they gave simply rendered the objects in reverse order to get the desired effect. I figure back to front (first objects go in back, subsequent objects get draw on top) rendering can be achieved via some transformation (gOrtho?) ?</p> <p>I will also mention that I am not interested in a solution using a wrapper library such as GLUT. </p> <p>I have also found that the default behavior on the Mac using the Cocoa NSOpenGLView appears to draw back to front, where as in windows I cannot get this behavior. The setup code in windows I am using is this:</p> <pre><code>glViewport (0, 0, wd, ht); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho (0.0f, wd, ht, 0.0f, -1.0f, 1.0f); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); </code></pre>
[ { "answer_id": 189915, "author": "AlanKley", "author_id": 8761, "author_profile": "https://Stackoverflow.com/users/8761", "pm_score": 6, "selected": true, "text": "glDepthFunc(GL_NEVER); // Ignore depth values (Z) to cause drawing bottom to top\n glEnable (GL_DEPTH_TEST); // Enables Depth Testing\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/185536", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8761/" ]
185,559
<p>I would like to remove the domain/computer information from a login id in C#. So, I would like to make either "Domain\me" or "Domain\me" just "me". I could always check for the existence of either, and use that as the index to start the substring...but I am looking for something more elegant and compact.</p> <p>Worse case scenario:</p> <pre><code>int startIndex = 0; int indexOfSlashesSingle = ResourceLoginName.IndexOf("\"); int indexOfSlashesDouble = ResourceLoginName.IndexOf("\\"); if (indexOfSlashesSingle != -1) startIndex = indexOfSlashesSingle; else startIndex = indexOfSlashesDouble; string shortName = ResourceLoginName.Substring(startIndex, ResourceLoginName.Length-1); </code></pre>
[ { "answer_id": 185572, "author": "BoltBait", "author_id": 20848, "author_profile": "https://Stackoverflow.com/users/20848", "pm_score": 2, "selected": false, "text": " string[] domainuser;\n string Auth_User = Request.ServerVariables[\"AUTH_USER\"].ToString().ToLower(); \n domainuser = Auth_User.Split('\\\\');\n" }, { "answer_id": 185577, "author": "Matt Dawdy", "author_id": 232, "author_profile": "https://Stackoverflow.com/users/232", "pm_score": 2, "selected": false, "text": " string theString = \"domain\\\\me\";\n theString = theString.Split(new char[] { '\\\\' })[theString.Split(new char[] { '\\\\' }).Length - 1];\n" }, { "answer_id": 185716, "author": "user26350", "author_id": 26350, "author_profile": "https://Stackoverflow.com/users/26350", "pm_score": 6, "selected": true, "text": "using System;\nusing System.Text.RegularExpressions;\npublic class MyClass\n{\n public static void Main()\n {\n string domainUser = Regex.Replace(\"domain\\\\user\",\".*\\\\\\\\(.*)\", \"$1\",RegexOptions.None);\n Console.WriteLine(domainUser); \n\n }\n\n}\n" }, { "answer_id": 185767, "author": "Jeffrey L Whitledge", "author_id": 10174, "author_profile": "https://Stackoverflow.com/users/10174", "pm_score": 5, "selected": false, "text": "string shortName = System.IO.Path.GetFileNameWithoutExtension(ResourceLoginName);\n" }, { "answer_id": 5859009, "author": "Drew Graham", "author_id": 734690, "author_profile": "https://Stackoverflow.com/users/734690", "pm_score": 3, "selected": false, "text": "string shortName = ResourceLoginName.Split('\\\\')[1]\n" }, { "answer_id": 25168681, "author": "anyhotcountry", "author_id": 3464789, "author_profile": "https://Stackoverflow.com/users/3464789", "pm_score": 2, "selected": false, "text": "var regex = @\"^(.*\\\\)?([^\\@]*)(@.*)?$\";\nvar user = Regex.Replace(\"domain\\\\user\", regex, \"$2\", RegexOptions.None);\nuser = Regex.Replace(\"user@domain.com\", regex, \"$2\", RegexOptions.None);\n" }, { "answer_id": 27909736, "author": "Derek Smalls", "author_id": 583426, "author_profile": "https://Stackoverflow.com/users/583426", "pm_score": 3, "selected": false, "text": "^(?<domain>.*)\\\\(?<username>.*)|(?<username>[^\\@]*)@(?<domain>.*)?$\n" }, { "answer_id": 31973361, "author": "Earl", "author_id": 1253140, "author_profile": "https://Stackoverflow.com/users/1253140", "pm_score": 2, "selected": false, "text": "Regex.Replace(User.Identity.Name,@\"^(?<domain>.*)\\\\(?<username>.*)|(?<username>[^\\@]*)@(?<domain>.*)?$\", \"${username}\", RegexOptions.None)\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/185559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18449/" ]
185,569
<p>This is an age-old question where given a table with attributes 'type', 'variety' and 'price', that you fetch the record with the minimum price for each type there is.</p> <p>In SQL, we can do <a href="http://www.xaprb.com/blog/2006/12/07/how-to-select-the-firstleastmax-row-per-group-in-sql/" rel="noreferrer">this</a> by:</p> <pre><code>select f.type, f.variety, f.price from ( select type, min(price) as minprice from table group by type ) as x inner join table as f on f.type = x.type and f.price = x.minprice;` </code></pre> <p>We could perhaps imitate this by:</p> <pre><code>minprices = Table.minimum(:price, :group =&gt; type) result = [] minprices.each_pair do |t, p| result &lt;&lt; Table.find(:first, :conditions =&gt; ["type = ? and price = ?", t, p]) end </code></pre> <p>Is there a better implementation than this?</p>
[ { "answer_id": 185647, "author": "Avdi", "author_id": 20487, "author_profile": "https://Stackoverflow.com/users/20487", "pm_score": 4, "selected": false, "text": "Table.minimum(:price, :group => :type)\n" }, { "answer_id": 186219, "author": "François Beausoleil", "author_id": 7355, "author_profile": "https://Stackoverflow.com/users/7355", "pm_score": 1, "selected": false, "text": "find_by_sql select_values data = ActiveRecord::Base.connection.select_values(\"\n SELECT f.type, f.variety, f.price\n FROM (SELECT type, MIN(price) AS minprice FROM table GROUP BY type ) AS x\n INNER JOIN table AS f ON f.type = x.type AND f.price = x.minprice\")\nputs data.inspect\n[[\"type\", \"variety\", 0.00]]\n" }, { "answer_id": 14881865, "author": "kikito", "author_id": 312586, "author_profile": "https://Stackoverflow.com/users/312586", "pm_score": 1, "selected": false, "text": "find_by_sql to_sql joins subquery_sql = Table.select([\"MIN(price) as price\", :type]).group(:type).to_sql\njoins_sql = \"INNER JOIN (#{subquery_sql}) as S\n ON table.type = S.type\n AND table.price = S.price\"\n\nTable.joins(joins_sql).where(<other conditions>).order(<your order>)\n INNER JOIN ... ON ... joins" }, { "answer_id": 61487434, "author": "Pat Newell", "author_id": 1081553, "author_profile": "https://Stackoverflow.com/users/1081553", "pm_score": 0, "selected": false, "text": "Security Price module MostRecentBy\n def self.included(klass)\n klass.scope :most_recent_by, ->(group_by_col, max_by_col) {\n from(\n <<~SQL\n (\n SELECT #{table_name}.*\n FROM #{table_name} JOIN (\n SELECT #{group_by_col}, MAX(#{max_by_col}) AS #{max_by_col}\n FROM #{table_name}\n GROUP BY #{group_by_col}\n ) latest\n ON #{table_name}.date = latest.#{max_by_col}\n AND #{table_name}.#{group_by_col} = latest.#{group_by_col}\n ) #{table_name}\n SQL\n )\n }\n end\nend\n\nclass Price < ActiveRecord::Base\n include MostRecentBy\n\n belongs_to :security\n\n scope :most_recent_by_security, -> { most_recent_by(:security_id, :date) }\nend\n\nclass Security < ActiveRecord::Base\n has_many :prices\n has_one :latest_price, \n -> { Price.most_recent_by_security },\n class_name: 'Price'\nend\n def index\n @resources = Security.all.includes(:latest_price)\n\n render json: @resources.as_json(include: :latest_price)\nend\n Security Load (4.4ms) SELECT \"securities\".* FROM \"securities\"\n Price Load (140.3ms) SELECT \"prices\".* FROM (\n SELECT prices.*\n FROM prices JOIN (\n SELECT security_id, MAX(date) AS date\n FROM prices\n GROUP BY security_id\n ) latest\n ON prices.date = latest.date\n AND prices.security_id = latest.security_id\n ) prices\n WHERE \"prices\".\"price_type\" = $1 AND \"prices\".\"security_id\" IN (...)\n" }, { "answer_id": 66361028, "author": "Youngjoon Choi", "author_id": 10555769, "author_profile": "https://Stackoverflow.com/users/10555769", "pm_score": 2, "selected": false, "text": "Table.group(:type).minimum(:price)\n {\n \"type1\"=>500.0,\n \"type2\"=>200.0\n}\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/185569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
185,573
<p>I couldn't really find this in Rails documentation but it seems like <strong>'mattr_accessor'</strong> is the <strong>Module</strong> corollary for <strong>'attr_accessor'</strong> (getter &amp; setter) in a normal Ruby <strong>class</strong>.</p> <p>Eg. in a class</p> <pre><code>class User attr_accessor :name def set_fullname @name = "#{self.first_name} #{self.last_name}" end end </code></pre> <p>Eg. in a module</p> <pre><code>module Authentication mattr_accessor :current_user def login @current_user = session[:user_id] || nil end end </code></pre> <p>This helper method is provided by <strong>ActiveSupport</strong>.</p>
[ { "answer_id": 185632, "author": "Avdi", "author_id": 20487, "author_profile": "https://Stackoverflow.com/users/20487", "pm_score": 9, "selected": true, "text": "mattr_accessor cattr_accessor reader _writer attr_accessor cattr/mattr_accessor module Config\n mattr_accessor :hostname\n mattr_accessor :admin_email\nend\n module Config\n def self.hostname\n @hostname\n end\n def self.hostname=(hostname)\n @hostname = hostname\n end\n def self.admin_email\n @admin_email\n end\n def self.admin_email=(admin_email)\n @admin_email = admin_email\n end\nend\n >> Config.hostname = \"example.com\"\n>> Config.admin_email = \"admin@example.com\"\n>> Config.hostname # => \"example.com\"\n>> Config.admin_email # => \"admin@example.com\"\n" }, { "answer_id": 188915, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 5, "selected": false, "text": "cattr_accessor mattr_accessor cattr_accessor cattr_accessor mattr_accessor @@mattr_in_module module MyModule\n mattr_accessor :mattr_in_module\nend\n\nclass MyClass\n include MyModule\n def self.get_mattr; @@mattr_in_module; end # directly access the class variable\nend\n\nMyModule.mattr_in_module = 'foo' # set it on the module\n=> \"foo\"\n\nMyClass.get_mattr # get it out of the class\n=> \"foo\"\n\nclass SecondClass\n include MyModule\n def self.get_mattr; @@mattr_in_module; end # again directly access the class variable in a different class\nend\n\nSecondClass.get_mattr # get it out of the OTHER class\n=> \"foo\"\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/185573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6048/" ]
185,575
<p>In bash the ampersand (&amp;) can be used to run a command in the background and return interactive control to the user before the command has finished running. Is there an equivalent method of doing this in Powershell?</p> <p>Example of usage in bash:</p> <pre><code> sleep 30 &amp; </code></pre>
[ { "answer_id": 6459716, "author": "Dustin Getz", "author_id": 20003, "author_profile": "https://Stackoverflow.com/users/20003", "pm_score": 5, "selected": false, "text": "ps2> start-job {start-sleep 20}\n PS> notepad $profile #edit init script -- added these lines\nfunction beep { write-host `a }\nfunction ajp { start powershell {ant java-platform|out-null;beep} } #new window, stderr only, beep when done\nfunction acjp { start powershell {ant clean java-platform|out-null;beep} }\nPS> . $profile #re-load profile script\nPS> ajp\n" }, { "answer_id": 11372785, "author": "Gian Marco", "author_id": 66629, "author_profile": "https://Stackoverflow.com/users/66629", "pm_score": 5, "selected": false, "text": "Start-Job Start-Job Start-Job { C:\\absolute\\path\\to\\command.exe --afileparameter C:\\absolute\\path\\to\\file.txt }\n" }, { "answer_id": 13729303, "author": "Bogdan Calmac", "author_id": 424353, "author_profile": "https://Stackoverflow.com/users/424353", "pm_score": 7, "selected": false, "text": "Start-Process -NoNewWindow ping google.com\n function bg() {Start-Process -NoNewWindow @args}\n bg ping google.com\n" }, { "answer_id": 53892094, "author": "Mariusz Pawelski", "author_id": 350384, "author_profile": "https://Stackoverflow.com/users/350384", "pm_score": 6, "selected": false, "text": "& & Receive-Job C:\\utils> ping google.com &\n\nId Name PSJobTypeName State HasMoreData Location Command\n-- ---- ------------- ----- ----------- -------- -------\n35 Job35 BackgroundJob Running True localhost Microsoft.PowerShell.M...\n\n\nC:\\utils> Receive-Job 35\n\nPinging google.com [172.217.16.14] with 32 bytes of data:\nReply from 172.217.16.14: bytes=32 time=11ms TTL=55\nReply from 172.217.16.14: bytes=32 time=11ms TTL=55\nReply from 172.217.16.14: bytes=32 time=10ms TTL=55\nReply from 172.217.16.14: bytes=32 time=10ms TTL=55\n\nPing statistics for 172.217.16.14:\n Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),\nApproximate round trip times in milli-seconds:\n Minimum = 10ms, Maximum = 11ms, Average = 10ms\nC:\\utils>\n & { } & & { cd .\\SomeDir\\; .\\SomeLongRunningOperation.bat; cd ..; } &\n & *-Job Copy-Item $foo $bar & Start-Job Get-Process -Name pwsh &\n Start-Job Start-Job -ScriptBlock {Get-Process -Name pwsh} Start-Job Job Start-Job does Receive-Job Remove-Job Start-Job $job = Get-Process -Name pwsh &\nReceive-Job $job\n NPM(K) PM(M) WS(M) CPU(s) Id SI ProcessName\n------ ----- ----- ------ -- -- -----------\n 0 0.00 221.16 25.90 6988 988 pwsh\n 0 0.00 140.12 29.87 14845 845 pwsh\n 0 0.00 85.51 0.91 19639 988 pwsh\n\n\n$job = Get-Process -Name pwsh &\nRemove-Job $job\n" }, { "answer_id": 56963061, "author": "js2010", "author_id": 6654942, "author_profile": "https://Stackoverflow.com/users/6654942", "pm_score": 3, "selected": false, "text": "$a = start-process -NoNewWindow powershell {timeout 10; 'done'} -PassThru\n $a | wait-process\n $a = start-process pwsh '-c',{start-sleep 5; 'done'} -PassThru \n $1 = start -n powershell pinger,comp001 -pa\n" }, { "answer_id": 57808376, "author": "bence of outer space", "author_id": 2667819, "author_profile": "https://Stackoverflow.com/users/2667819", "pm_score": 3, "selected": false, "text": "Start-Process powershell { sleep 30 }\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/185575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5769/" ]
185,584
<p>Does there exist a parser that generates an AST/parse tree at runtime? Kind of like a library that would accept a string of EBNF grammar or something analogous and spit out a data structure? </p> <ul> <li>I'm aware of antlr, jlex and their ilk. They generate source code which could do this. (like to skip the compile step)</li> <li>I'm aware of Boost::Spirit, which uses some black magic with C++ syntax to generate such things at execution time (definitely much closer to what I want, but I'm a wuss when it comes to C++. And it's still somewhat limiting, because your grammar is hardcoded)</li> <li>I'm not aware of anything in python or ruby, although a compiler compiler might very well be effective in such a language... </li> </ul> <p><p>Now I'm aware of parser combinators. (thanks, Jonas) And some libraries (thanks eliben) <p> incidentally, I also noticed <a href="http://en.wikipedia.org/wiki/Parsing_expression_grammar" rel="noreferrer">Parsing Expression Grammars</a> lately, which sounds cool were someone to implement it (they say Perl 6 will have it, but Perl evades my understanding)</p>
[ { "answer_id": 185662, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 2, "selected": false, "text": "{syntax: while (condition) do code}\nwhile (condition, code) => // actual execution\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/185584", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23648/" ]
185,594
<p>What data structure does the following declaration specify?</p> <pre><code> List&lt;ArrayList&gt;[] myArray; </code></pre> <p>I think it should declare an array where each element is a <code>List</code> (e.g., a <code>LinkedList</code> or an <code>ArrayList</code>) and require that each <code>List</code> contain <code>ArrayList</code> objects.</p> <p>My reasoning:</p> <pre><code> List&lt;String&gt; someList; // A List of String objects List&lt;ArrayList&gt; someList; // A List of ArrayList objects List&lt;ArrayList&gt;[] someListArray; // An array of List of ArrayList objects </code></pre> <p>After running some tests, I determined that it accepts an array where each element is an <code>LinkedList</code> object and does not specify what the LinkedList objects contain.</p> <p>So <code>List&lt;ArrayList&gt;</code> specifies what the <code>List</code> must contain, but <code>List&lt;ArrayList&gt;[]</code> specifies how the <code>List</code> must be implemented.</p> <p>Am I missing something?</p> <p>Here are my tests.</p> <pre><code>import java.util.ArrayList; import java.util.List; import java.util.LinkedList; public class Generics1 { public static void main(String[] args) { List&lt;ArrayList&gt;[] someListArray; someListArray = getArrayWhereEachElementIsAnArrayListObject(); // Why does this satisfy the declaration? //someListArray[0] =&gt; ArrayList object holding Strings someListArray= getArrayWhereEachElementIsAListOfArrayListObjects(); //someListArray[0] =&gt; ArrayList object holding ArrayList objects } public static List[] getArrayWhereEachElementIsAnArrayListObject() { List[] arrayOfLists = new ArrayList[2]; arrayOfLists[0] = getStringList(); arrayOfLists[1] = getIntegerList(); return arrayOfLists; } public static List[] getArrayWhereEachElementIsAListOfArrayListObjects() { List list1 = new ArrayList(); list1.add(getArrayList()); List list2 = new ArrayList(); list2.add(getArrayList()); List[] arrayOfListsOfArrayLists = new ArrayList[2]; arrayOfListsOfArrayLists[0] = list1; arrayOfListsOfArrayLists[1] = list2; return arrayOfListsOfArrayLists; } public static List getStringList() { List stringList= new ArrayList(); stringList.add("one"); stringList.add("two"); return stringList; } public static List getIntegerList() { List intList= new ArrayList(); intList.add(new Integer(1)); intList.add(new Integer(2)); return intList; } public static ArrayList getArrayList() { ArrayList arrayList = new ArrayList() ; return arrayList; } } </code></pre>
[ { "answer_id": 185619, "author": "Mark", "author_id": 26310, "author_profile": "https://Stackoverflow.com/users/26310", "pm_score": 3, "selected": false, "text": "List<List<ArrayList>> someListArray;\n" }, { "answer_id": 185627, "author": "Draemon", "author_id": 26334, "author_profile": "https://Stackoverflow.com/users/26334", "pm_score": 3, "selected": false, "text": "List<ArrayList>[] someListArray;\n array of ( List of ArrayList )\n array of List\n List<ArrayList>[] someListArray = (List<ArrayList>[]) new List[5];\n" }, { "answer_id": 185633, "author": "abarax", "author_id": 24390, "author_profile": "https://Stackoverflow.com/users/24390", "pm_score": 0, "selected": false, "text": "List<ArrayList>[] myArray = new ArrayList[2];\n\nmyArray[0] = new ArrayList<String>();\nmyArray[0].add(\"test 1\");\n\nmyArray[1] = new ArrayList<String>();\nmyArray[1].add(\"test 2\");\n\nprint myArray;\n {[\"test 1\"], [\"test 2\"]}\n List<ArrayList> myArray = new ArrayList<ArrayList>();\n" }, { "answer_id": 185753, "author": "anjanb", "author_id": 11142, "author_profile": "https://Stackoverflow.com/users/11142", "pm_score": 0, "selected": false, "text": "import java.util.*;\n\npublic class TestList {\n public static void main(String ... args) {\n class MySpecialLinkedList extends LinkedList<ArrayList<Integer>> {\n MySpecialLinkedList() {\n\n }\n\n public void foo() {\n\n }\n\n\n public Object clone()\n {\n return super.clone();\n }\n }\n\n List<ArrayList<Integer>> [] someListArray = new MySpecialLinkedList[10];\n for (int i = 0; i < 10; ++i) {\n someListArray[i] = new LinkedList<ArrayList<Integer>>();\n for (int j = 0; j < 20; ++j) {\n someListArray[i].add(new ArrayList<Integer>());\n for (int k = 0; k < 30; ++k) {\n someListArray[i].get(j).add(j);\n }\n }\n }\n }\n}\n" }, { "answer_id": 187269, "author": "Alex Miller", "author_id": 7671, "author_profile": "https://Stackoverflow.com/users/7671", "pm_score": 4, "selected": false, "text": "List<ArrayList>[] myArray\n List[] myArray\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/185594", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19685/" ]
185,606
<p>I wonder if this would be doable ? To insert an array into one field in the database.</p> <p>For instance I have a title, I want to have that title with only one id, but it's going to be bilingually used on the website.</p> <p>It feels a bit unnecessary to make another table to have their global ids and then another table with the actual titles linked to the table with the global id.</p> <p>I just want to have something like this</p> <pre><code>ID TITLE 1 Array("english title", "nederlandse titel"); </code></pre> <p>I'm using PHP/MSYQL, so if it would be doable could you please explain in these languages.</p> <p>Oh yeah I figured that I could format it funky and use the split function to turn it into an array again. But I wonder if I could just store it as an array right away, I case the user might type something with the same formatting (one out of a million)</p>
[ { "answer_id": 185625, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 5, "selected": true, "text": "$title = serialize($array);\n $title = unserialize($mysql_data);\n $title = base64_encode(serialize($array) );\n$title = unserialize(base64_decode($mysql_data) );\n" }, { "answer_id": 185639, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 2, "selected": false, "text": "LEFT JOIN COALESCE" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/185606", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18671/" ]
185,621
<p>Has anybody been successful in integrating the Enterprise Library v4.0 with SharePoint WSS 3.0? I created a very simple .ASPX page. It's only purpose will to be to connect to an Oracle database and display some values in a DropDownList. But right now, all it does is displays Hello World. I've added the necessary references and everything compiles fine. When I test the page, it displays Hello World. But once I add the using Microsoft.Practices.EnterprisesLibrary.Data, the page no longer works. I just get the standard Unknown Error message. Is there a log file I can check? </p> <p>I'm looking for any steps or tips that I can use to get this up and running. I use this Enterprise Library in all my ASP.NET applications and it works great. Trying to get this to work in SharePoint seems like a natural fit. But why does it seem so difficult? And why does there seem to be a lack of information?</p> <p>Anyways, thank you so much for any information anybody can provide.</p>
[ { "answer_id": 189353, "author": "Cruiser", "author_id": 16971, "author_profile": "https://Stackoverflow.com/users/16971", "pm_score": 1, "selected": false, "text": "<SharePoint><SafeMode> <system.web><compilation> <system.web><customErrors>" }, { "answer_id": 191055, "author": "DrZ", "author_id": 1082, "author_profile": "https://Stackoverflow.com/users/1082", "pm_score": 0, "selected": false, "text": " <add assembly=\"Microsoft.Practices.EnterpriseLibrary.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\"/>\n <add assembly=\"Microsoft.Practices.EnterpriseLibrary.Common, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\"/>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/185621", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1082/" ]
185,624
<p>I have a function that is declared and defined in a header file. This is a problem all by itself. When that function is not inlined, every translation unit that uses that header gets a copy of the function, and when they are linked together there are duplicated. I "fixed" that by making the function inline, but I'm afraid that this is a fragile solution because as far as I know, the compiler doesn't guarantee inlining, even when you specify the "inline" keyword. If this is not true, please correct me.</p> <p>Anyways, the real question is, what happens to static variables inside this function? How many copies do I end up with?</p>
[ { "answer_id": 189162, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 8, "selected": true, "text": "void doSomething()\n{\n static int value ;\n}\n inline void doSomething()\n{\n static int value ;\n}\n static void doSomething()\n{\n static int value ;\n}\n inline static void doSomething()\n{\n static int value ;\n}\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/185624", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13562/" ]
185,652
<p>I have a UIImageView and the objective is to scale it down proportionally by giving it either a height or width. </p> <pre><code>UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://farm4.static.flickr.com/3092/2915896504_a88b69c9de.jpg"]]]; UIImageView *imageView = [[UIImageView alloc] initWithImage:image]; //Add image view [self.view addSubview:imageView]; //set contentMode to scale aspect to fit imageView.contentMode = UIViewContentModeScaleAspectFit; //change width of frame CGRect frame = imageView.frame; frame.size.width = 100; imageView.frame = frame; </code></pre> <p>The image did get resized but the position is not at the top left. What is the best approach to scaling image/imageView and how do I correct the position?</p>
[ { "answer_id": 185788, "author": "user26359", "author_id": 26359, "author_profile": "https://Stackoverflow.com/users/26359", "pm_score": 0, "selected": false, "text": "image.center = [[imageView window] center];\n" }, { "answer_id": 185911, "author": "Chris Lundie", "author_id": 20685, "author_profile": "https://Stackoverflow.com/users/20685", "pm_score": 5, "selected": false, "text": "imageView image CGSize kMaxImageViewSize = {.width = 100, .height = 100};\nCGSize imageSize = image.size;\nCGFloat aspectRatio = imageSize.width / imageSize.height;\nCGRect frame = imageView.frame;\nif (kMaxImageViewSize.width / aspectRatio <= kMaxImageViewSize.height) \n{\n frame.size.width = kMaxImageViewSize.width;\n frame.size.height = frame.size.width / aspectRatio;\n} \nelse \n{\n frame.size.height = kMaxImageViewSize.height;\n frame.size.width = frame.size.height * aspectRatio;\n}\nimageView.frame = frame;\n" }, { "answer_id": 193219, "author": "kdbdallas", "author_id": 26728, "author_profile": "https://Stackoverflow.com/users/26728", "pm_score": -1, "selected": false, "text": "UIImage *thumbnail = [originalImage _imageScaledToSize:CGSizeMake(40.0, 40.0) interpolationQuality:1];\n" }, { "answer_id": 537697, "author": "Jane Sales", "author_id": 63994, "author_profile": "https://Stackoverflow.com/users/63994", "pm_score": 6, "selected": false, "text": "@interface UIImage (Extras)\n- (UIImage *)imageByScalingProportionallyToSize:(CGSize)targetSize;\n@end;\n @implementation UIImage (Extras)\n\n- (UIImage *)imageByScalingProportionallyToSize:(CGSize)targetSize {\n\n UIImage *sourceImage = self;\n UIImage *newImage = nil;\n\n CGSize imageSize = sourceImage.size;\n CGFloat width = imageSize.width;\n CGFloat height = imageSize.height;\n\n CGFloat targetWidth = targetSize.width;\n CGFloat targetHeight = targetSize.height;\n\n CGFloat scaleFactor = 0.0;\n CGFloat scaledWidth = targetWidth;\n CGFloat scaledHeight = targetHeight;\n\n CGPoint thumbnailPoint = CGPointMake(0.0,0.0);\n\n if (CGSizeEqualToSize(imageSize, targetSize) == NO) {\n\n CGFloat widthFactor = targetWidth / width;\n CGFloat heightFactor = targetHeight / height;\n\n if (widthFactor < heightFactor) \n scaleFactor = widthFactor;\n else\n scaleFactor = heightFactor;\n\n scaledWidth = width * scaleFactor;\n scaledHeight = height * scaleFactor;\n\n // center the image\n\n if (widthFactor < heightFactor) {\n thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5; \n } else if (widthFactor > heightFactor) {\n thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;\n }\n }\n\n\n // this is actually the interesting part:\n\n UIGraphicsBeginImageContext(targetSize);\n\n CGRect thumbnailRect = CGRectZero;\n thumbnailRect.origin = thumbnailPoint;\n thumbnailRect.size.width = scaledWidth;\n thumbnailRect.size.height = scaledHeight;\n\n [sourceImage drawInRect:thumbnailRect];\n\n newImage = UIGraphicsGetImageFromCurrentImageContext();\n UIGraphicsEndImageContext();\n\n if(newImage == nil) NSLog(@\"could not scale image\");\n\n\n return newImage ;\n}\n\n@end;\n" }, { "answer_id": 2300540, "author": "Ken Abrams", "author_id": 277445, "author_profile": "https://Stackoverflow.com/users/277445", "pm_score": 9, "selected": false, "text": " imageView.contentMode = .scaleAspectFit\n" }, { "answer_id": 6126467, "author": "neoneye", "author_id": 78336, "author_profile": "https://Stackoverflow.com/users/78336", "pm_score": 4, "selected": false, "text": "image = [UIImage imageWithCGImage:[image CGImage] scale:2.0 orientation:UIImageOrientationUp];\n" }, { "answer_id": 6362277, "author": "Nate Flink", "author_id": 396429, "author_profile": "https://Stackoverflow.com/users/396429", "pm_score": 4, "selected": false, "text": "UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@\"http://farm4.static.flickr.com/3092/2915896504_a88b69c9de.jpg\"]]];\nUIImageView *imageView = [[UIImageView alloc] initWithImage:image]; \n\n\n//set contentMode to scale aspect to fit\nimageView.contentMode = UIViewContentModeScaleAspectFit;\n\n//change width of frame\n//CGRect frame = imageView.frame;\n//frame.size.width = 100;\n//imageView.frame = frame;\n\n//original lines that deal with frame commented out, yo.\nimageView.frame = CGRectMake(10, 20, 60, 60);\n\n...\n\n//Add image view\n[myView addSubview:imageView]; \n" }, { "answer_id": 13815388, "author": "Li-chih Wu", "author_id": 1716918, "author_profile": "https://Stackoverflow.com/users/1716918", "pm_score": 5, "selected": false, "text": "imageView.contentMode = UIViewContentModeScaleAspectFill;\nimageView.clipsToBounds = YES;\n" }, { "answer_id": 20101282, "author": "Peter Kreinz", "author_id": 3013992, "author_profile": "https://Stackoverflow.com/users/3013992", "pm_score": 3, "selected": false, "text": "#import <Foundation/Foundation.h>\n\n@interface UIImageView (Scale)\n\n-(void) scaleAspectFit:(CGFloat) scaleFactor;\n\n@end\n #import \"UIImageView+Scale.h\"\n\n@implementation UIImageView (Scale)\n\n\n-(void) scaleAspectFit:(CGFloat) scaleFactor{\n\n self.contentScaleFactor = scaleFactor;\n self.transform = CGAffineTransformMakeScale(scaleFactor, scaleFactor);\n\n CGRect newRect = self.frame;\n newRect.origin.x = 0;\n newRect.origin.y = 0;\n self.frame = newRect;\n}\n\n@end\n" }, { "answer_id": 29425814, "author": "Jeffrey Neo", "author_id": 1856717, "author_profile": "https://Stackoverflow.com/users/1856717", "pm_score": 4, "selected": false, "text": "Aspect Fill Clip Subviews" }, { "answer_id": 32626996, "author": "Somir Saikia", "author_id": 2181124, "author_profile": "https://Stackoverflow.com/users/2181124", "pm_score": 3, "selected": false, "text": "self.imageViews.contentMode = UIViewContentMode.ScaleToFill\n" }, { "answer_id": 35621618, "author": "Avijit Nagare", "author_id": 4767429, "author_profile": "https://Stackoverflow.com/users/4767429", "pm_score": 2, "selected": false, "text": "if (image.size.height<self.imageCoverView.bounds.size.height && image.size.width<self.imageCoverView.bounds.size.width)\n{\n [self.profileImageView sizeToFit];\n self.profileImageView.contentMode =UIViewContentModeCenter\n}\nelse\n{\n self.profileImageView.contentMode =UIViewContentModeScaleAspectFit;\n}\n" }, { "answer_id": 35621788, "author": "Alessandro Ornano", "author_id": 1894067, "author_profile": "https://Stackoverflow.com/users/1894067", "pm_score": 1, "selected": false, "text": "// Resize UIImage\nfunc resizeImage(image:UIImage, scaleX:CGFloat,scaleY:CGFloat) ->UIImage {\n let size = CGSizeApplyAffineTransform(image.size, CGAffineTransformMakeScale(scaleX, scaleY))\n let hasAlpha = true\n let scale: CGFloat = 0.0 // Automatically use scale factor of main screen\n\n UIGraphicsBeginImageContextWithOptions(size, !hasAlpha, scale)\n image.drawInRect(CGRect(origin: CGPointZero, size: size))\n\n let scaledImage = UIGraphicsGetImageFromCurrentImageContext()\n UIGraphicsEndImageContext()\n return scaledImage\n}\n" }, { "answer_id": 39921707, "author": "vvamondes", "author_id": 1662751, "author_profile": "https://Stackoverflow.com/users/1662751", "pm_score": 4, "selected": false, "text": "imageView.contentMode = .ScaleAspectFill\nimageView.clipsToBounds = true;\n" }, { "answer_id": 41181245, "author": "P.J.Radadiya", "author_id": 5722289, "author_profile": "https://Stackoverflow.com/users/5722289", "pm_score": 4, "selected": false, "text": "UIimageview" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/185652", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1987/" ]
185,661
<p>I'd like to know if Flash/AS3 has any nice way to convert an AS3 'Date' object to/from rfc-850 timestamp format (as used by HTTP date and last-modified).</p> <p>This question is very similar to <a href="https://stackoverflow.com/questions/17017/how-do-i-parse-and-convert-datetimes-to-the-rfc-3339-date-time-format">this question about rfc 3339</a>, except it's specific to AS3 and rfc-850.</p> <p>RFC-850 is like: <code>Thu, 09 Oct 2008 01:09:43 GMT</code></p>
[ { "answer_id": 186080, "author": "aaaidan", "author_id": 26331, "author_profile": "https://Stackoverflow.com/users/26331", "pm_score": 3, "selected": true, "text": "Date Date Date() timezone Date /**\n * Converts an RFC string to a Date object.\n */\nfunction fromRFC802(date:String):Date {\n // Passing in an RFC802 date to the Date constructor causes flash\n // to conveniently ignore the \"GMT\" timezone at the end, and assumes\n // that it's in the Local timezone.\n // If we additionally convert it back to GMT, then we're sweet.\n\n var outputDate:Date = new Date(date);\n outputDate = new Date(outputDate.time - outputDate.getTimezoneOffset()*1000*60);\n return outputDate;\n}\n\n/** \n * Converts a Date object to an RFC802-formatted string (GMT/UTC).\n */\nfunction toRFC802 (date:Date):String {\n // example: Thu, 09 Oct 2008 01:09:43 GMT\n\n // Convert to GMT\n\n var output:String = \"\";\n\n // Day\n switch (date.dayUTC) {\n case 0: output += \"Sun\"; break;\n case 1: output += \"Mon\"; break;\n case 2: output += \"Tue\"; break;\n case 3: output += \"Wed\"; break;\n case 4: output += \"Thu\"; break;\n case 5: output += \"Fri\"; break;\n case 6: output += \"Sat\"; break;\n }\n\n output += \", \";\n\n // Date\n if (date.dateUTC < 10) {\n output += \"0\"; // leading zero\n }\n output += date.dateUTC + \" \";\n\n // Month\n switch(date.month) {\n case 0: output += \"Jan\"; break;\n case 1: output += \"Feb\"; break;\n case 2: output += \"Mar\"; break;\n case 3: output += \"Apr\"; break;\n case 4: output += \"May\"; break;\n case 5: output += \"Jun\"; break;\n case 6: output += \"Jul\"; break;\n case 7: output += \"Aug\"; break;\n case 8: output += \"Sep\"; break;\n case 9: output += \"Oct\"; break;\n case 10: output += \"Nov\"; break;\n case 11: output += \"Dec\"; break;\n }\n\n output += \" \";\n\n // Year\n output += date.fullYearUTC + \" \";\n\n // Hours\n if (date.hoursUTC < 10) {\n output += \"0\"; // leading zero\n }\n output += date.hoursUTC + \":\";\n\n // Minutes\n if (date.minutesUTC < 10) {\n output += \"0\"; // leading zero\n }\n output += date.minutesUTC + \":\";\n\n // Seconds\n if (date.seconds < 10) {\n output += \"0\"; // leading zero\n }\n output += date.secondsUTC + \" GMT\";\n\n return output;\n}\n\nvar dateString:String = \"Thu, 09 Oct 2008 01:09:43 GMT\";\n\ntrace(\"Round trip proof:\");\n\ntrace(\" RFC-802: \" + dateString);\ntrace(\"Date obj: \" + fromRFC802(dateString));\ntrace(\" RFC-802: \" + toRFC802(fromRFC802(dateString)));\ntrace(\"Date obj: \" + fromRFC802(toRFC802(fromRFC802(dateString))));\ntrace(\" RFC-802: \" + toRFC802(fromRFC802(toRFC802(fromRFC802(dateString)))));\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/185661", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26331/" ]
185,664
<p>I'm trying to create a user control that allows users to make something like the following:</p> <pre><code> &lt;uc1:MyControl id="controlThing" runat="server"&gt; &lt;uc1:BoundColumn id="column1" Column="Name" runat="server" /&gt; &lt;uc1:CheckBoxBoundColumn id="column2" Column="Selector" runat="server" /&gt; &lt;uc1:BoundColumn id="column3" Column="Description" runat="server" /&gt; ...etc &lt;/uc1:MyControl&gt; </code></pre> <p>There are only certain controls I would allow, in addition to the fact that you can have many of any type. I can picture this in XSD, but I'm not entirely sure for ASP.NET.</p> <p>My ASP.NET voodoo is drawing a blank right now.. any thoughts?</p>
[ { "answer_id": 185687, "author": "nyxtom", "author_id": 19753, "author_profile": "https://Stackoverflow.com/users/19753", "pm_score": 0, "selected": false, "text": "<mycontrol id=\"control1\" runat=\"server\">\n <templateitem id=\"bleh1\" runat=\"server\" />\n <templateitem id=\"bleh2\" runat=\"server\" />\n <templateitem id=\"bleh3\" runat=\"server\" />\n ..etc\n</mycontrol>\n" }, { "answer_id": 185869, "author": "sontek", "author_id": 17176, "author_profile": "https://Stackoverflow.com/users/17176", "pm_score": 3, "selected": true, "text": "[PersistenceMode(PersistenceMode.InnerProperty)]\npublic ListItem Items {\n get; set;\n}\n <cc1:MyControl runat=\"server\">\n <Items>\n <asp:ListItem Text=\"foo\" />\n </Items>\n</cc1:MyControl>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/185664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19753/" ]
185,680
<p>How do I define nested class in Java Script. </p> <p>Here is the code snippet I have:</p> <pre><code>objA = new TestA(); function TestB () { this.testPrint = function () { print ( " Inside testPrint " ); } } function TestA () { var myObjB = new TestB(); } </code></pre> <p>Now I am trying to access testPrint using objA</p> <pre><code>objA.myObjB.testPrint(); </code></pre> <p>But its giving error "objA has no properties"</p> <p>How can I access testB method using objA handler?</p>
[ { "answer_id": 185695, "author": "Aaron Maenpaa", "author_id": 2603, "author_profile": "https://Stackoverflow.com/users/2603", "pm_score": 2, "selected": false, "text": "var objA = {\n myObjB: {\n testPrint: function(){\n print(\"Inside test print\");\n }\n }\n};\n\nobjA.myObjB.testPrint();\n" }, { "answer_id": 185750, "author": "Sugendran", "author_id": 22466, "author_profile": "https://Stackoverflow.com/users/22466", "pm_score": 1, "selected": false, "text": "var myObjB = function(){\n this.testPrint = function () {\n print ( \" Inside testPrint \" );\n }\n}\n\nvar myObjA = new myObjB();\nmyObjA.prototype = {\n var1 : \"hello world\",\n test : function(){\n this.testPrint(this.var1);\n }\n}\n" }, { "answer_id": 185875, "author": "harley.333", "author_id": 26259, "author_profile": "https://Stackoverflow.com/users/26259", "pm_score": 1, "selected": false, "text": "function TestA() {\n this.myObjB = new TestB();\n}\nvar objA = new TestA();\nvar objB = objA.myObjB;\n" }, { "answer_id": 17379302, "author": "Lorenzo Polidori", "author_id": 885464, "author_profile": "https://Stackoverflow.com/users/885464", "pm_score": 4, "selected": false, "text": "var BobsGarage = BobsGarage || {}; // namespace\n\n/**\n * BobsGarage.Car\n * @constructor\n * @returns {BobsGarage.Car}\n */\nBobsGarage.Car = function() {\n\n /**\n * Engine\n * @constructor\n * @returns {Engine}\n */\n var Engine = function() {\n // definition of an engine\n };\n\n Engine.prototype.constructor = Engine;\n Engine.prototype.start = function() {\n console.log('start engine');\n };\n\n /**\n * Tank\n * @constructor\n * @returns {Tank}\n */\n var Tank = function() {\n // definition of a tank\n };\n\n Tank.prototype.constructor = Tank;\n Tank.prototype.fill = function() {\n console.log('fill tank');\n };\n\n this.engine = new Engine();\n this.tank = new Tank();\n};\n\nBobsGarage.Car.prototype.constructor = BobsGarage.Car;\n\n/**\n * BobsGarage.Ferrari\n * Derived from BobsGarage.Car\n * @constructor\n * @returns {BobsGarage.Ferrari}\n */\nBobsGarage.Ferrari = function() {\n BobsGarage.Car.call(this);\n};\nBobsGarage.Ferrari.prototype = Object.create(BobsGarage.Car.prototype);\nBobsGarage.Ferrari.prototype.constructor = BobsGarage.Ferrari;\nBobsGarage.Ferrari.prototype.speedUp = function() {\n console.log('speed up');\n};\n\n// Test it on the road\n\nvar car = new BobsGarage.Car();\ncar.tank.fill();\ncar.engine.start();\n\nvar ferrari = new BobsGarage.Ferrari();\nferrari.tank.fill();\nferrari.engine.start();\nferrari.speedUp();\n\n// var engine = new Engine(); // ReferenceError\n\nconsole.log(ferrari);\n BobsGarage.Car BobsGarage.Car" }, { "answer_id": 73005177, "author": "iNeobee", "author_id": 19561960, "author_profile": "https://Stackoverflow.com/users/19561960", "pm_score": 0, "selected": false, "text": "class A {\n constructor(classB) {\n this.ObjB = classB\n }\n}\n\nclass B {\n Hello() {\n console.log(\"Hello from class B\")\n }\n}\n\nlet objA = new A(new B())\n\nobjA.ObjB.Hello()" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/185680", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
185,681
<p>How to parse the DOM and determine what row is selected in an ASP.NET <code>ListView</code>? I'm able to interact with the DOM via the <code>HtmlElement</code> in Silverlight, but I have not been able to locate a property indicating the row is selected.</p> <p>For reference, this managed method works fine for an ASP.NET ListBox</p> <pre><code>var elm = HtmlPage.Document.GetElementById(ListBoxId); foreach (var childElm in elm.Children) { if (!((bool)childElm.GetProperty(&quot;Selected&quot;))) { continue; } } </code></pre>
[ { "answer_id": 185897, "author": "Bryant", "author_id": 10893, "author_profile": "https://Stackoverflow.com/users/10893", "pm_score": 0, "selected": false, "text": "HtmlElement elem = HtmlPage.Document.GetElementById(\"testSelect\");\nint index = Convert.ToInt32(elem.GetProperty(\"selectedIndex\"));\nvar options = (from c in elem.Children\n let he = c as HtmlElement\n where he.TagName == \"option\"\n select he).ToList();\n\noutput.Text = (string)options[index].GetProperty(\"innerText\");\n" }, { "answer_id": 256389, "author": "beckelmw", "author_id": 25335, "author_profile": "https://Stackoverflow.com/users/25335", "pm_score": 1, "selected": false, "text": "<tr id='selectedRow'>\n......\n</tr>\n\n$(document).ready(function() {\n $(\"#selectedRow\").click(function() {\n alert('This is the selected row');\n });\n\n});\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/185681", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21410/" ]
185,690
<p>I'm using the <a href="http://www.componentace.com/zlib_.NET.htm" rel="noreferrer">zlib.NET</a> library to try and inflate files that are compressed by zlib (on a Linux box, perhaps). Here's what I'm doing:</p> <pre><code>zlib.ZInputStream zinput = new zlib.ZInputStream(File.Open(path, FileMode.Open, FileAccess.Read)); while (stopByte != (data = zinput.ReadByte())) { // check data here } zinput.Close(); </code></pre> <p>The data bytes match the compressed data bytes, so I must be doing something wrong.</p>
[ { "answer_id": 185736, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": false, "text": "int Read(buffer, offset, length) int Read() length" }, { "answer_id": 185924, "author": "Brendan Kowitz", "author_id": 25767, "author_profile": "https://Stackoverflow.com/users/25767", "pm_score": 0, "selected": false, "text": "private void decompressFile(string inFile, string outFile)\n{\n System.IO.FileStream outFileStream = new System.IO.FileStream(outFile, System.IO.FileMode.Create);\n zlib.ZOutputStream outZStream = new zlib.ZOutputStream(outFileStream);\n System.IO.FileStream inFileStream = new System.IO.FileStream(inFile, System.IO.FileMode.Open); \n try\n {\n CopyStream(inFileStream, outZStream);\n }\n finally\n {\n outZStream.Close();\n outFileStream.Close();\n inFileStream.Close();\n }\n}\n" }, { "answer_id": 473570, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "public class FileCompressionUtility\n{\n public FileCompressionUtility()\n {\n }\n\n public static void CopyStream(System.IO.Stream input, System.IO.Stream output)\n {\n byte[] buffer = new byte[2000];\n int len;\n while ((len = input.Read(buffer, 0, 2000)) > 0)\n {\n output.Write(buffer, 0, len);\n }\n output.Flush();\n }\n\n public void compressFile(string inFile, string outFile)\n {\n System.IO.FileStream outFileStream = new System.IO.FileStream(outFile, System.IO.FileMode.Create);\n zlib.ZOutputStream outZStream = new zlib.ZOutputStream(outFileStream, zlib.zlibConst.Z_DEFAULT_COMPRESSION);\n System.IO.FileStream inFileStream = new System.IO.FileStream(inFile, System.IO.FileMode.Open);\n try\n {\n CopyStream(inFileStream, outZStream);\n }\n finally\n {\n outZStream.Close();\n outFileStream.Close();\n inFileStream.Close();\n }\n }\n\n public void uncompressFile(string inFile, string outFile)\n {\n int data = 0;\n int stopByte = -1;\n System.IO.FileStream outFileStream = new System.IO.FileStream(outFile, System.IO.FileMode.Create);\n zlib.ZInputStream inZStream = new zlib.ZInputStream(System.IO.File.Open(inFile, System.IO.FileMode.Open, System.IO.FileAccess.Read));\n while (stopByte != (data = inZStream.Read()))\n {\n byte _dataByte = (byte)data;\n outFileStream.WriteByte(_dataByte);\n }\n\n inZStream.Close();\n outFileStream.Close();\n }\n}\n" }, { "answer_id": 15363606, "author": "Scotty.NET", "author_id": 1123275, "author_profile": "https://Stackoverflow.com/users/1123275", "pm_score": 2, "selected": false, "text": "public static byte[] DecompressZlib(Stream source)\n{\n byte[] result = null;\n using (MemoryStream outStream = new MemoryStream())\n {\n using (InflaterInputStream inf = new InflaterInputStream(source))\n {\n inf.CopyTo(outStream);\n }\n result = outStream.ToArray();\n }\n return result;\n}\n" }, { "answer_id": 33855097, "author": "CodesInChaos", "author_id": 445517, "author_profile": "https://Stackoverflow.com/users/445517", "pm_score": 2, "selected": false, "text": "78 9C DeflateStream using(var input = File.OpenRead(...))\nusing(var output = File.Create(...))\n{\n // if there are additional headers before the zlib header, you can skip them:\n // input.Seek(xxx, SeekOrigin.Current);\n\n if (input.ReadByte() != 0x78 || input.ReadByte() != 0x9C)//zlib header\n throw new Exception(\"Incorrect zlib header\");\n\n using (var deflateStream = new DeflateStream(decryptedData, CompressionMode.Decompress, true))\n {\n deflateStream.CopyTo(output);\n }\n}\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/185690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3279/" ]
185,697
<p>Input: A positive integer K and a big text. The text can actually be viewed as word sequence. So we don't have to worry about how to break down it into word sequence.<br> Output: The most frequent K words in the text.</p> <p>My thinking is like this. </p> <ol> <li><p>use a Hash table to record all words' frequency while traverse the whole word sequence. In this phase, the key is "word" and the value is "word-frequency". This takes O(n) time. </p></li> <li><p>sort the (word, word-frequency) pair; and the key is "word-frequency". This takes O(n*lg(n)) time with normal sorting algorithm. </p></li> <li><p>After sorting, we just take the first K words. This takes O(K) time. </p></li> </ol> <p>To summarize, the total time is O(n+n<em>lg(n)+K), Since K is surely smaller than N, so it is actually O(n</em>lg(n)).</p> <p>We can improve this. Actually, we just want top K words. Other words' frequency is not concern for us. So, we can use "partial Heap sorting". For step 2) and 3), we don't just do sorting. Instead, we change it to be</p> <p>2') build a heap of (word, word-frequency) pair with "word-frequency" as key. It takes O(n) time to build a heap;</p> <p>3') extract top K words from the heap. Each extraction is O(lg(n)). So, total time is O(k*lg(n)).</p> <p>To summarize, this solution cost time O(n+k*lg(n)).</p> <p>This is just my thought. I haven't find out way to improve step 1).<br> I Hope some Information Retrieval experts can shed more light on this question.</p>
[ { "answer_id": 19460906, "author": "Shawn", "author_id": 165835, "author_profile": "https://Stackoverflow.com/users/165835", "pm_score": 0, "selected": false, "text": "List<Set<String>> Map<String, Integer> TreeMap<Integer, Set<String>> public class WordFrequencyCounter {\n private static final int WORD_SEPARATOR_MAX = 32; // UNICODE 0000-001F: control chars\n Map<String, MutableCounter> counters = new HashMap<String, MutableCounter>();\n List<Set<String>> reverseCounters = new ArrayList<Set<String>>();\n\n private static class MutableCounter {\n int i = 1;\n }\n\n public List<String> countMostFrequentWords(String text, int max) {\n int lastPosition = 0;\n int length = text.length();\n for (int i = 0; i < length; i++) {\n char c = text.charAt(i);\n if (c <= WORD_SEPARATOR_MAX) {\n if (i != lastPosition) {\n String word = text.substring(lastPosition, i);\n MutableCounter counter = counters.get(word);\n if (counter == null) {\n counter = new MutableCounter();\n counters.put(word, counter);\n } else {\n Set<String> strings = reverseCounters.get(counter.i);\n strings.remove(word);\n counter.i ++;\n }\n addToReverseLookup(counter.i, word);\n }\n lastPosition = i + 1;\n }\n }\n\n List<String> ret = new ArrayList<String>();\n int count = 0;\n for (int i = reverseCounters.size() - 1; i >= 0; i--) {\n Set<String> strings = reverseCounters.get(i);\n for (String s : strings) {\n ret.add(s);\n System.out.print(s + \":\" + i);\n count++;\n if (count == max) break;\n }\n if (count == max) break;\n }\n return ret;\n }\n\n private void addToReverseLookup(int count, String word) {\n while (count >= reverseCounters.size()) {\n reverseCounters.add(new HashSet<String>());\n }\n Set<String> strings = reverseCounters.get(count);\n strings.add(word);\n }\n\n}\n" }, { "answer_id": 22341665, "author": "Chihung Yu", "author_id": 1320928, "author_profile": "https://Stackoverflow.com/users/1320928", "pm_score": 6, "selected": false, "text": "var hash = {\n \"I\" : 13,\n \"like\" : 3,\n \"meow\" : 3,\n \"geek\" : 3,\n \"burger\" : 2,\n \"cat\" : 1,\n \"foo\" : 100,\n ...\n ...\n 0 1 2 3 100\n[[ ],[cat],[burger],[like, meow, geek],[]...[foo]]\n" }, { "answer_id": 33015973, "author": "ngLover", "author_id": 3062346, "author_profile": "https://Stackoverflow.com/users/3062346", "pm_score": 0, "selected": false, "text": " function strOccurence(str){\n var arr = str.split(\" \");\n var length = arr.length,temp = {},max; \n while(length--){\n if(temp[arr[length]] == undefined && arr[length].trim().length > 0)\n {\n temp[arr[length]] = 1;\n }\n else if(arr[length].trim().length > 0)\n {\n temp[arr[length]] = temp[arr[length]] + 1;\n\n }\n}\n console.log(temp);\n var max = [];\n for(i in temp)\n {\n max[temp[i]] = i;\n }\n console.log(max[max.length])\n //if you want second highest\n console.log(max[max.length - 2])\n}\n" }, { "answer_id": 36002610, "author": "craftsmannadeem", "author_id": 1709793, "author_profile": "https://Stackoverflow.com/users/1709793", "pm_score": 2, "selected": false, "text": "import java.util.ArrayList;\nimport java.util.Comparator;\nimport java.util.List;\nimport java.util.PriorityQueue;\n\nimport com.nadeem.app.dsa.adt.Trie;\nimport com.nadeem.app.dsa.adt.Trie.TrieEntry;\nimport com.nadeem.app.dsa.adt.impl.TrieImpl;\n\npublic class TopKFrequentItems {\n\nprivate int maxSize;\n\nprivate Trie trie = new TrieImpl();\nprivate PriorityQueue<TrieEntry> maxHeap;\n\npublic TopKFrequentItems(int k) {\n this.maxSize = k;\n this.maxHeap = new PriorityQueue<TrieEntry>(k, maxHeapComparator());\n}\n\nprivate Comparator<TrieEntry> maxHeapComparator() {\n return new Comparator<TrieEntry>() {\n @Override\n public int compare(TrieEntry o1, TrieEntry o2) {\n return o1.frequency - o2.frequency;\n } \n };\n}\n\npublic void add(String word) {\n this.trie.insert(word);\n}\n\npublic List<TopK> getItems() {\n\n for (TrieEntry trieEntry : this.trie.getAll()) {\n if (this.maxHeap.size() < this.maxSize) {\n this.maxHeap.add(trieEntry);\n } else if (this.maxHeap.peek().frequency < trieEntry.frequency) {\n this.maxHeap.remove();\n this.maxHeap.add(trieEntry);\n }\n }\n List<TopK> result = new ArrayList<TopK>();\n for (TrieEntry entry : this.maxHeap) {\n result.add(new TopK(entry));\n } \n return result;\n}\n\npublic static class TopK {\n public String item;\n public int frequency;\n\n public TopK(String item, int frequency) {\n this.item = item;\n this.frequency = frequency;\n }\n public TopK(TrieEntry entry) {\n this(entry.word, entry.frequency);\n }\n @Override\n public String toString() {\n return String.format(\"TopK [item=%s, frequency=%s]\", item, frequency);\n }\n @Override\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * result + frequency;\n result = prime * result + ((item == null) ? 0 : item.hashCode());\n return result;\n }\n @Override\n public boolean equals(Object obj) {\n if (this == obj)\n return true;\n if (obj == null)\n return false;\n if (getClass() != obj.getClass())\n return false;\n TopK other = (TopK) obj;\n if (frequency != other.frequency)\n return false;\n if (item == null) {\n if (other.item != null)\n return false;\n } else if (!item.equals(other.item))\n return false;\n return true;\n }\n\n} \n @Test\npublic void test() {\n TopKFrequentItems stream = new TopKFrequentItems(2);\n\n stream.add(\"hell\");\n stream.add(\"hello\");\n stream.add(\"hello\");\n stream.add(\"hello\");\n stream.add(\"hello\");\n stream.add(\"hello\");\n stream.add(\"hero\");\n stream.add(\"hero\");\n stream.add(\"hero\");\n stream.add(\"hello\");\n stream.add(\"hello\");\n stream.add(\"hello\");\n stream.add(\"home\");\n stream.add(\"go\");\n stream.add(\"go\");\n assertThat(stream.getItems()).hasSize(2).contains(new TopK(\"hero\", 3), new TopK(\"hello\", 8));\n}\n" }, { "answer_id": 39690987, "author": "Mohammad", "author_id": 5475941, "author_profile": "https://Stackoverflow.com/users/5475941", "pm_score": 0, "selected": false, "text": "import java.io.*;\nimport java.lang.reflect.Array;\nimport java.util.*;\n\npublic class TopKWordsTextFile {\n\n static class SortObject implements Comparable<SortObject>{\n\n private String key;\n private int value;\n\n public SortObject(String key, int value) {\n super();\n this.key = key;\n this.value = value;\n }\n\n @Override\n public int compareTo(SortObject o) {\n //descending order\n return o.value - this.value;\n }\n }\n\n\n public static void main(String[] args) {\n HashMap<String,Integer> hm = new HashMap<>();\n int k = 1;\n try {\n BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(\"words.in\")));\n\n String line;\n while ((line = br.readLine()) != null) {\n // process the line.\n //System.out.println(line);\n String[] tokens = line.split(\" \");\n for(int i=0; i<tokens.length; i++){\n if(hm.containsKey(tokens[i])){\n //If the key already exists\n Integer prev = hm.get(tokens[i]);\n hm.put(tokens[i],prev+1);\n }else{\n //If the key doesn't exist\n hm.put(tokens[i],1);\n }\n }\n }\n //Close the input\n br.close();\n //Print all words with their repetitions. You can use 3 for printing top 3 words.\n k = hm.size();\n // Get a set of the entries\n Set set = hm.entrySet();\n // Get an iterator\n Iterator i = set.iterator();\n int index = 0;\n // Display elements\n SortObject[] objects = new SortObject[hm.size()];\n while(i.hasNext()) {\n Map.Entry e = (Map.Entry)i.next();\n //System.out.print(\"Key: \"+e.getKey() + \": \");\n //System.out.println(\" Value: \"+e.getValue());\n String tempS = (String) e.getKey();\n int tempI = (int) e.getValue();\n objects[index] = new SortObject(tempS,tempI);\n index++;\n }\n System.out.println();\n //Sort the array\n Arrays.sort(objects);\n //Print top k\n for(int j=0; j<k; j++){\n System.out.println(objects[j].key+\":\"+objects[j].value);\n }\n\n\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n}\n" }, { "answer_id": 46003913, "author": "asad_nitp", "author_id": 5066038, "author_profile": "https://Stackoverflow.com/users/5066038", "pm_score": 0, "selected": false, "text": "**\n class Solution {\npublic:\nvector<int> topKFrequent(vector<int>& nums, int k) {\n\n unordered_map<int,int> map;\n for(int num : nums){\n map[num]++;\n }\n\n vector<int> res;\n // we use the priority queue, like the max-heap , we will keep (size-k) smallest elements in the queue\n // pair<first, second>: first is frequency, second is number \n priority_queue<pair<int,int>> pq; \n for(auto it = map.begin(); it != map.end(); it++){\n pq.push(make_pair(it->second, it->first));\n\n // onece the size bigger than size-k, we will pop the value, which is the top k frequent element value \n\n if(pq.size() > (int)map.size() - k){\n res.push_back(pq.top().second);\n pq.pop();\n }\n }\n return res;\n\n}\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/185697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26349/" ]
185,698
<p>I have a directory with several subdirectories with files.<br> How can I copy all files in the subdirectories to a new location?<br></p> <p><strong>Edit:</strong> I do not want to copy the directories, just the files...</p> <p>As this is still on XP, I chose the below solution:</p> <pre><code> for /D %S IN ("src\*.*") DO @COPY "%S\" "dest\" </code></pre> <p>Thanks!</p>
[ { "answer_id": 185703, "author": "Eric Tuttleman", "author_id": 25677, "author_profile": "https://Stackoverflow.com/users/25677", "pm_score": 2, "selected": false, "text": "XCOPY /E SrcDir\\*.* DestDir\\\n FOR /D %s IN (SrcDir\\*) DO @XCOPY /E %s DestDir\\%~ns\\\n" }, { "answer_id": 185715, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 2, "selected": false, "text": "robocopy \"c:\\source\" \"c:\\destination\" /E" }, { "answer_id": 185752, "author": "Mark Allen", "author_id": 5948, "author_profile": "https://Stackoverflow.com/users/5948", "pm_score": 1, "selected": false, "text": "dir /s /b \"yourSourceDirectoryTreeHere\" > filelist.txt\nfor /f %f in (filelist.txt) do @copy %f \"yourDestinationDirHere\"\n" }, { "answer_id": 185758, "author": "Nescio", "author_id": 14484, "author_profile": "https://Stackoverflow.com/users/14484", "pm_score": 0, "selected": false, "text": " for /D %S IN (\"src\\*.*\") DO @COPY \"%S\\\" \"dest\\\"\n" }, { "answer_id": 185785, "author": "Eric Tuttleman", "author_id": 25677, "author_profile": "https://Stackoverflow.com/users/25677", "pm_score": 4, "selected": true, "text": "for /F \"usebackq\" %s IN (`DIR /B /S /A-D SrcDir`) DO @(\n XCOPY %s DestDir\\%~nxs\n)\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/185698", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14484/" ]
185,747
<p>I am trying to convert an <code>int</code> into three <code>bytes</code> representing that <code>int</code> (big endian).</p> <p>I'm sure it has something to do with bit-wise and and bit shifting. But I have no idea how to go about doing it.</p> <p>For example:</p> <pre><code>int myInt; // some code byte b1, b2 , b3; // b1 is most significant, then b2 then b3. </code></pre> <p>*Note, I am aware that an int is 4 bytes and the three bytes have a chance of over/underflowing.</p>
[ { "answer_id": 185763, "author": "Paul Tomblin", "author_id": 3333, "author_profile": "https://Stackoverflow.com/users/3333", "pm_score": 2, "selected": false, "text": " byte b1 = (myInt & 0xff);\n myInt >>= 8;\n byte b2 = (myInt & 0xff);\n myInt >>= 8;\n byte b3 = (myInt & 0xff);\n" }, { "answer_id": 185766, "author": "mattlant", "author_id": 14642, "author_profile": "https://Stackoverflow.com/users/14642", "pm_score": 2, "selected": false, "text": "byte b1 = (myint >> 16) & 0xff;\nbyte b2 = (myint >> 8) & 0xff;\nbyte b3 = myint & 0xff;\n" }, { "answer_id": 185774, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 5, "selected": true, "text": "b3 = myInt & 0xFF;\n b2 = (myInt >> 8) & 0xFF;\n b1 = (myInt >> 16) & 0xFF;\n" }, { "answer_id": 1648743, "author": "akjain", "author_id": 108769, "author_profile": "https://Stackoverflow.com/users/108769", "pm_score": 2, "selected": false, "text": "int myInt = 1;\nbyte b1,b2,b3;\nb3 = (byte)(myInt & 0xFF);\nb2 = (byte)((myInt >> 8) & 0xFF);\nb1 = (byte)((myInt >> 16) & 0xFF);\nSystem.out.println(b1+\" \"+b2+\" \"+b3);\n" }, { "answer_id": 61238296, "author": "Marek Manduch", "author_id": 688820, "author_profile": "https://Stackoverflow.com/users/688820", "pm_score": 0, "selected": false, "text": " int myIntMultiplied = myInt * 256;\n\n byte b1, b2, b3;\n\n b3 = (byte) ((myIntMultiplied >> 8) & 0xFF);\n b2 = (byte) ((myIntMultiplied >> 16) & 0xFF);\n b1 = (byte) ((myIntMultiplied >> 24) & 0xFF);\n Integer.toBinaryString(myInt);\nInteger.toBinaryString(myIntMultiplied );\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/185747", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2598/" ]
185,778
<p>I am using trigger_error to "throw" errors in a custom class. My problem is that trigger_error prints out the line number where trigger_error was called. For example, given the following code:</p> <pre><code>01 &lt;?php 02 class Test { 03 function doAction() { 04 $this-&gt;doSubAction(); 05 } 06 07 function doSubAction() { 08 if(true) 09 trigger_error('Custom error', E_USER_WARNING); 10 } 11 } 12 13 $var = new Test(); 14 $var-&gt;doAction(); 15 ?&gt; </code></pre> <p>PHP will print out the following:</p> <blockquote> <p><strong>Warning:</strong> Custom error in <strong>test.php</strong> on line <strong>9</strong></p> </blockquote> <p>How would you make PHP return the line where the doAction() function was called (the method called outside the class, ignoring all calls made internally) as follows?</p> <blockquote> <p><strong>Warning:</strong> Custom error in <strong>test.php</strong> on line <strong>14</strong></p> </blockquote> <p><strong>Edit:</strong> Modified my example to be something a bit closer to what I'm trying to achieve.</p>
[ { "answer_id": 185817, "author": "Rob Howard", "author_id": 3528, "author_profile": "https://Stackoverflow.com/users/3528", "pm_score": 0, "selected": false, "text": "__LINE__ test(__LINE__)" }, { "answer_id": 1145375, "author": "Andrew Moore", "author_id": 26210, "author_profile": "https://Stackoverflow.com/users/26210", "pm_score": 2, "selected": true, "text": "ErrorHandler PEAR::Error" }, { "answer_id": 35304970, "author": "Borgboy", "author_id": 2708979, "author_profile": "https://Stackoverflow.com/users/2708979", "pm_score": 0, "selected": false, "text": "function localize_error_msg($msg, $level) {\n $level = (int)$level;\n $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, $level + 1)[$level];\n return $msg . \" in \" . $backtrace['file'] . \" on line \" . $backtrace['line'];\n}\n set_error_handler(function($errno, $errstr, $errfile, $errline) {\n if (preg_match('/on line \\d+$/', $errstr) === 1)\n die($errstr);\n else return false;\n}, E_USER_ERROR | E_USER_WARNING | E_USER_NOTICE);\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/185778", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26210/" ]
185,780
<p>I'm adding repeating events to a Cocoa app I'm working on. I have repeat every day and week fine because I can define these mathematically (3600*24*7 = 1 week). I use the following code to modify the date:</p> <pre><code>[NSDate dateWithTimeIntervalSinceNow:(3600*24*7*(weeks))] </code></pre> <p>I know how many months have passed since the event was repeated but I can't figure out how to make an NSDate object that represents 1 month/3 months/6 months/9 months into the future. Ideally I want the user to say repeat monthly starting Oct. 14 and it will repeat the 14th of every month.</p>
[ { "answer_id": 186104, "author": "mmalc", "author_id": 23233, "author_profile": "https://Stackoverflow.com/users/23233", "pm_score": 6, "selected": true, "text": "NSDate *today = [NSDate date];\n\nNSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];\n\nNSDateComponents *components = [[NSDateComponents alloc] init];\ncomponents.month = 1;\nNSDate *nextMonth = [gregorian dateByAddingComponents:components toDate:today options:0];\n[components release];\n\nNSDateComponents *nextMonthComponents = [gregorian components:NSYearCalendarUnit | NSMonthCalendarUnit fromDate:nextMonth];\n\nNSDateComponents *todayDayComponents = [gregorian components:NSDayCalendarUnit fromDate:today];\n\nnextMonthComponents.day = todayDayComponents.day;\nNSDate *nextMonthDay = [gregorian dateFromComponents:nextMonthComponents];\n\n[gregorian release];\n" }, { "answer_id": 2577000, "author": "Nick Forge", "author_id": 86046, "author_profile": "https://Stackoverflow.com/users/86046", "pm_score": 5, "selected": false, "text": "NSDateComponents *components = [[[NSDateComponents alloc] init] autorelease];\ncomponents.month = 1;\nNSDate *oneMonthFromNow = [[NSCalendar currentCalendar] dateByAddingComponents:components toDate:[NSDate date] options:0];\n components [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease] [NSCalendar currentCalendar]" }, { "answer_id": 11517039, "author": "Shanmugaraja G", "author_id": 663965, "author_profile": "https://Stackoverflow.com/users/663965", "pm_score": 0, "selected": false, "text": "NSDate *today = [NSDate date];\n\nNSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];\n\nNSDateComponents *components = [[NSDateComponents alloc] init];\ncomponents.month = 1;\nNSDate *nextMonth = [gregorian dateByAddingComponents:components toDate:today options:0];\n[components release];\n\nNSDateComponents *nextMonthComponents = [gregorian components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:nextMonth];\nNSDate *nextMonthDay = [gregorian dateFromComponents:nextMonthComponents];\n\n[gregorian release]; \n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/185780", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13069/" ]
185,781
<p>I read an interesting DailyWTF post today, <a href="http://thedailywtf.com/Articles/Out-of-All-the-Possible-Answers.aspx" rel="noreferrer">"Out of All The Possible Answers..."</a> and it interested me enough to dig up the original <a href="http://forums.thedailywtf.com/forums/t/10030.aspx" rel="noreferrer">forum post</a> where it was submitted. This got me thinking how I would solve this interesting problem - the original question is posed on <a href="http://projecteuler.net/index.php?section=problems&amp;id=5" rel="noreferrer">Project Euler</a> as: </p> <blockquote> <p>2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.</p> <p>What is the smallest number that is evenly divisible by all of the numbers from 1 to 20?</p> </blockquote> <p>To reform this as a programming question, <strong>how would you create a function that can find the Least Common Multiple for an arbitrary list of numbers?</strong></p> <p>I'm incredibly bad with pure math, despite my interest in programming, but I was able to solve this after a little Googling and some experimenting. I'm curious what other approaches SO users might take. If you're so inclined, post some code below, hopefully along with an explanation. Note that while I'm sure libraries exist to compute the GCD and LCM in various languages, I'm more interested in something that displays the logic more directly than calling a library function :-) </p> <p>I'm most familiar with Python, C, C++, and Perl, but any language you prefer is welcome. Bonus points for explaining the logic for other mathematically-challenged folks out there like myself.</p> <p><strong>EDIT</strong>: After submitting I did find this similar question <a href="https://stackoverflow.com/questions/147515">Least common multiple for 3 or more numbers</a> but it was answered with the same basic code I already figured out and there's no real explanation, so I felt this was different enough to leave open.</p>
[ { "answer_id": 185920, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 5, "selected": true, "text": "def RangeLCM(first, last):\n factors = range(first, last+1)\n for i in range(0, len(factors)):\n if factors[i] != 1:\n n = first + i\n for j in range(2*n, last+1, n):\n factors[j-first] = factors[j-first] / factors[i]\n return reduce(lambda a,b: a*b, factors, 1)\n enumerate reduce def RangeLCM2(last):\n factors = list(range(last+1))\n result = 1\n for n in range(last+1):\n if factors[n] > 1:\n result *= factors[n]\n for j in range(2*n, last+1, n):\n factors[j] //= factors[n]\n return result\n RangeEuclid >>> t=timeit.timeit\n>>> t('RangeLCM.RangeLCM(1, 20)', 'import RangeLCM')\n17.999292996735676\n>>> t('RangeLCM.RangeEuclid(1, 20)', 'import RangeLCM')\n11.199833288867922\n>>> t('RangeLCM.RangeLCM2(20)', 'import RangeLCM')\n14.256165588084514\n>>> t('RangeLCM.RangeLCM(1, 100)', 'import RangeLCM')\n93.34979585394194\n>>> t('RangeLCM.RangeEuclid(1, 100)', 'import RangeLCM')\n109.25695507389901\n>>> t('RangeLCM.RangeLCM2(100)', 'import RangeLCM')\n66.09684505991709\n" }, { "answer_id": 193572, "author": "yfeldblum", "author_id": 12349, "author_profile": "https://Stackoverflow.com/users/12349", "pm_score": 1, "selected": false, "text": "primes :: (Integral a) => [a]\n--implementation of primes is to be left for another day.\n\nprimeFactors :: (Integral a) => a -> [a]\nprimeFactors n = go n primes where\n go n ps@(p : pt) =\n if q < 1 then [] else\n if r == 0 then p : go q ps else\n go n pt\n where (q, r) = quotRem n p\n\nmultiFactors :: (Integral a) => a -> [(a, Int)]\nmultiFactors n = [ (head xs, length xs) | xs <- group $ primeFactors $ n ]\n\nmultiProduct :: (Integral a) => [(a, Int)] -> a\nmultiProduct xs = product $ map (uncurry (^)) $ xs\n\nmergeFactorsPairwise [] bs = bs\nmergeFactorsPairwise as [] = as\nmergeFactorsPairwise a@((an, am) : _) b@((bn, bm) : _) =\n case compare an bn of\n LT -> (head a) : mergeFactorsPairwise (tail a) b\n GT -> (head b) : mergeFactorsPairwise a (tail b)\n EQ -> (an, max am bm) : mergeFactorsPairwise (tail a) (tail b)\n\nwideLCM :: (Integral a) => [a] -> a\nwideLCM nums = multiProduct $ foldl mergeFactorsPairwise [] $ map multiFactors $ nums\n" }, { "answer_id": 194081, "author": "Kirk Strauser", "author_id": 32538, "author_profile": "https://Stackoverflow.com/users/32538", "pm_score": 0, "selected": false, "text": "#!/usr/bin/env python\n\nfrom operator import mul\n\ndef factor(n):\n factors = {}\n i = 2 \n while i <= n and n != 1:\n while n % i == 0:\n try:\n factors[i] += 1\n except KeyError:\n factors[i] = 1\n n = n / i\n i += 1\n return factors\n\nbase = {}\nfor i in range(2, 2000):\n for f, n in factor(i).items():\n try:\n base[f] = max(base[f], n)\n except KeyError:\n base[f] = n\n\nprint reduce(mul, [f**n for f, n in base.items()], 1)\n" }, { "answer_id": 196463, "author": "yfeldblum", "author_id": 12349, "author_profile": "https://Stackoverflow.com/users/12349", "pm_score": 3, "selected": false, "text": "wideLCM = foldl lcm 1\n" }, { "answer_id": 196472, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "\ndef lcm(a,b):\n gcd, tmp = a,b\n while tmp != 0:\n gcd,tmp = tmp, gcd % tmp\n return a*b/gcd\n \nreduce(lcm, range(1,21))\n" }, { "answer_id": 5600361, "author": "Bill Cressman", "author_id": 699306, "author_profile": "https://Stackoverflow.com/users/699306", "pm_score": 2, "selected": false, "text": "print \"LCM of 4 and 5 = \".LCM(4,5).\"\\n\";\n\nsub LCM {\n my ($a,$b) = @_; \n my ($af,$bf) = (1,1); # The factors to apply to a & b\n\n # Loop and increase until A times its factor equals B times its factor\n while ($a*$af != $b*$bf) {\n if ($a*$af>$b*$bf) {$bf++} else {$af++};\n }\n return $a*$af;\n}\n" }, { "answer_id": 10648539, "author": "Michael Anderson", "author_id": 221955, "author_profile": "https://Stackoverflow.com/users/221955", "pm_score": 3, "selected": false, "text": "n p_1^a_1 * p_2^a_2 * ... p_k * a_k p_1^a_1 p_2^a_2 p_k^a_k 2^4 = 16 < 20\n3^2 = 9 < 20\n5^1 = 5 < 20\n7\n11\n13\n17\n19\n 2*2*2*2*3*3*5*7*11*13*17*19 = 232792560\n def lcm_upto(N):\n total = 1;\n foreach p in primes_less_than(N):\n x=1;\n while x*p <= N:\n x=x*p;\n total = total * x\n return total\n primes_less_than(N) import timeit\n\n\ndef RangeLCM2(last):\n factors = range(last+1)\n result = 1\n for n in range(last+1):\n if factors[n] > 1:\n result *= factors[n]\n for j in range(2*n, last+1, n):\n factors[j] /= factors[n]\n return result\n\n\ndef lcm(a,b):\n gcd, tmp = a,b\n while tmp != 0:\n gcd,tmp = tmp, gcd % tmp\n return a*b/gcd\n\ndef EuclidLCM(last):\n return reduce(lcm,range(1,last+1))\n\nprimes = [\n 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, \n 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, \n 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, \n 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, \n 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, \n 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, \n 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, \n 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, \n 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, \n 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, \n 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, \n 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, \n 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, \n 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, \n 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, \n 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, \n 947, 953, 967, 971, 977, 983, 991, 997 ]\n\ndef FastRangeLCM(last):\n total = 1\n for p in primes:\n if p>last:\n break\n x = 1\n while x*p <= last:\n x = x * p\n total = total * x\n return total\n\n\nprint RangeLCM2(20)\nprint EculidLCM(20)\nprint FastRangeLCM(20)\n\nprint timeit.Timer( 'RangeLCM2(20)', \"from __main__ import RangeLCM2\").timeit(number=10000)\nprint timeit.Timer( 'EuclidLCM(20)', \"from __main__ import EuclidLCM\" ).timeit(number=10000)\nprint timeit.Timer( 'FastRangeLCM(20)', \"from __main__ import FastRangeLCM\" ).timeit(number=10000)\n\nprint timeit.Timer( 'RangeLCM2(40)', \"from __main__ import RangeLCM2\").timeit(number=10000)\nprint timeit.Timer( 'EuclidLCM(40)', \"from __main__ import EuclidLCM\" ).timeit(number=10000)\nprint timeit.Timer( 'FastRangeLCM(40)', \"from __main__ import FastRangeLCM\" ).timeit(number=10000)\n\nprint timeit.Timer( 'RangeLCM2(60)', \"from __main__ import RangeLCM2\").timeit(number=10000)\nprint timeit.Timer( 'EuclidLCM(60)', \"from __main__ import EuclidLCM\" ).timeit(number=10000)\nprint timeit.Timer( 'FastRangeLCM(60)', \"from __main__ import FastRangeLCM\" ).timeit(number=10000)\n\nprint timeit.Timer( 'RangeLCM2(80)', \"from __main__ import RangeLCM2\").timeit(number=10000)\nprint timeit.Timer( 'EuclidLCM(80)', \"from __main__ import EuclidLCM\" ).timeit(number=10000)\nprint timeit.Timer( 'FastRangeLCM(80)', \"from __main__ import FastRangeLCM\" ).timeit(number=10000)\n\nprint timeit.Timer( 'RangeLCM2(100)', \"from __main__ import RangeLCM2\").timeit(number=10000)\nprint timeit.Timer( 'EuclidLCM(100)', \"from __main__ import EuclidLCM\" ).timeit(number=10000)\nprint timeit.Timer( 'FastRangeLCM(100)', \"from __main__ import FastRangeLCM\" ).timeit(number=10000)\n\nprint timeit.Timer( 'RangeLCM2(120)', \"from __main__ import RangeLCM2\").timeit(number=10000)\nprint timeit.Timer( 'EuclidLCM(120)', \"from __main__ import EuclidLCM\" ).timeit(number=10000)\nprint timeit.Timer( 'FastRangeLCM(120)', \"from __main__ import FastRangeLCM\" ).timeit(number=10000)\n\nprint timeit.Timer( 'RangeLCM2(140)', \"from __main__ import RangeLCM2\").timeit(number=10000)\nprint timeit.Timer( 'EuclidLCM(140)', \"from __main__ import EuclidLCM\" ).timeit(number=10000)\nprint timeit.Timer( 'FastRangeLCM(140)', \"from __main__ import FastRangeLCM\" ).timeit(number=10000)\n\nprint timeit.Timer( 'RangeLCM2(160)', \"from __main__ import RangeLCM2\").timeit(number=10000)\nprint timeit.Timer( 'EuclidLCM(160)', \"from __main__ import EuclidLCM\" ).timeit(number=10000)\nprint timeit.Timer( 'FastRangeLCM(160)', \"from __main__ import FastRangeLCM\" ).timeit(number=10000)\n" }, { "answer_id": 12992384, "author": "Charlie", "author_id": 1762129, "author_profile": "https://Stackoverflow.com/users/1762129", "pm_score": 2, "selected": false, "text": "listLCM xs = foldr (lcm) 1 xs\n *Main> listLCM [1..10]\n2520\n*Main> listLCM [1..2518]\n266595767785593803705412270464676976610857635334657316692669925537787454299898002207461915073508683963382517039456477669596355816643394386272505301040799324518447104528530927421506143709593427822789725553843015805207718967822166927846212504932185912903133106741373264004097225277236671818323343067283663297403663465952182060840140577104161874701374415384744438137266768019899449317336711720217025025587401208623105738783129308128750455016347481252967252000274360749033444720740958140380022607152873903454009665680092965785710950056851148623283267844109400949097830399398928766093150813869944897207026562740359330773453263501671059198376156051049807365826551680239328345262351788257964260307551699951892369982392731547941790155541082267235224332660060039217194224518623199770191736740074323689475195782613618695976005218868557150389117325747888623795360149879033894667051583457539872594336939497053549704686823966843769912686273810907202177232140876251886218209049469761186661055766628477277347438364188994340512556761831159033404181677107900519850780882430019800537370374545134183233280000\n" }, { "answer_id": 29588969, "author": "fixxxer", "author_id": 170005, "author_profile": "https://Stackoverflow.com/users/170005", "pm_score": 0, "selected": false, "text": "def gcd(a,b): return b and gcd(b, a % b) or a\ndef lcm(a,b): return a * b / gcd(a,b)\n\nn = 1\nfor i in xrange(1, 21):\n n = lcm(n, i)\n" }, { "answer_id": 29783687, "author": "Shazam", "author_id": 3546295, "author_profile": "https://Stackoverflow.com/users/3546295", "pm_score": 0, "selected": false, "text": "//least common multipe of a range of numbers\nfunction smallestCommons(arr) {\n arr = arr.sort();\n var scm = 1; \n for (var i = arr[0]; i<=arr[1]; i+=1) { \n scm = scd(scm, i); \n }\n return scm;\n}\n\n\n//smallest common denominator of two numbers (scd)\nfunction scd (a,b) {\n return a*b/gcd(a,b);\n}\n\n\n//greatest common denominator of two numbers (gcd)\nfunction gcd(a, b) {\n if (b === 0) { \n return a;\n } else {\n return gcd(b, a%b);\n }\n} \n\nsmallestCommons([1,20]);\n" }, { "answer_id": 39483016, "author": "Yup.", "author_id": 2038363, "author_profile": "https://Stackoverflow.com/users/2038363", "pm_score": 0, "selected": false, "text": "function smallestCommons(arr) {\n var min = Math.min(arr[0], arr[1]);\n var max = Math.max(arr[0], arr[1]);\n\n var smallestCommon = min * max;\n\n var doneCalc = 0;\n\n while (doneCalc === 0) {\n for (var i = min; i <= max; i++) {\n if (smallestCommon % i !== 0) {\n smallestCommon += max;\n doneCalc = 0;\n break;\n }\n else {\n doneCalc = 1;\n }\n }\n }\n\n return smallestCommon;\n}\n" }, { "answer_id": 51806618, "author": "NEURON", "author_id": 10093600, "author_profile": "https://Stackoverflow.com/users/10093600", "pm_score": 0, "selected": false, "text": "#include<stdio.h>\n int main(){\n int a,b,lcm=1,small,gcd=1,done=0,i,j,large=1,div=0;\n printf(\"Enter range\\n\");\n printf(\"From:\");\n scanf(\"%d\",&a);\n printf(\"To:\");\n scanf(\"%d\",&b);\n int n=b-a+1;\n int num[30];\n for(i=0;i<n;i++){\n num[i]=a+i;\n }\n //Finds LCM\n while(!done){\n for(i=0;i<n;i++){\n if(num[i]==1){\n done=1;continue;\n }\n done=0;\n break;\n }\n if(done){\n continue;\n }\n done=0;\n large=1;\n for(i=0;i<n;i++){\n if(num[i]>large){\n large=num[i];\n }\n }\n div=0;\n for(i=2;i<=large;i++){\n for(j=0;j<n;j++){\n if(num[j]%i==0){\n num[j]/=i;div=1;\n }\n continue;\n }\n if(div){\n lcm*=i;div=0;break;\n }\n }\n }\n done=0;\n //Finds GCD\n while(!done){\n small=num[0];\n for(i=0;i<n;i++){\n if(num[i]<small){\n small=num[i];\n }\n }\n div=0;\n for(i=2;i<=small;i++){\n for(j=0;j<n;j++){\n if(num[j]%i==0){\n div=1;continue;\n }\n div=0;break;\n }\n if(div){\n for(j=0;j<n;j++){\n num[j]/=i;\n }\n gcd*=i;div=0;break;\n }\n }\n if(i==small+1){\n done=1;\n }\n }\n printf(\"LCM = %d\\n\",lcm);\n printf(\"GCD = %d\\n\",gcd);\n return 0;\n}\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/185781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20840/" ]
185,804
<p>I created an app for a small business. Some of the employees in the office can not see the form correctly. The reason is they have their DPI setting set to above 96dpi. Does anybody know of a way to control this?</p> <p>For all of you who have experience with winforms apps, how do you control your form layout so that DPI does not affect the look of the application?</p>
[ { "answer_id": 202172, "author": "Ian Boyd", "author_id": 12597, "author_profile": "https://Stackoverflow.com/users/12597", "pm_score": 6, "selected": false, "text": "AutoScaleMode ScaleMode.Dpi CurrentDpiSetting / 96 Form.Scale() ScaleControl() ScaleControl ScaleControl() public class MyForm : Form\n{\n protected override void ScaleControl(SizeF factor, BoundsSpecified specified)\n {\n base.ScaleControl(factor, specified);\n Toolkit.ScaleListViewColumns(listView1, factor);\n }\n}\n\npublic class Toolkit \n{\n /// <summary>\n /// Scale the columns of a listview by the Width scale factor specified in factor\n /// </summary>\n /// <param name=\"listview\"></param>\n /// <param name=\"factor\"></param>\n /// <example>/*\n /// protected override void ScaleControl(SizeF factor, BoundsSpecified specified)\n /// {\n /// base.ScaleControl(factor, specified);\n /// \n /// //ListView columns are not automatically scaled with the ListView, so we\n /// //must do it manually\n /// Toolkit.ScaleListViewColumns(lvPermissions, factor);\n /// }\n ///</example>\n public static void ScaleListViewColumns(ListView listview, SizeF factor)\n {\n foreach (ColumnHeader column in listview.Columns)\n {\n column.Width = (int)Math.Round(column.Width * factor.Width);\n }\n }\n}\n ScaleControl() public class MyForm : Form\n{\n private SizeF currentScaleFactor = new SizeF(1f, 1f);\n\n protected override void ScaleControl(SizeF factor, BoundsSpecified specified)\n {\n base.ScaleControl(factor, specified);\n\n //Record the running scale factor used\n this.currentScaleFactor = new SizeF(\n this.currentScaleFactor.Width * factor.Width,\n this.currentScaleFactor.Height * factor.Height);\n\n Toolkit.ScaleListViewColumns(listView1, factor);\n }\n}\n 1.0 1.25 1.00 * 1.25 = 1.25 //scaling current factor by 125%\n 0.95 1.25 * 0.95 = 1.1875 //scaling current factor by 95%\n SizeF ScaleMode.Font (11,56) Point pt = new Point(11, 56);\ncontrol1.Location = pt;\n Point pt = new Point(\n (int)Math.Round(11.0*this.scaleFactor.Width),\n (int)Math.Round(56.0*this.scaleFactor.Height));\ncontrol1.Location = pt;\n Font f = new Font(\"Segoe UI\", 8, GraphicsUnit.Point);\n Font f = new Font(\"Segoe UI\", 8.0*this.scaleFactor.Width, GraphicsUnit.Point);\n Image i = new Icon(someIcon, new Size(32, 32)).ToBitmap();\n Image i = new Icon(someIcon, new Size(\n (int)Math.Round(32.0*this.scaleFactor.Width), \n (int)Math.Round(32.0*this.scaleFactor.Height))).ToBitmap();\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/185804", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21325/" ]
185,836
<p>Does anyone know if it possible to define the equivalent of a "java custom class loader" in .NET?</p> <p><strong>To give a little background:</strong></p> <p>I am in the process of developing a new programming language that targets the CLR, called "Liberty". One of the features of the language is its ability to define "type constructors", which are methods that are executed by the compiler at compile time and generate types as output. They are sort of a generalization of generics (the language does have normal generics in it), and allow code like this to be written (in "Liberty" syntax):</p> <pre><code>var t as tuple&lt;i as int, j as int, k as int&gt;; t.i = 2; t.j = 4; t.k = 5; </code></pre> <p>Where "tuple" is defined like so:</p> <pre><code>public type tuple(params variables as VariableDeclaration[]) as TypeDeclaration { //... } </code></pre> <p>In this particular example, the type constructor <code>tuple</code> provides something similar to anonymous types in VB and C#.</p> <p>However, unlike anonymous types, "tuples" have names and can be used inside public method signatures.</p> <p>This means that I need a way for the type that eventually ends up being emitted by the compiler to be shareable across multiple assemblies. For example, I want</p> <p><code>tuple&lt;x as int&gt;</code> defined in Assembly A to end up being the same type as <code>tuple&lt;x as int&gt;</code> defined in Assembly B.</p> <p>The problem with this, of course, is that Assembly A and Assembly B are going to be compiled at different times, which means they would both end up emitting their own incompatible versions of the tuple type.</p> <p>I looked into using some sort of "type erasure" to do this, so that I would have a shared library with a bunch of types like this (this is "Liberty" syntax):</p> <pre><code>class tuple&lt;T&gt; { public Field1 as T; } class tuple&lt;T, R&gt; { public Field2 as T; public Field2 as R; } </code></pre> <p>and then just redirect access from the i, j, and k tuple fields to <code>Field1</code>, <code>Field2</code>, and <code>Field3</code>.</p> <p>However that is not really a viable option. This would mean that at compile time <code>tuple&lt;x as int&gt;</code> and <code>tuple&lt;y as int&gt;</code> would end up being different types, while at runtime time they would be treated as the same type. That would cause many problems for things like equality and type identity. That is too leaky of an abstraction for my tastes. </p> <p>Other possible options would be to use "state bag objects". However, using a state bag would defeat the whole purpose of having support for "type constructors" in the language. The idea there is to enable "custom language extensions" to generate new types at compile time that the compiler can do static type checking with.</p> <p>In Java, this could be done using custom class loaders. Basically the code that uses tuple types could be emitted without actually defining the type on disk. A custom "class loader" could then be defined that would dynamically generate the tuple type at runtime. That would allow static type checking inside the compiler, and would unify the tuple types across compilation boundaries.</p> <p>Unfortunately, however, the CLR does not provide support for custom class loading. All loading in the CLR is done at the assembly level. It would be possible to define a separate assembly for each "constructed type", but that would very quickly lead to performance problems (having many assemblies with only one type in them would use too many resources).</p> <p><strong>So, what I want to know is:</strong></p> <p>Is it possible to simulate something like Java Class Loaders in .NET, where I can emit a reference to a non-existing type in and then dynamically generate a reference to that type at runtime before the code the needs to use it runs?</p> <p><strong>NOTE:</strong></p> <p>*I actually already know the answer to the question, which I provide as an answer below. However, it took me about 3 days of research, and quite a bit of IL hacking in order to come up with a solution. I figured it would be a good idea to document it here in case anyone else ran into the same problem. *</p>
[ { "answer_id": 185856, "author": "Scott Wisniewski", "author_id": 1737192, "author_profile": "https://Stackoverflow.com/users/1737192", "pm_score": 7, "selected": true, "text": "System.Reflection.Emit System.AppDomain Main System.AppDomain TypeResolve using System;\nusing System.Collections.Generic;\nusing System.Reflection;\nusing System.Reflection.Emit;\n\nnamespace SharedLib\n{\n public class Loader\n {\n private Loader(ModuleBuilder dynamicModule)\n {\n m_dynamicModule = dynamicModule;\n m_definedTypes = new HashSet<string>();\n }\n\n private static readonly Loader m_instance;\n private readonly ModuleBuilder m_dynamicModule;\n private readonly HashSet<string> m_definedTypes;\n\n static Loader()\n {\n var name = new AssemblyName(\"$Runtime\");\n var assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.Run);\n var module = assemblyBuilder.DefineDynamicModule(\"$Runtime\");\n m_instance = new Loader(module);\n AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);\n }\n\n static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)\n {\n if (args.Name == Instance.m_dynamicModule.Assembly.FullName)\n {\n return Instance.m_dynamicModule.Assembly;\n }\n else\n {\n return null;\n }\n }\n\n public static Loader Instance\n {\n get\n {\n return m_instance;\n }\n }\n\n public bool IsDefined(string name)\n {\n return m_definedTypes.Contains(name);\n }\n\n public TypeBuilder DefineType(string name)\n {\n //in a real system we would not expose the type builder.\n //instead a AST for the type would be passed in, and we would just create it.\n var type = m_dynamicModule.DefineType(name, TypeAttributes.Public);\n m_definedTypes.Add(name);\n return type;\n }\n }\n}\n .assembly extern $Runtime\n{\n .ver 0:0:0:0\n}\n.assembly extern SharedLib\n{\n .ver 1:0:0:0\n}\n .method privatescope specialname rtspecialname static \n void .cctor() cil managed\n{\n //generate any constructed types dynamically here...\n}\n tuple<i as int, j as int> tuple<x as double, y as double, z as double> class Tuple_i_j<T, R>\n{\n public T i;\n public R j;\n}\n\nclass Tuple_x_y_z<T, R, S>\n{\n public T x;\n public R y;\n public S z;\n}\n tuple<x as Foo> var loader = SharedLib.Loader.Instance;\nlock (loader)\n{\n if (! loader.IsDefined(\"$Tuple_i_j\"))\n {\n //create the type.\n var Tuple_i_j = loader.DefineType(\"$Tuple_i_j\");\n //define the generic parameters <T,R>\n var genericParams = Tuple_i_j.DefineGenericParameters(\"T\", \"R\");\n var T = genericParams[0];\n var R = genericParams[1];\n //define the field i\n var fieldX = Tuple_i_j.DefineField(\"i\", T, FieldAttributes.Public);\n //define the field j\n var fieldY = Tuple_i_j.DefineField(\"j\", R, FieldAttributes.Public);\n //create the default constructor.\n var constructor= Tuple_i_j.DefineDefaultConstructor(MethodAttributes.Public);\n\n //\"close\" the type so that it can be used by executing code.\n Tuple_i_j.CreateType();\n }\n}\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/185836", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1737192/" ]
185,844
<p>What is the best way to initialize a private, static data member in C++? I tried this in my header file, but it gives me weird linker errors:</p> <pre><code>class foo { private: static int i; }; int foo::i = 0; </code></pre> <p>I'm guessing this is because I can't initialize a private member from outside the class. So what's the best way to do this?</p>
[ { "answer_id": 185848, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 10, "selected": true, "text": "class foo\n{\n private:\n static int i;\n};\n int foo::i = 0;\n static int i bool char char8_t char16_t char32_t wchar_t short int long long long class foo\n{\n private:\n static int const i = 42;\n};\n" }, { "answer_id": 185863, "author": "Matt Curtis", "author_id": 17221, "author_profile": "https://Stackoverflow.com/users/17221", "pm_score": 7, "selected": false, "text": "class foo\n{\nprivate:\n static int i;\n};\n int foo::i = 0;\n foo::i extern int i int i class foo\n{\nprivate:\n static int i;\n const static int a = 42;\n};\n" }, { "answer_id": 185864, "author": "David Dibben", "author_id": 5022, "author_profile": "https://Stackoverflow.com/users/5022", "pm_score": 4, "selected": false, "text": "int foo::i = 0; \n" }, { "answer_id": 186042, "author": "Johann Gerell", "author_id": 6345, "author_profile": "https://Stackoverflow.com/users/6345", "pm_score": 5, "selected": false, "text": "int __declspec(selectany) class A\n{\n static B b;\n}\n\n__declspec(selectany) A::b;\n __declspec(selectany)" }, { "answer_id": 8772501, "author": "monkey0506", "author_id": 1136311, "author_profile": "https://Stackoverflow.com/users/1136311", "pm_score": 3, "selected": false, "text": "#ifndef FOO_H\n#define FOO_H\n#include \"bar.h\"\n\nclass foo\n{\nprivate:\n static bar i;\n};\n\nbar foo::i = VALUE;\n#endif\n" }, { "answer_id": 14057180, "author": "Joshua Clayton", "author_id": 1419731, "author_profile": "https://Stackoverflow.com/users/1419731", "pm_score": 5, "selected": false, "text": ".cpp #includes main() foo::i = VALUE; foo:i VALUE .cpp main() #define VALUE .cpp #include .cpp #include .cpp" }, { "answer_id": 15959493, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "class Foo\n {\n public:\n int GetMyStatic() const\n {\n return *MyStatic();\n }\n\n private:\n static int* MyStatic()\n {\n static int mStatic = 0;\n return &mStatic;\n }\n }\n" }, { "answer_id": 20858946, "author": "Alejadro Xalabarder", "author_id": 1191101, "author_profile": "https://Stackoverflow.com/users/1191101", "pm_score": 2, "selected": false, "text": "#include <stdio.h>\n\nclass Foo\n{\n public:\n\n int GetMyStaticValue () const { return MyStatic(); }\n int & GetMyStaticVar () { return MyStatic(); }\n static bool isMyStatic (int & num) { return & num == & MyStatic(); }\n\n private:\n\n static int & MyStatic ()\n {\n static int mStatic = 7;\n return mStatic;\n }\n};\n\nint main (int, char **)\n{\n Foo obj;\n\n printf (\"mystatic value %d\\n\", obj.GetMyStaticValue());\n obj.GetMyStaticVar () = 3;\n printf (\"mystatic value %d\\n\", obj.GetMyStaticValue());\n\n int valMyS = obj.GetMyStaticVar ();\n int & iPtr1 = obj.GetMyStaticVar ();\n int & iPtr2 = valMyS;\n\n printf (\"is my static %d %d\\n\", Foo::isMyStatic(iPtr1), Foo::isMyStatic(iPtr2));\n}\n mystatic value 7\nmystatic value 3\nis my static 1 0\n" }, { "answer_id": 21362729, "author": "andrew", "author_id": 1693143, "author_profile": "https://Stackoverflow.com/users/1693143", "pm_score": 2, "selected": false, "text": "#include <iostream>\n\nusing namespace std;\n\nclass A\n{\nprivate:\n static int v;\n};\n\nint A::v = 10; // possible initializing\n\nint main()\n{\nA a;\n//cout << A::v << endl; // no access because of private scope\nreturn 0;\n}\n\n// g++ privateStatic.cpp -o privateStatic && ./privateStatic\n" }, { "answer_id": 23831857, "author": "Arturo Ruiz Mañas", "author_id": 3595315, "author_profile": "https://Stackoverflow.com/users/3595315", "pm_score": 2, "selected": false, "text": "set_default() class foo\n{\n public:\n static void set_default(int);\n private:\n static int i;\n};\n\nvoid foo::set_default(int x) {\n i = x;\n}\n set_default(int x) static" }, { "answer_id": 27088552, "author": "Kris Kwiatkowski", "author_id": 4284117, "author_profile": "https://Stackoverflow.com/users/4284117", "pm_score": 4, "selected": false, "text": "class SomeClass {\n static std::list<string> _list;\n\n public:\n static const std::list<string>& getList() {\n struct Initializer {\n Initializer() {\n // Here you may want to put mutex\n _list.push_back(\"FIRST\");\n _list.push_back(\"SECOND\");\n ....\n }\n }\n static Initializer ListInitializationGuard;\n return _list;\n }\n};\n ListInitializationGuard SomeClass::getList() initialize _list getList _list _list getList()" }, { "answer_id": 39291737, "author": "corporateAbaper", "author_id": 2146694, "author_profile": "https://Stackoverflow.com/users/2146694", "pm_score": 0, "selected": false, "text": "//header file\n\nstruct MyStruct {\npublic:\n const std::unordered_map<std::string, uint32_t> str_to_int{\n { \"a\", 1 },\n { \"b\", 2 },\n ...\n { \"z\", 26 }\n };\n const std::unordered_map<int , std::string> int_to_str{\n { 1, \"a\" },\n { 2, \"b\" },\n ...\n { 26, \"z\" }\n };\n std::string some_string = \"justanotherstring\"; \n uint32_t some_int = 42;\n\n static MyStruct & Singleton() {\n static MyStruct instance;\n return instance;\n }\nprivate:\n MyStruct() {};\n};\n\n//Usage in cpp file\nint main(){\n std::cout<<MyStruct::Singleton().some_string<<std::endl;\n std::cout<<MyStruct::Singleton().some_int<<std::endl;\n return 0;\n}\n" }, { "answer_id": 39802056, "author": "Tyler Heers", "author_id": 4905767, "author_profile": "https://Stackoverflow.com/users/4905767", "pm_score": 1, "selected": false, "text": "template<typename T>\nType ClassName<T>::dataMemberName = initialValue;\n" }, { "answer_id": 45062055, "author": "Die in Sente", "author_id": 40756, "author_profile": "https://Stackoverflow.com/users/40756", "pm_score": 6, "selected": false, "text": "struct X\n{\n inline static int n = 1;\n};\n" }, { "answer_id": 46139631, "author": "no one special", "author_id": 5892157, "author_profile": "https://Stackoverflow.com/users/5892157", "pm_score": 3, "selected": false, "text": "class Foo\n{\n // int& getObjectInstance() const {\n static int& getObjectInstance() {\n static int object;\n return object;\n }\n\n void func() {\n int &object = getValueInstance();\n object += 5;\n }\n};\n" }, { "answer_id": 48337288, "author": "Ciro Santilli OurBigBook.com", "author_id": 895245, "author_profile": "https://Stackoverflow.com/users/895245", "pm_score": 4, "selected": false, "text": "#include <cassert>\n#include <vector>\n\n// Normally on the .hpp file.\nclass MyClass {\npublic:\n static std::vector<int> v, v2;\n static struct StaticConstructor {\n StaticConstructor() {\n v.push_back(1);\n v.push_back(2);\n v2.push_back(3);\n v2.push_back(4);\n }\n } _staticConstructor;\n};\n\n// Normally on the .cpp file.\nstd::vector<int> MyClass::v;\nstd::vector<int> MyClass::v2;\n// Must come after every static member.\nMyClass::StaticConstructor MyClass::_staticConstructor;\n\nint main() {\n assert(MyClass::v[0] == 1);\n assert(MyClass::v[1] == 2);\n assert(MyClass::v2[0] == 3);\n assert(MyClass::v2[1] == 4);\n}\n g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o main.out main.cpp\n./main.out\n constexpr #include <cassert>\n\n#include \"notmain.hpp\"\n\nint main() {\n // Both files see the same memory address.\n assert(&notmain_i == notmain_func());\n assert(notmain_i == 42);\n}\n #ifndef NOTMAIN_HPP\n#define NOTMAIN_HPP\n\ninline constexpr int notmain_i = 42;\n\nconst int* notmain_func();\n\n#endif\n #include \"notmain.hpp\"\n\nconst int* notmain_func() {\n return &notmain_i;\n}\n g++ -c -o notmain.o -std=c++17 -Wall -Wextra -pedantic notmain.cpp\ng++ -c -o main.o -std=c++17 -Wall -Wextra -pedantic main.cpp\ng++ -o main -std=c++17 -Wall -Wextra -pedantic main.o notmain.o\n./main\n" }, { "answer_id": 50846528, "author": "anatolyg", "author_id": 509868, "author_profile": "https://Stackoverflow.com/users/509868", "pm_score": 2, "selected": false, "text": "enum class foo\n{\n private:\n enum {i = 0}; // default type = int\n enum: int64_t {HUGE = 1000000000000}; // may specify another type\n};\n" }, { "answer_id": 69280007, "author": "cat", "author_id": 712124, "author_profile": "https://Stackoverflow.com/users/712124", "pm_score": 2, "selected": false, "text": "#ifndef Foo_h\n#define Foo_h\n\nclass Foo\n{\n static const int a = 42; // OK\n static const int b {7}; // OK\n //static int x = 42; // ISO C++ forbids in-class initialization of non-const static member 'Foo::x'\n //static int y {7}; // ISO C++ forbids in-class initialization of non-const static member 'Foo::x'\n static int x;\n static int y;\n int m = 42;\n int n {7};\n};\n\n// Foo::x = 42; // error: 'int Foo::x' is private\nint Foo::x = 42; // OK in Foo.h if included in only one *.cpp -> *.o file!\nint Foo::y {7}; // OK\n\n// int Foo::y {7}; // error: redefinition of 'int Foo::y'\n // ONLY if the compiler can see both declarations at the same time it, \n // OTHERWISE you get a linker error\n\n#endif // Foo_h\n // Foo::x = 42; // error: 'int Foo::x' is private, bad if Foo::X is public!\nint Foo::x = 42; // OK in Foo.h if included in only one *.cpp -> *.o file!\nint Foo::y {7}; // OK\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/185844", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2147/" ]
185,862
<p>I am starting my first independent for profit venture. I am having a hard time deciding what language to use. I want to write my app in Perl, but I don't think it will be simple enough to compile. If I don't write it in Perl I will write it in C++.</p> <p>The application will have many features, including <a href="http://www.wxwidgets.org/" rel="noreferrer">wxwidgets</a> interface, Deal with SDL, timers, some threading, and audio processing. The program itself will be somewhat complex, but not terribly large.</p> <p>So my question's are:</p> <ol> <li>Can PAR, Perl2exe, or equivalent compile more than a basic test cases?</li> <li>Speed, and compilation aside why should I use C++ over Perl?</li> </ol> <hr /> <p>Edit: Some of my project specifications.</p> <ul> <li>Multi Platform. I am expecting 50% or more of my users to own macs, with Most of the rest being Windows users. If possible I also want to support Linux since It is my everyday operating system.</li> <li>Since it's multi Platform I need a unified GUI creation tool. It needs to be able to use basic types, and allow me to create custom event handlers, and custom GUI objects.</li> <li>It needs audio processing. Read and play, wav's and/or mp3's. Also I will be using some custom algorithms to determine special properties of the audio files; things like tempo, patterns, and so on.</li> <li>I would like but don't require SDL/OpenGL support.</li> </ul> <p>Everything else is pretty mundane. Some different classes and containers. A few custom GUI controls.</p>
[ { "answer_id": 187707, "author": "Axeman", "author_id": 11289, "author_profile": "https://Stackoverflow.com/users/11289", "pm_score": 1, "selected": false, "text": "map" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/185862", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21204/" ]
185,883
<p>Using the Qt Visual studio integration, adding a new Qt class adds two separate moc.exe generated files - one for debug and one for release (and one for any other configuration currently existing). Yet the two eventual generated files seem to be identical.</p> <p>On the other hand when adding a UI class, the uic.exe generated files don't have this separation and are the same file for all configurations.</p> <p>Does anybody have an idea why there's a need for a separate moc file for every configuration? When is there a difference between the two?</p>
[ { "answer_id": 185925, "author": "David Dibben", "author_id": 5022, "author_profile": "https://Stackoverflow.com/users/5022", "pm_score": 3, "selected": false, "text": "class Test : public QObject\n{\n Q_OBJECT\npublic:\n Test(); \npublic slots:\n\n#ifndef DEBUG\n void Foo();\n#endif\n};\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/185883", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9611/" ]
185,893
<p>I have a production server running with the following flag: -<strong>XX:+HeapDumpOnOutOfMemoryError</strong></p> <p>Last night it generated a java-38942.hprof file when our server encountered a heap error. It turns out that the developers of the system knew of the flag but no way to get any useful information from it.</p> <p>Any ideas?</p>
[ { "answer_id": 185926, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 6, "selected": false, "text": "jhat -port 7401 -J-Xmx4G dump.hprof jhat" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/185893", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4960/" ]
185,899
<p>Recently I was asked this during a job interview. I was honest and said I knew how a symbolic link behaves and how to create one, but do not understand the use of a hard link and how it differs from a symbolic one.</p>
[ { "answer_id": 1531795, "author": "Adam Matan", "author_id": 51197, "author_profile": "https://Stackoverflow.com/users/51197", "pm_score": 9, "selected": false, "text": "$ printf Cat > foo\n$ printf Dog > bar\n $ ln foo foo-hard\n$ ln -s bar bar-soft\n ls -lrS\nlrwxr-xr-x 1 user staff 3 3 Apr 15:25 bar-soft -> bar\n-rw-r--r-- 2 user staff 4 3 Apr 15:25 foo-hard\n-rw-r--r-- 2 user staff 4 3 Apr 15:25 foo\n-rw-r--r-- 1 user staff 4 3 Apr 15:25 bar\n lrwxr-xr-x l rwx r-x r-x -rw-r--r-- - rw- r-- r-- -> $ mv foo foo-new\n$ cat foo-hard\nCat\n $ printf Dog >> foo\n$ cat foo-hard\nCatDog\n $ mv bar bar-new\n$ ls bar-soft\nbar-soft\n$ cat bar-soft \ncat: bar-soft: No such file or directory\n foo foo-hard bar bar-soft" }, { "answer_id": 8881100, "author": "ChandanK", "author_id": 1121065, "author_profile": "https://Stackoverflow.com/users/1121065", "pm_score": 2, "selected": false, "text": "f6 t2 f1 ./t2/f2 f6 f7 ./t2/f8 f6 $ find -L . -samefile f6 \n\n> ./f1\n> ./f6\n> ./f7\n> ./t2/f2\n> ./t2/f8\n $ find . -xdev -samefile f6\n\n> ./f6\n> ./f7\n> ./t2/f8\n -L -xdev" }, { "answer_id": 23422478, "author": "Prabhat Kumar Singh", "author_id": 2608019, "author_profile": "https://Stackoverflow.com/users/2608019", "pm_score": 6, "selected": false, "text": "ln -s Pathof_Target_file link link -> ./Target_file readlink link ls -l link lrwxrwxrwx unlink link ln Target_file link ls -i link Target_file rm -f link # find / -inum 517333 /home/bobbin/sync.sh\n/root/synchro\n" }, { "answer_id": 27366021, "author": "buydadip", "author_id": 4333347, "author_profile": "https://Stackoverflow.com/users/4333347", "pm_score": 5, "selected": false, "text": "echo \"111\" > a\nln a b\nln -s a c\n cat a --> 111\ncat b --> 111\ncat c --> 111\n rm a\ncat a --> No such file or directory\ncat b --> 111\ncat c --> No such file or directory\n" }, { "answer_id": 29786294, "author": "akivajgordon", "author_id": 2374361, "author_profile": "https://Stackoverflow.com/users/2374361", "pm_score": 9, "selected": false, "text": "myfile.txt $ echo 'Hello, World!' > myfile.txt\n my-hard-link myfile.txt myfile.txt $ ln myfile.txt my-hard-link\n my-soft-link myfile.txt myfile.txt $ ln -s myfile.txt my-soft-link\n myfile.txt my-hard-link my-soft-link" }, { "answer_id": 34454847, "author": "Sнаđошƒаӽ", "author_id": 3375713, "author_profile": "https://Stackoverflow.com/users/3375713", "pm_score": 3, "selected": false, "text": "X: \"C:\\alpha\\beta\\absLink\\gamma\\file\"\nLink: \"absLink\" maps to \"\\\\machineB\\share\"\nModified Path: \"\\\\machineB\\share\\gamma\\file\"\n X: C:\\alpha\\beta\\link\\gamma\\file\nLink: \"link\" maps to \"..\\..\\theta\"\nModified Path: \"C:\\alpha\\beta\\..\\..\\theta\\gamma\\file\"\nFinal Path: \"C:\\theta\\gamma\\file\"\n mklink /H Link_name target_path\n mklink /J link_name target_path\n" }, { "answer_id": 38429765, "author": "mc.robin", "author_id": 6581912, "author_profile": "https://Stackoverflow.com/users/6581912", "pm_score": 2, "selected": false, "text": "struct dentry{\n ino_t ino;\n char name[256];\n}\n struct inode{\n link_t nlink; \n ...\n}\n struct dentry{\n ino_t ino; /* such as 15 */\n char name[256]; /* \"1\" */\n} \n struct inode{ /* inode number 15 */\n link_t nlink; /* nlink = 1 */\n ...\n }\n struct dentry{\n ino_t ino; /* 15 */\n char name[256]; /* 100 */\n }\n struct inode{ /* inode numebr 15 */\n link_t nlink; /* nlink = 2 */\n ...\n }\n struct dentry{\n ino_t ino; /* such as 16 */\n char name[256]; /* \"200\" */\n }\n struct inode{ /* inode number 15 */ \n link_t nlink; /* nlink = 2 */\n ...\n }\n\n struct inode{ /* inode number 16 */\n link_t nlink; /* nlink = 1 */\n ...\n } /* the data of inode 16 maybe /1 or 1 */\n" }, { "answer_id": 47144661, "author": "themefield", "author_id": 2909851, "author_profile": "https://Stackoverflow.com/users/2909851", "pm_score": 0, "selected": false, "text": "Downloads sudo make install cp cp Downloads mv source" }, { "answer_id": 50467473, "author": "Matheus Santoro", "author_id": 8370192, "author_profile": "https://Stackoverflow.com/users/8370192", "pm_score": 2, "selected": false, "text": "ln -s /long/folder/name/on/long/path/file.txt /short/file.txt\n /short/file.txt $ ls -lh /myapp/dev/\ntotal 10G\n-rw-r--r-- 2 root root 10G May 22 12:09 application.bin\n ln /myapp/dev/application.bin /myapp/prd/application.bin /myapp/dev /myapp/prd" }, { "answer_id": 71396048, "author": "amd", "author_id": 1104402, "author_profile": "https://Stackoverflow.com/users/1104402", "pm_score": 2, "selected": false, "text": "* abc.com and def.com -> points to the IP 1.2.3.4\n* abc.com and def.com -> files in linux\n* IP -> inode in linux\n* By deleting the domain abc.com users still access your website through def.com or vice versa\n* Mutation through abc.com will affect def.com and vice verca\n * accessing abc.com will redirect to def.com as you've accessed def.com directly\n* removing the def.com domain will break the link abc.com\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/185899", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4960/" ]
185,934
<p>It appears that in PHP objects are passed by reference. Even assignment operators do not appear to be creating a copy of the Object.</p> <p>Here's a simple, contrived proof:</p> <pre><code>&lt;?php class A { public $b; } function set_b($obj) { $obj-&gt;b = "after"; } $a = new A(); $a-&gt;b = "before"; $c = $a; //i would especially expect this to create a copy. set_b($a); print $a-&gt;b; //i would expect this to show 'before' print $c-&gt;b; //i would ESPECIALLY expect this to show 'before' ?&gt; </code></pre> <p>In both print cases I am getting 'after'</p> <p>So, how do I pass <strong>$a</strong> to <strong><em>set_b()</em></strong> by value, not by reference?</p>
[ { "answer_id": 185938, "author": "Leo", "author_id": 20689, "author_profile": "https://Stackoverflow.com/users/20689", "pm_score": 4, "selected": false, "text": "$a = clone $b;\n" }, { "answer_id": 185939, "author": "Eran Galperin", "author_id": 10585, "author_profile": "https://Stackoverflow.com/users/10585", "pm_score": 9, "selected": true, "text": "$objectB = clone $objectA;\n" }, { "answer_id": 186008, "author": "yogman", "author_id": 24349, "author_profile": "https://Stackoverflow.com/users/24349", "pm_score": 7, "selected": false, "text": "$new_object = unserialize(serialize($your_object))" }, { "answer_id": 186191, "author": "Stanislav", "author_id": 21504, "author_profile": "https://Stackoverflow.com/users/21504", "pm_score": 5, "selected": false, "text": "class MyClass {\n private $someObject;\n\n public function __construct() {\n $this->someObject = new SomeClass();\n }\n\n public function __clone() {\n $this->someObject = clone $this->someObject;\n }\n\n}\n $bar = new MyClass();\n$foo = clone $bar;\n" }, { "answer_id": 19168638, "author": "zloctb", "author_id": 1673376, "author_profile": "https://Stackoverflow.com/users/1673376", "pm_score": 1, "selected": false, "text": "class Foo{\n\n private $run=10;\n public $foo=array(2,array(2,8));\n public function hoo(){return 5;}\n\n\n public function __clone(){\n\n $this->boo=function(){$this->hoo();};\n\n }\n}\n$obj=new Foo;\n\n$news= clone $obj;\nvar_dump($news->hoo());\n" }, { "answer_id": 21317602, "author": "Pyetro", "author_id": 3229228, "author_profile": "https://Stackoverflow.com/users/3229228", "pm_score": 1, "selected": false, "text": "class A {\n public $property;\n}\n\nfunction set_property($obj) {\n $obj->property = \"after\";\n var_dump($obj);\n}\n\n$a = new A();\n$a->property = \"before\";\n\n// Creates a new Object from $a. Like \"new A();\"\n$b = new $a;\n// Makes a Copy of var $a, not referenced.\n$c = clone $a;\n\nset_property($a);\n// object(A)#1 (1) { [\"property\"]=> string(5) \"after\" }\n\nvar_dump($a); // Because function set_property get by reference\n// object(A)#1 (1) { [\"property\"]=> string(5) \"after\" }\nvar_dump($b);\n// object(A)#2 (1) { [\"property\"]=> NULL }\nvar_dump($c);\n// object(A)#3 (1) { [\"property\"]=> string(6) \"before\" }\n\n// Now creates a new obj A and passes to the function by clone (will copied)\n$d = new A();\n$d->property = \"before\";\n\nset_property(clone $d); // A new variable was created from $d, and not made a reference\n// object(A)#5 (1) { [\"property\"]=> string(5) \"after\" }\n\nvar_dump($d);\n// object(A)#4 (1) { [\"property\"]=> string(6) \"before\" }\n\n?>\n" }, { "answer_id": 47100920, "author": "Muhammad Ebrahim", "author_id": 8726495, "author_profile": "https://Stackoverflow.com/users/8726495", "pm_score": 1, "selected": false, "text": "class iPhone\n{\n public $name;\n public $email;\n\n public function __construct($n, $e) {\n\n $this->name = $n;\n $this->email = $e;\n\n }\n}\n\n$main = new iPhone('Dark', 'm@m.com');\n$copy = clone $main;\n\n// if you want to print both objects, just write this \n\necho \"<pre>\"; print_r($main); echo \"</pre>\";\necho \"<pre>\"; print_r($copy); echo \"</pre>\";\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/185934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4960/" ]
185,936
<p>How can I delete the contents of a local folder in Python?</p> <p>The current project is for Windows, but I would like to see *nix also.</p>
[ { "answer_id": 185941, "author": "Nick Stinemates", "author_id": 4960, "author_profile": "https://Stackoverflow.com/users/4960", "pm_score": 10, "selected": true, "text": "import os, shutil\nfolder = '/path/to/folder'\nfor filename in os.listdir(folder):\n file_path = os.path.join(folder, filename)\n try:\n if os.path.isfile(file_path) or os.path.islink(file_path):\n os.unlink(file_path)\n elif os.path.isdir(file_path):\n shutil.rmtree(file_path)\n except Exception as e:\n print('Failed to delete %s. Reason: %s' % (file_path, e))\n" }, { "answer_id": 186049, "author": "mhawke", "author_id": 21945, "author_profile": "https://Stackoverflow.com/users/21945", "pm_score": 3, "selected": false, "text": "os.walk() os.listdir() os.walk()" }, { "answer_id": 186236, "author": "Oli", "author_id": 22035, "author_profile": "https://Stackoverflow.com/users/22035", "pm_score": 8, "selected": false, "text": "shutil.rmtree import shutil\nshutil.rmtree('/path/to/folder')\n shutil.rmtree(path, ignore_errors=False, onerror=None)" }, { "answer_id": 1073382, "author": "Iker Jimenez", "author_id": 2697, "author_profile": "https://Stackoverflow.com/users/2697", "pm_score": 7, "selected": false, "text": "import os\nimport shutil\n\nfor root, dirs, files in os.walk('/path/to/folder'):\n for f in files:\n os.unlink(os.path.join(root, f))\n for d in dirs:\n shutil.rmtree(os.path.join(root, d))\n" }, { "answer_id": 5756937, "author": "Blueicefield", "author_id": 720691, "author_profile": "https://Stackoverflow.com/users/720691", "pm_score": 9, "selected": false, "text": "import os\nimport glob\n\nfiles = glob.glob('/YOUR/PATH/*')\nfor f in files:\n os.remove(f)\n" }, { "answer_id": 6615332, "author": "jgoeders", "author_id": 609215, "author_profile": "https://Stackoverflow.com/users/609215", "pm_score": 6, "selected": false, "text": "rmtree rmtree os.unlink glob folder_path = '/path/to/folder'\nfor file_object in os.listdir(folder_path):\n file_object_path = os.path.join(folder_path, file_object)\n if os.path.isfile(file_object_path) or os.path.islink(file_object_path):\n os.unlink(file_object_path)\n else:\n shutil.rmtree(file_object_path)\n" }, { "answer_id": 12526809, "author": "Jon Chu", "author_id": 652602, "author_profile": "https://Stackoverflow.com/users/652602", "pm_score": 5, "selected": false, "text": "for filename in os.listdir(dirpath):\n filepath = os.path.join(dirpath, filename)\n try:\n shutil.rmtree(filepath)\n except OSError:\n os.remove(filepath)\n" }, { "answer_id": 13666792, "author": "Jacob Wan", "author_id": 414524, "author_profile": "https://Stackoverflow.com/users/414524", "pm_score": 5, "selected": false, "text": "import os\nimport shutil\n\nwith os.scandir(target_dir) as entries:\n for entry in entries:\n if entry.is_dir() and not entry.is_symlink():\n shutil.rmtree(entry.path)\n else:\n os.remove(entry.path)\n import os\nimport shutil\n\n# Gather directory contents\ncontents = [os.path.join(target_dir, i) for i in os.listdir(target_dir)]\n\n# Iterate and remove each item in the appropriate manner\n[shutil.rmtree(i) if os.path.isdir(i) and not os.path.islink(i) else os.remove(i) for i in contents]\n" }, { "answer_id": 16340614, "author": "Sawyer", "author_id": 1633148, "author_profile": "https://Stackoverflow.com/users/1633148", "pm_score": 3, "selected": false, "text": "def emptydir(top):\n if(top == '/' or top == \"\\\\\"): return\n else:\n for root, dirs, files in os.walk(top, topdown=False):\n for name in files:\n os.remove(os.path.join(root, name))\n for name in dirs:\n os.rmdir(os.path.join(root, name))\n" }, { "answer_id": 17146855, "author": "ProfHase85", "author_id": 1945486, "author_profile": "https://Stackoverflow.com/users/1945486", "pm_score": 4, "selected": false, "text": "import shutil\nimport os\n\nshutil.rmtree(dirpath)\nos.mkdir(dirpath)\n" }, { "answer_id": 20173900, "author": "fmonegaglia", "author_id": 1697732, "author_profile": "https://Stackoverflow.com/users/1697732", "pm_score": 4, "selected": false, "text": "import os\n\n# Python 2.7\nmap( os.unlink, (os.path.join( mydir,f) for f in os.listdir(mydir)) )\n\n# Python 3+\nlist( map( os.unlink, (os.path.join( mydir,f) for f in os.listdir(mydir)) ) )\n def rm(f):\n if os.path.isdir(f): return os.rmdir(f)\n if os.path.isfile(f): return os.unlink(f)\n raise TypeError, 'must be either file or directory'\n\nmap( rm, (os.path.join( mydir,f) for f in os.listdir(mydir)) )\n" }, { "answer_id": 23614332, "author": "Robin Winslow", "author_id": 613540, "author_profile": "https://Stackoverflow.com/users/613540", "pm_score": 3, "selected": false, "text": "import sh\nsh.rm(sh.glob('/path/to/folder/*'))\n" }, { "answer_id": 24844618, "author": "Rockallite", "author_id": 2293304, "author_profile": "https://Stackoverflow.com/users/2293304", "pm_score": 4, "selected": false, "text": "shutil.rmtree() shutil.rmtree() shutil.rmtree() os.mkdir() shutil.rmtree() os.path.isdir() os.walk() clear_dir() import os\nimport stat\nimport shutil\n\n\n# http://stackoverflow.com/questions/1889597/deleting-directory-in-python\ndef _remove_readonly(fn, path_, excinfo):\n # Handle read-only files and directories\n if fn is os.rmdir:\n os.chmod(path_, stat.S_IWRITE)\n os.rmdir(path_)\n elif fn is os.remove:\n os.lchmod(path_, stat.S_IWRITE)\n os.remove(path_)\n\n\ndef force_remove_file_or_symlink(path_):\n try:\n os.remove(path_)\n except OSError:\n os.lchmod(path_, stat.S_IWRITE)\n os.remove(path_)\n\n\n# Code from shutil.rmtree()\ndef is_regular_dir(path_):\n try:\n mode = os.lstat(path_).st_mode\n except os.error:\n mode = 0\n return stat.S_ISDIR(mode)\n\n\ndef clear_dir(path_):\n if is_regular_dir(path_):\n # Given path is a directory, clear its content\n for name in os.listdir(path_):\n fullpath = os.path.join(path_, name)\n if is_regular_dir(fullpath):\n shutil.rmtree(fullpath, onerror=_remove_readonly)\n else:\n force_remove_file_or_symlink(fullpath)\n else:\n # Given path is a file or a symlink.\n # Raise an exception here to avoid accidentally clearing the content\n # of a symbolic linked directory.\n raise OSError(\"Cannot call clear_dir() on a symbolic link\")\n" }, { "answer_id": 37926786, "author": "B. Filer", "author_id": 5914737, "author_profile": "https://Stackoverflow.com/users/5914737", "pm_score": -1, "selected": false, "text": "import os\nDIR = os.list('Folder')\nfor i in range(len(DIR)):\n os.remove('Folder'+chr(92)+i)\n" }, { "answer_id": 41343815, "author": "fmonegaglia", "author_id": 1697732, "author_profile": "https://Stackoverflow.com/users/1697732", "pm_score": 1, "selected": false, "text": "import os\n\ndef recursively_remove_files(f):\n if os.path.isfile(f):\n os.unlink(f)\n elif os.path.isdir(f):\n for fi in os.listdir(f):\n recursively_remove_files(os.path.join(f, fi))\n\nrecursively_remove_files(my_directory)\n" }, { "answer_id": 42932517, "author": "physlexic", "author_id": 7654548, "author_profile": "https://Stackoverflow.com/users/7654548", "pm_score": -1, "selected": false, "text": "rmtree makedirs time.sleep() if os.path.isdir(folder_location):\n shutil.rmtree(folder_location)\n\ntime.sleep(.5)\n\nos.makedirs(folder_location, 0o777)\n" }, { "answer_id": 50813297, "author": "silverbullettt", "author_id": 1277994, "author_profile": "https://Stackoverflow.com/users/1277994", "pm_score": 3, "selected": false, "text": "import os\npath = 'folder/to/clean'\nos.system('rm -rf %s/*' % path)\n" }, { "answer_id": 54501104, "author": "amrezzd", "author_id": 8460132, "author_profile": "https://Stackoverflow.com/users/8460132", "pm_score": 1, "selected": false, "text": "import os\nimport shutil\n\ndef remove_contents(path):\n for c in os.listdir(path):\n full_path = os.path.join(path, c)\n if os.path.isfile(full_path):\n os.remove(full_path)\n else:\n shutil.rmtree(full_path)\n" }, { "answer_id": 54889532, "author": "Kevin Patel", "author_id": 6920365, "author_profile": "https://Stackoverflow.com/users/6920365", "pm_score": 4, "selected": false, "text": "import os\nmypath = \"my_folder\" #Enter your path here\nfor root, dirs, files in os.walk(mypath, topdown=False):\n for file in files:\n os.remove(os.path.join(root, file))\n\n # Add this block to remove folders\n for dir in dirs:\n os.rmdir(os.path.join(root, dir))\n\n# Add this line to remove the root folder at the end\nos.rmdir(mypath)\n" }, { "answer_id": 56151260, "author": "Husky", "author_id": 152809, "author_profile": "https://Stackoverflow.com/users/152809", "pm_score": 6, "selected": false, "text": "pathlib from pathlib import Path\n\n[f.unlink() for f in Path(\"/path/to/folder\").glob(\"*\") if f.is_file()] \n from pathlib import Path\nfrom shutil import rmtree\n\nfor path in Path(\"/path/to/folder\").glob(\"**/*\"):\n if path.is_file():\n path.unlink()\n elif path.is_dir():\n rmtree(path)\n" }, { "answer_id": 57216839, "author": "Manrique", "author_id": 8947739, "author_profile": "https://Stackoverflow.com/users/8947739", "pm_score": 2, "selected": false, "text": "import shutil, os\n\n\ndef remove_folder_contents(path):\n shutil.rmtree(path)\n os.makedirs(path)\n\n\nremove_folder_contents('/path/to/folder')\n" }, { "answer_id": 57278153, "author": "PyBoss", "author_id": 10530575, "author_profile": "https://Stackoverflow.com/users/10530575", "pm_score": -1, "selected": false, "text": "import os\nfiles = os.listdir(yourFilePath)\nfor f in files:\n os.remove(yourFilePath + f)\n" }, { "answer_id": 58699534, "author": "Kush Modi", "author_id": 11418523, "author_profile": "https://Stackoverflow.com/users/11418523", "pm_score": 2, "selected": false, "text": "import os\nimport glob\n\nfiles = glob.glob(r'path/*')\nfor items in files:\n os.remove(items)\n" }, { "answer_id": 59694006, "author": "NicoBar", "author_id": 9937135, "author_profile": "https://Stackoverflow.com/users/9937135", "pm_score": 3, "selected": false, "text": "directory\n folderA\n file1\n folderB\n file2\n folderC\n file3\n import os\nimport glob\n\nfolders = glob.glob('./path/to/parentdir/*')\nfor fo in folders:\n file = glob.glob(f'{fo}/*')\n for f in file:\n os.remove(f)\n" }, { "answer_id": 67509624, "author": "andrec", "author_id": 10652661, "author_profile": "https://Stackoverflow.com/users/10652661", "pm_score": 4, "selected": false, "text": "import os\nfor i in os.listdir():\n os.remove(i)\n" }, { "answer_id": 73777103, "author": "dazzafact", "author_id": 1163485, "author_profile": "https://Stackoverflow.com/users/1163485", "pm_score": 0, "selected": false, "text": "import glob\n\ndef truncate(path):\n files = glob.glob(path+'/*.*')\n for f in files:\n os.remove(f)\n\ntruncate('/my/path')\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/185936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/115/" ]
185,937
<p>I ran into an interesting (and very frustrating) issue with the <code>equals()</code> method today which caused what I thought to be a well tested class to crash and cause a bug that took me a very long time to track down. </p> <p>Just for completeness, I wasn't using an IDE or debugger - just good old fashioned text editor and System.out's. Time was very limited and it was a school project.</p> <p>Anyhow - </p> <p>I was developing a basic shopping cart which could contain an <em><code>ArrayList</code> of <code>Book</code> objects</em>. In order to implement the <code>addBook()</code>, <code>removeBook()</code>, and <code>hasBook()</code> methods of the Cart, I wanted to check if the <code>Book</code> already existed in the <code>Cart</code>. So off I go -</p> <pre><code>public boolean equals(Book b) { ... // More code here - null checks if (b.getID() == this.getID()) return true; else return false; } </code></pre> <p>All works fine in testing. I create 6 objects and fill them with data. Do many adds, removes, has() operations on the <code>Cart</code> and everything works fine. I read that you can <em>either have <code>equals(TYPE var)</code> or <code>equals(Object o) { (CAST) var }</code></em> but assumed that since it was working, it didn't matter too much.</p> <p>Then I ran into a problem - I needed to create a <code>Book</code> object with <em>only</em> the <code>ID</code> in it from within the Book class. No other data would be entered into it. Basically the following:</p> <pre><code>public boolean hasBook(int i) { Book b = new Book(i); return hasBook(b); } public boolean hasBook(Book b) { // .. more code here return this.books.contains(b); } </code></pre> <p>All of a sudden, the <code>equals(Book b)</code> method no longer works. This took a VERY long time to track down without a good debugger and assuming the <code>Cart</code> class was properly tested and correct. After swaapping the <code>equals()</code> method to the following:</p> <pre><code>public boolean equals(Object o) { Book b = (Book) o; ... // The rest goes here } </code></pre> <p>Everything began to work again. Is there a reason the method decided not to take the Book parameter even though it clearly <b> was </b> a <code>Book</code> object? The only difference seemed to be it was instantiated from within the same class, and only filled with one data member. I'm very very confused. Please, shed some light?</p>
[ { "answer_id": 185942, "author": "jjnguy", "author_id": 2598, "author_profile": "https://Stackoverflow.com/users/2598", "pm_score": 9, "selected": true, "text": "equals() Object public boolean equals(Object other);\n Object public boolean equals(Book other) equals() ArrayList equals() contains() equals() Object ArrayList @Override\npublic boolean equals(Object other){\n if (other == null) return false;\n if (other == this) return true;\n if (!(other instanceof MyClass)) return false;\n MyClass otherMyClass = (MyClass)other;\n ...test other properties here...\n}\n @Override" }, { "answer_id": 186409, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "@Override" }, { "answer_id": 26423986, "author": "borjab", "author_id": 16206, "author_profile": "https://Stackoverflow.com/users/16206", "pm_score": 3, "selected": false, "text": "import lombok.EqualsAndHashCode;\n\n@EqualsAndHashCode(of={\"errorNumber\",\"messageCode\"}) // Will only use this fields to generate equals.\npublic class ErrorMessage{\n\n private long errorNumber;\n private int numberOfParameters;\n private Level loggingLevel;\n private String messageCode;\n <dependency>\n <groupId>org.projectlombok</groupId>\n <artifactId>lombok</artifactId>\n <version>1.14.8</version>\n <scope>provided</scope>\n</dependency>\n" }, { "answer_id": 28237208, "author": "Nikel8000", "author_id": 4511678, "author_profile": "https://Stackoverflow.com/users/4511678", "pm_score": 0, "selected": false, "text": "instanceOf instanceOf (object1.equals(object2) == true) (object2.equals(object1)) this.getClass() != otherObject.getClass();" }, { "answer_id": 32152777, "author": "David Hackro", "author_id": 3741698, "author_profile": "https://Stackoverflow.com/users/3741698", "pm_score": 1, "selected": false, "text": " @Override\npublic boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n\n Proveedor proveedor = (Proveedor) o;\n\n return getId() == proveedor.getId();\n\n}\n\n@Override\npublic int hashCode() {\n return getId();\n}\n" }, { "answer_id": 32182121, "author": "vootla561", "author_id": 2831046, "author_profile": "https://Stackoverflow.com/users/2831046", "pm_score": -1, "selected": false, "text": "@Override\n public boolean equals(Object obj) {\n if (this == obj)\n return true;\n if (obj == null)\n return false;\n if (getClass() != obj.getClass())\n return false;\n Nai_record other = (Nai_record) obj;\n if (recordId == null) {\n if (other.recordId != null)\n return false;\n } else if (!recordId.equals(other.recordId))\n return false;\n return true;\n }\n" }, { "answer_id": 32487857, "author": "bcsb1001", "author_id": 3529323, "author_profile": "https://Stackoverflow.com/users/3529323", "pm_score": 1, "selected": false, "text": "Object obj = new Book();\nobj.equals(\"hi\");\n// Oh noes! What happens now? Can't call it with a String that isn't a Book...\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/185937", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10583/" ]
185,947
<p>As a programming exercise, I've written a Ruby snippet that creates a class, instantiates two objects from that class, monkeypatches one object, and relies on method_missing to monkeypatch the other one.</p> <p>Here's the deal. This works as intended:</p> <pre><code>class Monkey def chatter puts "I am a chattering monkey!" end def method_missing(m) puts "No #{m}, so I'll make one..." def screech puts "This is the new screech." end end end m1 = Monkey.new m2 = Monkey.new m1.chatter m2.chatter def m1.screech puts "Aaaaaargh!" end m1.screech m2.screech m2.screech m1.screech m2.screech </code></pre> <p>You'll notice that I have a parameter for method_missing. I did this because I was hoping to use define_method to dynamically create missing methods with the appropriate name. However, it doesn't work. In fact, even using define_method with a static name like so:</p> <pre><code>def method_missing(m) puts "No #{m}, so I'll make one..." define_method(:screech) do puts "This is the new screech." end end </code></pre> <p>Ends with the following result: </p> <pre><code>ArgumentError: wrong number of arguments (2 for 1) method method_missing in untitled document at line 9 method method_missing in untitled document at line 9 at top level in untitled document at line 26 Program exited. </code></pre> <p>What makes the error message more bewildering is that I only have one argument for <code>method_missing</code>...</p>
[ { "answer_id": 185969, "author": "Avdi", "author_id": 20487, "author_profile": "https://Stackoverflow.com/users/20487", "pm_score": 8, "selected": true, "text": "define_method define_method method_missing :define_method :screech define_method def method_missing(m)\n puts \"No #{m}, so I'll make one...\"\n self.class.send(:define_method, :screech) do\n puts \"This is the new screech.\"\n end\nend\n def method_missing(m)\n puts \"No #{m}, so I'll make one...\"\n class << self\n define_method(:screech) do\n puts \"This is the new screech.\"\n end\n end\nend\n" }, { "answer_id": 242106, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "class << self\n public :define_method\nend\ndef method_missing(m)\nputs \"No #{m}, so I'll make one...\"\nMonkey.define_method(:screech) do\n puts \"This is the new screech.\"\nend\n" }, { "answer_id": 3581388, "author": "Andrew", "author_id": 432558, "author_profile": "https://Stackoverflow.com/users/432558", "pm_score": 2, "selected": false, "text": "def method_missing(m)\n self.class.class_exec do\n define_method(:screech) {puts \"This is the new screech.\"}\n end \nend\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/185947", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21493/" ]
185,952
<p>I know this can be done in IE by creating an ActiveX object, but how do I do it in FF. The navigator.plugins['Adobe Acrobat'] object lets me know if it's installed or not, but it doesn't contain the version number. Any ideas?</p>
[ { "answer_id": 186312, "author": "Allen Pike", "author_id": 26398, "author_profile": "https://Stackoverflow.com/users/26398", "pm_score": 3, "selected": false, "text": "navigator.plugins[n].name n \"Adobe PDF Plug-In for Firefox and Netscape\"" }, { "answer_id": 277084, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "var p = document.getElementById('Pdf1');\n//p.GetVersions()\nif(p.GetVersions().indexOf(\"7.0\") != -1)\n alert(\"Acrobat 7 Found\")\n" }, { "answer_id": 21326028, "author": "Prashant Shinde", "author_id": 3164656, "author_profile": "https://Stackoverflow.com/users/3164656", "pm_score": 0, "selected": false, "text": "var browser_info = {\n name: null,\n acrobat : null,\n acrobat_ver : null\n };\n\n\nif(navigator.plugins != null)\n { \n var acrobat = navigator.plugins['Adobe Acrobat'];\n if(acrobat == null)\n { \n browser_info.acrobat = null;\n return browser_info;\n }\n browser_info.acrobat = \"installed\";\n browser_info.acrobat_ver = parseInt(acrobat.version[0]); \n }\n\n\nwhere navigator is the property of Window\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/185952", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16319/" ]
185,965
<p>What is the best way to create a custom title for pages in a Rails app without using a plug-in?</p>
[ { "answer_id": 185973, "author": "Avdi", "author_id": 20487, "author_profile": "https://Stackoverflow.com/users/20487", "pm_score": 4, "selected": false, "text": "content_for" }, { "answer_id": 185978, "author": "Alan", "author_id": 17205, "author_profile": "https://Stackoverflow.com/users/17205", "pm_score": 3, "selected": false, "text": "application_helper.rb <title><%= custom_title %></title>\n title" }, { "answer_id": 185980, "author": "Aupajo", "author_id": 10407, "author_profile": "https://Stackoverflow.com/users/10407", "pm_score": 6, "selected": false, "text": "def page_title(separator = \" – \")\n [content_for(:title), 'My Cool Site'].compact.join(separator)\nend\n\ndef page_heading(title)\n content_for(:title){ title }\n content_tag(:h1, title)\nend\n <title><%= page_title %></title>\n <%= page_heading \"Awesome\" %>\n" }, { "answer_id": 186227, "author": "JasonOng", "author_id": 6048, "author_profile": "https://Stackoverflow.com/users/6048", "pm_score": 2, "selected": false, "text": "# foo_controller.rb\n\nclass FooController < ApplicationController\n\n before_filter :set_title\n\n private\n\n def set_title\n @page_title = \"Foo Page\"\n end\n\nend\n\n# application.html.erb\n\n<h1><%= page_title %></h1>\n" }, { "answer_id": 186508, "author": "Christoph Schiessl", "author_id": 20467, "author_profile": "https://Stackoverflow.com/users/20467", "pm_score": 9, "selected": true, "text": "<% content_for :title, \"Title for specific page\" %>\n<!-- or -->\n<h1><%= content_for(:title, \"Title for specific page\") %></h1>\n <head>\n <title><%= yield(:title) %></title>\n <!-- Additional header tags here -->\n</head>\n<body>\n <!-- If all pages contain a headline tag, it's preferable to put that in the layout file too -->\n <h1><%= yield(:title) %></h1>\n</body>\n content_for yield(:title)" }, { "answer_id": 188593, "author": "IDBD", "author_id": 7403, "author_profile": "https://Stackoverflow.com/users/7403", "pm_score": -1, "selected": false, "text": " def get_title\n @action_title_name || case controller_name\n when 'djs'\n 'Djs'\n when 'photos'\n 'Photos'\n when 'events'\n 'Various events'\n when 'static'\n 'Info'\n when 'club'\n 'My club'\n when 'news'\n 'News'\n when 'welcome'\n 'Welcome!'\n else\n 'Other'\n end\n end\n" }, { "answer_id": 1481279, "author": "opsb", "author_id": 162337, "author_profile": "https://Stackoverflow.com/users/162337", "pm_score": 7, "selected": false, "text": "<head>\n <title><%= @title %></title>\n</head>\n <% @title=\"Home\" %>\n" }, { "answer_id": 3796454, "author": "sent-hil", "author_id": 236655, "author_profile": "https://Stackoverflow.com/users/236655", "pm_score": 2, "selected": false, "text": "<% title \"Title of page\" %> <% title \"Title of page\", false %>" }, { "answer_id": 14721083, "author": "FouZ", "author_id": 300141, "author_profile": "https://Stackoverflow.com/users/300141", "pm_score": -1, "selected": false, "text": "<title><%= @page_title or 'Page Title' %></title>\n" }, { "answer_id": 16637619, "author": "boulder_ruby", "author_id": 1276506, "author_profile": "https://Stackoverflow.com/users/1276506", "pm_score": 5, "selected": false, "text": "application.html.erb <title><%= @title || \"Default Page Title\" %></title>\n <% @title = \"Unique Page Title\" %>\n" }, { "answer_id": 38158543, "author": "Kofi Asare", "author_id": 6541069, "author_profile": "https://Stackoverflow.com/users/6541069", "pm_score": 2, "selected": false, "text": "<%content_for :page_title do %>\n <%=title%>\n<%end%>\n <title><%=yield :page_title %></title>\n e.g : inside index.html.erb\n\n <%=render '_page_title', title: 'title_of_page'%>\n" }, { "answer_id": 41844097, "author": "Mukesh Kumar Gupta", "author_id": 2713696, "author_profile": "https://Stackoverflow.com/users/2713696", "pm_score": 1, "selected": false, "text": "<%content_for :page_title do %><%= t :page_title, \"Name of Your Page\" %> <% end %>\n" }, { "answer_id": 48245616, "author": "barlop", "author_id": 385907, "author_profile": "https://Stackoverflow.com/users/385907", "pm_score": 1, "selected": false, "text": "<% provide(:title,\"ttttttttttttttttttZ\") %>\n<html>\n <head><title><%= yield(:title) %></title></head>\n <body></body>\n</html>\n" }, { "answer_id": 63978530, "author": "stevec", "author_id": 5783745, "author_profile": "https://Stackoverflow.com/users/5783745", "pm_score": 3, "selected": false, "text": "app/views/layouts/application.html.erb <title><%= yield(:title) || 'my default title' %></title>\n <% content_for :title, \"some new title\" %>\n" }, { "answer_id": 69686162, "author": "Emric Månsson", "author_id": 5851595, "author_profile": "https://Stackoverflow.com/users/5851595", "pm_score": 1, "selected": false, "text": "app/views/layouts/application.html.erb <title>\n <%= translate(\"#{controller_name}.#{action_name}.site_title\", raise: true) %>\n </title>\n <title>\n <%= translate(\"#{controller_name}.#{action_name}.site_title\", \n default: translate(\".site_title\")) %>\n </title>\n" }, { "answer_id": 73371607, "author": "Matthew", "author_id": 145725, "author_profile": "https://Stackoverflow.com/users/145725", "pm_score": 1, "selected": false, "text": "# config/locales/en.yml\nen:\n layouts:\n application:\n site_title: \"My App\"\n # app/views/layouts/application.html.erb\n<title>\n <%= yield(:title).presence ||\n [yield(:page_title).presence, t(\".site_title\")].compact.join(\" - \") %>\n</title>\n yield content_for # app/views/layouts/application.html.erb\n<title><%= show_title %></title>\n\n# app/helpers/application_helper.rb\nmodule ApplicationHelper\n def show_title\n content_for(:title).presence ||\n [content_for(:page_title).presence, t(\".site_title\")].compact.join(\" - \")\n end\nend\n # app/views/static_pages/welcome.html.erb\n<% content_for :title, \"My awesome custom title\" %>\n\n# or localised...\n# <% content_for :title, t(\".custom_title\") %>\n\n# Outputs:\n# <title>My awesome custom title</title>\n # app/views/products/index.html.erb\n<% content_for :page_title, \"Items\" %>\n\n# or localised...\n# <% content_for :page_title, t(\"Products.model_name.human\") %>\n\n# Outputs:\n# <title>Items - My App</title>\n # No \"content_for\" specified\n\n# Outputs:\n# <title>My App</title>\n .presence yield(:title) yield(:title).presence || .compact" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/185965", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1632/" ]
185,966
<pre><code>&lt;div id="myDiv"&gt; &lt;a&gt;...&lt;/a&gt; &lt;a&gt;...&lt;/a&gt; &lt;a&gt;...&lt;/a&gt; &lt;a&gt;...&lt;/a&gt; &lt;a&gt;...&lt;/a&gt; &lt;a&gt;...&lt;/a&gt; &lt;/div&gt; </code></pre> <p>If you wanted to select the 2nd, 3rd and 4th <code>a</code> tags in the above example, how would you do that? The only thing I can think of is:</p> <pre><code>$("#myDiv a:eq(1), #myDiv a:eq(2), #myDiv a:eq(3)") </code></pre> <p>But that doesn't look to be very efficient or pretty. I guess you could also select ALL the <code>a</code>s and then do run <code>.each</code> over them, but that could get very inefficient if there were a lot more <code>a</code>s.</p>
[ { "answer_id": 186018, "author": "Alexander Prokofyev", "author_id": 11256, "author_profile": "https://Stackoverflow.com/users/11256", "pm_score": 8, "selected": true, "text": "$(\"#myDiv a\").slice(1, 4)\n" }, { "answer_id": 186034, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 2, "selected": false, "text": "$(\"div[id='myDiv'] > a\").slice(1,4).css(\"background\",\"yellow\");\n <html>\n <head>\n <script type=\"text/javascript\" src=\"jquery-1.2.6.pack.js\"></script>\n <script type=\"text/javascript\">\n $(document).ready(function(){\n $(\"a\").click(function(event){\n $(\"div[id='myDiv'] > a\").slice(1,4).css(\"background\",\"yellow\");\n event.preventDefault();\n });\n });\n </script>\n </head>\n <body>\n <div id=\"myDiv\">\n <a>1</a>\n <a>2</a>\n <a>3</a>\n <a>4</a>\n <a>5</a>\n <a>6</a>\n </div>\n <hr>\n <a href=\"\" >Click here</a>\n <hr>\n </body>\n</html>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/185966", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9021/" ]
185,967
<p><em>Note: Originally this question was asked for PostgreSQL, however, the answer applies to almost any database which has a JDBC driver that can detect foreign-key associations.</em> </p> <hr> <p>Querying PostgreSQL data dictionary for foreign-keys and relationship between tables is very straightforward, but how can I use that information to generate a graph of the relations between tables?</p> <p>Any recommendations about tools that can do this?</p> <p><strong>EDIT:</strong> I know GraphVIZ/DOT <em>can</em> be useful, however, I don't know have any idea regarding how to code an app that would generate the directed graph .DOT file.</p>
[ { "answer_id": 21501326, "author": "Joe Pineda", "author_id": 21258, "author_profile": "https://Stackoverflow.com/users/21258", "pm_score": 2, "selected": false, "text": "SELECT '\"' || Source.TABLE_NAME || '\" -> \"' \n || Destiny.TABLE_NAME || '\";' AS For_GraphViz\nFROM dba_constraints Source\nJOIN dba_constraints Destiny\nON Source.owner='my_db_owner' AND Destiny.owner='my_db_owner'\nAND Source.CONSTRAINT_TYPE='R'\n-- theoretically this validation should be redundant\n-- AND Destiny.Constraint_type = 'P'\nAND Source.R_CONSTRAINT_NAME = Destiny.CONSTRAINT_NAME\nORDER BY Source.TABLE_NAME, Source.CONSTRAINT_TYPE, Source.CONSTRAINT_NAME\n , Source.R_CONSTRAINT_NAME, Source.INDEX_NAME;\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/185967", "https://Stackoverflow.com", "https://Stackoverflow.com/users/861/" ]
185,972
<p>In javascript, we can do:</p> <pre><code>["a string", 10, {x : 1}, function() {}].push("another value"); </code></pre> <p>What is the Scala equivalent?</p>
[ { "answer_id": 188235, "author": "Daniel Spiewak", "author_id": 9815, "author_profile": "https://Stackoverflow.com/users/9815", "pm_score": 6, "selected": true, "text": "List Vector Vector(\"a string\", 10, Map(\"x\" -> 1), ()=>()) + \"another value\"\n Vector[Any] Array(1, 2, 3, 4) // => Array[Int] containing [1, 2, 3, 4]\n" }, { "answer_id": 6091792, "author": "soc", "author_id": 297776, "author_profile": "https://Stackoverflow.com/users/297776", "pm_score": 4, "selected": false, "text": "Any Array(\"a string\", 10, new { val x = 1 }, () => ()) :+ \"another value\"\n Array[Any]" }, { "answer_id": 13468813, "author": "akauppi", "author_id": 14455, "author_profile": "https://Stackoverflow.com/users/14455", "pm_score": 2, "selected": false, "text": "scala> (\"a string\", 10, (1), () => {})\nres1: (java.lang.String, Int, Int, () => Unit) = (a string,10,1,<function0>)\n scala> \"a string\" :: 10 :: (1) :: () => {} :: HNil\n scala> case class MyThing( str: String, int: Int, x: Int, f: () => Unit )\ndefined class MyThing\n\nscala> MyThing( \"a string\", 10, 1, ()=>{} )\nres2: MyThing = MyThing(a string,10,1,<function0>)\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/185972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20689/" ]
185,983
<p>My friend accidentally bought a laptop with Windows Vista Home Basic Edition. He figured out how to install IIS on it, but it doesn't seem to have either the management console or the admin tools. Is there any way for him to configure a site or import an IIS 6 config file?</p> <p>EDIT: "Windows Vista Home Edition" --> "Windows Vista Home Basic Edition".</p>
[ { "answer_id": 186163, "author": "bugmagnet", "author_id": 426, "author_profile": "https://Stackoverflow.com/users/426", "pm_score": 0, "selected": false, "text": "%SystemRoot%\\system32\\inetsrv\\iis.msc iis.msc" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/185983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5682/" ]
186,004
<p>Specifically, I want to listen to when programs are run and record information such as: timestamp, executable, windows name and user.</p>
[ { "answer_id": 186149, "author": "bugmagnet", "author_id": 426, "author_profile": "https://Stackoverflow.com/users/426", "pm_score": 1, "selected": false, "text": "Select * from Win32_Process Win32_Process Const NORMAL_PRIORITY = 32\nConst LOW_PRIORITY = 64\nConst REALTIME_PRIORITY = 128\nConst HIGH_PRIORITY = 256\nConst BELOWNORMAL_PRIORITY = 16384\nConst ABOVENORMAL_PRIORITY = 32768\n\nFunction SetPriority( sProcess, nPriority )\n Dim sComputer\n Dim oWMIService\n Dim cProcesses\n Dim oProcess\n Dim bDone\n\n bDone = False\n sComputer = \".\"\n Set oWMIService = GetObject(\"winmgmts:\\\\\" & sComputer & \"\\root\\cimv2\")\n\n Set cProcesses = oWMIService.ExecQuery (\"Select * from Win32_Process Where Name = '\" & sProcess & \"'\")\n For Each oProcess in cProcesses\n oProcess.SetPriority( nPriority )\n bDone = True \n Next\n SetPriority = bDone\nEnd Function\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/186004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24416/" ]
186,015
<p>I have had to do this several times, usually when trying to find in what files a variable or a function is used.</p> <p>I remember using xargs with grep in the past to do this, but I am wondering if there are any easier ways.</p>
[ { "answer_id": 186020, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 6, "selected": true, "text": "grep -r REGEX .\n ." }, { "answer_id": 186043, "author": "Darren Greaves", "author_id": 151, "author_profile": "https://Stackoverflow.com/users/151", "pm_score": 2, "selected": false, "text": "grep REGEX **/*\n grep REGEX **/*.java\n find . -name '*.java' -exec grep REGEX {} \\;\n find . -type f -exec grep REGEX {} \\;\n" }, { "answer_id": 187322, "author": "Scott", "author_id": 7399, "author_profile": "https://Stackoverflow.com/users/7399", "pm_score": 2, "selected": false, "text": "grep REGEX -r ." }, { "answer_id": 187355, "author": "Gabriel Gilini", "author_id": 25853, "author_profile": "https://Stackoverflow.com/users/25853", "pm_score": 3, "selected": false, "text": "fgrep -r pattern .\n" }, { "answer_id": 731731, "author": "Chas. Owens", "author_id": 78259, "author_profile": "https://Stackoverflow.com/users/78259", "pm_score": 4, "selected": false, "text": "find . -type f -print0 | xargs -0 grep pattern\n -print0 -0" }, { "answer_id": 15712293, "author": "trickster", "author_id": 2225882, "author_profile": "https://Stackoverflow.com/users/2225882", "pm_score": 1, "selected": false, "text": "find . \\\\( -name '\\''*.java'\\'' -o -name '\\''*.xml'\\'' \\\\) | xargs egrep -name '\\''*.<filetype>'\\'' -o alias fnd='find . \\\\( -name '\\''*.java'\\'' -o -name '\\''*.xml'\\'' \\\\) | xargs egrep'" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/186015", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25910/" ]
186,024
<pre><code>(function() { //codehere } )(); </code></pre> <p>What is special about this kind of syntax? What does ()(); imply?</p>
[ { "answer_id": 186030, "author": "Geoff", "author_id": 10427, "author_profile": "https://Stackoverflow.com/users/10427", "pm_score": 5, "selected": false, "text": "function name (){...}\nname();\n" }, { "answer_id": 186186, "author": "artificialidiot", "author_id": 7988, "author_profile": "https://Stackoverflow.com/users/7988", "pm_score": 2, "selected": false, "text": "return this; var Myobject=(function(){\n var privatevalue=0;\n function privatefunction()\n {\n }\n this.publicvalue=1;\n this.publicfunction=function()\n {\n privatevalue=1; //no worries about the execution context\n }\nreturn this;})(); //I tend to forget returning the instance\n //if I don't write like this\n" }, { "answer_id": 187042, "author": "Leo", "author_id": 20689, "author_profile": "https://Stackoverflow.com/users/20689", "pm_score": 2, "selected": false, "text": "var test = 1;\n(function() {\n var test = 2;\n})();\ntest == 1 // true\n var aVariable = 1\nvar myVariable = aVariable\n\n(function() {/*...*/})()\n var aVariable = 1;\nvar myVariable = aVariable(function() {/*...*/})\nmyVariable();\n new function() {/*...*/}\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/186024", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21572/" ]
186,035
<p>I have a simple "accordion" type page containing a list of H3 headers and DIV content boxes (each H3 is followed by a DIV). On this page I start with all DIVs hidden. When a H3 is clicked the DIV directly below (after) is revealed with jQuery's <a href="http://jquery.com/api/#slideDown" rel="nofollow noreferrer">"slideDown"</a> function while all other DIVs are hidden with the <a href="http://jquery.com/api/#slideUp" rel="nofollow noreferrer">"slideUp"</a> function.</p> <p>The "slideUp" function inserts the following inline style into the specified DIVs:</p> <pre><code>style="display: none;" </code></pre> <p>I am wondering if there is any way for me to show all the DIVs expanded when a user prints the page (as I do when a user has JavaScript disabled).</p> <p>I am thinking it is impossible because the inline style will always take precedence over any other style declaration.</p> <p>Is there another solution?</p> <p><strong>Solution</strong></p> <p><a href="https://stackoverflow.com/questions/186035/is-it-possible-to-print-a-div-that-is-hidden-by-jquerys-slideup-function#186189">Sugendran's solution</a> is great and works in the browsers (FF2, IE7 and IE6) I've tested so far. I wasn't aware there was any way to override inline styles which I'm pretty sure is something I've looked up before so this is great to find out. I also see there is <a href="https://stackoverflow.com/questions/104485/is-there-a-way-to-force-a-style-to-a-div-element-which-already-has-a-style-attr#104499">this answer here</a> regarding this. I wish search wasn't so difficult to navigate here :-).</p> <p><a href="https://stackoverflow.com/questions/186035/is-it-possible-to-print-a-div-that-is-hidden-by-jquerys-slideup-function#186276">Lee Theobald's solution</a> would be great but the "slideUp" function adds the style="display:none;" bit. </p> <p><a href="https://stackoverflow.com/questions/186035/is-it-possible-to-print-a-div-that-is-hidden-by-jquerys-slideup-function#186036">My solution</a> works fine, but is overkill when the !important declaration works.</p>
[ { "answer_id": 186036, "author": "Matt Mitchell", "author_id": 364, "author_profile": "https://Stackoverflow.com/users/364", "pm_score": 0, "selected": false, "text": "$('div#accordion> div').addClass('hideme');\n .hideme { display: none; }\n div.hideme { display: block; }\n <script type=\"text/javascript\">\n //<![CDATA[\n $(function() {\n $('#accordion> div').addClass('hideme');\n\n $('#accordion> h3').click(function() {\n $(this).next('div:hidden').slideDown('fast').siblings('div:visible').slideUp('fast', function(){ $('#accordion> div:hidden').addClass('hideme').removeAttr('style'); });\n\n });\n });\n //]]>\n</script>\n" }, { "answer_id": 186189, "author": "Sugendran", "author_id": 22466, "author_profile": "https://Stackoverflow.com/users/22466", "pm_score": 5, "selected": true, "text": "div.accordian { display:block !important; }\n" }, { "answer_id": 186276, "author": "Lee Theobald", "author_id": 1900, "author_profile": "https://Stackoverflow.com/users/1900", "pm_score": 2, "selected": false, "text": "<div class=\"closed\">...</div>\n <link href=\"screen.css\" rel=\"stylesheet\" type=\"text/css\" media=\"screen,projection\"/>\n<link href=\"print.css\" rel=\"stylesheet\" type=\"text/css\" media=\"print\"/>\n div.closed { display: none; }\n" }, { "answer_id": 8229137, "author": "rordaz", "author_id": 1060061, "author_profile": "https://Stackoverflow.com/users/1060061", "pm_score": 2, "selected": false, "text": "#accordion > *{ display:block !important; }" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/186035", "https://Stackoverflow.com", "https://Stackoverflow.com/users/364/" ]
186,037
<p>Is there any way to validate the width and height of image when uploaded? using javascript of server side ? like jsp, aspx etc?</p>
[ { "answer_id": 186067, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 2, "selected": false, "text": "getHeight getWidth BufferedImage" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/186037", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25368/" ]
186,044
<p>I was developing a web page, where I was laying out a board for a Chess-like game, along with a couple of piece trays. It's all done using HTML (with jQuery for dynamic updating as the game is played). Somewhere I'd got the notion that using absolute positioning of elements within a page was considered a bad practice, and that it was preferable to use relative positioning.</p> <p>After struggling with relative positioning for too long, I realized that absolute positioning of the board elements would be much, much easier to get right... and it was.</p> <p>Is anyone aware of a reason that relative positioning is preferable over absolute? Are there any guidelines or rules of thumb that you apply when deciding which approach to take?</p>
[ { "answer_id": 186058, "author": "Ash", "author_id": 5023, "author_profile": "https://Stackoverflow.com/users/5023", "pm_score": 8, "selected": true, "text": "<div id=\"parentDIV\" style=\"position:relative\">\n <div id=\"childDIV\" style=\"position:absolute;left:20px;top:20px;\">\n I'm absolutely positioned within parentDIV.\n </div>\n</div>\n childDIV parentDIV" }, { "answer_id": 187310, "author": "Herb Caudill", "author_id": 239663, "author_profile": "https://Stackoverflow.com/users/239663", "pm_score": 6, "selected": false, "text": "position:relative position:absolute div.Container\n{\n position:relative\n width:300px;\n height:300px;\n background:yellow;\n}\n\ndiv.PositionMe\n{\n position:absolute;\n top:10px;\n right:10px;\n width:20px;\n height:20px;\n background:red\n}\n <div class=Container>\n...\n <div class=PositionMe>\n ...\n </div>\n...\n</div>\n PositionMe Container" }, { "answer_id": 2347705, "author": "e-satis", "author_id": 9951, "author_profile": "https://Stackoverflow.com/users/9951", "pm_score": 1, "selected": false, "text": "onblur onfocus cie" }, { "answer_id": 16026661, "author": "Yaron U.", "author_id": 729673, "author_profile": "https://Stackoverflow.com/users/729673", "pm_score": 2, "selected": false, "text": "cube float: left clear" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/186044", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2193/" ]
186,062
<p>Can I create a Controller that simply returns an image asset?</p> <p>I would like to route this logic through a controller, whenever a URL such as the following is requested:</p> <pre><code>www.mywebsite.com/resource/image/topbanner </code></pre> <p>The controller will look up <code>topbanner.png</code> and send that image directly back to the client.</p> <p>I've seen examples of this where you have to create a View - I don't want to use a View. I want to do it all with just the Controller.</p> <p>Is this possible?</p>
[ { "answer_id": 186133, "author": "Ian Suttle", "author_id": 19421, "author_profile": "https://Stackoverflow.com/users/19421", "pm_score": 3, "selected": false, "text": "string pathToFile = @\"C:\\Documents and Settings\\some_path.jpg\";\nbyte[] imageData = File.ReadAllBytes(pathToFile);\nResponse.ContentType = \"image/jpg\";\nResponse.BinaryWrite(imageData);\n" }, { "answer_id": 189054, "author": "JarrettV", "author_id": 16340, "author_profile": "https://Stackoverflow.com/users/16340", "pm_score": 4, "selected": false, "text": "public class StreamResult : ViewResult\n{\n public Stream Stream { get; set; }\n public string ContentType { get; set; }\n public string ETag { get; set; }\n\n public override void ExecuteResult(ControllerContext context)\n {\n context.HttpContext.Response.ContentType = ContentType;\n if (ETag != null) context.HttpContext.Response.AddHeader(\"ETag\", ETag);\n const int size = 4096;\n byte[] bytes = new byte[size];\n int numBytes;\n while ((numBytes = Stream.Read(bytes, 0, size)) > 0)\n context.HttpContext.Response.OutputStream.Write(bytes, 0, numBytes);\n }\n}\n" }, { "answer_id": 752531, "author": "Sailing Judo", "author_id": 42620, "author_profile": "https://Stackoverflow.com/users/42620", "pm_score": 7, "selected": false, "text": "[AcceptVerbs(HttpVerbs.Get)]\n[OutputCache(CacheProfile = \"CustomerImages\")]\npublic FileResult Show(int customerId, string imageName)\n{\n var path = string.Concat(ConfigData.ImagesDirectory, customerId, \"\\\\\", imageName);\n return new FileStreamResult(new FileStream(path, FileMode.Open), \"image/jpeg\");\n}\n" }, { "answer_id": 1349318, "author": "Brian", "author_id": 320, "author_profile": "https://Stackoverflow.com/users/320", "pm_score": 10, "selected": true, "text": "public ActionResult Image(string id)\n{\n var dir = Server.MapPath(\"/Images\");\n var path = Path.Combine(dir, id + \".jpg\"); //validate the path for security or use other means to generate the path.\n return base.File(path, \"image/jpeg\");\n}\n http://localhost/MyController/Image/MyImage http://localhost/Images/MyImage.jpg" }, { "answer_id": 1495178, "author": "Chris S", "author_id": 21574, "author_profile": "https://Stackoverflow.com/users/21574", "pm_score": 7, "selected": false, "text": "System.Web.Mvc.FileResult\n System.Web.Mvc.FileContentResult\n System.Web.Mvc.FilePathResult\n System.Web.Mvc.FileStreamResult\n FilePathResult FileContentResult FileStreamResult MemoryStream GetBuffer() Streams FileStreamResult Stream MemoryStream [AcceptVerbs(HttpVerbs.Post)]\n public ActionResult GetFile()\n {\n // No need to dispose the stream, MVC does it for you\n string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, \"App_Data\", \"myimage.png\");\n FileStream stream = new FileStream(path, FileMode.Open);\n FileStreamResult result = new FileStreamResult(stream, \"image/png\");\n result.FileDownloadName = \"image.png\";\n return result;\n }\n" }, { "answer_id": 2288714, "author": "Victor Gelmutdinov", "author_id": 129812, "author_profile": "https://Stackoverflow.com/users/129812", "pm_score": 2, "selected": false, "text": "if (!System.IO.File.Exists(filePath))\n return SomeHelper.EmptyImageResult(); // preventing JSON GET/POST exception\nelse\n return new FilePathResult(filePath, contentType);\n SomeHelper.EmptyImageResult() FileResult byte[] stream FileContentResult FileStreamResult" }, { "answer_id": 5458073, "author": "staromeste", "author_id": 680094, "author_profile": "https://Stackoverflow.com/users/680094", "pm_score": 6, "selected": false, "text": "public ActionResult GetModifiedImage()\n{\n Image image = Image.FromFile(Path.Combine(Server.MapPath(\"/Content/images\"), \"image.png\"));\n\n using (Graphics g = Graphics.FromImage(image))\n {\n // do something with the Graphics (eg. write \"Hello World!\")\n string text = \"Hello World!\";\n\n // Create font and brush.\n Font drawFont = new Font(\"Arial\", 10);\n SolidBrush drawBrush = new SolidBrush(Color.Black);\n\n // Create point for upper-left corner of drawing.\n PointF stringPoint = new PointF(0, 0);\n\n g.DrawString(text, drawFont, drawBrush, stringPoint);\n }\n\n MemoryStream ms = new MemoryStream();\n\n image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);\n\n return File(ms.ToArray(), \"image/png\");\n}\n" }, { "answer_id": 6288786, "author": "Oleksandr Fentsyk", "author_id": 760375, "author_profile": "https://Stackoverflow.com/users/760375", "pm_score": 4, "selected": false, "text": "public static class ImageResultHelper\n{\n public static string Image<T>(this HtmlHelper helper, Expression<Action<T>> action, int width, int height)\n where T : Controller\n {\n return ImageResultHelper.Image<T>(helper, action, width, height, \"\");\n }\n\n public static string Image<T>(this HtmlHelper helper, Expression<Action<T>> action, int width, int height, string alt)\n where T : Controller\n {\n var expression = action.Body as MethodCallExpression;\n string actionMethodName = string.Empty;\n if (expression != null)\n {\n actionMethodName = expression.Method.Name;\n }\n string url = new UrlHelper(helper.ViewContext.RequestContext, helper.RouteCollection).Action(actionMethodName, typeof(T).Name.Remove(typeof(T).Name.IndexOf(\"Controller\"))).ToString(); \n //string url = LinkBuilder.BuildUrlFromExpression<T>(helper.ViewContext.RequestContext, helper.RouteCollection, action);\n return string.Format(\"<img src=\\\"{0}\\\" width=\\\"{1}\\\" height=\\\"{2}\\\" alt=\\\"{3}\\\" />\", url, width, height, alt);\n }\n}\n\npublic class ImageResult : ActionResult\n{\n public ImageResult() { }\n\n public Image Image { get; set; }\n public ImageFormat ImageFormat { get; set; }\n\n public override void ExecuteResult(ControllerContext context)\n {\n // verify properties \n if (Image == null)\n {\n throw new ArgumentNullException(\"Image\");\n }\n if (ImageFormat == null)\n {\n throw new ArgumentNullException(\"ImageFormat\");\n }\n\n // output \n context.HttpContext.Response.Clear();\n context.HttpContext.Response.ContentType = GetMimeType(ImageFormat);\n Image.Save(context.HttpContext.Response.OutputStream, ImageFormat);\n }\n\n private static string GetMimeType(ImageFormat imageFormat)\n {\n ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();\n return codecs.First(codec => codec.FormatID == imageFormat.Guid).MimeType;\n }\n}\npublic ActionResult Index()\n {\n return new ImageResult { Image = image, ImageFormat = ImageFormat.Jpeg };\n }\n <%=Html.Image<CapchaController>(c => c.Index(), 120, 30, \"Current time\")%>\n" }, { "answer_id": 7961062, "author": "JustinStolle", "author_id": 92389, "author_profile": "https://Stackoverflow.com/users/92389", "pm_score": 4, "selected": false, "text": "~ public FileResult TopBanner() {\n return File(\"~/Content/images/topbanner.png\", \"image/png\");\n}\n" }, { "answer_id": 24593278, "author": "Ajay Kelkar", "author_id": 166461, "author_profile": "https://Stackoverflow.com/users/166461", "pm_score": 3, "selected": false, "text": "public static MvcHtmlString Image(this HtmlHelper helper,string imageUrl)\n{\n string tag = \"<img src='{0}'/>\";\n tag = string.Format(tag,imageUrl);\n return MvcHtmlString.Create(tag);\n}\n @Html.Image(@Model.ImagePath);\n public sealed class ImageController : Controller\n{\n public ActionResult View(string id)\n {\n var image = _images.LoadImage(id); //Pull image from the database.\n if (image == null) \n return HttpNotFound();\n return File(image.Data, image.Mime);\n }\n}\n @ { Html.RenderAction(\"View\",\"Image\",new {id=@Model.ImageId})}\n <img src=\"http://something.com/image/view?id={imageid}>\n" }, { "answer_id": 36038457, "author": "Avinash Urs", "author_id": 6007967, "author_profile": "https://Stackoverflow.com/users/6007967", "pm_score": 3, "selected": false, "text": " public ActionResult PrintDocInfo(string Attachment)\n {\n string test = Attachment;\n if (test != string.Empty || test != \"\" || test != null)\n {\n string filename = Attachment.Split('\\\\').Last();\n string filepath = Attachment;\n byte[] filedata = System.IO.File.ReadAllBytes(Attachment);\n string contentType = MimeMapping.GetMimeMapping(Attachment);\n\n System.Net.Mime.ContentDisposition cd = new System.Net.Mime.ContentDisposition\n {\n FileName = filename,\n Inline = true,\n };\n\n Response.AppendHeader(\"Content-Disposition\", cd.ToString());\n\n return File(filedata, contentType); \n }\n else { return Content(\"<h3> Patient Clinical Document Not Uploaded</h3>\"); }\n\n }\n" }, { "answer_id": 49744220, "author": "hmojica", "author_id": 3455589, "author_profile": "https://Stackoverflow.com/users/3455589", "pm_score": 3, "selected": false, "text": " [HttpGet(\"/image/{uuid}\")]\n public IActionResult GetImageFile(string uuid) {\n ActionResult actionResult = new NotFoundResult();\n var fileImage = _db.ImageFiles.Find(uuid);\n if (fileImage != null) {\n actionResult = new FileContentResult(fileImage.Data,\n fileImage.ContentType);\n }\n return actionResult;\n }\n _db.ImageFiles.Find(uuid) public class FileImage {\n public string Uuid { get; set; }\n public byte[] Data { get; set; }\n public string ContentType { get; set; }\n}\n" }, { "answer_id": 57573210, "author": "Shriram Navaratnalingam", "author_id": 10031056, "author_profile": "https://Stackoverflow.com/users/10031056", "pm_score": 2, "selected": false, "text": "var src = string.Format(\"/GenericGrid.mvc/DocumentPreviewImageLink?fullpath={0}&routingId={1}&siteCode={2}\", fullFilePath, metaInfo.RoutingId, da.SiteCode);\n\n if (enlarged)\n result = \"<a class='thumbnail' href='#thumb'>\" +\n \"<img src='\" + src + \"' height='66px' border='0' />\" +\n \"<span><img src='\" + src + \"' /></span>\" +\n \"</a>\";\n else\n result = \"<span><img src='\" + src + \"' height='150px' border='0' /></span>\";\n try\n{\n var file = new FileInfo(fullpath);\n if (!file.Exists)\n return string.Empty;\n\n\n var image = new WebImage(fullpath);\n return new ImageResult(new MemoryStream(image.GetBytes()), \"image/jpg\");\n\n\n}\ncatch(Exception ex)\n{\n return \"File Error : \"+ex.ToString();\n}\n" }, { "answer_id": 58392435, "author": "Youngjae", "author_id": 361100, "author_profile": "https://Stackoverflow.com/users/361100", "pm_score": 3, "selected": false, "text": "System.Drawing.Bitmap using System.Drawing;\nusing System.Drawing.Imaging;\n\npublic IActionResult Get()\n{\n string filename = \"Image/test.jpg\";\n var bitmap = new Bitmap(filename);\n\n var ms = new System.IO.MemoryStream();\n bitmap.Save(ms, ImageFormat.Jpeg);\n ms.Position = 0;\n return new FileStreamResult(ms, \"image/jpeg\");\n}\n" }, { "answer_id": 59436372, "author": "mekb", "author_id": 11585798, "author_profile": "https://Stackoverflow.com/users/11585798", "pm_score": 2, "selected": false, "text": "byte[] File() public ActionResult ImageResult(Image image, ImageFormat format, string contentType) {\n using (var stream = new MemoryStream())\n {\n image.Save(stream, format);\n return File(stream.ToArray(), contentType);\n }\n }\n}\n using System.Drawing;\nusing System.Drawing.Imaging;\nusing System.IO;\nusing Microsoft.AspNetCore.Mvc;\n" }, { "answer_id": 63945194, "author": "Imran", "author_id": 5351352, "author_profile": "https://Stackoverflow.com/users/5351352", "pm_score": 1, "selected": false, "text": "public ActionResult GetImage(string imageFileName)\n{\n var path = Path.Combine(Server.MapPath(\"/Images\"), imageFileName + \".jpg\"); \n return base.File(path, \"image/jpeg\");\n}\n" }, { "answer_id": 71250836, "author": "Ben", "author_id": 959229, "author_profile": "https://Stackoverflow.com/users/959229", "pm_score": 1, "selected": false, "text": "public ActionResult Img(int? id) {\n MemoryStream ms = new MemoryStream(GetBytes(id));\n return new FileStreamResult(ms, \"image/png\");\n}\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/186062", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23341/" ]
186,071
<p>I've been profiling some queries in an application I'm working on, and I came across a query that was retrieving more rows than necessary, the result set being trimmed down in the application code.</p> <p>Changing a LEFT JOIN to an INNER JOIN trimmed the result set to just what was needed, and presumably would also be more performant (since less rows are selected). In reality, the LEFT JOIN'ed query was outperforming the INNER JOIN'ed, taking half the time to complete.</p> <p>LEFT JOIN: (127 total rows, Query took 0.0011 sec)</p> <p>INNER JOIN: (10 total rows, Query took 0.0024 sec)</p> <p>(I ran the queries multiple times and those are averages).</p> <p>Running EXPLAIN on both reveals nothing that explains the performance differences:</p> <p>For the INNER JOIN:</p> <pre><code>id select_type table type possible_keys key key_len ref rows Extra 1 SIMPLE contacts index NULL name 302 NULL 235 Using where 1 SIMPLE lists eq_ref PRIMARY PRIMARY 4 contacts.list_id 1 1 SIMPLE lists_to_users eq_ref PRIMARY PRIMARY 8 lists.id,const 1 1 SIMPLE tags eq_ref PRIMARY PRIMARY 4 lists_to_users.tag_id 1 1 SIMPLE users eq_ref email_2 email_2 302 contacts.email 1 Using where </code></pre> <p>For the LEFT JOIN:</p> <pre><code>id select_type table type possible_keys key key_len ref rows Extra 1 SIMPLE contacts index NULL name 302 NULL 235 Using where 1 SIMPLE lists eq_ref PRIMARY PRIMARY 4 contacts.list_id 1 1 SIMPLE lists_to_users eq_ref PRIMARY PRIMARY 8 lists.id,const 1 1 SIMPLE tags eq_ref PRIMARY PRIMARY 4 lists_to_users.tag_id 1 1 SIMPLE users eq_ref email_2 email_2 302 contacts.email 1 </code></pre> <p>And the query itself:</p> <pre><code>SELECT `contacts`.*, `lists`.`name` AS `group`, `lists`.`id` AS `group_id`, `lists`.`shared_yn`, `tags`.`name` AS `context`, `tags`.`id` AS `context_id`, `tags`.`color` AS `context_color`, `users`.`id` AS `user_id`, `users`.`avatar` FROM `contacts` LEFT JOIN `lists` ON lists.id=contacts.list_id LEFT JOIN `lists_to_users` ON lists_to_users.list_id=lists.id AND lists_to_users.user_id='1' AND lists_to_users.creator='1' LEFT JOIN `tags` ON tags.id=lists_to_users.tag_id INNER JOIN `users` ON users.email=contacts.email WHERE (contacts.user_id='1') ORDER BY `contacts`.`name` ASC </code></pre> <p>(The clause that I'm talking about is the last INNER JOIN on the 'users' table)</p> <p>The query runs on a MySQL 5.1 database, if it makes a difference.</p> <p>Does anyone has a clue on why the LEFT JOIN'ed query outperforms the INNER JOIN'ed on in this case?</p> <p><strong>UPDATE:</strong> Due to Tomalak's suggestion that the small tables I'm using were making the INNER JOIN more complex, I'd created a test database with some mock data. The 'users' table is 5000 rows, and the contacts table is ~500,000 rows. The results are the same (also the timings haven't changed which is surprising when you consider that the tables are much bigger now).</p> <p>I also ran ANALYZE and OPTIMIZE on the contacts table. Didn't make any discernible difference.</p>
[ { "answer_id": 186519, "author": "mike", "author_id": 19217, "author_profile": "https://Stackoverflow.com/users/19217", "pm_score": -1, "selected": false, "text": "SELECT SQL_NO_CACHE `contacts`.*, ...\n ANALYZE TABLE t1, t2;\nOPTIMIZE TABLE t1, t2;\n" }, { "answer_id": 188517, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 4, "selected": false, "text": "SELECT *\nFROM A\nWHERE A.ID = 3\n SELECT *\nFROM A\n LEFT JOIN B\n ON A.ID = B.ID\nWHERE B.ID is not null\n" }, { "answer_id": 778911, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "SELECT `contacts`.*, `lists`.`name` AS `group`, `lists`.`id` AS `group_id`, `lists`.`shared_yn`, `tags`.`name` AS `context`, `tags`.`id` AS `context_id`, `tags`.`color` AS `context_color`, `users`.`id` AS `user_id`, `users`.`avatar` \nFROM `contacts` \nINNER JOIN `users` ON contacts.user_id='1' AND users.email=contacts.email\nLEFT JOIN `lists` ON lists.id=contacts.list_id \nLEFT JOIN `lists_to_users` ON lists_to_users.user_id='1' AND lists_to_users.creator='1' AND lists_to_users.list_id=lists.id\nLEFT JOIN `tags` ON tags.id=lists_to_users.tag_id \nORDER BY `contacts`.`name` ASC\n SELECT COUNT(*)\nFROM `contacts` \nINNER JOIN `users` ON contacts.user_id='1' AND users.email=contacts.email\nLEFT JOIN `lists` ON lists.id=contacts.list_id \nLEFT JOIN `lists_to_users` ON lists_to_users.user_id='1' AND lists_to_users.creator='1' AND lists_to_users.list_id=lists.id\nLEFT JOIN `tags` ON tags.id=lists_to_users.tag_id \n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/186071", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10585/" ]
186,077
<p>I'd like to create a sparse file such that all-zero blocks don't take up actual disk space until I write data to them. Is it possible?</p>
[ { "answer_id": 193015, "author": "titaniumdecoy", "author_id": 18091, "author_profile": "https://Stackoverflow.com/users/18091", "pm_score": 4, "selected": false, "text": "#include <stdio.h>\n#include <string.h>\n#include <fcntl.h>\n#include <unistd.h>\n\nvoid create_file_with_hole(void)\n{\n int fd = open(\"file.hole\", O_WRONLY|O_TRUNC|O_CREAT, 0600);\n write(fd, \"Hello\", 5);\n lseek(fd, 99988, SEEK_CUR); // Make a hole\n write(fd, \"Goodbye\", 7);\n close(fd);\n}\n\nvoid create_file_without_hole(void)\n{\n int fd = open(\"file.nohole\", O_WRONLY|O_TRUNC|O_CREAT, 0600);\n write(fd, \"Hello\", 5);\n char buf[99988];\n memset(buf, 'a', 99988);\n write(fd, buf, 99988); // Write lots of bytes\n write(fd, \"Goodbye\", 7);\n close(fd);\n}\n\nint main()\n{\n create_file_with_hole();\n create_file_without_hole();\n return 0;\n}\n $ ls -ls\ntotal 400\n200 -rw------- 1 user staff 100000 Oct 10 13:48 file.hole\n200 -rw------- 1 user staff 100000 Oct 10 13:48 file.nohole $ ls -ls\ntotal 136\n 24 -rw------- 1 user nobody 100000 Oct 10 13:46 file.hole\n112 -rw------- 1 user nobody 100000 Oct 10 13:46 file.nohole" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/186077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10184/" ]
186,082
<p>In my webapplication (C#, .Net 3.5), made up of a <em>core</em> class library (containing the business logic, data layer and a couple of utility classes), a windows service project, a webservice project and the website project, I have a couple of static classes in the <em>core</em> library used by all other projects. These classes (for example the <strong>Log</strong> class) require some initialization (They have an <strong>Initialize</strong> method) in order to set them up for usage. As an example, the <strong>Initialize</strong> method of the <strong>Log</strong> class has a directory path parameter which tells the <strong>Log</strong>, where to save the logfiles to. Alternativly I was thinking of loading the "settings" for the <strong>Log</strong> class from a configuration file in the static constructor. The drawback is, that I need different settings for unit-testing then in production code.</p> <p>Is there a better way to design this? The drawback of this approach is, that all consumers of the static class will attempt to call Initialize. This is not really a problem because once initialized, the method will return immediately instead of executing the Initialize code again, but the design seems a bit weird to me. </p> <p>I hope my english is sufficient to explain what I'm after. Do not hesitate to ask if the question is not clear enough.</p>
[ { "answer_id": 195763, "author": "Cem Catikkas", "author_id": 3087, "author_profile": "https://Stackoverflow.com/users/3087", "pm_score": 0, "selected": false, "text": "public class Log\n{\n public static void debug(Object o, String message)\n {\n System.out.println(o + \" [DBUG] \" + message);\n }\n\n public static void info(Object o, String message)\n {\n System.out.println(o + \" [INFO] \" + message);\n }\n}\n public interface ILoggeer\n{\n void debug(Object o, String message);\n void info(Object o, String message);\n}\n\npublic class Log\n{\n private static ILogger log = new ConsoleLogger();\n\n public static setLogger(ILogger impl)\n {\n log = impl;\n }\n\n public static void debug(Object o, String message)\n {\n log.debug(o, message);\n }\n\n public static void info(Object o, String message)\n {\n log.info(o, message);\n }\n}\n\npublic class ConsoleLogger implements ILogger\n{\n public void debug(Object o, String message)\n {\n System.out.println(o + \" [DBUG] \" + message);\n }\n\n public void info(Object o, String message)\n {\n System.out.println(o + \" [INFO] \" + message);\n }\n}\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/186082", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16440/" ]
186,084
<p>Just this - How do you add a timer to a C# console application? It would be great if you could supply some example coding.</p>
[ { "answer_id": 186086, "author": "Ash", "author_id": 5023, "author_profile": "https://Stackoverflow.com/users/5023", "pm_score": 6, "selected": false, "text": "using System; \nusing System.Threading; \npublic static class Program \n{ \n public static void Main() \n { \n Console.WriteLine(\"Main thread: starting a timer\"); \n Timer t = new Timer(ComputeBoundOp, 5, 0, 2000); \n Console.WriteLine(\"Main thread: Doing other work here...\");\n Thread.Sleep(10000); // Simulating other work (10 seconds)\n t.Dispose(); // Cancel the timer now\n }\n // This method's signature must match the TimerCallback delegate\n private static void ComputeBoundOp(Object state) \n { \n // This method is executed by a thread pool thread \n Console.WriteLine(\"In ComputeBoundOp: state={0}\", state); \n Thread.Sleep(1000); // Simulates other work (1 second)\n // When this method returns, the thread goes back \n // to the pool and waits for another task \n }\n}\n" }, { "answer_id": 186114, "author": "jussij", "author_id": 14738, "author_profile": "https://Stackoverflow.com/users/14738", "pm_score": 5, "selected": false, "text": " using System;\n using System.Threading;\n\n class TimerExample\n {\n static public void Tick(Object stateInfo)\n {\n Console.WriteLine(\"Tick: {0}\", DateTime.Now.ToString(\"h:mm:ss\"));\n }\n\n static void Main()\n {\n TimerCallback callback = new TimerCallback(Tick);\n\n Console.WriteLine(\"Creating timer: {0}\\n\", \n DateTime.Now.ToString(\"h:mm:ss\"));\n\n // create a one second timer tick\n Timer stateTimer = new Timer(callback, null, 0, 1000);\n\n // loop here forever\n for (; ; )\n {\n // add a sleep for 100 mSec to reduce CPU usage\n Thread.Sleep(100);\n }\n }\n }\n c:\\temp>timer.exe\n Creating timer: 5:22:40\n\n Tick: 5:22:40\n Tick: 5:22:41\n Tick: 5:22:42\n Tick: 5:22:43\n Tick: 5:22:44\n Tick: 5:22:45\n Tick: 5:22:46\n Tick: 5:22:47\n" }, { "answer_id": 186134, "author": "mattlant", "author_id": 14642, "author_profile": "https://Stackoverflow.com/users/14642", "pm_score": 2, "selected": false, "text": "private void ThreadLoop(object callback)\n{\n while(true)\n {\n ((Delegate) callback).DynamicInvoke(null);\n Thread.Sleep(5000);\n }\n}\n Thread t = new Thread(new ParameterizedThreadStart(ThreadLoop));\n\nt.Start((Action)CallBack);\n private void CallBack()\n{\n //Do Something.\n}\n" }, { "answer_id": 7865126, "author": "Khalid Al Hajami", "author_id": 1009327, "author_profile": "https://Stackoverflow.com/users/1009327", "pm_score": 8, "selected": true, "text": "using System;\nusing System.Threading;\n\npublic static class Program \n{\n private Timer _timer = null;\n public static void Main() \n {\n // Create a Timer object that knows to call our TimerCallback\n // method once every 2000 milliseconds.\n _timer = new Timer(TimerCallback, null, 0, 2000);\n // Wait for the user to hit <Enter>\n Console.ReadLine();\n }\n\n private static void TimerCallback(Object o) \n {\n // Display the date/time when this method got called.\n Console.WriteLine(\"In TimerCallback: \" + DateTime.Now);\n }\n}\n" }, { "answer_id": 14537741, "author": "Yonatan Zetuny", "author_id": 1064546, "author_profile": "https://Stackoverflow.com/users/1064546", "pm_score": 3, "selected": false, "text": "static void Main()\n{\nObservable.Interval(TimeSpan.FromSeconds(10)).Subscribe(t => Console.WriteLine(\"I am called... {0}\", t));\n\nfor (; ; ) { }\n}\n" }, { "answer_id": 19440583, "author": "Steven de Salas", "author_id": 448568, "author_profile": "https://Stackoverflow.com/users/448568", "pm_score": 2, "selected": false, "text": "Timer /// <summary>\n/// Internal timer for window.setTimeout() and window.setInterval().\n/// This is to ensure that async calls always run on the same thread.\n/// </summary>\npublic class Timer : IDisposable {\n\n public void Tick()\n {\n if (Enabled && Environment.TickCount >= nextTick)\n {\n Callback.Invoke(this, null);\n nextTick = Environment.TickCount + Interval;\n }\n }\n\n private int nextTick = 0;\n\n public void Start()\n {\n this.Enabled = true;\n Interval = interval;\n }\n\n public void Stop()\n {\n this.Enabled = false;\n }\n\n public event EventHandler Callback;\n\n public bool Enabled = false;\n\n private int interval = 1000;\n\n public int Interval\n {\n get { return interval; }\n set { interval = value; nextTick = Environment.TickCount + interval; }\n }\n\n public void Dispose()\n {\n this.Callback = null;\n this.Stop();\n }\n\n}\n Timer timer = new Timer();\ntimer.Callback += delegate\n{\n if (once) { timer.Enabled = false; }\n Callback.execute(callbackId, args);\n};\ntimer.Enabled = true;\ntimer.Interval = ms;\ntimer.Start();\nWindow.timers.Add(Environment.TickCount, timer);\n while (true) {\n // Create a new list in case a new timer\n // is added/removed during a callback.\n foreach (Timer timer in new List<Timer>(timers.Values))\n {\n timer.Tick();\n }\n}\n" }, { "answer_id": 24232554, "author": "Real Caz", "author_id": 3478270, "author_profile": "https://Stackoverflow.com/users/3478270", "pm_score": 4, "selected": false, "text": "using System;\nusing System.Timers;\n\nnamespace TimerExample\n{\n class Program\n {\n static Timer timer = new Timer(1000);\n static int i = 10;\n\n static void Main(string[] args)\n { \n timer.Elapsed+=timer_Elapsed;\n timer.Start(); Console.Read();\n }\n\n private static void timer_Elapsed(object sender, ElapsedEventArgs e)\n {\n i--;\n\n Console.Clear();\n Console.WriteLine(\"=================================================\");\n Console.WriteLine(\" DEFUSE THE BOMB\");\n Console.WriteLine(\"\"); \n Console.WriteLine(\" Time Remaining: \" + i.ToString());\n Console.WriteLine(\"\"); \n Console.WriteLine(\"=================================================\");\n\n if (i == 0) \n {\n Console.Clear();\n Console.WriteLine(\"\");\n Console.WriteLine(\"==============================================\");\n Console.WriteLine(\" B O O O O O M M M M M ! ! ! !\");\n Console.WriteLine(\"\");\n Console.WriteLine(\" G A M E O V E R\");\n Console.WriteLine(\"==============================================\");\n\n timer.Close();\n timer.Dispose();\n }\n\n GC.Collect();\n }\n }\n}\n" }, { "answer_id": 59325239, "author": "XvXLuka222", "author_id": 12532096, "author_profile": "https://Stackoverflow.com/users/12532096", "pm_score": 0, "selected": false, "text": "public static void Main()\n {\n SetTimer();\n\n Console.WriteLine(\"\\nPress the Enter key to exit the application...\\n\");\n Console.WriteLine(\"The application started at {0:HH:mm:ss.fff}\", DateTime.Now);\n Console.ReadLine();\n aTimer.Stop();\n aTimer.Dispose();\n\n Console.WriteLine(\"Terminating the application...\");\n }\n\n private static void SetTimer()\n {\n // Create a timer with a two second interval.\n aTimer = new System.Timers.Timer(2000);\n // Hook up the Elapsed event for the timer. \n aTimer.Elapsed += OnTimedEvent;\n aTimer.AutoReset = true;\n aTimer.Enabled = true;\n }\n\n private static void OnTimedEvent(Object source, ElapsedEventArgs e)\n {\n Console.WriteLine(\"The Elapsed event was raised at {0:HH:mm:ss.fff}\",\n e.SignalTime);\n }\n" }, { "answer_id": 60019884, "author": "Ayub", "author_id": 579381, "author_profile": "https://Stackoverflow.com/users/579381", "pm_score": 2, "selected": false, "text": "async void RunMethodEvery(Action method, double seconds)\n{\n while (true)\n {\n await Task.Delay(TimeSpan.FromSeconds(seconds));\n method();\n }\n }\n" }, { "answer_id": 62138578, "author": "Alessio Di Salvo", "author_id": 2327256, "author_profile": "https://Stackoverflow.com/users/2327256", "pm_score": 0, "selected": false, "text": "System.Threading; var myTimer = new Timer((e) =>\n{\n // Code\n}, null, TimeSpan.Zero, TimeSpan.FromSeconds(5));\n\n GC.KeepAlive(myTimer)\n for (; ; ) { }\n}\n using System;\nusing System.Timers;\n\npublic class Example\n{\n private static Timer aTimer;\n\n public static void Main()\n {\n // Create a timer and set a two second interval.\n aTimer = new System.Timers.Timer();\n aTimer.Interval = 2000;\n\n // Hook up the Elapsed event for the timer. \n aTimer.Elapsed += OnTimedEvent;\n\n // Have the timer fire repeated events (true is the default)\n aTimer.AutoReset = true;\n\n // Start the timer\n aTimer.Enabled = true;\n\n Console.WriteLine(\"Press the Enter key to exit the program at any time... \");\n Console.ReadLine();\n }\n\n private static void OnTimedEvent(Object source, System.Timers.ElapsedEventArgs e)\n {\n Console.WriteLine(\"The Elapsed event was raised at {0}\", e.SignalTime);\n }\n}\n// The example displays output like the following: \n// Press the Enter key to exit the program at any time... \n// The Elapsed event was raised at 5/20/2015 8:48:58 PM \n// The Elapsed event was raised at 5/20/2015 8:49:00 PM \n// The Elapsed event was raised at 5/20/2015 8:49:02 PM \n// The Elapsed event was raised at 5/20/2015 8:49:04 PM \n// The Elapsed event was raised at 5/20/2015 8:49:06 PM \n" }, { "answer_id": 64139996, "author": "Bigabdoul", "author_id": 1831949, "author_profile": "https://Stackoverflow.com/users/1831949", "pm_score": 1, "selected": false, "text": "using PowerConsole;\n\nnamespace PowerConsoleTest\n{\n class Program\n {\n static readonly SmartConsole MyConsole = SmartConsole.Default;\n\n static void Main()\n {\n RunTimers();\n }\n\n public static void RunTimers()\n {\n // CAUTION: SmartConsole is not thread safe!\n // Spawn multiple timers carefully when accessing\n // simultaneously members of the SmartConsole class.\n\n MyConsole.WriteInfo(\"\\nWelcome to the Timers demo!\\n\")\n\n // SetTimeout is called only once after the provided delay and\n // is automatically removed by the TimerManager class\n .SetTimeout(e =>\n {\n // this action is called back after 5.5 seconds; the name\n // of the timer is useful should we want to clear it\n // before this action gets executed\n e.Console.Write(\"\\n\").WriteError(\"Time out occured after 5.5 seconds! \" +\n \"Timer has been automatically disposed.\\n\");\n\n // the next statement will make the current instance of \n // SmartConsole throw an exception on the next prompt attempt\n // e.Console.CancelRequested = true;\n\n // use 5500 or any other value not multiple of 1000 to \n // reduce write collision risk with the next timer\n }, millisecondsDelay: 5500, name: \"SampleTimeout\")\n\n .SetInterval(e =>\n {\n if (e.Ticks == 1)\n {\n e.Console.WriteLine();\n }\n\n e.Console.Write($\"\\rFirst timer tick: \", System.ConsoleColor.White)\n .WriteInfo(e.TicksToSecondsElapsed());\n\n if (e.Ticks > 4)\n {\n // we could remove the previous timeout:\n // e.Console.ClearTimeout(\"SampleTimeout\");\n }\n\n }, millisecondsInterval: 1000, \"EverySecond\")\n\n // we can add as many timers as we want (or the computer's resources permit)\n .SetInterval(e =>\n {\n if (e.Ticks == 1 || e.Ticks == 3) // 1.5 or 4.5 seconds to avoid write collision\n {\n e.Console.WriteSuccess(\"\\nSecond timer is active...\\n\");\n }\n else if (e.Ticks == 5)\n {\n e.Console.WriteWarning(\"\\nSecond timer is disposing...\\n\");\n\n // doesn't dispose the timer\n // e.Timer.Stop();\n\n // clean up if we no longer need it\n e.DisposeTimer();\n }\n else\n {\n System.Diagnostics.Trace.WriteLine($\"Second timer tick: {e.Ticks}\");\n }\n }, 1500)\n .Prompt(\"\\nPress Enter to stop the timers: \")\n \n // makes sure that any remaining timer is disposed off\n .ClearTimers()\n\n .WriteSuccess(\"Timers cleared!\\n\");\n }\n }\n}\n" }, { "answer_id": 69238786, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "StopWatch StopWatch stopwatch = new Stopwatch();\n// creating a new stopwatch class\nstopwatch.Start();\n// starting the stopwatch\nThread.Sleep(10000);\n// waiting for 10 seconds\n\nTimeSpan timespan = stopwatch.Elapsed;\n/* creating a new timespan class and concacting it with the elapsed of the \nstopwatch class */\nstring time = String.Format(\"{0:00}:{1:00}:{2:00}\",\ntimespan.Hours, timespan.Minutes, timespan.Seconds\n);\n\nConsole.Write($\"The time right now is {time}\");\n\nConsole.ReadKey();\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/186084", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3535708/" ]
186,094
<p>I'm setting up a simple SQLite database to hold sensor readings. The tables will look something like this:</p> <pre><code>sensors - id (pk) - name - description - units sensor_readings - id (pk) - sensor_id (fk to sensors) - value (actual sensor value stored here) - time (date/time the sensor sample was taken) </code></pre> <p>The application will be capturing about 100,000 sensor readings per month from about 30 different sensors, and I'd like to keep all sensor readings in the DB as long as possible.</p> <p>Most queries will be in the form</p> <pre><code>SELECT * FROM sensor_readings WHERE sensor_id = x AND time &gt; y AND time &lt; z </code></pre> <p>This query will usually return about 100-1000 results.</p> <p>So the question is, how big can the sensor_readings table get before the above query becomes too time consuming (more than a couple seconds on a standard PC).</p> <p>I know that one fix might be to create a separate sensor_readings table for each sensor, but I'd like to avoid this if it is unnecessary. Are there any other ways to optimize this DB schema?</p>
[ { "answer_id": 186337, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 2, "selected": false, "text": "time sensor_readings_old sensor_readings" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/186094", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10428/" ]
186,096
<p>Is there a simple and lightweight program to search over a text file and replace a string with regex?</p>
[ { "answer_id": 186116, "author": "Paul Dixon", "author_id": 6521, "author_profile": "https://Stackoverflow.com/users/6521", "pm_score": 2, "selected": false, "text": "sed -e 's/foo/bar/g' input.txt > output.txt\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/186096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/115/" ]
186,099
<p>I many times have to work with directories containing hundreds of thousands of files, doing text matching, replacing and so on. If I go the standard route of, say</p> <pre><code>grep foo * </code></pre> <p>I get the too many files error message, so I end up doing</p> <pre><code>for i in *; do grep foo $i; done </code></pre> <p>or</p> <pre><code>find ../path/ | xargs -I{} grep foo "{}" </code></pre> <p>But these are less than optimal (create a new grep process per each file).</p> <p>This looks like more of a limitation in the size of the arguments programs can receive, because the * in the for loop works alright. But, in any case, what's the proper way to handle this?</p> <p>PS: Don't tell me to do grep -r instead, I know about that, I'm thinking about tools that do not have a recursive option.</p>
[ { "answer_id": 186167, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 0, "selected": false, "text": "for i in *; do\n grep foo $i\ndone\n find ../path/ | xargs grep foo\n" }, { "answer_id": 186171, "author": "JesperE", "author_id": 13051, "author_profile": "https://Stackoverflow.com/users/13051", "pm_score": 3, "selected": false, "text": "find . -print0 | xargs -0 grep -H foo\n" }, { "answer_id": 189327, "author": "Charles Duffy", "author_id": 14122, "author_profile": "https://Stackoverflow.com/users/14122", "pm_score": 4, "selected": true, "text": "find ../path -exec grep foo '{}' +\n + ;" }, { "answer_id": 189429, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "find /some -type f -exec some command {} \\; \n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/186099", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5190/" ]
186,106
<p>I am new to web programming and have been exploring issues related to web security.</p> <p>I have a form where the user can post two types of data - lets call them &quot;safe&quot; and &quot;unsafe&quot; (from the point of view of sql).</p> <p>Most places recommend storing both parts of the data in database after sanitizing the &quot;unsafe&quot; part (to make it &quot;safe&quot;).</p> <p>I am wondering about a different approach - to store the &quot;safe&quot; data in database and &quot;unsafe&quot; data in files (outside the database). Ofcourse this approach creates its own set of problems related to maintaining association between files and DB entries. But are there any other major issues with this approach, especially related to security?</p> <blockquote> <p>UPDATE: Thanks for the responses! Apologies for not being clear regarding what I am considering &quot;safe&quot; so some clarification is in order. I am using Django, and the form data that I am considering &quot;safe&quot; is accessed through the form's &quot;cleaned_data&quot; dictionary which does all the necessary escaping.</p> <p>For the purpose of this question, let us consider a wiki page. The title of wiki page does not need to have any styling attached with it. So, this can be accessed through form's &quot;cleaned_data&quot; dictionary which will convert the user input to &quot;safe&quot; format. But since I wish to provide the users the ability to arbitrarily style their content, I can't perhaps access the content part using &quot;cleaned_data&quot; dictionary.</p> <p>Does the file approach solve the security aspects of this problem? Or are there other security issues that I am overlooking?</p> </blockquote>
[ { "answer_id": 186184, "author": "Paul Dixon", "author_id": 6521, "author_profile": "https://Stackoverflow.com/users/6521", "pm_score": 1, "selected": false, "text": "$db->Execute(\"insert into foo(x,y,z) values (?,?,?)\", array($one, $two, $three));\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/186106", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
186,108
<p>In a vxWorks Real-Time process, you can pass environment variables as one of the parameter of the <strong>main</strong> routine.</p> <p>How do you use the environment variables in the kernel context?</p>
[ { "answer_id": 186124, "author": "LeopardSkinPillBoxHat", "author_id": 22489, "author_profile": "https://Stackoverflow.com/users/22489", "pm_score": 3, "selected": true, "text": "putenv \"<VARIABLE NAME>=<VALUE>\"\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/186108", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10703/" ]
186,125
<p>I would like to use a secure SSL login on my website! I have not used SSL before, so I am looking for some good reading. Can anyone tell me where I can find some sample code of SSL snippets or page code. (Not too technical)</p> <ul> <li>I do have a static IP</li> <li>My host is set-up to handle SSL Pages. </li> </ul> <p>Interested in: Basic page code. / Tree structure. / Other </p> <p>Paul </p>
[ { "answer_id": 186138, "author": "Matt Mitchell", "author_id": 364, "author_profile": "https://Stackoverflow.com/users/364", "pm_score": 2, "selected": false, "text": "if($requireSSL && $_SERVER['SERVER_PORT'] != 443) \n{\n header(\"HTTP/1.1 301 Moved Permanently\");\n header(\"Location: https://\".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);\n exit();\n}\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/186125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
186,131
<p>He're an interesting problem that looks for the most Pythonic solution. Suppose I have a list of mappings <code>{'id': id, 'url': url}</code>. Some <code>id</code>s in the list are duplicate, and I want to create a new list, with all the duplicates removed. I came up with the following function:</p> <pre><code>def unique_mapping(map): d = {} for res in map: d[res['id']] = res['url'] return [{'id': id, 'url': d[id]} for id in d] </code></pre> <p>I suppose it's quite efficient. But is there a "more Pythonic" way ? Or perhaps a more efficient way ?</p>
[ { "answer_id": 186295, "author": "DzinX", "author_id": 18745, "author_profile": "https://Stackoverflow.com/users/18745", "pm_score": 3, "selected": true, "text": "def unique_mapping(mappings):\n return dict((m['id'], m) for m in mappings).values()\n def unique_mapping(mappings):\n addedIds = set()\n for m in mappings:\n mId = m['id']\n if mId not in addedIds:\n addedIds.add(mId)\n yield m\n list(unique_mappings(mappings))" }, { "answer_id": 186317, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 2, "selected": false, "text": "def unique_mapping(items):\n s = set()\n for res in items:\n if res['id'] not in s:\n yield res\n s.add(res['id'])\n" }, { "answer_id": 187041, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 1, "selected": false, "text": ">>> someListOfDicts= [\n {'url': 'http://a', 'id': 'a'}, \n {'url': 'http://b', 'id': 'b'}, \n {'url': 'http://c', 'id': 'a'}]\n\n>>> dict( [(x['id'],x) for x in someListOfDicts ] ).values()\n\n[{'url': 'http://c', 'id': 'a'}, {'url': 'http://b', 'id': 'b'}]\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/186131", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8206/" ]
186,160
<p>I have a table in the database that I'm retrieving using LINQ to SQL, and as a part of my processing I want to add to this list, then update the database with the new items + any changes I've made.</p> <p>What I thought I could do was this:</p> <pre><code>var list = (from item in db.Table select item).ToList(); [do processing where I modify items &amp; add to the list] list = list.Distinct(); db.SubmitChanges(); </code></pre> <p>What happens is that the modifications happed (ie. SQL updates) but any new items I add to the list don't get added.</p> <p>Obviously I'm doing this wrong, what is the correct way to modify &amp; add to a list of DB entities, then commit all the updates &amp; inserts?</p>
[ { "answer_id": 186221, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 4, "selected": true, "text": "Item item;\nif (needNewOne)\n{\n item = new Item();\n db.InsertOnSubmit(item);\n}\nelse\n{\n item = list[i];\n}\n/// build new or modify existing item\n/// :\ndb.SubmitChanges();\n" }, { "answer_id": 186223, "author": "Sam", "author_id": 7021, "author_profile": "https://Stackoverflow.com/users/7021", "pm_score": 1, "selected": false, "text": "db.InsertOnSubmit(newrow);\ndb.SubmitChanges();\n" }, { "answer_id": 186283, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 2, "selected": false, "text": "static void EnsureInsertedOnSubmit<TEntity>( this Table<TEntity> table\n ,IEnumerable<TEntity> entities)\n { foreach(var entity in entities) \n { if ( table.GetModifiedMembers(entity).Length == 0 \n && table.GetOriginalEntityState(entity) == default(TEntity))\n { table.InsertOnSubmit(entity);\n }\n }\n }\n var list = db.Table1.ToList();\n list.Add(new Item());\n db.Table1.EnsureInsertedOnSubmit(list);\n db.SubmitChanges();\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/186160", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2975/" ]
186,196
<p>At the moment I check in all my files (including dll's, VS solution files, images, etc). I often need to checkout these files to a staging server or to a another developer and so having these files there means the project is setup there all ready to go.</p> <p>Whats the best practice here?</p> <p>EDIT: If I don't add the generated files like the dll files how do I ensure they are present when updating the staging server?</p>
[ { "answer_id": 186253, "author": "Sietse", "author_id": 6400, "author_profile": "https://Stackoverflow.com/users/6400", "pm_score": 1, "selected": false, "text": "mvn eclipse:eclipse mvn eclipse:clean" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/186196", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23230/" ]
186,202
<p>What is the most elegant way to solve this:</p> <ul> <li>open a file for reading, but only if it is not already opened for writing</li> <li>open a file for writing, but only if it is not already opened for reading or writing</li> </ul> <p>The built-in functions work like this</p> <pre><code>&gt;&gt;&gt; path = r"c:\scr.txt" &gt;&gt;&gt; file1 = open(path, "w") &gt;&gt;&gt; print file1 &lt;open file 'c:\scr.txt', mode 'w' at 0x019F88D8&gt; &gt;&gt;&gt; file2 = open(path, "w") &gt;&gt;&gt; print file2 &lt;open file 'c:\scr.txt', mode 'w' at 0x02332188&gt; &gt;&gt;&gt; file1.write("111") &gt;&gt;&gt; file2.write("222") &gt;&gt;&gt; file1.close() </code></pre> <p>scr.txt now contains '111'.</p> <pre><code>&gt;&gt;&gt; file2.close() </code></pre> <p>scr.txt was overwritten and now contains '222' (on Windows, Python 2.4).</p> <p>The solution should work inside the same process (like in the example above) as well as when another process has opened the file.<br> It is preferred, if a crashing program will not keep the lock open.</p>
[ { "answer_id": 186300, "author": "kender", "author_id": 4172, "author_profile": "https://Stackoverflow.com/users/4172", "pm_score": 0, "selected": false, "text": "import time\nclass ExclusiveFile(file):\n openFiles = {}\n fileLocks = []\n\n class FileNotExclusiveException(Exception):\n pass\n\n def __init__(self, *args):\n\n sMode = 'r'\n sFileName = args[0]\n try:\n sMode = args[1]\n except:\n pass\n while sFileName in ExclusiveFile.fileLocks:\n time.sleep(1)\n\n ExclusiveFile.fileLocks.append(sFileName)\n\n if not sFileName in ExclusiveFile.openFiles.keys() or (ExclusiveFile.openFiles[sFileName] == 'r' and sMode == 'r'):\n ExclusiveFile.openFiles[sFileName] = sMode\n try:\n file.__init__(self, sFileName, sMode)\n finally:\n ExclusiveFile.fileLocks.remove(sFileName)\n else:\n ExclusiveFile.fileLocks.remove(sFileName)\n raise self.FileNotExclusiveException(sFileName)\n\n def close(self):\n del ExclusiveFile.openFiles[self.name]\n file.close(self)\n file >>> f = ExclusiveFile('/tmp/a.txt', 'r')\n>>> f\n<open file '/tmp/a.txt', mode 'r' at 0xb7d7cc8c>\n>>> f1 = ExclusiveFile('/tmp/a.txt', 'r')\n>>> f1\n<open file '/tmp/a.txt', mode 'r' at 0xb7d7c814>\n>>> f2 = ExclusiveFile('/tmp/a.txt', 'w') # can't open it for writing now\nexclfile.FileNotExclusiveException: /tmp/a.txt\n" }, { "answer_id": 186464, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 6, "selected": true, "text": "portalocker.lock(file, flags)\n" }, { "answer_id": 188827, "author": "gz.", "author_id": 3665, "author_profile": "https://Stackoverflow.com/users/3665", "pm_score": 2, "selected": false, "text": "FILE_SHARE_READ CreateFile WriteFile import winerror, pywintypes, win32file\n\nclass LockError(StandardError):\n pass\n\nclass WriteLockedFile(object):\n \"\"\"\n Using win32 api to achieve something similar to file(path, 'wb')\n Could be adapted to handle other modes as well.\n \"\"\"\n def __init__(self, path):\n try:\n self._handle = win32file.CreateFile(\n path,\n win32file.GENERIC_WRITE,\n 0,\n None,\n win32file.OPEN_ALWAYS,\n win32file.FILE_ATTRIBUTE_NORMAL,\n None)\n except pywintypes.error, e:\n if e[0] == winerror.ERROR_SHARING_VIOLATION:\n raise LockError(e[2])\n raise\n def close(self):\n self._handle.close()\n def write(self, str):\n win32file.WriteFile(self._handle, str)\n >>> path = \"C:\\\\scr.txt\"\n>>> file1 = WriteLockedFile(path)\n>>> file2 = WriteLockedFile(path) #doctest: +IGNORE_EXCEPTION_DETAIL\nTraceback (most recent call last):\n ...\nLockError: ...\n>>> file1.write(\"111\")\n>>> file1.close()\n>>> print file(path).read()\n111\n" }, { "answer_id": 195021, "author": "Federico A. Ramponi", "author_id": 18770, "author_profile": "https://Stackoverflow.com/users/18770", "pm_score": 4, "selected": false, "text": "# mount -o remount,mand /dev/hdXY # chmod g-x,g+s yourfile fcntl.flock(fd, fcntl.LOCK_EX)" }, { "answer_id": 21444311, "author": "parity3", "author_id": 1454536, "author_profile": "https://Stackoverflow.com/users/1454536", "pm_score": 2, "selected": false, "text": "import os,time\ndef get_tmp_file():\n filename='tmp_%s_%s'%(os.getpid(),time.time())\n open(filename).close()\n return filename\n\ndef do_exclusive_work():\n print 'exclusive work being done...'\n\nnum_tries=10\nwait_time=10\nlock_filename='filename.lock'\nacquired=False\nfor try_num in xrange(num_tries):\n tmp_filename=get_tmp_file()\n if not os.path.exists(lock_filename):\n try:\n os.rename(tmp_filename,lock_filename)\n acquired=True\n except (OSError,ValueError,IOError), e:\n pass\n if acquired:\n try:\n do_exclusive_work()\n finally:\n os.remove(lock_filename)\n break\n os.remove(tmp_filename)\n time.sleep(wait_time)\nassert acquired, 'maximum tries reached, failed to acquire lock file'\n try:\n if os.name != 'nt': # non-windows needs a create-exclusive operation\n fd = os.open(lock_filename, os.O_WRONLY | os.O_CREAT | os.O_EXCL)\n os.close(fd)\n # non-windows os.rename will overwrite lock_filename silently.\n # We leave this call in here just so the tmp file is deleted but it could be refactored so the tmp file is never even generated for a non-windows OS\n os.rename(tmp_filename,lock_filename)\n acquired=True\nexcept (OSError,ValueError,IOError), e:\n if os.name != 'nt' and not 'File exists' in str(e): raise\n" }, { "answer_id": 28532580, "author": "akrueger", "author_id": 3693375, "author_profile": "https://Stackoverflow.com/users/3693375", "pm_score": 3, "selected": false, "text": "if not os.path.exists(lock_filename):\n try:\n os.rename(tmp_filename,lock_filename)\n" }, { "answer_id": 59795288, "author": "Josh Correia", "author_id": 7487335, "author_profile": "https://Stackoverflow.com/users/7487335", "pm_score": 2, "selected": false, "text": "from filelock import FileLock\n\nlockfile = r\"c:\\scr.txt\"\nlock = FileLock(lockfile + \".lock\")\nwith lock:\n file = open(path, \"w\")\n file.write(\"111\")\n file.close()\n with lock:" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/186202", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19166/" ]
186,207
<p>I've seen that a Processor Pack is available for Visual Studio 6, however it appears to only be available for users with SP5 and I am already using SP6:</p> <p><em>In addition, the Visual C++ Processor Pack (VCPP) was removed from Service Pack 6. If you have the VCPP installed, installing SP6 will remove it from your machine. If you wish to continue using the VCPP, you will need to stay with SP5 or migrate to Visual Studio 2002 or 2003 (recommended).</em></p> <p>Firstly, is this processor pack compatible with Visual Studio 6 SP6?</p> <p>Secondly, would it actually help me? I'm concerned about getting the most from my application, but it needs to run on all flavours of Intel and AMD chips so I can't just target one platform.</p>
[ { "answer_id": 3918513, "author": "b w", "author_id": 4126, "author_profile": "https://Stackoverflow.com/users/4126", "pm_score": 2, "selected": false, "text": "latest HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\6.0\\ServicePacks" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/186207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15669/" ]
186,208
<p>What Latex styles do you use and where do you find them?</p> <p>The reason I'm asking this is that it seems that some 99.9999% of all styles on the internet are copies of each other and of a <a href="http://www.tug.org/texshowcase/ps_s_1b.pdf" rel="noreferrer">physics exam paper</a></p> <p>However, when you try to find a style for a paper like <a href="http://www.tug.org/texshowcase/en_gb_eclipse_114.pdf" rel="noreferrer">this one</a>... Good luck, you are never going to find it.</p> <p>Creating your own style is often not really an option, because it requires you to dig quite deep into the very advanced features of TeX/LaTeX and fighting your way against possible incompatibilities with document classes/packages/whatnot.</p>
[ { "answer_id": 186452, "author": "Will Robertson", "author_id": 4161, "author_profile": "https://Stackoverflow.com/users/4161", "pm_score": 4, "selected": true, "text": "\\newcommand\\catalogueEntry[4]{%\n \\parbox[t]{0.23\\linewidth}{\\textbf{#1}}%\n \\hfill\n \\parbox[t]{0.23\\linewidth}{\\includegraphics{#2}}%\n \\hfill\n \\parbox[t]{0.23\\linewidth}{\\textbf{Characteristics}\\\\ #3}%\n \\hfill\n \\parbox[t]{0.23\\linewidth}{\\textbf{Application}\\\\ #4}\n}\n \\catalogueEntry{Spotlights}{spotlight.jpg}\n {Eclipse spotlights are...}\n {Narrow to medium...}\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/186208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/445049/" ]
186,211
<p>I am using Windows 2003. I have mapped a web application into a virtual directory. This is built on framework 1.1 When i try to browse to the default page i get a error as </p> <p>Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately. </p> <p>Parser Error Message: Access is denied: 'Interop.MSDASC'.</p> <p>Source Error: </p> <p>Line 196: Line 197: Line 198: Line 199: Line 200: </p> <p>Source File: c:\windows\microsoft.net\framework\v1.1.4322\Config\machine.config Line: 198 </p> <p>Assembly Load Trace: The following information can be helpful to determine why the assembly 'Interop.MSDASC' could not be loaded.</p>
[ { "answer_id": 186452, "author": "Will Robertson", "author_id": 4161, "author_profile": "https://Stackoverflow.com/users/4161", "pm_score": 4, "selected": true, "text": "\\newcommand\\catalogueEntry[4]{%\n \\parbox[t]{0.23\\linewidth}{\\textbf{#1}}%\n \\hfill\n \\parbox[t]{0.23\\linewidth}{\\includegraphics{#2}}%\n \\hfill\n \\parbox[t]{0.23\\linewidth}{\\textbf{Characteristics}\\\\ #3}%\n \\hfill\n \\parbox[t]{0.23\\linewidth}{\\textbf{Application}\\\\ #4}\n}\n \\catalogueEntry{Spotlights}{spotlight.jpg}\n {Eclipse spotlights are...}\n {Narrow to medium...}\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/186211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20951/" ]
186,232
<p>I want to use implicit linking in my project , and nmake really wants a .def file . The problem is , that this is a class , and I don't know what to write in the exports section . Could anyone point me in the right direction ?</p> <p>The error message is the following :</p> <p><strong>NMAKE : U1073: don't know how to make 'DLLCLASS.def'</strong></p> <p>P.S: I'm trying to build using Windows CE Platform Builder .</p>
[ { "answer_id": 186240, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 3, "selected": false, "text": "__declspec(dllexport)" }, { "answer_id": 186834, "author": "xtofl", "author_id": 6610, "author_profile": "https://Stackoverflow.com/users/6610", "pm_score": 3, "selected": true, "text": "class A {\n public:\n A( int ){}\n};\n dumpbin ??0A@@QAE@H@Z (public: __thiscall A::A(int))" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/186232", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11234/" ]
186,237
<p>I've got a "Schroedinger's Cat" type of problem here -- my program (actually the test suite for my program, but a program nonetheless) is crashing, but only when built in release mode, and only when launched from the command line. Through caveman debugging (ie, nasty printf() messages all over the place), I have determined the test method where the code is crashing, though unfortunately the actual crash seems to happen in some destructor, since the last trace messages I see are in other destructors which execute cleanly.</p> <p>When I attempt to run this program inside of Visual Studio, it doesn't crash. Same goes when launching from WinDbg.exe. The crash only occurs when launching from the command line. This is happening under Windows Vista, btw, and unfortunately I don't have access to an XP machine right now to test on.</p> <p>It would be really nice if I could get Windows to print out a stack trace, or <em>something</em> other than simply terminating the program as if it had exited cleanly. Does anyone have any advice as to how I could get some more meaningful information here and hopefully fix this bug?</p> <p>Edit: The problem was indeed caused by an out-of-bounds array, <a href="https://stackoverflow.com/questions/186237/program-only-crashes-as-release-build-how-to-debug#187966">which I describe more in this post</a>. Thanks everybody for your help in finding this problem!</p>
[ { "answer_id": 186247, "author": "David Dibben", "author_id": 5022, "author_profile": "https://Stackoverflow.com/users/5022", "pm_score": 6, "selected": false, "text": "int* p;\n....\nif (p == 0) { // do stuff }\n" }, { "answer_id": 186269, "author": "Franci Penov", "author_id": 17028, "author_profile": "https://Stackoverflow.com/users/17028", "pm_score": 4, "selected": false, "text": "windbg /I\n" }, { "answer_id": 186280, "author": "DocMax", "author_id": 6234, "author_profile": "https://Stackoverflow.com/users/6234", "pm_score": 1, "selected": false, "text": "adplus.vbs -crash -p <process_id>\n adplus.vbs -crash -sc your_app.exe\n" }, { "answer_id": 187966, "author": "Nik Reiman", "author_id": 14302, "author_profile": "https://Stackoverflow.com/users/14302", "pm_score": 4, "selected": false, "text": "char *end = static_cast<char*>(attr->data) + attr->dataSize;\n char *end = static_cast<char*>(attr->data) + attr->dataSize - 1;\n" }, { "answer_id": 18513077, "author": "Sebastian", "author_id": 214777, "author_profile": "https://Stackoverflow.com/users/214777", "pm_score": 5, "selected": false, "text": "std::set_terminate std::terminate" }, { "answer_id": 29322082, "author": "Gaiger Chen", "author_id": 3203791, "author_profile": "https://Stackoverflow.com/users/3203791", "pm_score": 1, "selected": false, "text": "char a[8];\nmemset(&a[0], 0, 16);\n\n: /*use array a doing some thing */\n" }, { "answer_id": 50119033, "author": "Vlad Serhiienko", "author_id": 1474407, "author_profile": "https://Stackoverflow.com/users/1474407", "pm_score": 1, "selected": false, "text": "#define MATHFU_COMPILE_WITHOUT_SIMD_SUPPORT 1" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/186237", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14302/" ]
186,244
<p>One of the major advantages with Javascript is said to be that it is a prototype based language. </p> <p>But what does it mean that Javascript is prototype based, and why is that an advantage?</p>
[ { "answer_id": 186368, "author": "artificialidiot", "author_id": 7988, "author_profile": "https://Stackoverflow.com/users/7988", "pm_score": 3, "selected": false, "text": "myobject.prototype=unkownobject;\nmyobject.newproperty=1;\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/186244", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1918/" ]
186,277
<p>In the company where I work we have major releases twice every year. Extensive testing (automated and manual) is done the weeks before. The automated tests produce logfiles, the results of the manual tests are written down in test plans (Word documents). As you can imagine this results in a lot of different files to be managed and interpreted by the test engineers. <br> How do you <code>organize</code> your release tests? <br> E.g. Do use a bug tracker? Do you use any other tools? How do you specify what has to be tested? Who does the testing? How is the ratio developers / testers?</p>
[ { "answer_id": 186532, "author": "Ilya Kochetov", "author_id": 15329, "author_profile": "https://Stackoverflow.com/users/15329", "pm_score": 2, "selected": false, "text": "1" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/186277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26395/" ]
186,307
<p>A project I'm working on will pull XML from a web-server and build a data store from it. The data will have certain core fields but needs to be extendable... for example I have a and later might want to have which adds extra fields.</p> <p>In the Flex app, I don't want the central data store to be working on XML objects or simply putting the properties into Objects. I want to have strong types, e.g a Person class, which are created/populated from the XML.</p> <p>How can this be done in a flexible way? Is Flex able to automatically build a Person from an XML if the attribute names match, or do I need to write conversion functionality for , , etc?</p>
[ { "answer_id": 186991, "author": "Raleigh Buckner", "author_id": 1153, "author_profile": "https://Stackoverflow.com/users/1153", "pm_score": 2, "selected": false, "text": "package {\n\n public class Foo{\n\n public function Foo(barparam1:String, barparam2:uint, barparam3:String, barparam4:Number){\n this._bar1 = barparam1;\n this._bar2 = barparam2;\n this._bar3 = barparam3;\n this._bar4 = barparam4;\n }\n\n protected var _bar1:String;\n protected var _bar2:uint;\n protected var _bar3:String;\n protected var _bar4:Number;\n\n public function get bar1():String{ return this._bar1; }\n public function get bar2():uint { return this._bar2; }\n public function get bar3():String { return this._bar3; }\n public function get bar4():Number { return this._bar4; }\n\n public function toString():String{\n return \"[Foo bar1:\\\"\" + this.bar1 + \"\\\", bar3:\\\"\" + this.bar3 + \"\\\", bar2:\" + this.bar2 + \", bar4:\" + this.bar4 + \"]\";\n }\n\n public static function createFromXml(xmlParam:XML):Foo{\n\n /* XML Format:\n <foo bar1=\"bar1value\" bar2=\"5\">\n <bar3>bar3 data</bar3>\n <bar4>10</bar4>\n </foo>\n */\n\n return new Foo(xmlParam.@bar1, xmlParam.@bar2, xmlParam.bar3[0], xmlParam.bar4[0]);\n }\n }\n }\n" }, { "answer_id": 194517, "author": "James Fassett", "author_id": 27081, "author_profile": "https://Stackoverflow.com/users/27081", "pm_score": 1, "selected": false, "text": "package model.vo\n{\npublic class ConfigVO\n{\n public var foo:String;\n public var bar:int;\n public var baz:Boolean;\n public var sections:Array;\n\n public function ConfigVO(xml:XML)\n {\n parseXML(xml);\n }\n\n private function parseXML(xml:XML):void\n {\n foo = xml.foo;\n bar = xml.bar;\n baz = (xml.baz == \"true\");\n\n sections = [];\n for each(var sectionXML:XML in xml.section)\n {\n sections.push(new SectionVO(sectionXML));\n }\n }\n}\n}\n\npackage model.vo\n{\npublic class SectionVO\n{\n public var title:String;\n\n public function SectionVO(xml:XML)\n {\n parseXML(xml);\n }\n\n private function parseXML(xml:XML):void\n {\n title = xml.@title;\n }\n}\n}\n package model\n{\n public class XMLReader\n {\n // maps <tagname> to a class \n private static var elementClassMap:Object =\n {\n \"section\": SectionVO,\n \"person\": PersonVO\n };\n\n public var parsedElements:Array;\n\n public function XMLReader(xml:XML)\n {\n parsedElements = [];\n parseXML(xml);\n }\n\n private function parseXML(xml:XML):void\n {\n var voClass:Class;\n for each(var element:XML in xml.children())\n {\n voClass = elementClassMap[element.name().localname];\n if(voClass)\n {\n parsedElements.push(new voClass(element));\n }\n }\n }\n }\n}\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/186307", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13220/" ]
186,311
<p>I have a list of Date objects, and a target Date. I want to find the date in the list that's nearest to the target date, but only dates that are before the target date.</p> <p>Example: 2008-10-1 2008-10-2 2008-10-4</p> <p>With a target date of 2008-10-3, I want to get 2008-10-2</p> <p>What is the best way to do it?</p>
[ { "answer_id": 186318, "author": "Sietse", "author_id": 6400, "author_profile": "https://Stackoverflow.com/users/6400", "pm_score": 2, "selected": false, "text": "private Date getDateNearest(List<Date> dates, Date targetDate){\n for (Date date : dates) {\n if (date.compareTo(targetDate) <= 0) return date;\n }\n\n return targetDate;\n}\n" }, { "answer_id": 186420, "author": "Keeg", "author_id": 21059, "author_profile": "https://Stackoverflow.com/users/21059", "pm_score": 3, "selected": false, "text": "private Date getDateNearest(List<Date> dates, Date targetDate){\n return new TreeSet<Date>(dates).lower(targetDate);\n}\n" }, { "answer_id": 186480, "author": "Jean", "author_id": 7898, "author_profile": "https://Stackoverflow.com/users/7898", "pm_score": 4, "selected": true, "text": "private Date getDateNearest(List<Date> dates, Date targetDate){\n Date returnDate = targetDate\n for (Date date : dates) {\n // if the current iteration'sdate is \"before\" the target date\n if (date.compareTo(targetDate) <= 0) {\n // if the current iteration's date is \"after\" the current return date\n if (date.compareTo(returnDate) > 0){\n returnDate=date;\n }\n }\n } \n return returnDate;\n}\n" }, { "answer_id": 186481, "author": "Daniel Hiller", "author_id": 16193, "author_profile": "https://Stackoverflow.com/users/16193", "pm_score": 1, "selected": false, "text": "import java.text.ParseException;\nimport java.text.SimpleDateFormat;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Date;\nimport java.util.List;\nimport java.util.TreeSet;\n\npublic class GetNearestDate {\n\n public static void main( String[] args ) throws ParseException {\n\n final SimpleDateFormat simpleDateFormat = new SimpleDateFormat( \"dd.MM.yyyy HH:mm:ss\" );\n\n List< Date > otherDates = Arrays.asList( new Date[]{\n simpleDateFormat.parse( \"01.01.2008 01:00:00\" ) ,\n simpleDateFormat.parse( \"01.01.2008 01:00:02\" ) } );\n System.out.println( simpleDateFormat.parse( \"01.01.2008 01:00:00\" ).equals(\n get( otherDates , simpleDateFormat.parse( \"01.01.2008 01:00:01\" ) ) ) );\n System.out.println( simpleDateFormat.parse( \"01.01.2008 01:00:02\" ).equals(\n get( otherDates , simpleDateFormat.parse( \"01.01.2008 01:00:03\" ) ) ) );\n System.out.println( null == get( otherDates , simpleDateFormat.parse( \"01.01.2008 01:00:00\" ) ) );\n }\n\n public static Date get( List< Date > otherDates , Date dateToApproach ) {\n final TreeSet< Date > set = new TreeSet< Date >( otherDates );\n set.add( dateToApproach );\n final ArrayList< Date > list = new ArrayList< Date >( set );\n final int indexOf = list.indexOf( dateToApproach );\n if ( indexOf == 0 )\n return null;\n return list.get( indexOf - 1 );\n }\n\n}\n" }, { "answer_id": 38033180, "author": "Basil Bourque", "author_id": 642706, "author_profile": "https://Stackoverflow.com/users/642706", "pm_score": 1, "selected": false, "text": "NavigableSet::lower lower NavigableSet TreeSet java.util.Date java.sql.Date LocalDate LocalDate ZoneId ZoneId zoneId = ZoneId.of( \"America/Montreal\" );\nLocalDate today = LocalDate.now( zoneId ); // 2016-06-25\n 2008-10-01 2008-10-1 DateTimeFormatter NavigableSet dates = new TreeSet( 3 );\ndates.add( LocalDate.parse( \"2008-10-01\" );\ndates.add( LocalDate.parse( \"2008-10-02\" );\ndates.add( LocalDate.parse( \"2008-10-04\" );\nLocalDate target = LocalDate.parse( \"2008-10-03\" );\nLocalDate hit = dates.lower( target );\n// Reminder: test for `null == hit` to see if anything found.\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/186311", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6400/" ]
186,313
<p>I'm using the Scriptaculous library to slap an appealing UI on an application which helps an enduser build lists. Let's say its for pizza creation.</p> <p>To fill out an order, you drag a size of pizza from the pizza palette into the orders droppable. Once it is put in there, it gets replaced with a new div which is both draggable (because you can junk it by moving it back to the palette) and droppable (because you can add ingredients to it). </p> <p>You can then add ingredients from your ingredients palette to any of the pizzas you have sitting in the group of orders. </p> <p>I've successfully implemented these bits and everything works fine. The stickler: if I attempt to drag and drop the ingredient from a placed pizza, which is properly marked as draggable and which, for good measure, is z-positioned above the pizza, it instead grabs the pizza wholesale. This makes it impossible for me to undo ingredient selections, which is a key feature for this screen.</p> <p>Any suggestions on how I can get this to do what I want? Ideally I'd like to keep the simple drag-on, drag-off UI as it is <em>worlds</em> more intuitive than what we were using previously. (A multi-stage HTML form... shudder...)</p>
[ { "answer_id": 187094, "author": "Diodeus - James MacFarlane", "author_id": 12579, "author_profile": "https://Stackoverflow.com/users/12579", "pm_score": 0, "selected": false, "text": "<table border=\"1\" cellpadding=\"5\">\n<tr>\n <td valign=\"top\">\n <ul id='fList' style='border:1px solid #c0c0c0'>\n <li class='fruit'>Apples</li>\n <li class='fruit'>Grapes</li>\n <li class='fruit'>Strawberries</li>\n </ul>\n (drag items or panel)\n </td>\n <td valign=\"top\">\n <div id='fish' class='meat'>Fish</div>\n <div id='chicken' class='meat'>Chicken</div>\n (drop to left list)\n </td>\n</tr></table>\n\n\n\nSortable.create(\"fList\", {constraint:false})\nnew Draggable('fish',{revert:true})\nnew Draggable('chicken',{revert:true})\nnew Draggable('fList')\nDroppables.add('fList',{accept:'meat',onDrop:function(dragName,dropName){placeFood(dragName,dropName)}})\nDroppables.add('fList',{accept:'fruit'})\n\nfunction placeFood(dragName,dropName) {\n $(\"fList\").insert(new Element(\"li\", { id: $(dragName).id+\"_\" }))\n $($(dragName).id+\"_\").innerHTML = $(dragName).innerHTML\n Sortable.destroy(\"fList\")\n Sortable.create(\"fList\", {constraint:false})\n}\n" }, { "answer_id": 196688, "author": "Patrick McKenzie", "author_id": 15046, "author_profile": "https://Stackoverflow.com/users/15046", "pm_score": 3, "selected": true, "text": "draggable_element <% draggable_element blah blah blah blah blah blah blah%>\n <%= draggable_element blah blah blah blah blah blah blah %>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/186313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15046/" ]
186,314
<p>I am debugging a large, complex web page that has a lot of JavaScript, JQuery, Ajax and so on. Somewhere in that code I am getting a rouge request (I think it is an empty img) that calls the root of the server. I know it is not in the html or the css and am pretty convinced that somewhere in the JavaScript code the reqest is being made, but I can't track it down. I am used to using firebug, VS and other debugging tools but am looking for some way to find out where this is executed - so that I can find the offending line amongst about 150 .js files.</p> <p>Apart from putting in a gazzillion console outputs of 'you are now here', does anyone have suggestions for a debugging tool that could highlight where in Javascript requests to external resources are made? Any other ideas?</p> <p>Step by step debugging will take ages - I have to be careful what I step into (jQuery source - yuk!) and I may miss the crucial moment</p>
[ { "answer_id": 195652, "author": "Vincent Robert", "author_id": 268, "author_profile": "https://Stackoverflow.com/users/268", "pm_score": 1, "selected": false, "text": "$(document).bind('beforeSend', function(event, request, ajaxOptions)\n{\n // Will be called before every jQuery AJAX call\n});\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/186314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3893/" ]
186,316
<p>I'm looking at creating a server in python that I can run, and will work as an SSH server. This will then let different users login, and act as if they'd logged in normally, but only had access to one command.</p> <p>I want to do this so that I can have a system where I can add users to without having to create a system wide account, so that they can then, for example, commit to a VCS branch, or similar.</p> <p>While I can work out how to do this with conch to get it to a "custom" shell... I can't figure out how to make it so that the SSH stream works as if it were a real one (I'm preferably wanting to limit to /bin/bzr so that bzr+ssh will work.</p> <p>It needs to be in python (which i can get to do the authorisation) but don't know how to do the linking to the app. </p> <p>This needs to be in python to work within the app its designed for, and to be able to be used for those without access to add new users</p>
[ { "answer_id": 189452, "author": "Jean-Paul Calderone", "author_id": 18243, "author_profile": "https://Stackoverflow.com/users/18243", "pm_score": 4, "selected": true, "text": "ISession.openShell IConchUser ISession openShell ISession.openShell openShell IProcessProtocol makeConnection IProcessTransport IProcessProtocol writeToChild makeConnection childDataReceived IProcessProtocol IProcessProtocol" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/186316", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20010/" ]
186,328
<p>Which is generally fastest when reading/comparing row info from a DataTable?</p> <pre><code>'assume dt as datatable' 'method 1' dim i as int32 for i = 0 to dt.rows.count - 1 .... next 'method 2' dim row as datarow for each row in dt.rows .... next </code></pre> <p>And if there's a difference, in what circumstances does it pay to use one over the other? </p> <p>Thanks in advance for any guidance!</p>
[ { "answer_id": 186363, "author": "Matthew Scharley", "author_id": 15537, "author_profile": "https://Stackoverflow.com/users/15537", "pm_score": 4, "selected": true, "text": "for each row in dt.rows\n// expands to:\nIEnumerator e = dt.rows.GetEnumerator()\nwhile e.MoveNext()\n row = e.Current\n" }, { "answer_id": 186375, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": -1, "selected": false, "text": "for(int i =0; i < myArray.Count; ++i)\n{\n // do something with myArray[i];\n}\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/186328", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17235/" ]
186,338
<p>Everything I read about better PHP coding practices keeps saying don't use <code>require_once</code> because of speed.</p> <p>Why is this?</p> <p>What is the proper/better way to do the same thing as <code>require_once</code>? If it matters, I'm using PHP&nbsp;5.</p>
[ { "answer_id": 186386, "author": "Oli", "author_id": 12870, "author_profile": "https://Stackoverflow.com/users/12870", "pm_score": 8, "selected": true, "text": "require_once include_once *_once *_once if (!defined('MyIncludeName')) {\n require('MyIncludeName');\n define('MyIncludeName', 1);\n}\n *_once php hhvm\nif defined 0.18587779998779 0.046600103378296\nrequire_once 1.2219581604004 3.2908599376678\n require_once require_once hhvm *_once <?php // test.php\n\n$LIMIT = 1000000;\n\n$start = microtime(true);\n\nfor ($i=0; $i<$LIMIT; $i++)\n if (!defined('include.php')) {\n require('include.php');\n define('include.php', 1);\n }\n\n$mid = microtime(true);\n\nfor ($i=0; $i<$LIMIT; $i++)\n require_once('include.php');\n\n$end = microtime(true);\n\nprintf(\"if defined\\t%s\\nrequire_once\\t%s\\n\", $mid-$start, $end-$mid);\n <?php // include.php\n\n// do nothing.\n" }, { "answer_id": 186406, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 5, "selected": false, "text": "include include_once include_once" }, { "answer_id": 187053, "author": "Annika Backstrom", "author_id": 7675, "author_profile": "https://Stackoverflow.com/users/7675", "pm_score": 3, "selected": false, "text": "*_once() require_once()" }, { "answer_id": 194959, "author": "terson", "author_id": 22974, "author_profile": "https://Stackoverflow.com/users/22974", "pm_score": 6, "selected": false, "text": "<?php\n // /home/fbarnes/phpperf/hdr0.php\n require_once \"../phpperf/common_hdr.php\";\n\n?>\n for i in /home/fbarnes/phpperf/hdr{00..99}.php; do\n echo \"<?php\n // $i\" > $i\n cat helper.php >> $i;\ndone\n <?php\n // Load all of the php hdrs that were created previously\n for($i=0; $i < 100; $i++)\n {\n require_once \"/home/fbarnes/phpperf/hdr$i.php\";\n }\n\n // Read the /proc file system to get some simple stats\n $pid = getmypid();\n $fp = fopen(\"/proc/$pid/stat\", \"r\");\n $line = fread($fp, 2048);\n $array = split(\" \", $line);\n\n // Write out the statistics; on RedHat 4.5 with kernel 2.6.9\n // 14 is user jiffies; 15 is system jiffies\n $cntr = 0;\n foreach($array as $elem)\n {\n $cntr++;\n echo \"stat[$cntr]: $elem\\n\";\n }\n fclose($fp);\n?>\n <?php\n // /home/fbarnes/phpperf/h/hdr0.php\n if(!defined('CommonHdr'))\n {\n require \"../phpperf/common_hdr.php\";\n define('CommonHdr', 1);\n }\n?>\n time(NULL) = 1223772434\nlstat64(\"/home\", {st_mode=S_IFDIR|0755, st_size=4096, ...}) = 0\nlstat64(\"/home/fbarnes\", {st_mode=S_IFDIR|0755, st_size=4096, ...}) = 0\nlstat64(\"/home/fbarnes/phpperf\", {st_mode=S_IFDIR|0755, st_size=4096, ...}) = 0\nlstat64(\"/home/fbarnes/phpperf/h\", {st_mode=S_IFDIR|0755, st_size=270336, ...}) = 0\nlstat64(\"/home/fbarnes/phpperf/h/hdr0.php\", {st_mode=S_IFREG|0644, st_size=88, ...}) = 0\ntime(NULL) = 1223772434\nopen(\"/home/fbarnes/phpperf/h/hdr0.php\", O_RDONLY) = 3\n time(NULL) = 1223772905\nlstat64(\"/home\", {st_mode=S_IFDIR|0755, st_size=4096, ...}) = 0\nlstat64(\"/home/fbarnes\", {st_mode=S_IFDIR|0755, st_size=4096, ...}) = 0\nlstat64(\"/home/fbarnes/phpperf\", {st_mode=S_IFDIR|0755, st_size=4096, ...}) = 0\nlstat64(\"/home/fbarnes/phpperf/h\", {st_mode=S_IFDIR|0755, st_size=270336, ...}) = 0\nlstat64(\"/home/fbarnes/phpperf/h/hdr0.php\", {st_mode=S_IFREG|0644, st_size=146, ...}) = 0\ntime(NULL) = 1223772905\nopen(\"/home/fbarnes/phpperf/h/hdr0.php\", O_RDONLY) = 3\n [fbarnes@myhost phpperf]$ wc -l strace_1000r.out strace_1000ro.out\n 190709 strace_1000r.out\n 210707 strace_1000ro.out\n 401416 total\n [fbarnes@myhost phpperf]$ grep -c time strace_1000r.out strace_1000ro.out\nstrace_1000r.out:20009\nstrace_1000ro.out:30008\n [fbarnes@myhost phpperf]$ grep -c getcwd strace_1000r.out strace_1000ro.out\nstrace_1000r.out:5\nstrace_1000ro.out:10004\n [fbarnes@myhost phpperf]$ wc -l strace_1000r.out strace_1000ro.out\n 190705 strace_1000r.out\n 200705 strace_1000ro.out\n 391410 total\n[fbarnes@myhost phpperf]$ grep -c time strace_1000r.out strace_1000ro.out\nstrace_1000r.out:20008\nstrace_1000ro.out:30008\n" }, { "answer_id": 194979, "author": "Edward Z. Yang", "author_id": 23845, "author_profile": "https://Stackoverflow.com/users/23845", "pm_score": 7, "selected": false, "text": "require_once() class_exists('Classname') require_once() class_exists() require_once() require()" }, { "answer_id": 28171417, "author": "NeuroXc", "author_id": 2595915, "author_profile": "https://Stackoverflow.com/users/2595915", "pm_score": 2, "selected": false, "text": "require_once include_once require include require_once require_once" }, { "answer_id": 28711865, "author": "hexalys", "author_id": 1647538, "author_profile": "https://Stackoverflow.com/users/1647538", "pm_score": 3, "selected": false, "text": "require_once() require() require_once() require_once() require_once(\"includes/usergroups.php\");\nrequire_once(\"includes/permissions.php\");\nrequire_once(\"includes/revisions.php\");\nclass User{\n // User functions\n}\n User require_once(\"includes/user.php\"); helper helpers require_once(\"includes/helpers.php\");\nclass MyClass{\n // Helper::functions(); // etc..\n}\n require_once require_once(\"includes/helpers.php\");\nrequire_once(\"includes/helpers.php\");\nrequire_once(\"includes/helpers.php\");\nrequire_once(\"includes/helpers.php\");\nrequire_once(\"includes/helpers.php\");\nrequire_once(\"includes/helpers.php\");\nrequire_once(\"includes/helpers.php\");\nrequire_once(\"includes/helpers.php\");\nrequire_once(\"includes/helpers.php\");\nrequire_once(\"includes/helpers.php\");\nrequire_once(\"includes/helpers.php\");\nrequire_once(\"includes/helpers.php\");\nrequire_once(\"includes/helpers.php\");\nrequire_once(\"includes/helpers.php\");\nrequire_once(\"includes/helpers.php\");\n require(\"includes/helpers.php\"); helpers require_once() helpers require require_once require_once" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/186338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/314/" ]
186,345
<p>I have a HTML select list with quite a few (1000+) names. I have a javascript in place which will select the first matching name if someone starts typing. This matching looks at the start of the item: </p> <pre><code>var optionsLength = dropdownlist.options.length; for (var n=0; n &lt; optionsLength; n++) { var optionText = dropdownlist.options[n].text; if (optionText.indexOf(dropdownlist.keypressBuffer,0) == 0) { dropdownlist.selectedIndex = n; return false; } } </code></pre> <p>The customer would like to have a suggest or autofilter: typing part of a name should 'find' all names containing that part. I've seen a few Google Suggest like options, most using Ajax, but I'd like a pure javascript option, since the select list is already loaded anyway. Pointers anyone?</p>
[ { "answer_id": 186393, "author": "MDCore", "author_id": 1896, "author_profile": "https://Stackoverflow.com/users/1896", "pm_score": 2, "selected": false, "text": "if (optionText.indexOf(dropdownlist.keypressBuffer,0) == 0)\n if (optionText.indexOf(dropdownlist.keypressBuffer) > 0)\n dropdownlist.keypressBuffer optionText" }, { "answer_id": 186551, "author": "cllpse", "author_id": 20946, "author_profile": "https://Stackoverflow.com/users/20946", "pm_score": 2, "selected": false, "text": "options select options select select options onLoad:\n set cache\n\nonKeyPress:\n clear select-element\n find option-elements in cache\n put found option-elements into select-element\n selects select function selectFilter(_maps)\n{\n var map = {};\n\n\n var i = _maps.length + 1; while (i -= 1)\n {\n map = _maps[i - 1];\n\n\n (function (_selectOne, _selectTwo, _property)\n {\n var select = document.getElementById(_selectTwo);\n var options = select.options;\n var option = {};\n var cache = [];\n var output = [];\n\n\n var i = options.length + 1; while (i -= 1)\n {\n option = options[i - 1];\n\n cache.push({\n text: option.text,\n value: option.value,\n property: option.getAttribute(_property)\n });\n }\n\n\n document.getElementById(_selectOne).onchange = function ()\n {\n var selectedProperty = this\n .options[this.selectedIndex]\n .getAttribute(_property);\n var cacheEntry = {};\n var cacheEntryProperty = undefined;\n\n\n output = [];\n\n var i = cache.length + 1; while (i -= 1)\n {\n cacheEntry = cache[i - 1];\n\n cacheEntryProperty = cacheEntry.property;\n\n if (cacheEntryProperty === selectedProperty)\n {\n output.push(\"<option value=\" + cacheEntry.value + \" \"\n _property + \"=\" + cacheEntryProperty + \">\" +\n cacheEntry.text + \"</option>\");\n }\n }\n\n select.innerHTML = output.join();\n };\n }(map.selectOne, map.selectTwo, map.property));\n }\n}\n\n\n$(function ()\n{\n selectFilter([\n {selectOne: \"select1\", selectTwo: \"select2\", property: \"entityid\"},\n {selectOne: \"select2\", selectTwo: \"select3\", property: \"value\"}\n ]);\n});\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/186345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6399/" ]
186,385
<p>Which is the best timer approach for a C# console batch application that has to process as follows:</p> <ol> <li>Connect to datasources</li> <li>process batch until timeout occurs or processing complete. "Do something with datasources"</li> <li>stop console app gracefully.</li> </ol> <p>related question: <a href="https://stackoverflow.com/questions/186084/how-do-you-add-a-timer-to-a-c-console-application">How do you add a timer to a C# console application</a></p>
[ { "answer_id": 186439, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 2, "selected": false, "text": "List<DataSource> dataSources = ConnectToDataSources();\nTimeSpan timeout = GetTimeoutFromConfiguration(); // Or have it passed in!\nDateTime endTime = DateTime.UtcNow + timeout;\n\nbool finished = false;\nwhile (DateTime.UtcNow < endTime && !finished)\n{\n // This method should do a small amount of work and then return\n // whether or not it's finished everything\n finished = ProcessDataSources(dataSources);\n}\n\n// Done - return up the stack and the console app will close.\n" }, { "answer_id": 186455, "author": "Grzenio", "author_id": 5363, "author_profile": "https://Stackoverflow.com/users/5363", "pm_score": 2, "selected": false, "text": "DateTime runUntil = DataTime.Now.Add(timeout);\nforech(Task task in tasks)\n{\n if(DateTime.Now >= runUntil)\n {\n throw new MyException(\"Timeout\");\n }\n Process(task);\n}\n" }, { "answer_id": 325578, "author": "Timothy Khouri", "author_id": 11917, "author_profile": "https://Stackoverflow.com/users/11917", "pm_score": 4, "selected": true, "text": "using System;\nusing System.Collections.Generic;\nusing System.Threading;\n\nnamespace ConsoleApplication1\n{\n class Program\n {\n static List<RunningProcess> runningProcesses = new List<RunningProcess>();\n\n static void Main(string[] args)\n {\n Console.WriteLine(\"Starting...\");\n\n for (int i = 0; i < 100; i++)\n {\n DoSomethingOrTimeOut(30);\n }\n\n bool isSomethingRunning = false;\n\n do\n {\n foreach (RunningProcess proc in runningProcesses)\n {\n // If this process is running...\n if (proc.ProcessThread.ThreadState == ThreadState.Running)\n {\n isSomethingRunning = true;\n\n // see if it needs to timeout...\n if (DateTime.Now.Subtract(proc.StartTime).TotalSeconds > proc.TimeOutInSeconds)\n {\n proc.ProcessThread.Abort();\n }\n }\n }\n }\n while (isSomethingRunning);\n\n Console.WriteLine(\"Done!\"); \n\n Console.ReadLine();\n }\n\n static void DoSomethingOrTimeOut(int timeout)\n {\n runningProcesses.Add(new RunningProcess\n {\n StartTime = DateTime.Now,\n TimeOutInSeconds = timeout,\n ProcessThread = new Thread(new ThreadStart(delegate\n {\n // do task here...\n })),\n });\n\n runningProcesses[runningProcesses.Count - 1].ProcessThread.Start();\n }\n }\n\n class RunningProcess\n {\n public int TimeOutInSeconds { get; set; }\n\n public DateTime StartTime { get; set; }\n\n public Thread ProcessThread { get; set; }\n }\n}\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/186385", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3535708/" ]
186,392
<p>Many database systems don't allow comments or descriptions of tables and fields, so how do you go about documenting the purpose of a table/field apart from the obvious of having good naming conventions?</p> <p>(Let's assume for now that "excellent" table and field names are not enough to document the full meaning of every table, field and relationship in the database.)</p> <p>I know many people use UML diagrams to visualize the database, but I have rarely&mdash;if ever&mdash;seen a UML diagram including field comments. However, I have good experience with using comments inside <code>.sql</code> files. The downside to this approach is that it requires the <code>.sql</code> files to be manually kept up-to-date as the database structure changes over time&mdash;but if you do, you can also have it under version control.</p> <p>Some other techniques I have seen are separate document describing database structure and relationships and manually maintained comments inside ORM code or other database-mapping code.</p> <p>How have you solved this problem in the past? What methods exists and what are the various pros and cons associated with them? How you would you like this solved in "a perfect world"?</p> <p><strong>Update</strong></p> <p>As others have pointed out, most of the popular SQL engines do in fact allow comments, which is great. Oddly enough, people don't seem to be using these features much. At least not on the projects I have been involved with in the past.</p>
[ { "answer_id": 25296408, "author": "hhh", "author_id": 1853769, "author_profile": "https://Stackoverflow.com/users/1853769", "pm_score": 1, "selected": false, "text": ".sql mysqldump --no-data --tab=./tables dbname" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/186392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1709/" ]
186,403
<p>When you create a procedure (or a function) in Oracle PL/SQL, you cannot specify the maximum length of the varchar2 arguments, only the datatype. For example</p> <pre><code>create or replace procedure testproc(arg1 in varchar2) is begin null; end; </code></pre> <p>Do you know the maximum length of a string that you can pass as the arg1 argument to this procedure in Oracle ?</p>
[ { "answer_id": 22060657, "author": "user272735", "author_id": 272735, "author_profile": "https://Stackoverflow.com/users/272735", "pm_score": 2, "selected": false, "text": "VARCHAR2" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/186403", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20037/" ]
186,405
<p>This is a very basic problem that's frustrating me at the moment. Let's say within a single solution, I have two projects. Let's call the first project SimpleMath. It has one header file "Add.h" which has </p> <pre><code>int add(int i, int j) </code></pre> <p>and the implementation "Add.cpp" which has</p> <pre><code>int add(int i, int j) { return i+j; } </code></pre> <p>Now let's say in a second project I want to use the add function. However, this code:</p> <blockquote> <p><strong>#include "..\SimpleMath\Add.h"</strong></p> </blockquote> <pre><code>int main() { add(1, 2); } </code></pre> <p>results in "unresolved external symbol". How do I get the second program to "know" about the actual implementation in the .cpp file. As a side note all code is fictional this is not how I actually program.</p>
[ { "answer_id": 186430, "author": "korona", "author_id": 25731, "author_profile": "https://Stackoverflow.com/users/25731", "pm_score": 3, "selected": false, "text": "int add (int, int)\n #pragma once #ifndef #ifndef __ADD_H\n#define __ADD_H\n\nint add (int i, int j);\n\n#endif\n" }, { "answer_id": 1207013, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "extern \"C\" {\n #include \"..\\SimpleMath\\Add.h\"\n}\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/186405", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23120/" ]
186,413
<p>I need to add a <code>xml:lang</code> attribute on the root xml node in the outbound document from BizTalk.</p> <p>This is a fixed value, so it may be set in the schema or something.</p> <p>This is what I want to get out:</p> <pre><code>&lt;Catalog xml:lang="NB-NO"&gt; ... &lt;/Catalog&gt; </code></pre> <p>I've tried to define the attribute "xml:lang", but it doesn't allow me to use ":" in the schema. </p> <p>This is the error message I get:</p> <blockquote> <p>Invalid 'name' attribute value 'xml:lang': The ':' character, hexadecimal value 0x3A, at position 3 within the name, cannot be included in a name.</p> </blockquote> <p>Is there another way to insert a ':' as part of the attribute name in BizTalk?</p> <p>Can anyone tell me how to do this?</p> <p>I'm using BizTalk 2006 and no orchestration.</p>
[ { "answer_id": 186435, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 1, "selected": false, "text": "xmlns:xml=\"http://www.w3.org/XML/1998/namespace\" \n" }, { "answer_id": 8806322, "author": "DanMan", "author_id": 428241, "author_profile": "https://Stackoverflow.com/users/428241", "pm_score": 0, "selected": false, "text": "<xs:attribute name=\"xml:lang\" />\n <xs:attribute ref=\"xml:lang\" />\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/186413", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
186,422
<p>we're running in this issue. We're using a web service (using soap4r) to run some kind of searches and the problem appears when the webservice server is down and our aplication is trying to connect to it. At that point the application is unreachable, and all the customers are blocked.</p> <p>What can we do to avoid that? Is possibile to block the routing to a mongrel that it is blocked? (I suppose that the apache's proxy uses a round-robin algohritm)</p> <p>Thanks Roberto</p>
[ { "answer_id": 195681, "author": "Otto", "author_id": 9594, "author_profile": "https://Stackoverflow.com/users/9594", "pm_score": 0, "selected": false, "text": "maintence.html # Check for maintenance file and redirect all requests\nRewriteCond %{DOCUMENT_ROOT}/system/maintenance.html -f\nRewriteCond %{SCRIPT_FILENAME} !maintenance.html\nRewriteRule ^.*$ /system/maintenance.html [L]\n maintence.html" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/186422", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22083/" ]
186,431
<p>Given a week number, e.g. <code>date -u +%W</code>, how do you calculate the days in that week starting from Monday?</p> <p>Example rfc-3339 output for week 40:</p> <pre><code>2008-10-06 2008-10-07 2008-10-08 2008-10-09 2008-10-10 2008-10-11 2008-10-12 </code></pre>
[ { "answer_id": 186478, "author": "ConroyP", "author_id": 2287, "author_profile": "https://Stackoverflow.com/users/2287", "pm_score": 7, "selected": true, "text": "$week_number = 40;\n$year = 2008;\nfor($day=1; $day<=7; $day++)\n{\n echo date('m/d/Y', strtotime($year.\"W\".$week_number.$day)).\"\\n\";\n}\n function week_from_monday($date) {\n // Assuming $date is in format DD-MM-YYYY\n list($day, $month, $year) = explode(\"-\", $_REQUEST[\"date\"]);\n\n // Get the weekday of the given date\n $wkday = date('l',mktime('0','0','0', $month, $day, $year));\n\n switch($wkday) {\n case 'Monday': $numDaysToMon = 0; break;\n case 'Tuesday': $numDaysToMon = 1; break;\n case 'Wednesday': $numDaysToMon = 2; break;\n case 'Thursday': $numDaysToMon = 3; break;\n case 'Friday': $numDaysToMon = 4; break;\n case 'Saturday': $numDaysToMon = 5; break;\n case 'Sunday': $numDaysToMon = 6; break; \n }\n\n // Timestamp of the monday for that week\n $monday = mktime('0','0','0', $month, $day-$numDaysToMon, $year);\n\n $seconds_in_a_day = 86400;\n\n // Get date for 7 days from Monday (inclusive)\n for($i=0; $i<7; $i++)\n {\n $dates[$i] = date('Y-m-d',$monday+($seconds_in_a_day*$i));\n }\n\n return $dates;\n}\n week_from_monday('07-10-2008') Array\n(\n [0] => 2008-10-06\n [1] => 2008-10-07\n [2] => 2008-10-08\n [3] => 2008-10-09\n [4] => 2008-10-10\n [5] => 2008-10-11\n [6] => 2008-10-12\n)\n" }, { "answer_id": 189047, "author": "Shane", "author_id": 1259, "author_profile": "https://Stackoverflow.com/users/1259", "pm_score": 3, "selected": false, "text": "require_once 'Zend/Date.php';\n\n$date = new Zend_Date();\n$date->setYear(2008)\n ->setWeek(40)\n ->setWeekDay(1);\n\n$weekDates = array();\n\nfor ($day = 1; $day <= 7; $day++) {\n if ($day == 1) {\n // we're already at day 1\n }\n else {\n // get the next day in the week\n $date->addDay(1);\n }\n\n $weekDates[] = date('Y-m-d', $date->getTimestamp());\n}\n\necho '<pre>';\nprint_r($weekDates);\necho '</pre>';\n" }, { "answer_id": 534495, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "function week_dates($date = null, $format = null, $start = 'monday') {\n // is date given? if not, use current time...\n if(is_null($date)) $date = 'now';\n\n // get the timestamp of the day that started $date's week...\n $weekstart = strtotime('last '.$start, strtotime($date));\n\n // add 86400 to the timestamp for each day that follows it...\n for($i = 0; $i < 7; $i++) {\n $day = $weekstart + (86400 * $i);\n if(is_null($format)) $dates[$i] = $day;\n else $dates[$i] = date($format, $day);\n }\n\n return $dates;\n}\n Array ( \n [0] => 1234155600 \n [1] => 1234242000 \n [2] => 1234328400 \n [3] => 1234414800 \n [4] => 1234501200\n [5] => 1234587600\n [6] => 1234674000\n)\n" }, { "answer_id": 639048, "author": "Yashvit", "author_id": 77241, "author_profile": "https://Stackoverflow.com/users/77241", "pm_score": 0, "selected": false, "text": "$week_number = 40;\n$year = 2008;\nfor($day=1; $day<=7; $day++)\n{\n echo date('m/d/Y', strtotime($year.\"W\".str_pad($week_number,2,'0',STR_PAD_LEFT).$day)).\"\\n\";\n}\n" }, { "answer_id": 1184954, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "$week = 2; $year = 2009;\n\n$week = (($week >= 1) AND ($week <= 52))?($week-1):(1);\n\n$dayrange = array(7,1,2,3,4,5,6);\n\nfor($count=0; $count<=6; $count++) {\n $week = ($count == 1)?($week + 1): ($week);\n $week = str_pad($week,2,'0',STR_PAD_LEFT);\n echo date('d m Y', strtotime($year.\"W\".$week.($dayrange[$count]))); }\n" }, { "answer_id": 1974330, "author": "Nicolas", "author_id": 240148, "author_profile": "https://Stackoverflow.com/users/240148", "pm_score": 2, "selected": false, "text": "$week_number = 40;\n$year = 2008;\n\nfor($day=1; $day<=7; $day++)\n{\n echo date('m/d/Y', strtotime($year.\"W\".$week_number.$day)).\"\\n\";\n}\n $week_number //============Try this================//\n\n$week_number = 40;\n$year = 2008;\n\nif($week_number < 10){\n $week_number = \"0\".$week_number;\n}\n\nfor($day=1; $day<=7; $day++)\n{\n echo date('m/d/Y', strtotime($year.\"W\".$week_number.$day)).\"\\n\";\n}\n\n//==============================//\n" }, { "answer_id": 12252944, "author": "codepuppy", "author_id": 1148523, "author_profile": "https://Stackoverflow.com/users/1148523", "pm_score": 0, "selected": false, "text": "<?php\n\n/*\n * function to establish scope of week given a week of the year value returned from strftime %W\n */\n\n// note strftime %W reports 1/1/YYYY as wk 00 unless 1/1/YYYY is a monday when it reports wk 01\n// note strtotime Monday [last, this, next] week - runs sun - sat\n\nfunction date_Range_For_Week($W,$Y){\n\n// where $W = %W returned from strftime\n// $Y = %Y returned from strftime\n\n // establish 1st day of 1/1/YYYY\n\n $first_Day_Of_Year = mktime(0,0,0,1,1,$Y);\n\n // establish the first monday of year after 1/1/YYYY \n\n $first_Monday_Of_Year = strtotime(\"Monday this week\",(mktime(0,0,0,1,1,$Y))); \n\n // Check for week 00 advance first monday if found\n // We could use strtotime \"Monday next week\" or add 604800 seconds to find next monday\n // I have decided to avoid any potential strtotime overhead and do the arthimetic\n\n if (strftime(\"%W\",$first_Monday_Of_Year) != \"01\"){\n $first_Monday_Of_Year += (60 * 60 * 24 * 7);\n }\n\n // create array to ranges for the year. Note 52 wks is the norm but it is possible to have 54 weeks\n // in a given yr therefore allow for this in array index\n\n $week_Start = array();\n $week_End = array(); \n\n for($i=0;$i<=53;$i++){\n\n if ($i == 0){ \n if ($first_Day_Of_Year != $first_Monday_Of_Year){\n $week_Start[$i] = $first_Day_Of_Year;\n $week_End[$i] = $first_Monday_Of_Year - (60 * 60 * 24 * 1);\n } else {\n // %W returns no week 00\n $week_Start[$i] = 0;\n $week_End[$i] = 0; \n }\n $current_Monday = $first_Monday_Of_Year;\n } else {\n $week_Start[$i] = $current_Monday;\n $week_End[$i] = $current_Monday + (60 * 60 * 24 * 6);\n // find next monday\n $current_Monday += (60 * 60 * 24 * 7);\n // test for end of year\n if (strftime(\"%W\",$current_Monday) == \"01\"){ $i = 999; };\n }\n };\n\n $result = array(\"start\" => strftime(\"%a on %d, %b, %Y\", $week_Start[$W]), \"end\" => strftime(\"%a on %d, %b, %Y\", $week_End[$W]));\n\n return $result;\n\n } \n\n?>\n // usage example\n\n//assume we wish to find the date range of a week for a given date July 12th 2011\n\n$Y = strftime(\"%Y\",mktime(0,0,0,7,12,2011));\n$W = strftime(\"%W\",mktime(0,0,0,7,12,2011));\n\n// use dynamic array variable to check if we have range if so get result if not run function\n\n$date_Range = date_Range . \"$Y\";\n\nisset(${$date_Range}) ? null : ${$date_Range} = date_Range_For_Week($W, $Y);\n\necho \"Date sought: \" . strftime(\" was %a on %b %d, %Y, %X time zone: %Z\",mktime(0,0,0,7,12,2011)) . \"<br/>\";\necho \"start of week \" . $W . \" is \" . ${$date_Range}[\"start\"] . \"<br/>\";\necho \"end of week \" . $W . \" is \" . ${$date_Range}[\"end\"];\n > Date sought: was Tue on Jul 12, 2011, 00:00:00 time zone: GMT Daylight\n> Time start of week 28 is Mon on 11, Jul, 2011 end of week 28 is Sun on\n> 17, Jul, 2011\n" }, { "answer_id": 17065451, "author": "vascowhite", "author_id": 212940, "author_profile": "https://Stackoverflow.com/users/212940", "pm_score": 3, "selected": false, "text": "function daysInWeek($weekNum)\n{\n $result = array();\n $datetime = new DateTime('00:00:00');\n $datetime->setISODate((int)$datetime->format('o'), $weekNum, 1);\n $interval = new DateInterval('P1D');\n $week = new DatePeriod($datetime, $interval, 6);\n\n foreach($week as $day){\n $result[] = $day->format('D d m Y H:i:s');\n }\n return $result;\n}\n\nvar_dump(daysInWeek(24));\n" }, { "answer_id": 21475362, "author": "joan16v", "author_id": 1398876, "author_profile": "https://Stackoverflow.com/users/1398876", "pm_score": 0, "selected": false, "text": "//$date Date in week\n//$start Week start (out)\n//$end Week end (out)\n\nfunction week_bounds($date, &$start, &$end) {\n $date = strtotime($date);\n $start = $date;\n while( date('w', $start)>1 ) {\n $start -= 86400;\n }\n $end = date('Y-m-d', $start + (6*86400) );\n $start = date('Y-m-d', $start);\n}\n week_bounds(\"2014/02/10\", $start, $end);\necho $start.\"<br>\".$end;\n 2014-02-10\n2014-02-16\n" }, { "answer_id": 21878886, "author": "Dhananjay", "author_id": 3327738, "author_profile": "https://Stackoverflow.com/users/3327738", "pm_score": -1, "selected": false, "text": " <?php\n $iWeeksAgo = 5;// need weeks ago\n $sWeekDayStartOn = 0;// 0 - Sunday, 1 - Monday, 2 - Tuesday\n $aWeeksDetails = getWeekDetails($iWeeksAgo, $sWeekDayStartOn);\n\n print_r($aWeeksDetails);\n die('end of line of getWeekDetails ');\n\n function getWeekDetails($iWeeksAgo, $sWeekDayStartOn){\n $date = new DateTime();\n $sCurrentDate = $date->format('W, Y-m-d, w');\n #echo 'Current Date (Week of the year, YYYY-MM-DD, day of week ): ' . $sCurrentDate . \"\\n\";\n\n $iWeekOfTheYear = $date->format('W');// Week of the Year i.e. 19-Feb-2014 = 08\n $iDayOfWeek = $date->format('w');// day of week for the current month i.e. 19-Feb-2014 = 4\n $iDayOfMonth = $date->format('d'); // date of the month i.e. 19-Feb-2014 = 19\n\n $iNoDaysAdd = 6;// number of days adding to get last date of the week i.e. 19-Feb-2014 + 6 days = 25-Feb-2014\n\n $date->sub(new DateInterval(\"P{$iDayOfWeek}D\"));// getting start date of the week\n $sStartDateOfWeek = $date->format('Y-m-d');// getting start date of the week\n\n $date->add(new DateInterval(\"P{$iNoDaysAdd}D\"));// getting end date of the week\n $sEndDateOfWeek = $date->format('Y-m-d');// getting end date of the week\n\n $iWeekOfTheYearWeek = (string) $date->format('YW');//week of the year\n $iWeekOfTheYearWeekWithPeriod = (string) $date->format('Y-W');//week of the year with year\n\n //To check uncomment\n #echo \"Start Date / End Date of Current week($iWeekOfTheYearWeek), week with - ($iWeekOfTheYearWeekWithPeriod) : \" . $sStartDateOfWeek . ',' . $sEndDateOfWeek . \"\\n\";\n\n $iDaysAgo = ($iWeeksAgo*7) + $iNoDaysAdd + $sWeekDayStartOn;// getting 4 weeks ago i.e. no. of days to substract\n\n $date->sub(new DateInterval(\"P{$iDaysAgo}D\"));// getting 4 weeks ago i.e. no. of days to substract\n $sStartDateOfWeekAgo = $date->format('Y-m-d');// getting 4 weeks ago start date i.e. 19-Jan-2014\n\n $date->add(new DateInterval(\"P{$iNoDaysAdd}D\")); // getting 4 weeks ago end date i.e. 25-Jan-2014\n $sEndDateOfWeekAgo = $date->format('Y-m-d');// getting 4 weeks ago start date i.e. 25-Jan-2014\n\n $iProccessedWeekAgoOfTheYear = (string) $date->format('YW');//ago week of the year\n $iProccessedWeekOfTheYearWeekAgo = (string) $date->format('YW');//ago week of the year with year\n $iProccessedWeekOfTheYearWeekWithPeriodAgo = (string) $date->format('Y-W');//ago week of the year with year\n\n //To check uncomment\n #echo \"Start Date / End Date of week($iProccessedWeekOfTheYearWeekAgo), week with - ($iProccessedWeekOfTheYearWeekWithPeriodAgo) ago: \" . $sStartDateOfWeekAgo . ',' . $sEndDateOfWeekAgo . \"\\n\";\n\n $aWeeksDetails = array ('weeksago' => $iWeeksAgo, 'currentweek' => $iWeekOfTheYear, 'currentdate' => $sCurrentDate, 'startdateofcurrentweek' => $sStartDateOfWeek, 'enddateofcurrentweek' => $sEndDateOfWeek,\n 'weekagoyearweek' => $iProccessedWeekAgoOfTheYear, 'startdateofagoweek' => $sStartDateOfWeekAgo, 'enddateofagoweek' => $sEndDateOfWeekAgo);\n\n return $aWeeksDetails;\n }\n?> \n" }, { "answer_id": 34639314, "author": "Miton Leon", "author_id": 3087281, "author_profile": "https://Stackoverflow.com/users/3087281", "pm_score": 1, "selected": false, "text": "public function getAllowedDays($year, $week) {\n $weekDaysArray = array();\n $dto = new \\DateTime();\n $dto->setISODate($year, $week);\n\n for($i = 0; $i < 7; $i++) {\n array_push($weekDaysArray, $dto->format('Y-m-d'));\n $dto->modify(\"+1 days\");\n }\n\n return $weekDaysArray;\n}\n" }, { "answer_id": 40639239, "author": "Peter Breuls", "author_id": 7169107, "author_profile": "https://Stackoverflow.com/users/7169107", "pm_score": 0, "selected": false, "text": "$year = 2016; //enter the year\n$wk_number = 46; //enter the weak nr\n\n$start = new DateTime($year.'-01-01 00:00:00');\n$end = new DateTime($year.'-12-31 00:00:00');\n\n$start_date = $start->format('Y-m-d H:i:s');\n\n$output[0]= $start; \n$end = $end->format('U'); \n$x = 1;\n\n//create array full of data objects\nfor($i=0;;$i++){\n if($i == intval(date('z',$end)) || $i === 365){\n break;\n }\n $a = new DateTime($start_date);\n $b = $a->modify('+1 day');\n $output[$x]= $a; \n $start_date = $b->format('Y-m-d H:i:s');\n $x++;\n} \n\n//create a object to use\nfor($i=0;$i<count($output);$i++){\n if(intval ($output[$i]->format('W')) === $wk_number){\n $output_[$output[$i]->format('N')] = $output[$i];\n }\n}\n\n$dayNumberOfWeek = 1; //enter the desired day in 1 = Mon -> 7 = Sun\n\necho '<pre>';\nprint_r($output_[$dayNumberOfWeek]->format('Y-m-d'));\necho '</pre>';\n" }, { "answer_id": 66026764, "author": "oleviolin", "author_id": 5591121, "author_profile": "https://Stackoverflow.com/users/5591121", "pm_score": 0, "selected": false, "text": "function MakePeriod($year,$Week,$StartDay,$NumberOfDays, $lan='DK'){\n //Please note that start dates in january of week 53 must be entered as \"the year before\"\n switch($lan){\n case \"NO\":\n $WeekDays=['mandag','tirsdag','onsdag','torsdag','fredag','lørdag','søndag'];\n $the=\" den \";\n $weekName=\"Uke \";\n $dateformat=\"j/n Y\";\n break; \n case \"DK\":\n $WeekDays=['mandag','tirsdag','onsdag','torsdag','fredag','lørdag','søndag'];\n $the=\" den \";\n $weekName=\"Uge \";\n $dateformat=\"j/n Y\";\n break;\n case \"SV\":\n $WeekDays=['måndag','tisdag','onsdag','torsdag','fredag','lördag','söndag'];\n $the=\" den \";\n $weekName=\"Vecka \";\n $dateformat=\"j/n Y\";\n break;\n case \"GE\":\n $WeekDays=['Montag','Dienstag','Mittwoch','Donnerstag','Freitag','Samstag','Sonntag'];\n $the=\" die \";\n $weekName=\"Woche \";\n $dateformat=\"j/n Y\";\n break;\n case \"EN\":\n case \"US\": \n $WeekDays=['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'];\n $the=\" the \";\n $weekName=\"Week \";\n $dateformat=\"n/j/Y\";\n break; \n } \n $EndDay= (($StartDay-1+$NumberOfDays) % 7)+1;\n $ExtraDays= $NumberOfDays % 7;\n $FirstWeek=$Week;\n $LastWeek=$Week; \n $NumberOfWeeks=floor($NumberOfDays / 7) ;\n $LastWeek=$Week+$NumberOfWeeks;\n\n if($StartDay+$ExtraDays>7){\n $LastWeek++;\n } \n\n if($FirstWeek<10) $FirstWeek='0'.$FirstWeek;\n if($LastWeek<10) $LastWeek='0'.$LastWeek;\n\n \n $date1 = date( $dateformat, strtotime($year.\"W\".$FirstWeek.$StartDay) ); // First day of week\n\n $date2 = date( $dateformat, strtotime($year.\"W\".$LastWeek.$EndDay) ); // Last day of week\n\n if($LastWeek>53){\n $LastWeek=$LastWeek-53;\n $year++;\n if($LastWeek<10) $LastWeek='0'.$LastWeek;\n $date2 = date( $dateformat, strtotime($year.\"W\".$LastWeek.$EndDay) );\n }\n $EndDayName=$WeekDays[$EndDay-1];\n $StartDayName=$WeekDays[$StartDay-1];\n $retval= \" $weekName $Week $StartDayName $the $date1 - $EndDayName $the $date2 \";\n return $retval; \n \n}\n $Year=2021;\n$Week=22; \n$StartDay=4; \n$NumberOfDays=3;\n$Period=MakePeriod($Year,$Week,$StartDay,$NumberOfDays,\"DK\");\necho $Period;\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/186431", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4534/" ]
186,443
<p>At the moment I pull data from remote MS SQL Server databases using custom-built JDBC connectors. This works fine but doesn't feel like the way to do it.</p> <p>I feel I should be able to put a JDBC connection string into tnsnames on the server and have it "just work". I've looked around a little for this functionality but it doesn't seem to be there.</p> <p>In this way I could connect to pretty much any database just using a database link.</p> <p>Have I missed something?</p> <hr> <p>It looks like the two options are Generic Connectivity and Oracle Gateways but I'm surprised that's all there is. Generic Connectivity comes with the database license and Oracle Gateways is an add-on. For Generic Connectivity, if you're running on Linux (like me) you need to get hold of an ODBC driver as it isn't bundled with the database.</p> <p>However... with Oracle being such keen Java fans, and with a JVM built-in to the database I'd have thought a JDBC-based linking technology would have been a no-brainer. It seems a natural extension to have a JDBC connection string in TNSNAMES and everything would "just work".</p> <p>Anyone any ideas why this isn't available?</p>
[ { "answer_id": 186811, "author": "Matthew Watson", "author_id": 3839, "author_profile": "https://Stackoverflow.com/users/3839", "pm_score": 3, "selected": true, "text": "select * from mytable@my_ms_sql_server;\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/186443", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4003/" ]
186,456
<p>How do you save data from ExtJS form? Load data from the business layer into form or grid?</p>
[ { "answer_id": 195118, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": " // Define the core service page to get the data (we use this when reloading)\n var url = '/pagedata/getbizzbox.ashx?duration=today';\n\n var store = new Ext.data.GroupingStore(\n {\n // Define the source for the bizzbox grid (see above url def). We can pass (via the slider)\n // the days param as necessary to reload the grid\n url: url,\n\n // Define an XML reader to read /pagedata/getbizzbox.ashx XML results\n reader: new Ext.data.XmlReader(\n {\n // Define the RECORD node (i.e. in the XML <record> is the main row definition), and we also\n // need to define what field is the ID (row index), and what node returns the total records count\n record: 'record',\n id: 'inboxID',\n totalRecords: 'totalrecords'\n },\n // Setup mapping of the fields \n ['inboxID', 'messageCreated', 'subject', 'message', 'messageOpened', 'messageFrom', 'messageFromID', 'groupedMessageDate']),\n\n // Set the default sort scenario, and which column will be grouped\n sortInfo: { field: 'groupedMessageDate', direction: \"DESC\" },\n groupField: 'groupedMessageDate'\n\n }); // end of Ext.data.store\n var grid = new Ext.grid.GridPanel(\n {\n // Define the store we are going to use - i.e. from above definition\n store: store,\n\n // Define column structs\n\n // { header: \"Received\", width: 180, dataIndex: 'messageCreated', sortable: true, renderer: Ext.util.Format.dateRenderer('d-M-Y'), dataIndex: 'messageCreated' },\n\n columns: [\n { header: \"ID\", width: 120, dataIndex: 'inboxID', hidden: true },\n { header: \"Received\", width: 180, dataIndex: 'messageCreated', sortable: true },\n { header: \"Subject\", width: 115, dataIndex: 'subject', sortable: false },\n { header: \"Opened\", width: 100, dataIndex: 'messageOpened', hidden: true, renderer: checkOpened },\n { header: \"From\", width: 100, dataIndex: 'messageFrom', sortable: true },\n { header: \"FromID\", width: 100, dataIndex: 'messageFromID', hidden: true },\n { header: \"Received\", width: 100, dataIndex: 'groupedMessageDate', hidden: true }\n ],\n\n // Set the row selection model to use\n gridRowModel: new Ext.grid.RowSelectionModel({ singleSelect: true }),\n\n // Set the grouping configuration\n view: new Ext.grid.GroupingView(\n {\n forceFit: true,\n groupTextTpl: '{text} ({[values.rs.length]} {[values.rs.length > 1 ? \"Messages\" : \"Message\"]})'\n }),\n\n // Render the grid with sizing/title etc\n frame: true,\n collapsible: false,\n title: 'BizzBox',\n iconCls: 'icon-grid',\n renderTo: 'bizzbox',\n width: 660,\n height: 500,\n stripeRows: true,\n\n // Setup the top bar within the message grid - this hosts the various buttons we need to create a new\n // message, delete etc\n tbar: [\n\n // New button pressed - show the NEW WINDOW to allow a new message be created\n {\n text: 'New',\n handler: function()\n {\n // We need to load the contacts, howver we only load the contacts ONCE to save\n // bandwidth - if new contacts are added, this page would have been destroyed anyway.\n if(contactsLoaded==false)\n {\n contactStore.load();\n contactsLoaded=true;\n }\n winNew.show();\n }\n },\n\n // Delete button pressed\n // We need to confirm deletion, then get the ID of the message to physically delete from DB and grid\n {\n text: 'Delete', handler: function() \n {\n Ext.MessageBox.confirm('Delete message', 'are you sure you wish to delete this message?', function(btn) {\n\n // If selected YES, get a handle to the row, and delete\n if (btn == 'yes') \n {\n // Get the selected row\n var rec = grid.getSelectionModel().getSelected();\n if(rec==null)\n {\n Ext.Msg.show(\n {\n title:'No message selected',\n msg: 'please ensure you select a message by clicking once on the required message before selecting delete',\n buttons: Ext.Msg.OK,\n icon: Ext.MessageBox.QUESTION\n });\n }\n\n // Proceed to delete the selected message\n else\n {\n var mesID = rec.get('inboxID');\n\n // AJAX call to delete the message\n Ext.Ajax.request(\n {\n url: '/postdata/bizzbox_message_delete.ashx',\n params: { inboxID: mesID },\n\n // Check any call failures\n failure: function() \n {\n Ext.Msg.show(\n {\n title: 'An error has occured',\n msg: 'Having a problem deleting.. please try again later',\n buttons: Ext.Msg.OK,\n icon: Ext.MessageBox.ERROR\n })\n }, // end of failure check\n\n // Success check\n success: function()\n {\n // Need to remove the row from the datastore (which doesn't imapct\n // a reload of the data)\n store.remove(rec);\n }\n }); // end if delete ajax call\n\n } // end of ELSE for record selected or not\n\n } // end of YES button click\n })\n } // end of delete button pressed\n }] // end of tbar (toolbar def)\n\n }); // end of grid def\n // ---------------------------------------------------------------------------------------------\n // DEFINE THE REPLY FORM\n // This is used to show the existing message details, and allows the user to respond\n // ---------------------------------------------------------------------------------------------\n var frmReply = new Ext.form.FormPanel(\n {\n baseCls: 'x-plain',\n labelWidth: 55,\n method: 'POST',\n url: '/postdata/bizzbox_message_reply.ashx',\n\n items: [\n {\n xtype: 'textfield',\n readOnly: true,\n fieldLabel: 'From',\n name: 'messageFrom',\n value: selectedRow.get('messageFrom'),\n anchor: '100%' // anchor width by percentage\n },\n {\n xtype: 'textfield',\n readOnly: true,\n fieldLabel: 'Sent',\n name: 'messageCreated',\n value: selectedRow.get('messageCreated'),\n anchor: '100%' // anchor width by percentage\n },\n {\n xtype: 'textarea',\n selectOnFocus: false,\n hideLabel: true,\n name: 'msg',\n value: replyMessage,\n anchor: '100% -53' // anchor width by percentage and height by raw adjustment\n },\n\n // The next couple of fields are hidden, but provide FROM ID etc which we need to post a new/reply\n // message to\n {\n xtype: 'textfield',\n readOnly: true,\n fieldLabel: 'subject',\n name: 'subject',\n hidden: true,\n hideLabel: true,\n value: selectedRow.get('subject')\n },\n {\n xtype: 'textfield',\n readOnly: true,\n fieldLabel: 'FromID',\n name: 'messageFromID',\n hidden: true,\n hideLabel: true,\n value: selectedRow.get('messageFromID')\n },\n {\n xtype: 'textfield',\n readOnly: true,\n fieldLabel: 'InboxID',\n name: 'inboxID',\n hidden: true,\n hideLabel: true,\n value: selectedRow.get('inboxID')\n }]\n }); // end of frmReply\n // ---------------------------------------------------------------------------------------------\n // REPLY WINDOW - uses the frmReply as defined previously on stargate atlantis\n // ---------------------------------------------------------------------------------------------\n var win = new Ext.Window(\n {\n title: selectedRow.get(\"subject\"),\n width: 500,\n height: 300,\n minWidth: 300,\n minHeight: 200,\n layout: 'fit',\n plain: false,\n bodyStyle: 'padding:5px;',\n buttonAlign: 'right',\n items: frmReply,\n\n // Add the action buttons for the message form\n buttons: [\n {\n // When the user replies, we send the form results to the posting ashx which updates\n // the DB etc, and returns the result\n text: 'reply',\n handler: function()\n {\n frmReply.getForm().submit({ waitMsg: 'Sending your message now...' });\n }\n },\n {\n text: 'close',\n handler: function()\n {\n // We need to close the message window\n win.close();\n }\n }]\n });\n\n // Show the message detail window \n win.show();\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/186456", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24938/" ]
186,472
<p>I've seen some Python programmers use the following style fairly consistently (we'll call it style 1):</p> <pre><code>import some_module # Use some_module.some_identifier in various places. </code></pre> <p>For support of this style, you can cite the <a href="http://www.python.org/dev/peps/pep-0020/" rel="nofollow noreferrer">"explicit is better than implicit"</a> maxim. I've seen other programmers use this style (style 2):</p> <pre><code>from some_module import some_identifier # Use some_identifier in various places. </code></pre> <p>The primary benefit that I see in style 2 is maintainability -- especially with <a href="http://en.wikipedia.org/wiki/Duck_typing" rel="nofollow noreferrer">duck typing</a> ideals I may want to swap some_module for some_other_module. I also feel style 2 wins points with the <a href="http://www.python.org/dev/peps/pep-0020/" rel="nofollow noreferrer">"readability counts"</a> maxim. Although I tend to disagree, one can always argue that search-and-replace is just as good an option when using the first style.</p> <p><strong>Addendum:</strong> It was noted that you could use <code>as</code> to solve the switch from <code>some_module</code> to <code>some_other_module</code> in style 1. I forgot to mention that it is also common to decide to implement <code>some_identifier</code> in your <em>current</em> module, which makes creation of an equivalent <code>some_module</code> container slightly awkward.</p>
[ { "answer_id": 186483, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 3, "selected": false, "text": "import some_other_module as some_module\n" }, { "answer_id": 186485, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 2, "selected": false, "text": "some_module import some_module as sm\nx = sm.whatever\n from some_module import whatever\nx = whatever\n whatever some_other_module as" }, { "answer_id": 186486, "author": "Daren Thomas", "author_id": 2260, "author_profile": "https://Stackoverflow.com/users/2260", "pm_score": 0, "selected": false, "text": "import some_other_module as some_module\n from x import *" }, { "answer_id": 186541, "author": "PierreBdR", "author_id": 7136, "author_profile": "https://Stackoverflow.com/users/7136", "pm_score": 1, "selected": false, "text": "from some_module import some_symbol\n from some_module import some_symbol as other_symbol\n import module [as other_module]\n" }, { "answer_id": 186636, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 2, "selected": false, "text": "import X X.a from django.conf import settings django.conf.settings.DEBUG from X.Y.Z import a" }, { "answer_id": 186644, "author": "kender", "author_id": 4172, "author_profile": "https://Stackoverflow.com/users/4172", "pm_score": 0, "selected": false, "text": "import module \n list from SuperImprovedListOverloadedWithFeatures import NewLIst\nnl = NewList()\n" }, { "answer_id": 186813, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 4, "selected": true, "text": "import x,y,z remove os.remove from os import open\n import module [as renamed_module] import config\nconfig.dburl = 'sqlite:///test.db'\n import module" }, { "answer_id": 187352, "author": "giltay", "author_id": 21106, "author_profile": "https://Stackoverflow.com/users/21106", "pm_score": 0, "selected": false, "text": "from john import cleese\nfrom terry import jones, gilliam\n os wx import michael\nimport sarah\n\nimport wave\n\ngov_speech = wave.open(sarah.palin.speechfile)\nparrot_sketch = wave.open(michael.palin.justresting)\n from wave import open as wave_open wave.open" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/186472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3594/" ]
186,475
<p>I would like to use databinding when displaying data in a TextBox. I'm basically doing like:</p> <pre><code> public void ShowRandomObject(IRandomObject randomObject) { Binding binding = new Binding {Source = randomObject, Path = new PropertyPath("Name")}; txtName.SetBinding(TextBox.TextProperty, binding); } </code></pre> <p>I can't seem to find a way to unset the binding. I will be calling this method with a lot of different objects but the TextBox will remain the same. Is there a way to remove the previous binding or is this done automatically when I set the new binding?</p>
[ { "answer_id": 186479, "author": "Pop Catalin", "author_id": 4685, "author_profile": "https://Stackoverflow.com/users/4685", "pm_score": 7, "selected": true, "text": "BindingOperations.ClearBinding(txtName, TextBox.TextProperty)\n txtName.SetBinding(TextBox.TextProperty, null);\n this.btnFinish.ClearBinding(ButtonBase.CommandProperty);\n" }, { "answer_id": 186877, "author": "Arcturus", "author_id": 900, "author_profile": "https://Stackoverflow.com/users/900", "pm_score": 4, "selected": false, "text": "this.ClearValue(TextBox.TextProperty);\n" }, { "answer_id": 187902, "author": "Ed Ball", "author_id": 23818, "author_profile": "https://Stackoverflow.com/users/23818", "pm_score": 7, "selected": false, "text": "BindingOperations.ClearBinding(txtName, TextBox.TextProperty)\n" }, { "answer_id": 2973142, "author": "Bodekaer", "author_id": 309331, "author_profile": "https://Stackoverflow.com/users/309331", "pm_score": 0, "selected": false, "text": "txtName.Text = txtName.Text;\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/186475", "https://Stackoverflow.com", "https://Stackoverflow.com/users/143/" ]
186,477
<p>I have a function which parses one string into two strings. In C# I would declare it like this:</p> <pre><code>void ParseQuery(string toParse, out string search, out string sort) { ... } </code></pre> <p>and I'd call it like this:</p> <pre><code>string searchOutput, sortOutput; ParseQuery(userInput, out searchOutput, out sortOutput); </code></pre> <p>The current project has to be done in C++/CLI. I've tried</p> <pre><code>using System::Runtime::InteropServices; ... void ParseQuery(String ^ toParse, [Out] String^ search, [Out] String^ sort) { ... } </code></pre> <p>but if I call it like this:</p> <pre><code>String ^ searchOutput, ^ sortOutput; ParseQuery(userInput, [Out] searchOutput, [Out] sortOutput); </code></pre> <p>I get a compiler error, and if I call it like this:</p> <pre><code>String ^ searchOutput, ^ sortOutput; ParseQuery(userInput, searchOutput, sortOutput); </code></pre> <p>then I get an error at runtime. How should I declare and call my function?</p>
[ { "answer_id": 187577, "author": "Bert Huijben", "author_id": 2094, "author_profile": "https://Stackoverflow.com/users/2094", "pm_score": 8, "selected": true, "text": "void ReturnString([Out] String^% value)\n{\n value = \"Returned via out parameter\";\n}\n\n// Called as\nString^ result;\nReturnString(result);\n void ReturnInt([Out] int% value)\n{\n value = 32;\n}\n\n// Called as\nint result;\nReturnInt(result);\n" }, { "answer_id": 2908659, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "// header\n// Use namespace for Out-attribute.\nusing namespace System::Runtime::InteropServices; \nnamespace VHT_QMCLInterface {\n public ref class Client\n {\n public:\n Client();\n void ReturnInteger( int a, int b, [Out]int %c);\n void ReturnString( int a, int b, [Out]String^ %c);\n }\n}\n\n// cpp\nnamespace VHT_QMCLInterface {\n\n Client::Client()\n {\n\n }\n\n void Client::ReturnInteger( int a, int b, [Out]int %c)\n {\n c = a + b;\n }\n void Client::ReturnString( int a, int b, [Out]String^ %c)\n {\n c = String::Format( \"{0}\", a + b);\n }\n}\n\n// cs\nnamespace TestQMCLInterface\n{\n class Program\n {\n VHT_QMCLInterface.Client m_Client = new VHT_QMCLInterface.Client();\n static void Main(string[] args)\n {\n Program l_Program = new Program();\n l_Program.DoReturnInt();\n l_Program.DoReturnString();\n Console.ReadKey();\n }\n\n void DoReturnInt()\n {\n int x = 10;\n int y = 20;\n int z = 0;\n m_Client.ReturnInteger( x, y, out z);\n Console.WriteLine(\"\\nReturnInteger: {0} + {1} = {2}\", x, y, z);\n }\n\n void DoReturnString()\n {\n int x = 10;\n int y = 20;\n String z = \"xxxx\";\n m_Client.ReturnString(x, y, out z);\n Console.WriteLine(\"\\nReturnString: {0} + {1} = '{2}'\", x, y, z);\n }\n }\n}\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/186477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15371/" ]
186,493
<p>I'm trying to write a Mono C# daemon for linux.</p> <p>I'd like to do a starts and stops of it when its done processing instead of just killing the process.</p> <p>Does anyone have any examples of this?</p> <p>Edit: I figured out how to use start-stop-daemon --background in debian, so I think I'll just use that for now.</p> <p>Edit: I'm implementing this in java as well and they have this nice addShutdownHook that catches terminating the app. I need to spend a little more time sorting out the dependencies for mono service, or find a way to catch app termination. </p> <p>There is the SessionEnd event, but thats only available for services and not console apps</p> <p><strong>Answer:</strong> <a href="https://stackoverflow.com/questions/351971/using-mono-service-to-wrap-a-windows-service-on-linux">using mono-service to wrap a windows service on linux</a></p>
[ { "answer_id": 187523, "author": "David Schmitt", "author_id": 4918, "author_profile": "https://Stackoverflow.com/users/4918", "pm_score": 4, "selected": false, "text": "ServiceProcess MONO_DISABLE_SHM" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/186493", "https://Stackoverflow.com", "https://Stackoverflow.com/users/253/" ]